diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 2a230aa271..c9e08087c4 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -214,7 +214,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 northArrow's N and a scaleBar's labels; 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); profile: written over its curve ("" for none; default its layer's name), "##, + 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); profile: written over its curve ("" for none; default its layer's name), "##, r##""subtitle"?: text (legend: one line under its title, at the rows' text size, up to 200 characters; "" for none, the default; refused for other kinds), "##, r##""allClasses"?: bool (legend: every class, not only those the frame draws), "##, r##""hideOther"?: bool (legend: leave out ), "##, diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index 531fd6d317..f142766b83 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -853,7 +853,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); diff --git a/crates/engine/src/cmd/layout/legend.rs b/crates/engine/src/cmd/layout/legend.rs index 81d1a99d8e..c105a166a2 100644 --- a/crates/engine/src/cmd/layout/legend.rs +++ b/crates/engine/src/cmd/layout/legend.rs @@ -116,8 +116,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 { @@ -127,7 +128,9 @@ pub(in crate::cmd::layout) fn tells_legend_fit(kind: &ElementKind, p: &Value) -> *columns > 1 || !column_breaks.is_empty() || *text_size != rustgis_map::layout::LEGEND_TEXT_PT || fit.kept() != LegendFit::Manual; let refitted = ["w", "h", "title", "allClasses", "hideOther", "exclude", "layerOrder", "labels", "classLabels"].iter().any(|k| given(k)); - ["columns", "showNoData", "labels", "classLabels", "fit", "showLayerNames", "showCounts", "subtitle", "sizes"].iter().any(|k| given(k)) + ["columns", "showNoData", "labels", "classLabels", "fit", "showLayerNames", "showCounts", "title", "subtitle", "sizes"] + .iter() + .any(|k| given(k)) || p.get("textSize").is_some() || (watched && refitted) || given("columnBreaks") @@ -135,7 +138,7 @@ pub(in crate::cmd::layout) fn tells_legend_fit(kind: &ElementKind, p: &Value) -> /// 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 }; @@ -167,7 +170,10 @@ 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 - crate::render::layout::legend_head_mm(title, subtitle, *text_size)); + // The title wraps to the box (#3129), and a subtitle takes a row under it: the rows have what is left. + let head = crate::render::layout::legend_title_block_mm(title, (e.w, e.h), *text_size) + + crate::render::layout::legend_head_mm("", subtitle, *text_size); + let room = (e.w, e.h - head); 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, class_labels) = (fit.kept(), show_layer_names.shown(), class_labels.clone()); diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index 6d72deb26f..11663c7ea8 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -2030,10 +2030,16 @@ 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 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| { + 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 { warnings.push("the legend's title is wider than its box: shorten it".into()); diff --git a/crates/engine/src/cmd/layout/text.rs b/crates/engine/src/cmd/layout/text.rs index 70716bde3d..39f46b0e71 100644 --- a/crates/engine/src/cmd/layout/text.rs +++ b/crates/engine/src/cmd/layout/text.rs @@ -150,10 +150,11 @@ pub(in crate::cmd::layout) const ONLY_LAYOUT_TEXT_SIZE: &str = "only legends, sc /// 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 e8c9cfbebf..a08c10f220 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -993,7 +993,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 01f12864e8..edbea4c228 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -14166,6 +14166,74 @@ 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: &[], + layer_order: &[], + labels: &labels, + class_labels: &NO_CLASS_LABELS, + show_counts: false, + column_breaks: &[], + sizes: Default::default(), + }; + 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 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/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index f3da4378aa..dea8a62005 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -454,6 +454,37 @@ 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"]); +} + +/// 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); @@ -461,7 +492,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 2b5ac5c85f..7d1c66b70e 100644 --- a/crates/render/src/layout/colorbar.rs +++ b/crates/render/src/layout/colorbar.rs @@ -263,7 +263,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 } @@ -278,11 +283,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 3ee202bf93..dbbe022995 100644 --- a/crates/render/src/layout/legend.rs +++ b/crates/render/src/layout/legend.rs @@ -1213,9 +1213,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); } if !subtitle.is_empty() { // At the legend's own size, as the title is: a fit shrinks the rows alone. @@ -1590,7 +1597,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, @@ -1612,12 +1619,64 @@ 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 { + (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`] +/// rows for one, and a line's pitch more for each line past the first (#3129). +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) +} + +/// 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; + } + // 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() +} + +/// 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 [`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. diff --git a/crates/render/src/layout/losses.rs b/crates/render/src/layout/losses.rs index edd2a25c4a..b5ede0f391 100644 --- a/crates/render/src/layout/losses.rs +++ b/crates/render/src/layout/losses.rs @@ -184,21 +184,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), ) } @@ -256,8 +259,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 { @@ -301,7 +303,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 @@ -328,8 +337,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; @@ -338,12 +346,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 f57f2d8042..58d7e9f08e 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -964,7 +964,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(), @@ -987,8 +987,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 { @@ -4175,7 +4175,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 + // 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}"); @@ -5214,6 +5215,200 @@ 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, + column_breaks: Default::default(), + 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(), + sizes: Default::default(), + subtitle: String::new(), + }; + 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 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, + column_breaks: Default::default(), + 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(), + sizes: 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). +#[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] diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 9a40dc66ee..0fdb2d5b7c 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -518,13 +518,17 @@ 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"`, `"classLabels"`, `"fit"`, `"showLayerNames"`, `"showCounts"`, `"subtitle"` or `"sizes"`, and, - in columns, at a text size of its own or with a fit, when its box, the order of its layers 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 + `"textSize"` (`null` included), `"showNoData"`, `"labels"`, `"classLabels"`, `"fit"`, + `"showLayerNames"`, `"showCounts"`, `"title"`, `"subtitle"` or `"sizes"`, and, in columns, at a + text size of its own or with a fit, when its box, the order of its layers 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 @@ -725,14 +729,15 @@ 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. Exporting a report that draws a layout as a page says the same of that page's texts, in a notice for each such layout that names it. 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