From fe26f09fab7d493dfb66c3a790e374fac4016cd2 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:26:46 +0800 Subject: [PATCH 01/12] fix(layout): a legend's title wraps to its box, and its rows start under the last line (#3129) --- crates/engine/src/cmd/layout/legend.rs | 12 +- .../engine/src/cmd/layout/publication/mod.rs | 6 +- crates/engine/src/tests.rs | 38 ++++++ .../src/tests/layout_publication_parts.rs | 19 ++- crates/render/src/layout/colorbar.rs | 18 ++- crates/render/src/layout/legend.rs | 74 +++++++++- crates/render/src/layout/losses.rs | 22 +-- crates/render/src/layout/tests.rs | 129 +++++++++++++++++- docs/user-guide/layouts.md | 11 +- 9 files changed, 296 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/layout/legend.rs b/crates/engine/src/cmd/layout/legend.rs index d2d9613cb2..fc1210213d 100644 --- a/crates/engine/src/cmd/layout/legend.rs +++ b/crates/engine/src/cmd/layout/legend.rs @@ -111,8 +111,9 @@ pub(in crate::cmd::layout) fn say_raster_keys(s: &mut Session, li: usize, id: u3 /// Whether a legend `kind`, after a command with `p`, says what it loses in its box (#2581): the /// one rule `layout.addElement` and `layout.update` both take. Told when it is given what sets -/// what it needs of its box (its columns, its missing-value row, its fit, its layer names, or its -/// text size, `null` included, which gives the default back) or labels (text chosen for the box), +/// what it needs of its box (its columns, its missing-value row, its fit, its layer names, its +/// title, which wraps to the box and takes the rows' room (#3129), or its text size, `null` +/// included, which gives the default back) or labels (text chosen for the box), /// and, in columns, at a text size of its own or under a fit, which can stop fitting, when its box /// or what it lists changes. A move changes neither. pub(in crate::cmd::layout) fn tells_legend_fit(kind: &ElementKind, p: &Value) -> bool { @@ -120,14 +121,14 @@ pub(in crate::cmd::layout) fn tells_legend_fit(kind: &ElementKind, p: &Value) -> let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); let watched = *columns > 1 || *text_size != rustgis_map::layout::LEGEND_TEXT_PT || fit.kept() != LegendFit::Manual; let refitted = ["w", "h", "title", "allClasses", "hideOther", "exclude", "labels"].iter().any(|k| given(k)); - ["columns", "showNoData", "labels", "fit", "showLayerNames"].iter().any(|k| given(k)) + ["columns", "showNoData", "labels", "fit", "showLayerNames", "title"].iter().any(|k| given(k)) || p.get("textSize").is_some() || (watched && refitted) } /// Says what a legend loses in its box, as `layout.publication` does for its own, or that it can't /// tell. A manual legend is measured in its own columns at its own size; a fitted one by the -/// drawing's own fit ([`crate::render::layout::legend_fitted_mm`]), in the room its title leaves, +/// drawing's own fit ([`crate::render::layout::legend_fitted_mm`]), in the room its wrapped title leaves, /// so it says nothing when the page draws it whole and what it tried when it can't. pub(in crate::cmd::layout) fn say_legend_fit(s: &mut Session, li: usize, id: u32) { let Some(l) = s.project.layouts.get(li) else { return }; @@ -153,7 +154,8 @@ pub(in crate::cmd::layout) fn say_legend_fit(s: &mut Session, li: usize, id: u32 Some(ElementKind::MapFrame { map, center, scale, .. }) => Some((map.clone(), *center, *scale)), _ => None, }; - let room = (e.w, e.h - if title.is_empty() { 0.0 } else { crate::render::layout::legend_title_mm(*text_size) }); + // The title wraps to the box (#3129): the rows have what is left under its lines. + let room = (e.w, e.h - crate::render::layout::legend_title_block_mm(title, (e.w, e.h), *text_size)); let (all_classes, hide_other, show_no_data, exclude, columns, labels, text_size) = (*all_classes, *hide_other, *show_no_data, exclude.clone(), *columns, labels.clone(), *text_size); let (fit, layer_names) = (fit.kept(), show_layer_names.shown()); diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index 9acd033c4f..4dbbfca076 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -1919,10 +1919,12 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let bar_need = bar.as_deref().map_or(0.0, |title| colorbar_mm(title, iw)); 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); - let (mut too_wide, too_tall) = overflows((cw, ch), (iw, rows_h)); // A title wider than the box is named: the width past it is the title's, unless the rows - // are wider still. + // are wider still. It wraps to the box (#3129), and the lines past its first take the + // rows' room, which `ch` (one line of title) doesn't hold. let title = legend.as_ref().map(|l| l.title.as_str()).filter(|t| ch > 0.0 && !t.is_empty()); + let title_extra = title.map_or(0.0, |t| crate::render::layout::legend_title_extra_mm(t, iw, legend_pt)); + let (mut too_wide, too_tall) = overflows((cw, ch + title_extra), (iw, rows_h)); let title_w = title.map_or(0.0, |t| crate::render::layout::legend_title_width_mm(t, legend_pt)); if title_w > iw + LEGEND_FIT_MM { warnings.push("the legend's title is wider than its box: shorten it".into()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 106c90811f..644d6d0048 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -13128,6 +13128,44 @@ fn legend_said(s: &Session, mark: u64) -> Vec { s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|n| n.starts_with("the legend")).collect() } +/// A title that wraps to a legend's box takes the rows' room (#3129): the legend whose box held +/// its rows under a title of one line says what it loses when its title is made long, as it would +/// when its rows grew, and says nothing for a title that fits in a line. +#[test] +fn a_legend_titled_past_its_box_says_the_rows_the_wrapped_title_takes() { + use std::collections::BTreeMap; + let mut s = world(); + s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "map"})).unwrap(); + let frame = s.project.layouts[0].first_frame().unwrap(); + let labels = BTreeMap::new(); + let asked = crate::render::layout::LegendAsked { + all_classes: true, + hide_other: false, + show_no_data: false, + layer_names: true, + text_size: 9.0, + exclude: &[], + labels: &labels, + }; + let rows = legend_sizes(&mut s, frame, &asked)[0]; + let title = crate::render::layout::legend_title_mm(9.0); + let mark = s.notice_mark(); + let added = json!({"kind": "legend", "allClasses": true, "columns": 1, "title": "Key", "x": 10, "y": 10, "w": rows.0 + 5.0, "h": title + rows.1 + 0.5}); + let id = s.run("layout.addElement", &added).unwrap()["element"].clone(); + assert_eq!(legend_said(&s, mark), Vec::::new()); + let long = "A very long legend title that is much wider than the legend itself"; + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "title": long})).unwrap(); + assert_eq!(legend_said(&s, mark), ["the legend lists more than fits its box: its last rows or the ends of long labels are left out"]); + // Back to a title of one line, it fits again; and a box that is taller holds the long one. + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "title": "Key"})).unwrap(); + assert_eq!(legend_said(&s, mark), Vec::::new()); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "title": long, "h": 200.0})).unwrap(); + assert_eq!(legend_said(&s, mark), Vec::::new()); +} + /// A manual legend that overflows its box says so as it always has; the same legend set to a fit /// that makes it fit says nothing, made a little smaller still nothing; given back manual, it says /// so again, word for word. diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index 28407ece7c..2208a176a5 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -454,6 +454,20 @@ fn the_publication_legend_fixture_opens_and_keeps_its_requirement() { assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["layout-publication-legend"])); } +/// A title wider than a side column's box wraps (#3129), and its lines past the first take the +/// room of the rows, which the sheet then says it left out: a title of two lines in a panel's one +/// column used to say only that it was wider than its box. +#[test] +fn a_publication_legend_title_wrapped_in_its_box_says_the_rows_it_loses() { + let (_, r) = sheet(json!({"legend": {"title": "A legend title ".repeat(2), "columns": 1}, "style": "panel"})); + let said = r["warnings"].to_string(); + assert!(said.contains("the legend's title is wider than its box: shorten it"), "{said}"); + assert!(said.contains("the legend lists more than fits its box: its last rows or the ends of long labels are left out"), "{said}"); + // A title that fits its box in one line loses nothing to it. + let (_, r) = sheet(json!({"legend": {"title": "Key", "columns": 1}, "style": "panel"})); + assert!(!r["warnings"].to_string().contains("legend lists more"), "{}", r["warnings"]); +} + #[test] fn a_publication_legend_title_wider_than_its_box_is_named() { let long = "A very long legend title ".repeat(8); @@ -461,7 +475,10 @@ fn a_publication_legend_title_wider_than_its_box_is_named() { let (_, r) = sheet(json!({"legend": {"title": long, "columns": columns}, "style": style})); let said = r["warnings"].to_string(); assert!(said.contains("the legend's title is wider than its box: shorten it"), "{columns} {style}: {said}"); - assert!(!said.contains("columns are wider") && !said.contains("ends of long labels"), "{columns} {style}: {said}"); + // The title is named, not the rows' columns as wider than the box; its lines, wrapped to the + // box (#3129), take the rows' room, which is said. + assert!(!said.contains("columns are wider"), "{columns} {style}: {said}"); + assert!(said.contains("its last rows"), "{columns} {style}: {said}"); } let (_, r) = sheet(json!({"legend": {"title": "Key"}})); assert!(!r["warnings"].to_string().contains("wider than its box"), "{}", r["warnings"]); diff --git a/crates/render/src/layout/colorbar.rs b/crates/render/src/layout/colorbar.rs index 4ed80107a1..4374645b93 100644 --- a/crates/render/src/layout/colorbar.rs +++ b/crates/render/src/layout/colorbar.rs @@ -231,7 +231,12 @@ pub(super) fn colorbar_title_style() -> TextStyle { /// A colorbar's title's width in mm, its widest line, measured as [`colorbar_title_lines`] breaks /// it. pub fn colorbar_title_width_mm(title: &str) -> f64 { - let px = (COLORBAR_TITLE_PT * 1.33 * WRAP_PX_PER_MM / PT_PER_MM) as f32; + title_width_mm(title, COLORBAR_TITLE_PT) +} + +/// A bold title's width in mm at `pt` points, its widest line, at the resolution titles are broken at. +fn title_width_mm(title: &str, pt: f64) -> f64 { + let px = (pt * 1.33 * WRAP_PX_PER_MM / PT_PER_MM) as f32; let face = colorbar_title_style().face; title.lines().map(|line| f64::from(text::styled_extent(line, px, face, 0.0).1)).fold(0.0, f64::max) / WRAP_PX_PER_MM } @@ -246,11 +251,18 @@ pub(super) const COLORBAR_TITLE_SLACK_MM: f64 = 0.01; /// title of one line that fits is that line, as it is. Past 200 lines, one more line with text /// says it goes on, as for a wrapped text. pub fn colorbar_title_lines(title: &str, width: f64) -> Vec { + title_lines(title, width, COLORBAR_TITLE_PT) +} + +/// A bold title of `pt` points as the lines it is drawn in, broken to fit `width` mm +/// ([`colorbar_title_lines`], and a legend's, #3129, which differ only in size). +pub(super) fn title_lines(title: &str, width: f64, pt: f64) -> Vec { + let pt = pt.clamp(2.0, 400.0); let width = width + COLORBAR_TITLE_SLACK_MM; - if !title.contains('\n') && colorbar_title_width_mm(title) <= width { + if !title.contains('\n') && title_width_mm(title, pt) <= width { return vec![title.to_string()]; } - wrapped(title, width, COLORBAR_TITLE_PT, colorbar_title_style()).lines().map(str::to_string).collect() + wrapped(title, width, 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` (pixels), its diff --git a/crates/render/src/layout/legend.rs b/crates/render/src/layout/legend.rs index 7c9bac3122..89960bcebb 100644 --- a/crates/render/src/layout/legend.rs +++ b/crates/render/src/layout/legend.rs @@ -664,6 +664,8 @@ pub(super) const LEGEND_TITLE_PT: f32 = 12.0; pub(super) const LEGEND_NAME_PT: f32 = 9.0; pub(super) const LEGEND_LABEL_PT: f32 = 8.5; pub(super) const LEGEND_TITLE_ROWS: f32 = 1.3; +/// The spacing of a legend's title's lines, times its size: the usual line pitch. +const LEGEND_TITLE_LINE_SPACING: f32 = 1.25; pub(super) const LEGEND_INDENT: f32 = 6.0; pub(super) const LEGEND_LABEL_INDENT: f32 = 12.0; /// A legend swatch's width, in points. @@ -999,9 +1001,16 @@ pub(super) fn legend_missing( let ppp = ppp as f32; let mut y = r.y(); if !title.is_empty() { + // Wrapped to the box (#3129), as a colorbar's is: the rows start under its last line. + let lines = legend_title_lines(title, f64::from(r.width()) / (f64::from(ppp) * PT_PER_MM), opts.text_size); + let drawn = legend_title_drawn(lines.len(), r.height(), opts.size, ppp); let line = LEGEND_ROW * opts.size * ppp; - text::text_at(pm, title, r.x(), y + line / 2.0, LEGEND_TITLE_PT * opts.size * 1.33 * ppp, ink, true, text::Align::Left, false); - y += line * LEGEND_TITLE_ROWS; + let pitch = title_pitch(opts.size, ppp); + for (i, text) in lines.iter().take(drawn).enumerate() { + let at = y + line / 2.0 + pitch * i as f32; + text::text_at(pm, text, r.x(), at, LEGEND_TITLE_PT * opts.size * 1.33 * ppp, ink, true, text::Align::Left, false); + } + y += title_block(drawn, opts.size, ppp); } let (rows, missing) = legend_rows_missing(map, drawn, &opts); let sides = symbol_sides(&rows, opts.scale); @@ -1325,8 +1334,65 @@ pub fn legend_title_width_mm(title: &str, text_size: f64) -> f64 { f64::from(text::measure(title, LEGEND_TITLE_PT * legend_size(text_size), true)) / PT_PER_MM } -/// The height in mm [`legend`] gives a title above its rows, which [`legend_sizes_mm`] leaves out, -/// in a legend whose text is `text_size` points (#2581). +/// The height in mm [`legend`] gives a title of one line above its rows, which [`legend_sizes_mm`] +/// leaves out, in a legend whose text is `text_size` points (#2581). pub fn legend_title_mm(text_size: f64) -> f64 { f64::from(LEGEND_ROW * legend_size(text_size)) * f64::from(LEGEND_TITLE_ROWS) * 25.4 / 96.0 } + +/// The distance between two lines of a legend's title, in pixels at `ppp`, for a legend `size` +/// times the default ([`line_pitch_mm`]'s, at the title's size). +fn title_pitch(size: f32, ppp: f32) -> f32 { + LEGEND_TITLE_PT * size * 1.33 * LEGEND_TITLE_LINE_SPACING * ppp +} + +/// The room in pixels a title of `lines` lines takes above a legend's rows: [`LEGEND_TITLE_ROWS`] +/// rows for one, and a line's pitch more for each line past the first (#3129). +fn title_block(lines: usize, size: f32, ppp: f32) -> f32 { + LEGEND_ROW * size * ppp * LEGEND_TITLE_ROWS + lines.saturating_sub(1) as f32 * title_pitch(size, ppp) +} + +/// A legend's title as the lines it is drawn in (#3129): broken at spaces to fit `width_mm`, a +/// word wider than that across lines, as a colorbar's title is ([`colorbar_title_lines`]), at one +/// resolution whatever it is drawn at, in a legend whose text is `text_size` points. A title with +/// no text is one empty line, which takes the room it always took; none for no title. +pub fn legend_title_lines(title: &str, width_mm: f64, text_size: f64) -> Vec { + if title.is_empty() { + return Vec::new(); + } + let lines = title_lines(title, width_mm, f64::from(LEGEND_TITLE_PT * legend_size(text_size))); + if lines.is_empty() { vec![String::new()] } else { lines } +} + +/// How many of a legend title's `lines` it draws in a box `height` pixels high, its text `size` +/// times the default (#3129): the first always, as a title is always drawn, each further one only +/// when the title's block, with the room it leaves the rows, still ends inside the box; at most 200. +/// The page's cut-off check ([`text_losses`]) counts the lines left out the same way. +pub(super) fn legend_title_drawn(lines: usize, height: f32, size: f32, ppp: f32) -> usize { + let most = lines.min(MAX_TEXT_LINES); + if most == 0 { + return 0; + } + 1 + (2..=most).take_while(|n| title_block(*n, size, ppp) <= height).count() +} + +/// The height in mm [`legend`] gives a title above its rows in a box `w` × `h` mm, in a legend +/// whose text is `text_size` points: [`legend_title_mm`] for one line, a line's pitch more for each +/// line it wraps to that the box has the height to draw (#3129). 0 for no title. +pub fn legend_title_block_mm(title: &str, (w, h): (f64, f64), text_size: f64) -> f64 { + let lines = legend_title_lines(title, w, text_size).len(); + if lines == 0 { + return 0.0; + } + let size = legend_size(text_size); + let drawn = legend_title_drawn(lines, (h * PT_PER_MM) as f32, size, 1.0); + legend_title_mm(text_size) + drawn.saturating_sub(1) as f64 * line_pitch_mm(f64::from(LEGEND_TITLE_PT * size)) +} + +/// The height in mm a title wraps to in a legend `w` mm wide above what [`legend_title_mm`] gives +/// it, whatever the height of the box: what a box sized for a title of one line is short by +/// (#3129). +pub fn legend_title_extra_mm(title: &str, w: f64, text_size: f64) -> f64 { + let lines = legend_title_lines(title, w, text_size).len().min(MAX_TEXT_LINES); + lines.saturating_sub(1) as f64 * line_pitch_mm(f64::from(LEGEND_TITLE_PT * legend_size(text_size))) +} diff --git a/crates/render/src/layout/losses.rs b/crates/render/src/layout/losses.rs index 49b0d4576c..eedd6629a8 100644 --- a/crates/render/src/layout/losses.rs +++ b/crates/render/src/layout/losses.rs @@ -165,21 +165,24 @@ pub(super) fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, o (style.valign, style.line_spacing), ) } - // Its title at the size it is drawn at, its legend's text size (#2581). + // Its title at the size it is drawn at, its legend's text size (#2581), in the + // lines it is wrapped to and draws in its box's height (#3129). ElementKind::Legend { title, frame, text_size, .. } => { let ElementKind::MapFrame { map, .. } = &layout.element(*frame)?.kind else { return None }; map_index(maps, map)?; let size = LEGEND_TITLE_PT * legend_size(*text_size); + let lines = legend_title_lines(title, e.w, *text_size); + let fits = legend_title_drawn(lines.len(), r.height(), legend_size(*text_size), ppp); ( - title.clone(), + lines.join("\n"), size, text::Face { bold: true, ..Default::default() }, TextAlign::Left, 0.0, 0.0, true, - false, - None, + true, + Some(fits), (TextVAlign::Top, USUAL_LINE_SPACING), ) } @@ -235,8 +238,7 @@ pub(super) fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, o r.y() + shift + px * 0.6 }; let turn = Transform::from_rotate_at(rotation, r.x() + r.width() / 2.0, r.y() + r.height() / 2.0); - // Legend titles are drawn on one line, unlike text elements' explicit line breaks. - let lines = std::iter::once(s.as_str()).filter(|_| title).chain(s.lines().filter(|_| !title)); + let lines = s.lines(); let (mut cut, mut left_out, mut below_box, mut past_limit, mut off_page) = (false, 0, false, false, false); for (i, line) in lines.enumerate() { let drawn = match fits { @@ -295,8 +297,7 @@ pub(super) fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, o /// can merge repeated element IDs across series pages before calling this, so a PDF's fallback /// rendering and repeated pages never multiply the count. Its advice fits the texts of `layout` /// named: breaking lines by hand or wrapping them for a text not wrapped (#2346), only the box or -/// the size when all are wrapped to their boxes, and line breaks without the wrap for a legend's -/// title, which has none. +/// the size when all are wrapped to their boxes, a legend's and a colorbar's titles being so. pub fn clipped_text_notice(layout: &Layout, clipped: &[(u32, String)]) -> Option { if clipped.is_empty() { return None; @@ -305,12 +306,13 @@ pub fn clipped_text_notice(layout: &Layout, clipped: &[(u32, String)]) -> Option if clipped.len() > 10 { names.push_str(&format!(" and {} more", clipped.len() - 10)); } - // Each text's wrap; `None` for a legend's or a colorbar's title, or an element gone since, - // which keep the advice they always had. + // Each text's wrap; `None` for an element gone since, which keeps the advice it always had. let wraps = clipped .iter() .map(|(id, _)| match layout.element(*id).map(|e| &e.kind) { Some(ElementKind::Text { wrap, .. }) => Some(*wrap), + // A legend's title (#3129) and a colorbar's wrap to their boxes. + Some(ElementKind::Legend { .. } | ElementKind::Colorbar { .. }) => Some(true), _ => None, }) .collect::>(); diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 5987cf4aad..ded5d11e7b 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -825,7 +825,7 @@ fn layout_text_clipping_uses_ink_and_visibility() { ); let legend = l.add( "Legend", - (115.0, 10.0, 5.0, 40.0), + (115.0, 10.0, 40.0, 40.0), ElementKind::Legend { frame, title: "Long legend title".into(), @@ -842,8 +842,8 @@ fn layout_text_clipping_uses_ink_and_visibility() { }, ); assert_eq!(clipped_text(&l, &[Map::new("m")], 96.0, &info), vec![(legend, "Legend".into())]); - // Its title is measured at the size it is drawn at (#2581): one that fits on the page at - // 9 points runs past its edge at 36. + // Its title is measured at the size it is drawn at (#2581): one that fits its box at 9 points + // loses lines, wrapped to the box, at 36 (#3129). l.element_mut(legend).unwrap().x = 60.0; assert!(clipped_text(&l, &[Map::new("m")], 96.0, &info).is_empty(), "fits at 9 points"); if let ElementKind::Legend { text_size, .. } = &mut l.element_mut(legend).unwrap().kind { @@ -3599,7 +3599,8 @@ fn the_cut_off_notice_suggests_wrapping_a_text_not_wrapped() { assert_eq!(note.contains("add line breaks"), !wrap, "{note}"); assert!(note.contains("reduce its size"), "{note}"); } - // A legend's title, or an element gone since, has no wrap to turn on: line breaks, as before. + // An element gone since has no wrap to turn on: line breaks, as before. A legend's title is + // wrapped to its box (#3129): the size and the box, as for any wrapped text. let l = note_page(NOTE, true, TextAlign::Left, 0.0); let note = clipped_text_notice(&l, &[(999, "Gone".into())]).unwrap(); assert!(note.ends_with("resize or move the text, reduce its size, or add line breaks"), "{note}"); @@ -4622,6 +4623,126 @@ fn rgb(pm: &Pixmap, x: u32, y: u32) -> (u8, u8, u8) { pm.pixel(x, y).map(|p| (p.red(), p.green(), p.blue())).unwrap_or((255, 255, 255)) } +/// The long title of the legend in #3129. +const LONG_LEGEND_TITLE: &str = "A very long legend title that is much wider than the legend itself"; + +/// The columns from `x0` to `x1` and rows from `y0` to `y1` of `pm` holding dark ink. +fn dark_in(pm: &Pixmap, (x0, x1): (u32, u32), (y0, y1): (u32, u32)) -> bool { + (y0..y1).any(|y| (x0..x1).any(|x| pm.pixel(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120 && p.green() < 120))) +} + +/// A legend's title longer than its box is wide wraps inside it (#3129), every word kept, as a +/// colorbar's does: no ink past the box's right edge, and a second line under the first. +#[test] +fn a_legends_long_title_wraps_inside_its_box() { + let pm = titled(&Map::new("m"), LONG_LEGEND_TITLE, (200.0, 300.0), (1, LegendFit::Manual), 9.0); + assert!(!dark_in(&pm, (201, 600), (0, 600)), "the title's ink past the box's right edge"); + let lines = legend_title_lines(LONG_LEGEND_TITLE, 200.0 / PT_PER_MM, 9.0); + assert!(lines.len() >= 2, "{lines:?}"); + assert_eq!(lines.join(" "), LONG_LEGEND_TITLE, "every word is kept"); + let pitch = (LEGEND_TITLE_PT * 1.33 * 1.25) as u32; + for k in 0..lines.len() as u32 { + assert!(dark_in(&pm, (0, 200), (k * pitch + 6, k * pitch + 14)), "line {k} of the title"); + } + // One that fits is the one line, as it was drawn. + assert_eq!(legend_title_lines("Key", 200.0 / PT_PER_MM, 9.0), ["Key"]); + assert_eq!(legend_title_lines("", 200.0 / PT_PER_MM, 9.0), Vec::::new()); +} + +/// A legend's rows start under the last line of its title (#3129): as much lower as the lines it +/// wraps to past the first, and where they always did under a title of one line. +#[test] +fn a_legends_rows_start_under_its_last_title_line() { + let map = point_rows_map(5, None); + let rows_bottom = |title: &str| ink_bounds(&titled(&map, title, (200.0, 400.0), (1, LegendFit::Manual), 9.0)).3; + let one = rows_bottom("Key"); + let lines = legend_title_lines(LONG_LEGEND_TITLE, 200.0 / PT_PER_MM, 9.0).len(); + let pitch = LEGEND_TITLE_PT * 1.33 * 1.25; + let moved = rows_bottom(LONG_LEGEND_TITLE) as f32 - one as f32; + assert!((moved - (lines - 1) as f32 * pitch).abs() <= 2.0, "{moved} px lower for {lines} lines of {pitch} px"); + // Under a title of one line they are where they were: the title's block is 1.3 rows. A title + // of only spaces has no ink and takes the same room. + let top = |title: &str| ink_bounds(&titled(&map, title, (200.0, 400.0), (1, LegendFit::Manual), 9.0)).1 as f32; + assert!((top(" ") - top("") - LEGEND_ROW * LEGEND_TITLE_ROWS).abs() <= 1.0, "{} against {}", top(" "), top("")); +} + +/// The same lines at every resolution: a legend's title is measured at one (#3129), as a text's +/// is, so the layout view, an image export and a print break it alike. +#[test] +fn a_legends_title_breaks_alike_at_every_resolution() { + let map = Map::new("m"); + let lines = |ppp: f32| { + let mut pm = Pixmap::new(1800, 1800).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let opts = LegendOptions { size: 1.0, text_size: 9.0, ..opts(true) }; + crate::canvas::with_canvas(&mut pm, |c| { + let r = Rect::from_xywh(0.0, 0.0, 200.0 * ppp, 600.0 * ppp).unwrap(); + legend_missing(c, r, &map, (LONG_LEGEND_TITLE, 1, LegendFit::Manual), None, opts, INK, f64::from(ppp)); + }); + (ink_bounds(&pm).3 as f32 / ppp, pm) + }; + let (one, _) = lines(1.0); + let (three, pm) = lines(3.0); + assert!((one - three).abs() <= 3.0, "{one} against {three} px at 96 dpi"); + assert!(!dark_in(&pm, (601, 1800), (0, 1800)), "no ink past the box at 3x"); +} + +/// A legend whose box is too short for the lines its title wraps to draws those that fit, and the +/// cut-off check counts the rest (#3129) with a wrapped text's advice; a box tall enough loses +/// none. A title in a box of no width, or of 200 letters with no space, stays within 200 lines. +#[test] +fn a_legends_title_lines_past_its_box_are_left_out_and_said() { + let info = PageInfo::default(); + let page = |title: &str, (w, h): (f64, f64)| { + 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::Legend { + frame, + title: title.into(), + all_classes: false, + hide_other: false, + show_no_data: false, + exclude: vec![], + columns: 1, + labels: BTreeMap::new(), + color: None, + text_size: rustgis_map::layout::LEGEND_TEXT_PT, + fit: LegendFit::Manual, + show_layer_names: rustgis_map::layout::LayerNames::Shown, + }; + let id = l.add("Legend", (10.0, 10.0, w, h), kind); + (l, id) + }; + let losses = |l: &Layout| text_losses(l, &[Map::new("m")], 96.0, &info); + let lines = legend_title_lines(LONG_LEGEND_TITLE, 30.0, 9.0).len(); + assert!(lines >= 4, "{lines} lines"); + // 15 mm is 57 px: the block of two lines (19.5 + 20 px) ends in it, of three (59.5) doesn't. + let (l, id) = page(LONG_LEGEND_TITLE, (30.0, 15.0)); + let loss = losses(&l); + assert_eq!(loss.len(), 1, "{loss:?}"); + assert_eq!((loss[0].id, loss[0].left_out, loss[0].below_box, loss[0].off_page), (id, lines - 2, true, false), "{loss:?}"); + let note = clipped_text_notice(&l, &clipped_text(&l, &[Map::new("m")], 96.0, &info)).unwrap(); + assert_eq!(note, format!("Text is cut off in 1 layout element(s): Legend ({id}); resize or move the text, or reduce its size")); + // Tall enough for every line, or a title that fits: nothing is lost. + assert!(losses(&page(LONG_LEGEND_TITLE, (30.0, 60.0)).0).is_empty()); + assert!(losses(&page("Key", (30.0, 6.0)).0).is_empty()); + assert!(losses(&page("", (30.0, 6.0)).0).is_empty()); + // Hostile titles and boxes: counted within the 200 a text draws, none a panic. + for title in ["x".repeat(200), "word ".repeat(40), "a\nb\n\nc".to_string(), " ".into()] { + for w in [0.0, 0.01, 1.0] { + let (l, _) = page(&title, (w, 20.0)); + assert!(losses(&l).iter().all(|loss| loss.left_out <= 200), "{title:?} {w}"); + let _ = render(&l, &mut [Map::new("m")], 96.0, &info).unwrap(); + } + } + // And drawn in a box one pixel across. + let _ = titled(&Map::new("m"), &"x".repeat(200), (1.0, 1.0), (1, LegendFit::Manual), 9.0); +} + /// A colorbar's title longer than the element is wide wraps inside it (#2493), every word kept; /// the bar goes under its lines. #[test] diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index ad3c188044..116452bf76 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -419,13 +419,16 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu short fills each column in turn and leaves out the last rows (a **Fit**, below, can change that). A legend says when its box loses rows or closes its columns up when it is given `"columns"`, - `"textSize"` (`null` included), `"showNoData"`, `"labels"`, `"fit"` or `"showLayerNames"`, and, - in columns, at a text size of its own or with a fit, when its box or what it lists changes. A + `"textSize"` (`null` included), `"showNoData"`, `"labels"`, `"fit"`, `"showLayerNames"` or + `"title"`, and, in columns, at a text size of its own or with a fit, when its box or what it lists changes. A legend in one column at the default size and with no fit is told so only when given one of those. A manual legend is checked when it is added or changed, as it always has been, not again when the map's layers change later. A legend with a fit is checked then too, and again by every export, which says, in the same words, when its fit no longer makes it fit (a layer added to the map, the frame's scale changed); the drawing itself fits again on every draw, as below. + - **Title** (`"title"`): a title wider than the legend's box wraps to it, as a colorbar's does, + and the rows start under its last line, so a long title leaves them less room (said as above). + Lines that don't fit the box's height are left out, and the cut-off notice counts the legend. - **Fit** (`"fit"`): what gives way when the rows don't fit the box. **Manual** (`"manual"`, the default) keeps the text's size and the columns and leaves out the last rows, as legends always have. **Shrink the text** (`"adjustSize"`) draws the rows' text a quarter point smaller at a @@ -555,8 +558,8 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu The notice counts and names the affected elements with their IDs. A line may extend beyond its element's width while remaining on the page; that alone is not clipped. Reduce the size, add line breaks, turn on **Wrap to the box**, or resize or move the element to keep all its text; - when every text it names is already wrapped, the notice suggests only the size and the box, and - a legend's title, which has no wrap, is told to add line breaks. Lines left out below a text's + when every text it names is already wrapped (a legend's and a colorbar's titles always are), the + notice suggests only the size and the box. Lines left out below a text's box are said as soon as they are: `layout.addElement` and `layout.update` warn how many lines don't fit when they set a text, its size, font or fallback font, bold, italic, alignment, spacing, line spacing, case, wrap or box, or show it, and the Format pane shows the count under From 780c53e78c1738287c5d9ba0cff69dfa9c30ae9a Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:48:46 +0800 Subject: [PATCH 02/12] fix(layout): review fixes for the legend title wrap (#3129) --- crates/engine/src/cmd/layout.rs | 2 +- crates/engine/src/cmd/layout/legend.rs | 2 +- crates/render/src/layout/legend.rs | 4 +--- crates/render/src/layout/tests.rs | 4 ++-- docs/user-guide/layouts.md | 3 ++- 5 files changed, 7 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index d0aa917e5e..12e67efbff 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -199,7 +199,7 @@ pub fn commands() -> Vec { r##""case"?: "none"|"upper"|"lower" (text, dynamicText: drawn in upper or lower case once its dynamic text is filled in, its text kept as typed; default none; refused for other kinds), "##, r##""font"?: "sans"|"serif"|an installed font family's name, as labels.fonts lists them (text, dynamicText; a family not installed here is drawn in its fallback, and a serif where none is installed in the sans, with a warning; refused for other kinds), "##, r##""fallback"?: "sans"|"serif" (a named font's, where it isn't installed; default its own class, else sans), "##, - r##""title"?: legend title (default "Legend"); chart: its own title ("" for none; default: its field, or the statistic of its field by the group), "##, + r##""title"?: legend title (default "Legend"; wrapped within the legend's box); chart: its own title ("" for none; default: its field, or the statistic of its field by the group), "##, r##""allClasses"?: bool (legend: every class, not only those the frame draws), "##, r##""hideOther"?: bool (legend: leave out ), "##, r##""showNoData"?: bool (legend: include Graduated Colors’ missing-value symbol; default false), "##, diff --git a/crates/engine/src/cmd/layout/legend.rs b/crates/engine/src/cmd/layout/legend.rs index fc1210213d..c110ab7025 100644 --- a/crates/engine/src/cmd/layout/legend.rs +++ b/crates/engine/src/cmd/layout/legend.rs @@ -120,7 +120,7 @@ pub(in crate::cmd::layout) fn tells_legend_fit(kind: &ElementKind, p: &Value) -> let ElementKind::Legend { columns, text_size, fit, .. } = kind else { return false }; let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); let watched = *columns > 1 || *text_size != rustgis_map::layout::LEGEND_TEXT_PT || fit.kept() != LegendFit::Manual; - let refitted = ["w", "h", "title", "allClasses", "hideOther", "exclude", "labels"].iter().any(|k| given(k)); + let refitted = ["w", "h", "allClasses", "hideOther", "exclude", "labels"].iter().any(|k| given(k)); ["columns", "showNoData", "labels", "fit", "showLayerNames", "title"].iter().any(|k| given(k)) || p.get("textSize").is_some() || (watched && refitted) diff --git a/crates/render/src/layout/legend.rs b/crates/render/src/layout/legend.rs index 89960bcebb..d79e197379 100644 --- a/crates/render/src/layout/legend.rs +++ b/crates/render/src/layout/legend.rs @@ -664,8 +664,6 @@ pub(super) const LEGEND_TITLE_PT: f32 = 12.0; pub(super) const LEGEND_NAME_PT: f32 = 9.0; pub(super) const LEGEND_LABEL_PT: f32 = 8.5; pub(super) const LEGEND_TITLE_ROWS: f32 = 1.3; -/// The spacing of a legend's title's lines, times its size: the usual line pitch. -const LEGEND_TITLE_LINE_SPACING: f32 = 1.25; pub(super) const LEGEND_INDENT: f32 = 6.0; pub(super) const LEGEND_LABEL_INDENT: f32 = 12.0; /// A legend swatch's width, in points. @@ -1343,7 +1341,7 @@ pub fn legend_title_mm(text_size: f64) -> f64 { /// The distance between two lines of a legend's title, in pixels at `ppp`, for a legend `size` /// times the default ([`line_pitch_mm`]'s, at the title's size). fn title_pitch(size: f32, ppp: f32) -> f32 { - LEGEND_TITLE_PT * size * 1.33 * LEGEND_TITLE_LINE_SPACING * ppp + (line_pitch_mm(f64::from(LEGEND_TITLE_PT * size)) * PT_PER_MM) as f32 * ppp } /// The room in pixels a title of `lines` lines takes above a legend's rows: [`LEGEND_TITLE_ROWS`] diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index ded5d11e7b..941a8aab47 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -3599,8 +3599,8 @@ fn the_cut_off_notice_suggests_wrapping_a_text_not_wrapped() { assert_eq!(note.contains("add line breaks"), !wrap, "{note}"); assert!(note.contains("reduce its size"), "{note}"); } - // An element gone since has no wrap to turn on: line breaks, as before. A legend's title is - // wrapped to its box (#3129): the size and the box, as for any wrapped text. + // An element gone since has no wrap to turn on: line breaks, as before. (A legend's title + // wraps to its box, and gets the wrapped text's advice: `a_legends_title_lines_past_its_box_are_left_out_and_said`.) let l = note_page(NOTE, true, TextAlign::Left, 0.0); let note = clipped_text_notice(&l, &[(999, "Gone".into())]).unwrap(); assert!(note.ends_with("resize or move the text, reduce its size, or add line breaks"), "{note}"); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 116452bf76..22bacdce90 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -554,7 +554,8 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu `layout.addElement={"kind":"arrow","angle":30,"length":60}`, or `layout.update={"element":7,"angle":-90}` to turn one. - **Text clipping**: the layout view and PNG, PDF and SVG exports warn when a text element or - legend title runs off the page, or a text element has more lines than its height allows. + legend title runs off the page or loses lines to its box, or a text element has more lines than + its height allows. The notice counts and names the affected elements with their IDs. A line may extend beyond its element's width while remaining on the page; that alone is not clipped. Reduce the size, add line breaks, turn on **Wrap to the box**, or resize or move the element to keep all its text; From 103e9e12093509f186484c7b4237cb15080b21d3 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:44:51 +0800 Subject: [PATCH 03/12] layout: leave omitted title lines out of the publication legend's row-loss check (#3129) --- crates/engine/src/cmd/layout/publication/mod.rs | 10 +++++++--- .../src/tests/layout_publication_parts.rs | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index 4dbbfca076..2d671ee8d3 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -1920,10 +1920,14 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu 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); // A title wider than the box is named: the width past it is the title's, unless the rows - // are wider still. It wraps to the box (#3129), and the lines past its first take the - // rows' room, which `ch` (one line of title) doesn't hold. + // are wider still. It wraps to the box (#3129), and the lines it draws past its first take + // the rows' room, which `ch` (one line of title) doesn't hold. A line the box has no height + // for is left out, takes none, and is the text-loss report's to say, not the rows'. let title = legend.as_ref().map(|l| l.title.as_str()).filter(|t| ch > 0.0 && !t.is_empty()); - let title_extra = title.map_or(0.0, |t| crate::render::layout::legend_title_extra_mm(t, iw, legend_pt)); + let title_extra = title.map_or(0.0, |t| { + let drawn = crate::render::layout::legend_title_block_mm(t, (iw, rows_h), legend_pt); + (drawn - crate::render::layout::legend_title_mm(legend_pt)).max(0.0) + }); let (mut too_wide, too_tall) = overflows((cw, ch + title_extra), (iw, rows_h)); let title_w = title.map_or(0.0, |t| crate::render::layout::legend_title_width_mm(t, legend_pt)); if title_w > iw + LEGEND_FIT_MM { diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index 2208a176a5..be226048a2 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -468,6 +468,23 @@ fn a_publication_legend_title_wrapped_in_its_box_says_the_rows_it_loses() { assert!(!r["warnings"].to_string().contains("legend lists more"), "{}", r["warnings"]); } +/// A title line the box has no height to draw is left out (#3129), so it takes no room from the +/// rows: with one row and a two-line title in a box that holds the first line and the row, every +/// row is drawn and the sheet doesn't say rows are lost. +#[test] +fn a_publication_legend_title_line_left_out_does_not_say_a_drawn_row_is_lost() { + // One layer drawn in one plain colour: a single row. + let mut w = world(); + w.map_mut().layers.retain(|l| l.name == "Rivers"); + let (s, r) = { + let r = publish(&mut w, json!({"legend": {"title": "A legend title ".repeat(2), "columns": 1}, "style": "panel"})).unwrap(); + (w, r) + }; + let said = r["warnings"].to_string(); + assert!(find(&s, "Legend").is_some(), "{said}"); + assert!(!said.contains("the legend lists more than fits its box"), "{said}"); +} + #[test] fn a_publication_legend_title_wider_than_its_box_is_named() { let long = "A very long legend title ".repeat(8); From 2c2aa9d4a120d7b0b5f2db49384047cdcb663609 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:30:43 +0800 Subject: [PATCH 04/12] render: legend title fit allows rounding slack at translated boxes (#3129) --- crates/render/src/layout/legend.rs | 3 +++ crates/render/src/layout/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/crates/render/src/layout/legend.rs b/crates/render/src/layout/legend.rs index 3a35884421..4083f6ac96 100644 --- a/crates/render/src/layout/legend.rs +++ b/crates/render/src/layout/legend.rs @@ -1568,6 +1568,9 @@ pub(super) fn legend_title_drawn(lines: usize, height: f32, size: f32, ppp: f32) if most == 0 { return 0; } + // A thousandth of a row's slack, as the rows have: a translated `Rect` stores its edges, so its + // height is off by a rounding from the one it was made with. + let height = height + LEGEND_ROW * size * ppp * 1e-3; 1 + (2..=most).take_while(|n| title_block(*n, size, ppp) <= height).count() } diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 144a32c1dd..0a30606939 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -4957,6 +4957,27 @@ fn a_legends_title_lines_past_its_box_are_left_out_and_said() { let _ = titled(&Map::new("m"), &"x".repeat(200), (1.0, 1.0), (1, LegendFit::Manual), 9.0); } +/// A box whose height is a title's two-line block to the pixel keeps the second line wherever it +/// sits on the page: `Rect` stores edges, so a translated one's height is off by a rounding +/// (#3129). +#[test] +fn a_legends_title_fit_allows_rounding_at_translated_boxes() { + let h_mm = 10.4378125; + let size = legend_size(9.0); + let drawn = |y_mm: f64| { + let r = Rect::from_xywh(10.0, (y_mm * PT_PER_MM) as f32, 100.0, (h_mm * PT_PER_MM) as f32).unwrap(); + legend_title_drawn(2, r.height(), size, 1.0) + }; + assert_eq!(drawn(0.0), 2); + assert_eq!(drawn(100.0 / PT_PER_MM), 2, "translated"); + let block = legend_title_block_mm("A\nB", (100.0 / PT_PER_MM, h_mm), 9.0); + assert!(block > legend_title_mm(9.0), "{block}"); + // A clearly undersized box still leaves the second line out, wherever it is. + let short = Rect::from_xywh(10.0, 100.0, 100.0, (h_mm * PT_PER_MM) as f32 - 0.5).unwrap(); + assert_eq!(legend_title_drawn(2, short.height(), size, 1.0), 1); + assert_eq!(legend_title_block_mm("A\nB", (100.0 / PT_PER_MM, h_mm - 0.5 / PT_PER_MM), 9.0), legend_title_mm(9.0)); +} + /// A colorbar's title longer than the element is wide wraps inside it (#2493), every word kept; /// the bar goes under its lines. #[test] From 1ad99dc960e5fefac23b623df0fdab4171484847 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:55:30 +0800 Subject: [PATCH 05/12] layout: title-wrap tests follow the legend's subtitle (#3129) --- crates/render/src/layout/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index add720da74..13ee9a36a7 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -5053,7 +5053,7 @@ fn a_legends_title_breaks_alike_at_every_resolution() { let opts = LegendOptions { size: 1.0, text_size: 9.0, ..opts(true) }; crate::canvas::with_canvas(&mut pm, |c| { let r = Rect::from_xywh(0.0, 0.0, 200.0 * ppp, 600.0 * ppp).unwrap(); - legend_missing(c, r, &map, (LONG_LEGEND_TITLE, 1, LegendFit::Manual), None, opts, INK, f64::from(ppp)); + legend_missing(c, r, &map, ((LONG_LEGEND_TITLE, ""), 1, LegendFit::Manual), None, opts, INK, f64::from(ppp)); }); (ink_bounds(&pm).3 as f32 / ppp, pm) }; @@ -5092,6 +5092,7 @@ fn a_legends_title_lines_past_its_box_are_left_out_and_said() { fit: LegendFit::Manual, show_layer_names: rustgis_map::layout::LayerNames::Shown, show_counts: Default::default(), + subtitle: String::new(), }; let id = l.add("Legend", (10.0, 10.0, w, h), kind); (l, id) From ab442e784a1794b867e866c8b0db4fc36639c830 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:28:09 +0800 Subject: [PATCH 06/12] layout: a legend's subtitle is checked against the page under its wrapped title (#3129) --- crates/render/src/layout/legend.rs | 2 +- crates/render/src/layout/losses.rs | 9 +++++- crates/render/src/layout/tests.rs | 45 ++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/crates/render/src/layout/legend.rs b/crates/render/src/layout/legend.rs index 418bdd9b05..beb2ec3d90 100644 --- a/crates/render/src/layout/legend.rs +++ b/crates/render/src/layout/legend.rs @@ -1537,7 +1537,7 @@ fn title_pitch(size: f32, ppp: f32) -> f32 { /// The room in pixels a title of `lines` lines takes above a legend's rows: [`LEGEND_TITLE_ROWS`] /// rows for one, and a line's pitch more for each line past the first (#3129). -fn title_block(lines: usize, size: f32, ppp: f32) -> f32 { +pub(super) fn title_block(lines: usize, size: f32, ppp: f32) -> f32 { LEGEND_ROW * size * ppp * LEGEND_TITLE_ROWS + lines.saturating_sub(1) as f32 * title_pitch(size, ppp) } diff --git a/crates/render/src/layout/losses.rs b/crates/render/src/layout/losses.rs index 89d662fdeb..5c9c574cc3 100644 --- a/crates/render/src/layout/losses.rs +++ b/crates/render/src/layout/losses.rs @@ -282,7 +282,14 @@ pub(super) fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, o { let size = legend_size(*text_size); let row = LEGEND_ROW * size * ppp; - let cy = r.y() + if title.is_empty() { 0.0 } else { row * LEGEND_TITLE_ROWS } + row / 2.0; + // Under the title's lines as it is drawn, wrapped to its box (#3129). + let head = if title.is_empty() { + 0.0 + } else { + let lines = legend_title_lines(title, e.w, *text_size); + title_block(legend_title_drawn(lines.len(), r.height(), size, ppp), size, ppp) + }; + let cy = r.y() + head + row / 2.0; let ink = text::styled_bounds(subtitle, LEGEND_LABEL_PT * size * 1.33 * ppp, text::Face::default(), 0.0); off_page |= ink.is_some_and(|ink| { r.x() + ink.left() < 0.0 || r.x() + ink.right() > w as f32 || cy + ink.top() < 0.0 || cy + ink.bottom() > h as f32 diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 13ee9a36a7..8c0b153ba3 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -5123,6 +5123,51 @@ fn a_legends_title_lines_past_its_box_are_left_out_and_said() { let _ = titled(&Map::new("m"), &"x".repeat(200), (1.0, 1.0), (1, LegendFit::Manual), 9.0); } +/// A subtitle sits under the title's wrapped lines, so the check that it stays on the page measures +/// it there, not under a title of one line (#3129, #3324). +#[test] +fn a_legends_subtitle_is_checked_under_its_wrapped_title() { + let info = PageInfo::default(); + let (w, h) = (30.0, 60.0); + let head = legend_title_block_mm(LONG_LEGEND_TITLE, (w, h), 9.0); + let row = legend_head_mm("", "Wg", 9.0); + assert!(head > 2.0 * legend_title_mm(9.0), "the title wraps: {head}"); + let losses = |page_h: f64| { + let mut l = Layout::new("Page", 120.0, page_h); + let frame = l.add( + "Frame", + (0.0, 0.0, 5.0, 5.0), + serde_json::from_value(serde_json::json!({"MapFrame":{"map":"m", "center":{"x":0,"y":0}, "scale":1000000}})).unwrap(), + ); + let kind = ElementKind::Legend { + frame, + title: LONG_LEGEND_TITLE.into(), + all_classes: false, + hide_other: false, + show_no_data: false, + exclude: vec![], + columns: 1, + layer_order: Default::default(), + labels: BTreeMap::new(), + class_labels: Default::default(), + color: None, + text_size: rustgis_map::layout::LEGEND_TEXT_PT, + fit: LegendFit::Manual, + show_layer_names: rustgis_map::layout::LayerNames::Shown, + show_counts: Default::default(), + subtitle: "Wg".into(), + }; + l.add("Legend", (0.0, 0.0, w, h), kind); + text_losses(&l, &[Map::new("m")], 96.0, &info) + }; + // A page that ends at the middle of the subtitle's row, under the wrapped title: its text + // runs off the page, though it would end well inside it under a title of one line. + let off = losses(h.min(head + row / 2.0)); + assert!(off.iter().any(|loss| loss.off_page), "{off:?}"); + // A page with room for the row under the wrapped title: nothing is lost. + assert!(losses(head + 2.0 * row).iter().all(|loss| !loss.off_page)); +} + /// A box whose height is a title's two-line block to the pixel keeps the second line wherever it /// sits on the page: `Rect` stores edges, so a translated one's height is off by a rounding /// (#3129). From 3931f6ad513e984efb4ee3eb8233ad5e7210849b Mon Sep 17 00:00:00 2001 From: giswqs <5016453+giswqs@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:05:48 +0000 Subject: [PATCH 07/12] fix(layout): say when a legend title's lines leave its box A legend title wrapped to its box can have lines its box has no height for. Those lines were only reported by the export's cut-off check, so layout.addElement and layout.update set the title silently. say_text_fit now takes legends, so the lines left out are said when the legend is added or its title or subtitle is set. The same call also checks whether the title or subtitle runs off the page, which is new for legends at that point. Adds a regression test that the notice is said when the title doesn't fit and not said when it does. Also removes legend_title_extra_mm, which had no callers, and corrects the doc of legend_fitted_mm. Applied by the claude-autofix workflow. --- crates/engine/src/cmd/layout/text.rs | 5 +++-- crates/engine/src/cmd/layout/update.rs | 7 ++++++- crates/engine/src/tests.rs | 25 +++++++++++++++++++++++++ crates/render/src/layout/legend.rs | 10 +--------- 4 files changed, 35 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/layout/text.rs b/crates/engine/src/cmd/layout/text.rs index 180d88fe61..5e80396d1f 100644 --- a/crates/engine/src/cmd/layout/text.rs +++ b/crates/engine/src/cmd/layout/text.rs @@ -133,10 +133,11 @@ pub(in crate::cmd::layout) const ONLY_LAYOUT_TEXT_SIZE: &str = "only legends and /// layout view and an export count them: on the series' current page, measured at 300 dpi as a /// wrapped text is broken, and, a notice of its own, that its ink runs off the page (#2703). A /// `lines` of false (a move or a turn, which change no line) says only the edge. For a scale bar -/// `id`, whether its box is too short for its labels or one runs off the page (#2581). +/// `id`, whether its box is too short for its labels or one runs off the page (#2581). A legend's +/// title is said as a text's lines are, its wrapped lines that its box has no height for (#3129). pub(in crate::cmd::layout) fn say_text_fit(s: &mut Session, li: usize, id: u32, lines: bool) { let bar = match s.project.layouts.get(li).and_then(|l| l.element(id)).map(|e| &e.kind) { - Some(ElementKind::Text { .. }) => false, + Some(ElementKind::Text { .. } | ElementKind::Legend { .. }) => false, Some(ElementKind::ScaleBar { .. }) => true, _ => return, }; diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 72b30bf8b6..7191ac43b6 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -845,7 +845,12 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { } // After the scale box is refitted: a text is measured in the box it is saved with, and a text // or scale bar moved, whose ink can then run off the page, too. - if shown || TEXT_FIT_KEYS.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) || BAR_FIT_KEYS.iter().any(|k| p.get(*k).is_some()) { + // A legend's title or subtitle too: its lines may not fit the box they are wrapped to (#3129). + if shown + || TEXT_FIT_KEYS.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) + || BAR_FIT_KEYS.iter().any(|k| p.get(*k).is_some()) + || given(&["title", "subtitle"]) + { say_text_fit(s, li, id, true); } else if given(&["x", "y", "rotation", "valign"]) { // A move, a turn or a block alignment changes no line a text breaks into, but can take its diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ac51aba39c..95fad2facf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -13875,6 +13875,31 @@ fn a_legend_titled_past_its_box_says_the_rows_the_wrapped_title_takes() { assert_eq!(legend_said(&s, mark), Vec::::new()); } +/// A legend title whose wrapped lines its box has no height for says how many are left out, when +/// the legend is added and when its title is set; a title that fits its box says nothing (#3129). +#[test] +fn a_legend_title_whose_lines_leave_its_box_is_said() { + let said = |s: &Session, mark: u64| -> Vec { + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|n| n.contains("of the text")).collect() + }; + let mut s = world(); + s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "map"})).unwrap(); + // A box as tall as one line of title, so the lines a long title wraps to past its first are left out. + let h = crate::render::layout::legend_title_mm(9.0) + 0.5; + let long = "A very long legend title that is much wider than the legend itself"; + let mark = s.notice_mark(); + let added = json!({"kind": "legend", "allClasses": true, "columns": 1, "title": long, "x": 10, "y": 10, "w": 30.0, "h": h}); + let id = s.run("layout.addElement", &added).unwrap()["element"].clone(); + assert_eq!(said(&s, mark).len(), 1, "{:?}", said(&s, mark)); + assert!(said(&s, mark)[0].contains("drawn; make the box taller"), "{:?}", said(&s, mark)); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "title": "Key"})).unwrap(); + assert_eq!(said(&s, mark), Vec::::new()); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "title": long})).unwrap(); + assert_eq!(said(&s, mark).len(), 1, "{:?}", said(&s, mark)); +} + /// A manual legend that overflows its box says so as it always has; the same legend set to a fit /// that makes it fit says nothing, made a little smaller still nothing; given back manual, it says /// so again, word for word. diff --git a/crates/render/src/layout/legend.rs b/crates/render/src/layout/legend.rs index 6e58b68163..24f7a57766 100644 --- a/crates/render/src/layout/legend.rs +++ b/crates/render/src/layout/legend.rs @@ -1550,7 +1550,7 @@ fn measure_mm(m: Measured, columns: usize) -> (f64, f64) { /// The columns and text size the legend `asked` of `map` at the renderer's scale denominator /// `scale` is drawn at under its `fit` from its `columns`, in a room of `room_mm` (its box less its -/// title, as [`legend_title_mm`] gives it), and whether it is still wider or taller than that: the +/// wrapped title block, as [`legend_title_block_mm`] gives it), and whether it is still wider or taller than that: the /// drawing's own rule ([`fit_legend`]). `None` when a listed layer's complete source can't be read. pub fn legend_fitted_mm( map: &mut Map, @@ -1630,14 +1630,6 @@ pub fn legend_title_block_mm(title: &str, (w, h): (f64, f64), text_size: f64) -> legend_title_mm(text_size) + drawn.saturating_sub(1) as f64 * line_pitch_mm(f64::from(LEGEND_TITLE_PT * size)) } -/// The height in mm a title wraps to in a legend `w` mm wide above what [`legend_title_mm`] gives -/// it, whatever the height of the box: what a box sized for a title of one line is short by -/// (#3129). -pub fn legend_title_extra_mm(title: &str, w: f64, text_size: f64) -> f64 { - let lines = legend_title_lines(title, w, text_size).len().min(MAX_TEXT_LINES); - lines.saturating_sub(1) as f64 * line_pitch_mm(f64::from(LEGEND_TITLE_PT * legend_size(text_size))) -} - /// The height in mm [`legend`] gives what is above its rows, in a legend whose text is /// `text_size` points: its title's ([`legend_title_mm`]) and one row for a subtitle (#3324), each /// when it has one. From ad9168230e8245a767928236d7c71d92e50d5e5b Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:37:03 +0800 Subject: [PATCH 08/12] layout: the legend tests follow main's legend sizes (#3129) --- crates/engine/src/tests.rs | 1 + crates/render/src/layout/tests.rs | 2 ++ 2 files changed, 3 insertions(+) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 95fad2facf..5ff6792b05 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -13855,6 +13855,7 @@ fn a_legend_titled_past_its_box_says_the_rows_the_wrapped_title_takes() { labels: &labels, class_labels: &NO_CLASS_LABELS, show_counts: false, + sizes: Default::default(), }; let rows = legend_sizes(&mut s, frame, &asked)[0]; let title = crate::render::layout::legend_title_mm(9.0); diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 4481f472d7..cb331c0ee7 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -5124,6 +5124,7 @@ fn a_legends_title_lines_past_its_box_are_left_out_and_said() { fit: LegendFit::Manual, show_layer_names: rustgis_map::layout::LayerNames::Shown, show_counts: Default::default(), + sizes: Default::default(), subtitle: String::new(), }; let id = l.add("Legend", (10.0, 10.0, w, h), kind); @@ -5187,6 +5188,7 @@ fn a_legends_subtitle_is_checked_under_its_wrapped_title() { fit: LegendFit::Manual, show_layer_names: rustgis_map::layout::LayerNames::Shown, show_counts: Default::default(), + sizes: Default::default(), subtitle: "Wg".into(), }; l.add("Legend", (0.0, 0.0, w, h), kind); From 8747922dc43d428ee14dde7e9d241be77bbc4291 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:20:08 +0800 Subject: [PATCH 09/12] layout: a legend added with no title or subtitle says nothing of its title lines (#3129) --- crates/engine/src/cmd/layout/elements.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index d406d72f1b..d552bc59e4 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -804,7 +804,11 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu say_chart_losses(s, i, id); } say_table_cut(s, i, id); - say_text_fit(s, i, id, true); + // A legend's title lines its box has no height for are said when it is given a title or a + // subtitle (#3129), as `layout.update` does; a legend given neither says nothing, as before. + if kind != "legend" || ["title", "subtitle"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + say_text_fit(s, i, id, true); + } say_text_statistics(s, i, id); if let Some(said) = empty_colorbar { s.warn(said); From aa57db83501ff614cb7bfadb5ed946c7e998361b Mon Sep 17 00:00:00 2001 From: choupeanut Date: Tue, 1 Dec 2026 11:50:37 +0800 Subject: [PATCH 10/12] ci: rerun docs-preview (runner was shut down) From 5ac23d387040643208a08185aa1a85bbb952d9cf Mon Sep 17 00:00:00 2001 From: choupeanut Date: Tue, 1 Dec 2026 12:33:42 +0800 Subject: [PATCH 11/12] test: fill LegendAsked.column_breaks in the legend title test (#3129) --- crates/engine/src/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a3d6112e2d..edbea4c228 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -14187,6 +14187,7 @@ fn a_legend_titled_past_its_box_says_the_rows_the_wrapped_title_takes() { labels: &labels, class_labels: &NO_CLASS_LABELS, show_counts: false, + column_breaks: &[], sizes: Default::default(), }; let rows = legend_sizes(&mut s, frame, &asked)[0]; From 72ce7bcbd3ebc4b9b46e9ac09d7e78eaaa37cc64 Mon Sep 17 00:00:00 2001 From: choupeanut Date: Tue, 1 Dec 2026 13:14:20 +0800 Subject: [PATCH 12/12] test: fill column_breaks in the legend title layout tests (#3129) --- crates/render/src/layout/tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 33304dac0e..58d7e9f08e 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -5300,6 +5300,7 @@ fn a_legends_title_lines_past_its_box_are_left_out_and_said() { show_no_data: false, exclude: vec![], columns: 1, + column_breaks: Default::default(), layer_order: Default::default(), labels: BTreeMap::new(), class_labels: Default::default(), @@ -5364,6 +5365,7 @@ fn a_legends_subtitle_is_checked_under_its_wrapped_title() { show_no_data: false, exclude: vec![], columns: 1, + column_breaks: Default::default(), layer_order: Default::default(), labels: BTreeMap::new(), class_labels: Default::default(),