From 74deb60e60c6f56259557a3fb68d29fc69882f94 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 07:56:35 -0300 Subject: [PATCH 01/22] Layouts: a publication layout in one command, a sheet or a figure sized to its page (#682, part 1) layout.publication builds a finished A4/A3/A2 sheet (frame, title, subtitle, the map at a round scale with a graticule, a footer of two boxed columns with a note and authorship, every text wrapped with the layout's font) or a journal or thesis figure (the map edge to edge, its texts left to the caption). The legend is sized to what it lists through legend_rows/legend_size_mm, shared with the drawing. Home > New Layout > Publication Layout lists the profiles. Co-Authored-By: Claude Opus 5.5 --- crates/assistant/skills/print-layout/SKILL.md | 6 +- crates/engine/src/cmd/layout.rs | 325 ++++++++++++++++++ crates/engine/src/tests.rs | 118 +++++++ crates/render/src/layout.rs | 136 ++++++-- crates/render/src/report.rs | 9 +- crates/ui-egui/src/ribbon.rs | 10 + docs/user-guide/layouts.md | 30 ++ 7 files changed, 597 insertions(+), 37 deletions(-) diff --git a/crates/assistant/skills/print-layout/SKILL.md b/crates/assistant/skills/print-layout/SKILL.md index c39d2059be..542fa6db8b 100644 --- a/crates/assistant/skills/print-layout/SKILL.md +++ b/crates/assistant/skills/print-layout/SKILL.md @@ -6,7 +6,11 @@ description: Make a printable page layout — map frame, title, legend, north ar # Print layout 1. Get the map right first: symbology, labels and extent. A layout's map frame shows the map's current view. -2. `layout.new` `{"name": N, "page": "letter"|"a4"|…, "orientation": "landscape"|"portrait"}` creates the layout and +2. For a finished sheet or a figure for a paper in one step, use `layout.publication` with a `"profile"` + (`"a4-portrait"`, `"a3-landscape"`, … for a sheet; `"figure-1col"`, `"thesis-full"`, … for a figure), the `"extent"` + to fit, and the texts: `"title"`, `"subtitle"`, `"sources"`, `"note"`. It places the frame at a round scale, the + graticule, legend, scale bar and north arrow, and wraps the footer, so skip to step 5 to adjust it. Otherwise, + `layout.new` `{"name": N, "page": "letter"|"a4"|…, "orientation": "landscape"|"portrait"}` creates the layout and opens it. 3. `layout.addFrame` for the map frame (`search_commands` "map frame" for its position and size parameters, in millimetres from the page's top-left). diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 6139417e59..720451d87d 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -28,6 +28,9 @@ pub fn commands() -> Vec { C::new("layout.new", "New Layout", "Home › Project", new_layout).params( r#"{"name"?: string, "page"?: "letter"|"legal"|"tabloid"|"a5"|"a4"|"a3"|"a2"|"a1"|"a0", "orientation"?: "landscape"|"portrait", "width"?: mm, "height"?: mm, "template"?: "map" (frame, title, legend, north arrow, scale bar; the default)|"blank"}"#, ), + C::new("layout.publication", "New Publication Layout", "Publish › Layout", publication).params( + r#"{"profile"?: "a4-portrait" (the default)|"a4-landscape"|"a3-portrait"|"a3-landscape"|"a2-portrait"|"a2-landscape" (a sheet: frame, title, subtitle, the map, a boxed footer)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"), "headings"?: [the sources' heading, the reference's heading]} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, + ), C::new("layout.activate", "Open Layout", "Browser", |s, p| { let i = index(s, &by_name(p))?; s.active_layout = Some(i); @@ -295,6 +298,328 @@ pub(crate) fn new_layout(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"layout": i, "name": name})) } +/// `layout.publication`'s profiles: an id, a label, a sheet (a frame, title and boxed footer) or a +/// figure (the map edge to edge, its title and sources left to the caption), and its size in mm. +/// A height of 0 follows the map's shape. +pub const PUBLICATION_PROFILES: &[(&str, &str, bool, f64, f64)] = &[ + ("a4-portrait", "A4 portrait sheet", true, 210.0, 297.0), + ("a4-landscape", "A4 landscape sheet", true, 297.0, 210.0), + ("a3-portrait", "A3 portrait sheet", true, 297.0, 420.0), + ("a3-landscape", "A3 landscape sheet", true, 420.0, 297.0), + ("a2-portrait", "A2 portrait sheet", true, 420.0, 594.0), + ("a2-landscape", "A2 landscape sheet", true, 594.0, 420.0), + ("figure-1col", "Journal figure, 1 column (90 mm)", false, 90.0, 0.0), + ("figure-1.5col", "Journal figure, 1.5 columns (140 mm)", false, 140.0, 0.0), + ("figure-2col", "Journal figure, 2 columns (190 mm)", false, 190.0, 0.0), + ("thesis-full", "Thesis figure, full page (160 × 225 mm)", false, 160.0, 225.0), + ("thesis-half", "Thesis figure, half page (160 × 110 mm)", false, 160.0, 110.0), +]; + +/// A figure's text size, in points at its printed size: journals ask for 6 to 8. +const FIGURE_PT: f64 = 7.0; + +/// The graticule steps a publication layout picks from, in degrees. +const GRID_STEPS: &[f64] = &[0.01, 0.02, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 15.0, 30.0]; + +/// The strips a frame's graticule labels take inside its edges, in mm: beside the left and right +/// edges (a latitude such as `10°S` across), and along the top and bottom ones. +const LABEL_ROOM_SIDE: f64 = 9.0; +const LABEL_ROOM_END: f64 = 6.0; + +/// The longest text a publication layout takes in one field, in characters. +const MAX_PUBLICATION_TEXT: usize = 2000; + +/// A scale denominator rounded up to two significant figures (1:1,234,567 to 1:1,300,000), so the +/// extent fitted at it still fits. +pub(crate) fn round_scale(scale: f64) -> f64 { + if !(scale.is_finite() && scale > 0.0) { + return scale; + } + let unit = 10f64.powf(scale.log10().floor() - 1.0); + ((scale / unit) - 1e-9).ceil() * unit +} + +/// The graticule step for an extent: the smallest that draws at most five lines across its longer +/// side. +pub(crate) fn grid_step(e: &Extent) -> f64 { + let span = e.width().max(e.height()); + GRID_STEPS.iter().copied().find(|step| span / step <= 5.0).unwrap_or(30.0) +} + +/// A graticule step as printed: degrees, else minutes, else seconds of arc. +pub(crate) fn step_text(step: f64) -> String { + let minutes = step * 60.0; + if step >= 1.0 { + format!("{step}°") + } else if (minutes - minutes.round()).abs() < 1e-9 { + format!("{}′", minutes.round()) + } else { + format!("{}″", (step * 3600.0).round()) + } +} + +/// The map's projection and datum for a layout's texts: an EPSG name's two halves (`SIRGAS 2000 / +/// UTM zone 23S`), else the projection's name over WGS 84, as the presets take longitudes and +/// latitudes. +fn projection_and_datum(s: &Session) -> (String, String) { + let label = s.map().projection.label(); + match label.split_once(" / ") { + Some((datum, projection)) => (projection.trim().to_string(), datum.trim().to_string()), + None => (label, "WGS 84".to_string()), + } +} + +/// Texts given as one or a list (up to 50), each cut to [`MAX_PUBLICATION_TEXT`] characters. +fn texts_of(p: &Value, k: &str) -> Result>, String> { + let cut = |t: &str| t.chars().take(MAX_PUBLICATION_TEXT).collect::(); + match p.get(k) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(t)) => Ok(Some(vec![cut(t)])), + Some(Value::Array(a)) if a.len() <= 50 => a + .iter() + .map(|v| v.as_str().map(cut).ok_or_else(|| format!("{k} is a text or a list of texts"))) + .collect::>() + .map(Some), + Some(_) => Err(format!("{k} is a text or a list of up to 50 texts")), + } +} + +/// The extent's height over its width on the active map's projection, along its edges. +fn aspect(s: &Session, e: &Extent) -> Option { + let flat = s.map().flat(); + let mut ext = Extent::EMPTY; + for i in 0..=32 { + let t = f64::from(i) / 32.0; + let (x, y) = (e.min_x + e.width() * t, e.min_y + e.height() * t); + for c in [Coord::new(x, e.min_y), Coord::new(x, e.max_y), Coord::new(e.min_x, y), Coord::new(e.max_x, y)] { + if let Some(q) = flat.forward_checked(c) { + ext.expand(q); + } + } + } + (ext.width() > 0.0 && ext.height() > 0.0).then(|| ext.height() / ext.width()) +} + +/// A text element in a publication layout's style: upright, sans, in `align`. +fn pub_text(text: String, size: f64, color: Rgba, bold: bool, align: TextAlign) -> ElementKind { + ElementKind::Text { text, size, color, bold, italic: false, align, letter_spacing: 0.0, font: FontFamily::Sans } +} + +/// A rectangle with no outline (`width` 0) or no fill (`fill` transparent). +fn pub_box(fill: Rgba, outline: Rgba, width: f64) -> ElementKind { + ElementKind::Rectangle { fill, outline, width } +} + +/// `layout.publication`: a finished sheet or figure of the active map, its extent fitted at a +/// round scale, with a graticule, legend, scale bar and north arrow; a sheet adds a frame, title, +/// subtitle and a footer of two boxed columns (sources, cartographic reference) with a note and +/// authorship under them, each text wrapped to its box with the layout's own font. +fn publication(s: &mut Session, p: &Value) -> CmdResult { + let id = ps(p, "profile").unwrap_or("a4-portrait").trim().to_ascii_lowercase(); + let &(_, _, sheet, page_w, page_h) = PUBLICATION_PROFILES.iter().find(|(n, ..)| *n == id).ok_or_else(|| { + let names: Vec<&str> = PUBLICATION_PROFILES.iter().map(|(n, ..)| *n).collect(); + format!("unknown profile '{id}': {}", names.join(", ")) + })?; + let extent = match p.get("extent").filter(|v| !v.is_null()) { + None => { + let e = super::workspace::view_extent(s); + Extent::new(e.min_x.max(-180.0), e.min_y.max(-90.0), e.max_x.min(180.0), e.max_y.min(90.0)) + } + Some(v) => { + let b: Option> = + v.as_array().filter(|a| a.len() == 4).and_then(|a| a.iter().map(|x| x.as_f64().filter(|x| x.is_finite())).collect()); + match b.as_deref() { + Some([w, so, e, n]) if w < e && so < n && *w >= -180.0 && *e <= 180.0 && *so >= -90.0 && *n <= 90.0 => { + Extent::new(*w, *so, *e, *n) + } + _ => return Err("extent is [west, south, east, north] in degrees".into()), + } + } + }; + if !(extent.width() > 0.0 && extent.height() > 0.0) { + return Err("the map's extent isn't known; give extent".into()); + } + let one = |k: &str| texts_of(p, k).map(|t| t.map(|t| t.join(" ")).filter(|t| !t.trim().is_empty())); + let (title, subtitle, note) = (one("title")?, one("subtitle")?, one("note")?); + let sources = texts_of(p, "sources")?.unwrap_or_default(); + let reference = + texts_of(p, "reference")?.unwrap_or_else(|| vec!["Projection: {projection}".into(), "Datum: {datum} · Graticule: {grid}".into()]); + let author = one("author")?.unwrap_or_else(|| "Made with RustGIS · {date}".into()); + let headings = texts_of(p, "headings")?.unwrap_or_default(); + let heading = |i: usize, or: &str| headings.get(i).cloned().unwrap_or_else(|| or.to_string()); + let (projection, datum) = projection_and_datum(s); + let step = grid_step(&extent); + let fill = |t: &str| t.replace("{projection}", &projection).replace("{datum}", &datum).replace("{grid}", &step_text(step)); + let wrap = |t: &str, w: f64, pt: f64| crate::render::report::wrap(&fill(t), w.max(1.0), pt as f32); + let pitch = crate::render::layout::line_pitch_mm; + let ink = Rgba::rgb(0x2B, 0x26, 0x20); + let soft = Rgba::rgb(0x5E, 0x55, 0x47); + let clear = Rgba::new(0, 0, 0, 0); + let mut warnings: Vec = Vec::new(); + // Texts and boxes around the map, placed while its frame is worked out. + let mut around: Vec<(String, (f64, f64, f64, f64), ElementKind)> = Vec::new(); + // A sheet's sizes follow its short side (A4's 210 mm is 1); a figure keeps its texts at their + // printed size, whatever its width. + let k = if sheet { page_w.min(page_h) / 210.0 } else { 1.0 }; + let (w, h, (fx, fy, fw, fh)) = if sheet { + let (m, pad) = (10.0 * k, 5.0 * k); + let (x0, iw) = (m + pad, page_w - 2.0 * (m + pad)); + let (title_pt, sub_pt, head_pt, body_pt, small_pt) = (18.0 * k, 10.5 * k, 7.5 * k, 7.0 * k, 6.5 * k); + around.push(("Frame".into(), (m, m, page_w - 2.0 * m, page_h - 2.0 * m), pub_box(clear, ink, 0.8))); + let mut top = m + pad; + if let Some(t) = &title { + let th = pitch(title_pt) + 1.5 * k; + around.push(("Title".into(), (x0, top, iw, th), pub_text(fill(t), title_pt, ink, true, TextAlign::Center))); + top += th; + } + if let Some(t) = &subtitle { + let lines = wrap(t, iw, sub_pt); + let sh = lines.len() as f64 * pitch(sub_pt) + 1.0 * k; + around.push(("Subtitle".into(), (x0, top, iw, sh), pub_text(lines.join("\n"), sub_pt, soft, false, TextAlign::Center))); + top += sh; + } + // The footer, from the bottom up: authorship, the note, then the two boxes side by side, + // as tall as the longer column. + let bottom = page_h - m - pad; + let author_y = bottom - pitch(small_pt); + around.push(( + "Author".into(), + (x0, author_y, iw, pitch(small_pt)), + pub_text(fill(&author), small_pt, soft, false, TextAlign::Right), + )); + let note_lines = note.as_deref().map(|t| wrap(t, iw, body_pt)).unwrap_or_default(); + let mut foot = author_y; + if !note_lines.is_empty() { + let nh = note_lines.len() as f64 * pitch(body_pt); + foot -= nh + 1.5 * k; + around.push(("Note".into(), (x0, foot, iw, nh), pub_text(note_lines.join("\n"), body_pt, soft, false, TextAlign::Left))); + } + let (gap, inner) = (4.0 * k, 2.5 * k); + let cw = (iw - gap) / 2.0; + let column = |lines: &[String]| lines.iter().flat_map(|t| wrap(t, cw - 2.0 * inner, body_pt)).collect::>(); + let columns = [(heading(0, "Sources"), column(&sources)), (heading(1, "Cartographic reference"), column(&reference))]; + let rows = columns.iter().map(|(_, l)| l.len()).max().unwrap_or(0); + if rows > 0 { + let bh = 2.0 * inner + pitch(head_pt) + rows as f64 * pitch(body_pt); + foot -= bh + 2.0 * k; + for (i, (head, lines)) in columns.into_iter().enumerate() { + let bx = x0 + i as f64 * (cw + gap); + around.push((format!("{head} Box"), (bx, foot, cw, bh), pub_box(clear, Rgba::new(0x2B, 0x26, 0x20, 140), 0.5))); + let (tx, tw) = (bx + inner, cw - 2.0 * inner); + around.push(( + format!("{head} Heading"), + (tx, foot + inner, tw, pitch(head_pt)), + pub_text(head.to_uppercase(), head_pt, ink, true, TextAlign::Left), + )); + if !lines.is_empty() { + let body = (tx, foot + inner + pitch(head_pt), tw, lines.len() as f64 * pitch(body_pt)); + around.push((head, body, pub_text(lines.join("\n"), body_pt, soft, false, TextAlign::Left))); + } + } + } + let (frame_top, frame_bottom) = (top + 3.0 * k, foot - 4.0 * k); + if frame_bottom - frame_top < 40.0 * k { + return Err("the texts leave the map no room: shorten the footer, the note or the subtitle".into()); + } + (page_w, page_h, (x0, frame_top, iw, frame_bottom - frame_top)) + } else { + // A figure: the map edge to edge, a line of the projection and datum under it. + for (k, given) in + [("title", title.is_some()), ("subtitle", subtitle.is_some()), ("sources", !sources.is_empty()), ("note", note.is_some())] + { + if given { + warnings.push(format!("{k} goes in the figure's caption, not on it: left out")); + } + } + let line = reference.iter().map(|t| fill(t)).collect::>().join(" · "); + let lines = crate::render::report::wrap(&line, page_w, FIGURE_PT as f32); + if lines.len() > 1 { + warnings.push("the reference is wider than the figure: it wraps under the map".into()); + } + let note_h = lines.len() as f64 * pitch(FIGURE_PT) + 1.0; + let fh = if page_h > 0.0 { + page_h - note_h + } else { + (page_w * aspect(s, &extent).unwrap_or(0.75)).clamp(0.45 * page_w, 1.3 * page_w).round() + }; + let h = if page_h > 0.0 { page_h } else { (fh + note_h).ceil() }; + around.push(( + "Reference".into(), + (0.0, fh + 1.0, page_w, note_h - 1.0), + pub_text(lines.join("\n"), FIGURE_PT, ink, false, TextAlign::Left), + )); + (page_w, h, (0.0, 0.0, page_w, fh)) + }; + let (center, scale) = fit_scale(s.map(), &extent, fw, fh).ok_or("the extent can't be drawn on the map's projection")?; + let scale = round_scale(scale); + let edges = GridEdges { top: sheet, bottom: true, left: true, right: sheet }; + let grid = Grid { step, edges, ..Grid::default() }; + let name = unique_name(s, ps(p, "name").unwrap_or("Publication")); + let mut l = Layout::new(name.clone(), w, h); + let frame = l.add( + "Map Frame", + (fx, fy, fw, fh), + ElementKind::MapFrame { + map: s.map().name.clone(), + center, + scale, + shape: FrameShape::Rectangle, + grid: Some(grid), + extent_of: None, + extent_color: rustgis_map::layout::INDICATOR_COLOR, + extent_width: rustgis_map::layout::INDICATOR_WIDTH, + bearing: 0.0, + pitch: 0.0, + }, + ); + // Over the map, in its corners, clear of the graticule's labels (drawn inside the frame along + // its labelled edges): the north arrow at the top right, the legend at the bottom left sized + // to what it lists, the scale bar and the numeric scale under it at the bottom right, each on + // a pale box. + let paper = Rgba::new(0xFF, 0xFF, 0xFF, 225); + let (e, small_pt) = if sheet { (4.0 * k, 6.5 * k) } else { (2.0, 6.0) }; + let room = |labelled: bool, side: bool| { + e + if !labelled { + 0.0 + } else if side { + LABEL_ROOM_SIDE + } else { + LABEL_ROOM_END + } + }; + let (left, right, top, bottom) = (room(edges.left, true), room(edges.right, true), room(edges.top, false), room(edges.bottom, false)); + let (aw, ah) = if sheet { (8.0 * k, 12.0 * k) } else { (5.0, 7.5) }; + l.add("North Arrow", (fx + fw - right - aw, fy + top, aw, ah), ElementKind::north_arrow(frame)); + let render_scale = crate::render::layout::frame_render_scale(s.map(), center, scale); + let (cw, ch) = crate::render::layout::legend_size_mm(s.map(), render_scale, false, false, &[]); + if ch > 0.0 { + let pad = 2.0; + let (lw, lh) = ((cw + 2.0 * pad).min(fw * 0.45), (ch + 2.0 * pad).min(fh * 0.6)); + if cw + 2.0 * pad > lw || ch + 2.0 * pad > lh { + warnings.push("the legend lists more than fits its corner: its last rows or the ends of long labels are left out".into()); + } + let (lx, ly) = (fx + left, fy + fh - bottom - lh); + l.add("Legend Box", (lx, ly, lw, lh), pub_box(paper, clear, 0.0)); + l.add( + "Legend", + (lx + pad, ly + pad, lw - 2.0 * pad, lh - 2.0 * pad), + ElementKind::Legend { frame, title: String::new(), all_classes: false, hide_other: false, exclude: Vec::new() }, + ); + } + let (sw, sh, nh) = ((fw * 0.3).max(25.0), if sheet { 8.0 * k } else { 6.0 }, pitch(small_pt) + 0.5); + let (sx, sy) = (fx + fw - right - sw, fy + fh - bottom - sh - nh); + l.add("Scale Box", (sx, sy, sw, sh + nh), pub_box(paper, clear, 0.0)); + l.add("Scale Bar", (sx, sy, sw, sh), ElementKind::scale_bar(frame)); + l.add("Scale", (sx, sy + sh, sw, nh), pub_text("{scale}".into(), small_pt, ink, false, TextAlign::Center)); + for (n, r, kind) in around { + l.add(&n, r, kind); + } + s.project.layouts.push(l); + let i = s.project.layouts.len() - 1; + s.active_layout = Some(i); + Ok(json!({"layout": i, "name": name, "page": [w, h], "scale": scale, "grid": step, "warnings": warnings})) +} + fn page(s: &mut Session, p: &Value) -> CmdResult { let i = index(s, p)?; let cur = s.project.layouts.get(i).map(|l| (l.width, l.height)); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index aa868f808d..7617be7105 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2260,6 +2260,124 @@ fn layout_colorbars_follow_a_raster() { assert_eq!(s.project.layouts[0].element(id).map(|e| e.visible), Some(true), "undo brings it back"); } +/// `layout.publication` (#682): every profile builds a layout that fits its page, the map frame +/// at a round scale that still fits the extent, the footer boxed in two columns below the map +/// with long lines wrapped, the tokens filled from the map; a figure leaves its title to the +/// caption. +#[test] +fn publication_layouts_fit_their_pages() { + use rustgis_map::layout::ElementKind; + let dir = std::env::temp_dir().join(format!("rustgis-publication-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = world(); + let piaui = json!([-46.8, -11.6, -38.5, -2.2]); + let long = + "NDVI: MOD13Q1 v6.1 (NASA LP DAAC), 16-day composites at 250 m, read through the Brazil Data Cube (INPE) and averaged to 1 km"; + let profiles = [ + "a4-portrait", + "a4-landscape", + "a3-portrait", + "a3-landscape", + "a2-portrait", + "a2-landscape", + "figure-1col", + "figure-1.5col", + "figure-2col", + "thesis-full", + "thesis-half", + ]; + for profile in profiles { + let r = s + .run( + "layout.publication", + &json!({"profile": profile, "extent": piaui, "name": profile, "title": "PIAUÍ", "subtitle": "Greening and browning of vegetation: NDVI trend, 2001–2025", + "sources": [long, "Boundaries: IBGE 2022"], "note": "Only cells with a significant trend (p < 0.05) are coloured."}), + ) + .unwrap_or_else(|e| panic!("{profile}: {e}")); + let l = s.project.layouts.last().unwrap(); + assert_eq!(r["name"], profile); + let sheet = profile.starts_with('a'); + for e in &l.elements { + assert!( + e.x >= -1e-9 && e.y >= -1e-9 && e.x + e.w <= l.width + 1e-6 && e.y + e.h <= l.height + 1e-6, + "{profile}: {} at ({}, {}, {}, {}) is off the {} × {} page", + e.name, + e.x, + e.y, + e.w, + e.h, + l.width, + l.height + ); + } + let frame = l.elements.iter().find(|e| e.kind.code() == "mapFrame").unwrap(); + let ElementKind::MapFrame { scale, grid: Some(grid), .. } = &frame.kind else { panic!("{profile}: no grid") }; + // A round scale, two significant figures, at which the extent still fits. + let unit = 10f64.powf(scale.log10().floor() - 1.0); + assert!(((scale / unit) - (scale / unit).round()).abs() < 1e-6, "{profile}: 1:{scale}"); + let extent = rustgis_geom::Extent::new(-46.8, -11.6, -38.5, -2.2); + let (_, fits) = rustgis_map::layout::fit_scale(s.map(), &extent, frame.w, frame.h).unwrap(); + assert!(fits <= *scale && *scale < fits * 1.1, "{profile}: 1:{scale} for 1:{fits}"); + assert_eq!(grid.step, 2.0, "{profile}: Piauí's 9.4° take a 2° graticule"); + let text = |name: &str| { + l.elements.iter().find(|e| e.name == name).map(|e| match &e.kind { + ElementKind::Text { text, .. } => text.clone(), + _ => panic!("{name} isn't text"), + }) + }; + if sheet { + assert_eq!(text("Title").as_deref(), Some("PIAUÍ"), "{profile}"); + // The footer under the map, the long source wrapped within its box. + let foot = l.elements.iter().find(|e| e.name == "Sources Box").unwrap(); + assert!(foot.y >= frame.y + frame.h, "{profile}: the footer is under the map"); + let sources = l.elements.iter().find(|e| e.name == "Sources").unwrap(); + assert!(sources.x + sources.w <= foot.x + foot.w + 1e-6); + let lines = text("Sources").unwrap(); + assert!(lines.lines().count() >= 3, "{profile}: {lines}"); + for line in lines.lines() { + assert!( + crate::render::report::width_mm(line, 7.0 * l.width.min(l.height) as f32 / 210.0, false) <= sources.w + 1e-6, + "{profile}: {line}" + ); + } + // The tokens filled from the map: Web Mercator over WGS 84, the 2° graticule. + let reference = text("Cartographic reference").unwrap(); + assert!(reference.contains("Web Mercator") && reference.contains("WGS 84") && reference.contains("2°"), "{reference}"); + assert!(text("Author").unwrap().contains("{date}"), "the date stays a token the layout fills"); + assert!(r["warnings"].as_array().unwrap().is_empty(), "{profile}: {r}"); + } else { + assert!(text("Title").is_none() && text("Sources").is_none(), "{profile}: a figure's texts are its caption's"); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("caption")), "{r}"); + assert!(text("Reference").unwrap().contains("Datum: WGS 84"), "{profile}"); + assert_eq!(l.width, r["page"][0].as_f64().unwrap()); + } + let png = dir.join(format!("{profile}.png")); + s.run("layout.export", &json!({"path": png.display().to_string(), "dpi": 72})).unwrap(); + assert!(std::fs::metadata(&png).unwrap().len() > 1000, "{profile}"); + } + assert_eq!(s.project.layouts.len(), profiles.len(), "a layout each, the earlier ones untouched"); + // A journal figure is as tall as the map's shape asks: Piauí in Web Mercator is taller than wide. + let one = s.project.layouts.iter().find(|l| l.name == "figure-1col").unwrap(); + assert!(one.width == 90.0 && one.height > 90.0, "{} × {}", one.width, one.height); + // Graticule steps and round scales. + use crate::cmd::layout::{grid_step, round_scale, step_text}; + assert_eq!(grid_step(&rustgis_geom::Extent::new(10.0, 45.0, 11.0, 46.0)), 0.25); + assert_eq!(grid_step(&rustgis_geom::Extent::new(-180.0, -90.0, 180.0, 90.0)), 30.0); + assert_eq!((step_text(2.0), step_text(0.25), step_text(0.02)), ("2°".to_string(), "15′".to_string(), "72″".to_string())); + assert_eq!((round_scale(1_234_567.0), round_scale(4_500_000.0), round_scale(999.0)), (1_300_000.0, 4_500_000.0, 1_000.0)); + // Refused: an unknown profile, a malformed extent, a footer that leaves the map no room. + for (p, said) in [ + (json!({"profile": "a5-portrait"}), "unknown profile"), + (json!({"extent": [10, 0, 5, 1]}), "extent is"), + (json!({"extent": [10, 0, 11], "profile": "a4-portrait"}), "extent is"), + (json!({"sources": vec![long; 40], "profile": "a4-landscape", "extent": piaui}), "no room"), + ] { + let e = s.run("layout.publication", &p).unwrap_err(); + assert!(e.contains(said), "{p}: {e}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn layouts_compose_export_and_round_trip() { use base64::Engine; diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index d1ce6b3eb8..d516dfc583 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -757,25 +757,26 @@ struct LegendOptions<'a> { exclude: &'a [String], } -/// The legend of a frame's map. With `drawn` (from [`shown_legends`]) it shows what the frame -/// draws: only the layers listed there, with their classes. Without, every class of every visible -/// layer. `opts` leaves out `` and the layers it names, either way. -fn legend(pm: &mut Pixmap, r: Rect, map: &Map, title: &str, drawn: Option<&[(u32, Vec)]>, opts: LegendOptions, ppp: f64) { - let hide_other = opts.hide_other; +/// A row of a legend: a layer drawn in one symbol (its swatch and name), a layer's name over its +/// classes, or one of them. +enum LegendRow<'a> { + Plain(&'a rustgis_map::Layer), + Head(&'a str), + Class(GeometryType, LegendEntry), +} + +/// A legend row's height, in points. +const LEGEND_ROW: f32 = 15.0; +/// A legend swatch's width, in points. +const LEGEND_SWATCH: f32 = 16.0; + +/// The rows of the legend of a frame's map. With `drawn` (from [`shown_legends`]) it shows what the +/// frame draws: only the layers listed there, with their classes. Without, every class of every +/// visible layer. `opts` leaves out `` and the layers it names, either way. +fn legend_rows<'a>(map: &'a Map, drawn: Option<&[(u32, Vec)]>, opts: &LegendOptions) -> Vec> { let excluded = |name: &str| opts.exclude.iter().any(|n| n.eq_ignore_ascii_case(name)); - let ppp = ppp as f32; - let dark = Rgba::rgb(0x22, 0x22, 0x22); - let mut y = r.y(); - let line = 15.0 * ppp; - if !title.is_empty() { - text::text_at(pm, title, r.x(), y + line / 2.0, 12.0 * 1.33 * ppp, dark, true, text::Align::Left, false); - y += line * 1.3; - } - let sw = 16.0 * ppp; + let mut rows = Vec::new(); for l in map.layers.iter().filter(|l| map.shows(l) && !l.graphics && !l.is_raster() && !excluded(&l.name)) { - if y + line > r.y() + r.height() { - break; - } let mut entries = match drawn { Some(d) => match d.iter().find(|(id, _)| *id == l.id) { Some((_, entries)) => entries.clone(), @@ -784,37 +785,94 @@ fn legend(pm: &mut Pixmap, r: Rect, map: &Map, title: &str, drawn: Option<&[(u32 None => l.renderer.legend(), }; // The fallback row only (a class that happens to bear its name stays). - if hide_other && entries.iter().any(|e| e.fallback) { + if opts.hide_other && entries.iter().any(|e| e.fallback) { entries.retain(|e| !e.fallback); // Nothing left to show for this layer: leave it out rather than draw its plain swatch. if entries.is_empty() { continue; } } - let gt = l.geometry_type(); if entries.is_empty() { // A Unique Values layer that lists nothing draws nothing visible (#207). - if matches!(l.renderer, rustgis_map::Renderer::Unique { .. }) { - continue; + if !matches!(l.renderer, rustgis_map::Renderer::Unique { .. }) { + rows.push(LegendRow::Plain(l)); } - swatch(pm, r.x(), y, sw, line, gt, &l.renderer.symbol_for(&l.dataset, 0), ppp); - text::text_at(pm, &l.name, r.x() + sw + 6.0 * ppp, y + line / 2.0, 9.0 * 1.33 * ppp, dark, false, text::Align::Left, false); - y += line; continue; } - text::text_at(pm, &l.name, r.x(), y + line / 2.0, 9.0 * 1.33 * ppp, dark, true, text::Align::Left, false); - y += line; - for en in entries { - if y + line > r.y() + r.height() { - break; + rows.push(LegendRow::Head(&l.name)); + let gt = l.geometry_type(); + rows.extend(entries.into_iter().map(|en| LegendRow::Class(gt, en))); + } + rows +} + +/// The legend of a frame's map: its rows ([`legend_rows`]) from the top, as many as fit. +fn legend(pm: &mut Pixmap, r: Rect, map: &Map, title: &str, drawn: Option<&[(u32, Vec)]>, opts: LegendOptions, ppp: f64) { + let ppp = ppp as f32; + let dark = Rgba::rgb(0x22, 0x22, 0x22); + let mut y = r.y(); + let line = LEGEND_ROW * ppp; + if !title.is_empty() { + text::text_at(pm, title, r.x(), y + line / 2.0, 12.0 * 1.33 * ppp, dark, true, text::Align::Left, false); + y += line * 1.3; + } + let sw = LEGEND_SWATCH * ppp; + for row in legend_rows(map, drawn, &opts) { + if y + line > r.y() + r.height() { + break; + } + match row { + LegendRow::Plain(l) => { + swatch(pm, r.x(), y, sw, line, l.geometry_type(), &l.renderer.symbol_for(&l.dataset, 0), ppp); + text::text_at(pm, &l.name, r.x() + sw + 6.0 * ppp, y + line / 2.0, 9.0 * 1.33 * ppp, dark, false, text::Align::Left, false); + } + LegendRow::Head(name) => { + text::text_at(pm, name, r.x(), y + line / 2.0, 9.0 * 1.33 * ppp, dark, true, text::Align::Left, false); + } + LegendRow::Class(gt, en) => { + swatch(pm, r.x() + 6.0 * ppp, y, sw, line, gt, &en.symbol, ppp); + text::text_at( + pm, + &en.label, + r.x() + sw + 12.0 * ppp, + y + line / 2.0, + 8.5 * 1.33 * ppp, + dark, + false, + text::Align::Left, + false, + ); } - swatch(pm, r.x() + 6.0 * ppp, y, sw, line, gt, &en.symbol, ppp); - text::text_at(pm, &en.label, r.x() + sw + 12.0 * ppp, y + line / 2.0, 8.5 * 1.33 * ppp, dark, false, text::Align::Left, false); - y += line; } + y += line; } } +/// The size a legend with no title takes, in mm (width, height): its rows as [`legend`] draws +/// them, the classes a frame shows at the renderer's scale denominator `scale` (as the layout +/// finds it for a frame), or every class with `all_classes`. For sizing a legend to its content. +pub fn legend_size_mm(map: &Map, scale: f64, all_classes: bool, hide_other: bool, exclude: &[String]) -> (f64, f64) { + let drawn = (!all_classes).then(|| shown_legends(map, scale)); + let rows = legend_rows(map, drawn.as_deref(), &LegendOptions { hide_other, exclude }); + let width = rows + .iter() + .map(|row| match row { + LegendRow::Plain(l) => LEGEND_SWATCH + 6.0 + text::measure(&l.name, 9.0, false), + LegendRow::Head(name) => text::measure(name, 9.0, true), + LegendRow::Class(_, en) => LEGEND_SWATCH + 12.0 + text::measure(&en.label, 8.5, false), + }) + .fold(0.0f32, f32::max); + let mm = 25.4 / 96.0; + (f64::from(width) * mm, rows.len() as f64 * f64::from(LEGEND_ROW) * mm) +} + +/// The renderer's scale denominator for a frame showing `map` at paper scale 1:`scale` (the one +/// [`legend_size_mm`] takes). +pub fn frame_render_scale(map: &Map, center: Coord, scale: f64) -> f64 { + let cam = frame_camera(map, center, scale, 0.0, 0.0); + map.ground_res_at(&cam) / rustgis_geom::PIXEL_M +} + fn swatch(pm: &mut Pixmap, x: f32, y: f32, w: f32, h: f32, gt: GeometryType, s: &rustgis_map::Symbol, ppp: f32) { let cy = y + h / 2.0; match gt { @@ -1022,6 +1080,11 @@ struct TextStyle { spacing: f32, } +/// The distance between two lines of text at `size` points, in mm, as [`text_block`] sets them. +pub fn line_pitch_mm(size: f64) -> f64 { + size.clamp(2.0, 400.0) * 1.33 * 1.25 * 25.4 / 96.0 +} + /// Text in an element: lines split at `\n` from the top, each placed by the style's alignment. A /// centred or right-aligned line wider than the element runs out past its left edge, as a /// left-aligned one runs past its right. @@ -1205,6 +1268,15 @@ mod tests { // the font and antialiasing don't matter. assert!(shown > 0, "the drawn class is listed"); assert!(all >= 2 * shown, "{shown} px of {all}"); + // The size a legend takes holds what it draws, to within a row: two rows drawn, six with + // every class. + let row = f64::from(LEGEND_ROW) * 25.4 / 96.0; + for (all_classes, ink) in [(false, shown), (true, all)] { + let (w, h) = legend_size_mm(&map, 1e6, all_classes, false, &[]); + let ink = f64::from(ink) * 25.4 / 96.0; + assert!(w > 0.0 && ink <= h && h - ink < row, "{ink} mm drawn in {h} mm"); + } + assert!((legend_size_mm(&map, 1e6, false, false, &[]).1 - 2.0 * row).abs() < 1e-9); // A layer the legend leaves out (by name, any case) isn't listed, drawn or not. let name = map.layer(pts).unwrap().name.to_uppercase(); assert_eq!(depth_without(&map, Some(&drawn), false, std::slice::from_ref(&name)), 0, "its only drawn layer left out"); diff --git a/crates/render/src/report.rs b/crates/render/src/report.rs index 6440632566..86bf10c411 100644 --- a/crates/render/src/report.rs +++ b/crates/render/src/report.rs @@ -47,8 +47,8 @@ pub struct Placed { pub lines: Vec, } -/// Text width in millimetres. -fn width_mm(s: &str, pt: f32, bold: bool) -> f64 { +/// Text width in millimetres at `pt` points, as layouts and reports draw it. +pub fn width_mm(s: &str, pt: f32, bold: bool) -> f64 { text::measure(s, pt, bold) as f64 * 25.4 / 96.0 } @@ -66,8 +66,9 @@ fn style(b: &Block) -> (f32, bool, f64) { } } -/// Splits text into lines no wider than `w` millimetres. -fn wrap(s: &str, w: f64, pt: f32) -> Vec { +/// Splits text into lines no wider than `w` millimetres at `pt` points: whole words, a word wider +/// than the line broken across lines. +pub fn wrap(s: &str, w: f64, pt: f32) -> Vec { let mut out = Vec::new(); for para in s.lines().take(2000) { let mut line = String::new(); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 27aefa1806..fb767ec703 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -941,6 +941,16 @@ fn project_group(app: &mut RustGisApp, ui: &mut Ui) { ui.close(); } } + // A finished sheet or figure of the map view, its texts to fill in on the page. + ui.menu_button(tl!("Publication Layout"), |ui| { + for (id, label, ..) in rustgis_engine::cmd::layout::PUBLICATION_PROFILES { + if ui.button(tl!(*label)).clicked() { + let _ = app.run("layout.publication", json!({"profile": id, "title": app.session.map().name.clone()})); + app.ui.tab = "Publish".into(); + ui.close(); + } + } + }); ui.separator(); if ui.button(tl!("Blank Letter page")).clicked() { let _ = app.run("layout.new", json!({"template": "blank"})); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index c75c5e44bc..c0c22d7205 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -11,6 +11,36 @@ Home › New Layout adds a page layout (Letter to A0, landscape or portrait) wit title, legend, north arrow, scale bar and a dynamic credits line. Layouts open as tabs next to the maps; while one is open, its groups lead the Publish tab: +- **Publication layouts**: Home › New Layout › **Publication Layout** builds a finished sheet or + figure of the map view in one step, with `layout.publication` behind it: + - **Sheets** (A4, A3 or A2, portrait or landscape): a frame and margin, the title and subtitle, + the map, and a footer of two boxed columns (sources, and the cartographic reference) with a + note and the authorship under them. Text sizes follow the sheet: an A3's are 1.41 times an + A4's. + - **Figures** for a journal (90, 140 or 190 mm wide, as tall as the map's shape asks) or a + thesis (160 × 225 or 160 × 110 mm): the map edge to edge with a line of its projection and + datum under it, at 7 pt. A figure's title and sources belong in its caption, so they are + left out, and the result says so. + - **The map**: the `extent` given (or the view) fitted at a round scale, two significant + figures, rounded up so it still fits. A graticule has its step picked from the extent, at + most five lines across (2° for a state, 15′ for a city), and labels on every edge of a sheet. + The north arrow, the legend (sized to what it lists) and the scale bar with the numeric scale + under it sit in the frame's corners, on pale boxes, clear of the graticule's labels. + - **Texts**: the footer's lines are measured with the layout's font and wrapped to their box, + so none runs past it, and the footer grows to hold them. `{projection}`, `{datum}` and + `{grid}` are filled from the map when the layout is made. `{date}` and the other dynamic text + tokens stay live. The reference defaults to the projection, datum and graticule, and the + authorship to "Made with RustGIS · {date}". `headings` renames the two columns. + - Every element is an ordinary one, to move or restyle afterwards. Running it again with + another `profile` makes another layout of the same map. + + ``` + layout.publication={"profile": "a4-portrait", "extent": [-46.8, -11.6, -38.5, -2.2], + "title": "PIAUÍ", "subtitle": "Greening and browning of vegetation: NDVI trend, 2001–2025", + "sources": ["NDVI: MOD13Q1 v6.1 (NASA LP DAAC), via the Brazil Data Cube (INPE)", "Boundaries: IBGE 2022"], + "note": "Only cells with a significant trend (p < 0.05) are coloured."} + ``` + - **Map frames**: rectangle, circle and ellipse frames, or polygon and lasso frames drawn on the page. Each frame shows a map of the project at its own centre and scale. Turn on **Pan/Zoom Map** (Map Frames group, or a frame's properties) to drag inside frames to pan their maps and From 932dc63e7d3521edb8159355a19e2a462e1b15e8 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 08:42:19 -0300 Subject: [PATCH 02/22] layout.publication: the title and authorship wrap, a figure's reference can't crowd out the map, the legend is sized after syncing the frame's view, the result lists the elements; the menu says why it failed Co-Authored-By: Claude Opus 5.5 --- crates/assistant/skills/print-layout/SKILL.md | 3 +- crates/engine/src/cmd/layout.rs | 44 +++++++++++++++---- crates/engine/src/tests.rs | 17 +++++++ crates/render/src/layout.rs | 3 +- crates/ui-egui/src/ribbon.rs | 7 ++- 5 files changed, 61 insertions(+), 13 deletions(-) diff --git a/crates/assistant/skills/print-layout/SKILL.md b/crates/assistant/skills/print-layout/SKILL.md index 542fa6db8b..37af7e819f 100644 --- a/crates/assistant/skills/print-layout/SKILL.md +++ b/crates/assistant/skills/print-layout/SKILL.md @@ -9,7 +9,8 @@ description: Make a printable page layout — map frame, title, legend, north ar 2. For a finished sheet or a figure for a paper in one step, use `layout.publication` with a `"profile"` (`"a4-portrait"`, `"a3-landscape"`, … for a sheet; `"figure-1col"`, `"thesis-full"`, … for a figure), the `"extent"` to fit, and the texts: `"title"`, `"subtitle"`, `"sources"`, `"note"`. It places the frame at a round scale, the - graticule, legend, scale bar and north arrow, and wraps the footer, so skip to step 5 to adjust it. Otherwise, + graticule, legend, scale bar and north arrow, and wraps the footer. Its result lists every element's id and name + (`"elements"`), so skip to step 5 to adjust them. Otherwise, `layout.new` `{"name": N, "page": "letter"|"a4"|…, "orientation": "landscape"|"portrait"}` creates the layout and opens it. 3. `layout.addFrame` for the map frame (`search_commands` "map frame" for its position and size parameters, in diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 720451d87d..e41da4cb85 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -468,8 +468,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { around.push(("Frame".into(), (m, m, page_w - 2.0 * m, page_h - 2.0 * m), pub_box(clear, ink, 0.8))); let mut top = m + pad; if let Some(t) = &title { - let th = pitch(title_pt) + 1.5 * k; - around.push(("Title".into(), (x0, top, iw, th), pub_text(fill(t), title_pt, ink, true, TextAlign::Center))); + let lines = wrap(t, iw, title_pt); + let th = lines.len() as f64 * pitch(title_pt) + 1.5 * k; + around.push(("Title".into(), (x0, top, iw, th), pub_text(lines.join("\n"), title_pt, ink, true, TextAlign::Center))); top += th; } if let Some(t) = &subtitle { @@ -481,11 +482,13 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // The footer, from the bottom up: authorship, the note, then the two boxes side by side, // as tall as the longer column. let bottom = page_h - m - pad; - let author_y = bottom - pitch(small_pt); + let author_lines = wrap(&author, iw, small_pt); + let author_h = author_lines.len() as f64 * pitch(small_pt); + let author_y = bottom - author_h; around.push(( "Author".into(), - (x0, author_y, iw, pitch(small_pt)), - pub_text(fill(&author), small_pt, soft, false, TextAlign::Right), + (x0, author_y, iw, author_h), + pub_text(author_lines.join("\n"), small_pt, soft, false, TextAlign::Right), )); let note_lines = note.as_deref().map(|t| wrap(t, iw, body_pt)).unwrap_or_default(); let mut foot = author_y; @@ -524,11 +527,11 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { (page_w, page_h, (x0, frame_top, iw, frame_bottom - frame_top)) } else { // A figure: the map edge to edge, a line of the projection and datum under it. - for (k, given) in + for (field, given) in [("title", title.is_some()), ("subtitle", subtitle.is_some()), ("sources", !sources.is_empty()), ("note", note.is_some())] { if given { - warnings.push(format!("{k} goes in the figure's caption, not on it: left out")); + warnings.push(format!("{field} goes in the figure's caption, not on it: left out")); } } let line = reference.iter().map(|t| fill(t)).collect::>().join(" · "); @@ -542,6 +545,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } else { (page_w * aspect(s, &extent).unwrap_or(0.75)).clamp(0.45 * page_w, 1.3 * page_w).round() }; + if fh < 40.0 { + return Err("the reference leaves the map no room: shorten it".into()); + } let h = if page_h > 0.0 { page_h } else { (fh + note_h).ceil() }; around.push(( "Reference".into(), @@ -590,8 +596,26 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let (left, right, top, bottom) = (room(edges.left, true), room(edges.right, true), room(edges.top, false), room(edges.bottom, false)); let (aw, ah) = if sheet { (8.0 * k, 12.0 * k) } else { (5.0, 7.5) }; l.add("North Arrow", (fx + fw - right - aw, fy + top, aw, ah), ElementKind::north_arrow(frame)); + // The legend lists what the frame draws: its map synced to the frame's view first, as an + // export does, so a streamed layer has its features there. While one is still reading, the + // classes can't be known: the legend gets a fixed size, to fit by hand. Nothing drawn in the + // frame, no legend. let render_scale = crate::render::layout::frame_render_scale(s.map(), center, scale); - let (cw, ch) = crate::render::layout::legend_size_mm(s.map(), render_scale, false, false, &[]); + let view = crate::render::View { + width: fw * rustgis_map::layout::PT_PER_MM, + height: fh * rustgis_map::layout::PT_PER_MM, + pixels_per_point: 1.0, + camera: rustgis_map::layout::frame_camera(s.map(), center, scale, 0.0, 0.0), + sky: false, + }; + let lonlat = crate::render::view_lonlat(s.map(), &view); + let reading = s.map_mut().sync_sources(&lonlat, render_scale, true); + let (mut cw, mut ch) = crate::render::layout::legend_size_mm(s.map(), render_scale, false, false, &[]); + let listed = s.map().layers.iter().any(|l| s.map().shows(l) && !l.graphics && !l.is_raster()); + if reading && listed { + (cw, ch) = (cw.max(fw * 0.3), ch.max(fh * 0.25)); + warnings.push("the legend's classes aren't known yet (a layer still reading): it has a fixed size to fit by hand".into()); + } if ch > 0.0 { let pad = 2.0; let (lw, lh) = ((cw + 2.0 * pad).min(fw * 0.45), (ch + 2.0 * pad).min(fh * 0.6)); @@ -614,10 +638,12 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { for (n, r, kind) in around { l.add(&n, r, kind); } + // Every element by name and id, for `layout.update`. + let elements: Vec = l.elements.iter().map(|e| json!({"element": e.id, "name": e.name, "kind": e.kind.code()})).collect(); s.project.layouts.push(l); let i = s.project.layouts.len() - 1; s.active_layout = Some(i); - Ok(json!({"layout": i, "name": name, "page": [w, h], "scale": scale, "grid": step, "warnings": warnings})) + Ok(json!({"layout": i, "name": name, "page": [w, h], "scale": scale, "grid": step, "elements": elements, "warnings": warnings})) } fn page(s: &mut Session, p: &Value) -> CmdResult { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7617be7105..7990911ac5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2356,6 +2356,22 @@ fn publication_layouts_fit_their_pages() { assert!(std::fs::metadata(&png).unwrap().len() > 1000, "{profile}"); } assert_eq!(s.project.layouts.len(), profiles.len(), "a layout each, the earlier ones untouched"); + // A long title wraps within the frame, and pushes the map down; the result names every + // element for layout.update. + let r = s.run("layout.publication", &json!({"extent": piaui, "title": long})).unwrap(); + let l = s.project.layouts.last().unwrap(); + let title = l.elements.iter().find(|e| e.name == "Title").unwrap(); + let ElementKind::Text { text, size, .. } = &title.kind else { panic!() }; + assert!(text.lines().count() >= 2, "{text}"); + for line in text.lines() { + assert!(crate::render::report::width_mm(line, *size as f32, false) <= title.w, "{line}"); + } + let frame = l.elements.iter().find(|e| e.kind.code() == "mapFrame").unwrap(); + assert!(frame.y >= title.y + title.h); + let listed = r["elements"].as_array().unwrap(); + assert_eq!(listed.len(), l.elements.len()); + assert!(listed.iter().any(|e| e["name"] == "Map Frame" && e["element"] == frame.id && e["kind"] == "mapFrame"), "{r}"); + s.project.layouts.pop(); // A journal figure is as tall as the map's shape asks: Piauí in Web Mercator is taller than wide. let one = s.project.layouts.iter().find(|l| l.name == "figure-1col").unwrap(); assert!(one.width == 90.0 && one.height > 90.0, "{} × {}", one.width, one.height); @@ -2371,6 +2387,7 @@ fn publication_layouts_fit_their_pages() { (json!({"extent": [10, 0, 5, 1]}), "extent is"), (json!({"extent": [10, 0, 11], "profile": "a4-portrait"}), "extent is"), (json!({"sources": vec![long; 40], "profile": "a4-landscape", "extent": piaui}), "no room"), + (json!({"reference": vec![long; 50], "profile": "thesis-half", "extent": piaui}), "no room"), ] { let e = s.run("layout.publication", &p).unwrap_err(); assert!(e.contains(said), "{p}: {e}"); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index d516dfc583..d520277338 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -818,7 +818,8 @@ fn legend(pm: &mut Pixmap, r: Rect, map: &Map, title: &str, drawn: Option<&[(u32 } let sw = LEGEND_SWATCH * ppp; for row in legend_rows(map, drawn, &opts) { - if y + line > r.y() + r.height() { + // The rectangle's own bottom, which a sum of its top and height can miss by a rounding. + if y + line > r.bottom() { break; } match row { diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index fb767ec703..9522db4794 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -945,8 +945,11 @@ fn project_group(app: &mut RustGisApp, ui: &mut Ui) { ui.menu_button(tl!("Publication Layout"), |ui| { for (id, label, ..) in rustgis_engine::cmd::layout::PUBLICATION_PROFILES { if ui.button(tl!(*label)).clicked() { - let _ = app.run("layout.publication", json!({"profile": id, "title": app.session.map().name.clone()})); - app.ui.tab = "Publish".into(); + // The view's extent may not be known (an empty map): said, and the tab stays. + match app.run("layout.publication", json!({"profile": id, "title": app.session.map().name.clone()})) { + Ok(_) => app.ui.tab = "Publish".into(), + Err(e) => app.session.notify(e, true), + } ui.close(); } } From f6499fd8d61a13c0bc3c304491c00ea36c25399a Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 08:49:13 -0300 Subject: [PATCH 03/22] layout.publication: footer elements keep their names whatever the headings read, headings filled and wrapped; the legend stops short of the scale bar; profiles as a struct; the menu titles only sheets Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 81 +++++++++++++++++++++------------ crates/engine/src/tests.rs | 20 +++++++- crates/ui-egui/src/ribbon.rs | 11 +++-- 3 files changed, 78 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index e41da4cb85..92debba96a 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -298,21 +298,31 @@ pub(crate) fn new_layout(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"layout": i, "name": name})) } -/// `layout.publication`'s profiles: an id, a label, a sheet (a frame, title and boxed footer) or a -/// figure (the map edge to edge, its title and sources left to the caption), and its size in mm. -/// A height of 0 follows the map's shape. -pub const PUBLICATION_PROFILES: &[(&str, &str, bool, f64, f64)] = &[ - ("a4-portrait", "A4 portrait sheet", true, 210.0, 297.0), - ("a4-landscape", "A4 landscape sheet", true, 297.0, 210.0), - ("a3-portrait", "A3 portrait sheet", true, 297.0, 420.0), - ("a3-landscape", "A3 landscape sheet", true, 420.0, 297.0), - ("a2-portrait", "A2 portrait sheet", true, 420.0, 594.0), - ("a2-landscape", "A2 landscape sheet", true, 594.0, 420.0), - ("figure-1col", "Journal figure, 1 column (90 mm)", false, 90.0, 0.0), - ("figure-1.5col", "Journal figure, 1.5 columns (140 mm)", false, 140.0, 0.0), - ("figure-2col", "Journal figure, 2 columns (190 mm)", false, 190.0, 0.0), - ("thesis-full", "Thesis figure, full page (160 × 225 mm)", false, 160.0, 225.0), - ("thesis-half", "Thesis figure, half page (160 × 110 mm)", false, 160.0, 110.0), +/// One of `layout.publication`'s profiles. +pub struct PublicationProfile { + pub id: &'static str, + pub label: &'static str, + /// A sheet (a frame, title and boxed footer), else a figure (the map edge to edge, its title + /// and sources left to the caption). + pub sheet: bool, + /// The page, in mm. A height of 0 follows the map's shape. + pub width: f64, + pub height: f64, +} + +/// `layout.publication`'s profiles: sheets for printing, figures for a journal or a thesis. +pub const PUBLICATION_PROFILES: &[PublicationProfile] = &[ + PublicationProfile { id: "a4-portrait", label: "A4 portrait sheet", sheet: true, width: 210.0, height: 297.0 }, + PublicationProfile { id: "a4-landscape", label: "A4 landscape sheet", sheet: true, width: 297.0, height: 210.0 }, + PublicationProfile { id: "a3-portrait", label: "A3 portrait sheet", sheet: true, width: 297.0, height: 420.0 }, + PublicationProfile { id: "a3-landscape", label: "A3 landscape sheet", sheet: true, width: 420.0, height: 297.0 }, + PublicationProfile { id: "a2-portrait", label: "A2 portrait sheet", sheet: true, width: 420.0, height: 594.0 }, + PublicationProfile { id: "a2-landscape", label: "A2 landscape sheet", sheet: true, width: 594.0, height: 420.0 }, + PublicationProfile { id: "figure-1col", label: "Journal figure, 1 column (90 mm)", sheet: false, width: 90.0, height: 0.0 }, + PublicationProfile { id: "figure-1.5col", label: "Journal figure, 1.5 columns (140 mm)", sheet: false, width: 140.0, height: 0.0 }, + PublicationProfile { id: "figure-2col", label: "Journal figure, 2 columns (190 mm)", sheet: false, width: 190.0, height: 0.0 }, + PublicationProfile { id: "thesis-full", label: "Thesis figure, full page (160 × 225 mm)", sheet: false, width: 160.0, height: 225.0 }, + PublicationProfile { id: "thesis-half", label: "Thesis figure, half page (160 × 110 mm)", sheet: false, width: 160.0, height: 110.0 }, ]; /// A figure's text size, in points at its printed size: journals ask for 6 to 8. @@ -416,10 +426,11 @@ fn pub_box(fill: Rgba, outline: Rgba, width: f64) -> ElementKind { /// authorship under them, each text wrapped to its box with the layout's own font. fn publication(s: &mut Session, p: &Value) -> CmdResult { let id = ps(p, "profile").unwrap_or("a4-portrait").trim().to_ascii_lowercase(); - let &(_, _, sheet, page_w, page_h) = PUBLICATION_PROFILES.iter().find(|(n, ..)| *n == id).ok_or_else(|| { - let names: Vec<&str> = PUBLICATION_PROFILES.iter().map(|(n, ..)| *n).collect(); + let profile = PUBLICATION_PROFILES.iter().find(|pr| pr.id == id).ok_or_else(|| { + let names: Vec<&str> = PUBLICATION_PROFILES.iter().map(|pr| pr.id).collect(); format!("unknown profile '{id}': {}", names.join(", ")) })?; + let (sheet, page_w, page_h) = (profile.sheet, profile.width, profile.height); let extent = match p.get("extent").filter(|v| !v.is_null()) { None => { let e = super::workspace::view_extent(s); @@ -500,23 +511,30 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let (gap, inner) = (4.0 * k, 2.5 * k); let cw = (iw - gap) / 2.0; let column = |lines: &[String]| lines.iter().flat_map(|t| wrap(t, cw - 2.0 * inner, body_pt)).collect::>(); - let columns = [(heading(0, "Sources"), column(&sources)), (heading(1, "Cartographic reference"), column(&reference))]; - let rows = columns.iter().map(|(_, l)| l.len()).max().unwrap_or(0); + // Each column's elements keep their names (`Sources`, `Reference`) whatever its heading + // reads, the heading filled and wrapped like the rest. + let tw = cw - 2.0 * inner; + let titled = |i: usize, or: &str| wrap(&fill(&heading(i, or)).to_uppercase(), tw, head_pt); + let columns = + [("Sources", titled(0, "Sources"), column(&sources)), ("Reference", titled(1, "Cartographic reference"), column(&reference))]; + let heads = columns.iter().map(|(_, h, _)| h.len()).max().unwrap_or(1); + let rows = columns.iter().map(|(.., l)| l.len()).max().unwrap_or(0); if rows > 0 { - let bh = 2.0 * inner + pitch(head_pt) + rows as f64 * pitch(body_pt); + let head_h = heads as f64 * pitch(head_pt); + let bh = 2.0 * inner + head_h + rows as f64 * pitch(body_pt); foot -= bh + 2.0 * k; - for (i, (head, lines)) in columns.into_iter().enumerate() { + for (i, (name, head, lines)) in columns.into_iter().enumerate() { let bx = x0 + i as f64 * (cw + gap); - around.push((format!("{head} Box"), (bx, foot, cw, bh), pub_box(clear, Rgba::new(0x2B, 0x26, 0x20, 140), 0.5))); - let (tx, tw) = (bx + inner, cw - 2.0 * inner); + around.push((format!("{name} Box"), (bx, foot, cw, bh), pub_box(clear, Rgba::new(0x2B, 0x26, 0x20, 140), 0.5))); + let tx = bx + inner; around.push(( - format!("{head} Heading"), - (tx, foot + inner, tw, pitch(head_pt)), - pub_text(head.to_uppercase(), head_pt, ink, true, TextAlign::Left), + format!("{name} Heading"), + (tx, foot + inner, tw, head.len() as f64 * pitch(head_pt)), + pub_text(head.join("\n"), head_pt, ink, true, TextAlign::Left), )); if !lines.is_empty() { - let body = (tx, foot + inner + pitch(head_pt), tw, lines.len() as f64 * pitch(body_pt)); - around.push((head, body, pub_text(lines.join("\n"), body_pt, soft, false, TextAlign::Left))); + let body = (tx, foot + inner + head_h, tw, lines.len() as f64 * pitch(body_pt)); + around.push((name.to_string(), body, pub_text(lines.join("\n"), body_pt, soft, false, TextAlign::Left))); } } } @@ -616,9 +634,13 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { (cw, ch) = (cw.max(fw * 0.3), ch.max(fh * 0.25)); warnings.push("the legend's classes aren't known yet (a layer still reading): it has a fixed size to fit by hand".into()); } + // The scale bar's box, at the bottom right: the legend stops short of it (and so of the north + // arrow above it, which is narrower), however narrow the frame. + let (sw, sh, nh) = ((fw * 0.3).max(25.0), if sheet { 8.0 * k } else { 6.0 }, pitch(small_pt) + 0.5); if ch > 0.0 { let pad = 2.0; - let (lw, lh) = ((cw + 2.0 * pad).min(fw * 0.45), (ch + 2.0 * pad).min(fh * 0.6)); + let room_w = (fw - left - right - sw - 2.0).max(10.0); + let (lw, lh) = ((cw + 2.0 * pad).min(fw * 0.45).min(room_w), (ch + 2.0 * pad).min(fh * 0.6)); if cw + 2.0 * pad > lw || ch + 2.0 * pad > lh { warnings.push("the legend lists more than fits its corner: its last rows or the ends of long labels are left out".into()); } @@ -630,7 +652,6 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { ElementKind::Legend { frame, title: String::new(), all_classes: false, hide_other: false, exclude: Vec::new() }, ); } - let (sw, sh, nh) = ((fw * 0.3).max(25.0), if sheet { 8.0 * k } else { 6.0 }, pitch(small_pt) + 0.5); let (sx, sy) = (fx + fw - right - sw, fy + fh - bottom - sh - nh); l.add("Scale Box", (sx, sy, sw, sh + nh), pub_box(paper, clear, 0.0)); l.add("Scale Bar", (sx, sy, sw, sh), ElementKind::scale_bar(frame)); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7990911ac5..bc13994e36 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2312,6 +2312,9 @@ fn publication_layouts_fit_their_pages() { } let frame = l.elements.iter().find(|e| e.kind.code() == "mapFrame").unwrap(); let ElementKind::MapFrame { scale, grid: Some(grid), .. } = &frame.kind else { panic!("{profile}: no grid") }; + // The legend stops short of the scale bar's box, however narrow the frame. + let named = |n: &str| l.elements.iter().find(|e| e.name == n).unwrap(); + assert!(named("Legend Box").x + named("Legend Box").w <= named("Scale Box").x, "{profile}: the legend reaches the scale bar"); // A round scale, two significant figures, at which the extent still fits. let unit = 10f64.powf(scale.log10().floor() - 1.0); assert!(((scale / unit) - (scale / unit).round()).abs() < 1e-6, "{profile}: 1:{scale}"); @@ -2341,7 +2344,7 @@ fn publication_layouts_fit_their_pages() { ); } // The tokens filled from the map: Web Mercator over WGS 84, the 2° graticule. - let reference = text("Cartographic reference").unwrap(); + let reference = text("Reference").unwrap(); assert!(reference.contains("Web Mercator") && reference.contains("WGS 84") && reference.contains("2°"), "{reference}"); assert!(text("Author").unwrap().contains("{date}"), "the date stays a token the layout fills"); assert!(r["warnings"].as_array().unwrap().is_empty(), "{profile}: {r}"); @@ -2372,6 +2375,21 @@ fn publication_layouts_fit_their_pages() { assert_eq!(listed.len(), l.elements.len()); assert!(listed.iter().any(|e| e["name"] == "Map Frame" && e["element"] == frame.id && e["kind"] == "mapFrame"), "{r}"); s.project.layouts.pop(); + // Headings rename what the columns read, filled and wrapped; their elements keep their names. + let r = s + .run( + "layout.publication", + &json!({"extent": piaui, "sources": "IBGE", "headings": ["Fontes dos dados", "Referência cartográfica na projeção {projection}, a mais longa que se possa imaginar"]}), + ) + .unwrap(); + let l = s.project.layouts.last().unwrap(); + let heading = l.elements.iter().find(|e| e.name == "Reference Heading").unwrap(); + let ElementKind::Text { text, .. } = &heading.kind else { panic!() }; + assert!(text.contains("WEB MERCATOR") && !text.contains('{') && text.lines().count() >= 2, "{text}"); + assert!(l.elements.iter().any(|e| e.name == "Sources Heading") && l.elements.iter().any(|e| e.name == "Reference"), "{r}"); + let body = l.elements.iter().find(|e| e.name == "Reference").unwrap(); + assert!(body.y >= heading.y + heading.h - 1e-9, "the reference starts under its wrapped heading"); + s.project.layouts.pop(); // A journal figure is as tall as the map's shape asks: Piauí in Web Mercator is taller than wide. let one = s.project.layouts.iter().find(|l| l.name == "figure-1col").unwrap(); assert!(one.width == 90.0 && one.height > 90.0, "{} × {}", one.width, one.height); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 9522db4794..f39f0d47cc 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -943,10 +943,15 @@ fn project_group(app: &mut RustGisApp, ui: &mut Ui) { } // A finished sheet or figure of the map view, its texts to fill in on the page. ui.menu_button(tl!("Publication Layout"), |ui| { - for (id, label, ..) in rustgis_engine::cmd::layout::PUBLICATION_PROFILES { - if ui.button(tl!(*label)).clicked() { + for profile in rustgis_engine::cmd::layout::PUBLICATION_PROFILES { + if ui.button(tl!(profile.label)).clicked() { + // A sheet is titled with the map's name; a figure's title is its caption's. + let mut p = json!({"profile": profile.id}); + if profile.sheet { + p["title"] = json!(app.session.map().name.clone()); + } // The view's extent may not be known (an empty map): said, and the tab stays. - match app.run("layout.publication", json!({"profile": id, "title": app.session.map().name.clone()})) { + match app.run("layout.publication", p) { Ok(_) => app.ui.tab = "Publish".into(), Err(e) => app.session.notify(e, true), } From 38dd4c25319a00c01692d8619a5be4147b6f17a9 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 09:07:14 -0300 Subject: [PATCH 04/22] layout.publication: text measured as drawn (bold titles, live tokens at a typical width); a footer column with nothing in it left out; a legend row's rounding slack Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 48 ++++++++++++++++++++++++++------- crates/engine/src/tests.rs | 10 ++++++- crates/render/src/layout.rs | 5 ++-- crates/render/src/report.rs | 12 ++++++--- docs/user-guide/layouts.md | 5 ++-- 5 files changed, 62 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 92debba96a..96891520f7 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -461,7 +461,28 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let (projection, datum) = projection_and_datum(s); let step = grid_step(&extent); let fill = |t: &str| t.replace("{projection}", &projection).replace("{datum}", &datum).replace("{grid}", &step_text(step)); - let wrap = |t: &str, w: f64, pt: f64| crate::render::report::wrap(&fill(t), w.max(1.0), pt as f32); + // Text is measured as it is drawn: bold as bold, and the tokens the layout fills only when it + // draws (`{date}`, `{scale}`…) as wide as a typical value of theirs. + let (map_name, crs) = (s.map().name.clone(), s.map().projection.label()); + let drawn = move |t: &str| { + [ + ("{date}", "0000-00-00"), + ("{time}", "00:00"), + ("{scale}", "1:10,000,000"), + ("{pages}", "00"), + ("{page}", "00"), + ("{layers}", "00"), + ("{center}", "00.000°S, 000.000°W"), + ("{map}", map_name.as_str()), + ("{crs}", crs.as_str()), + ] + .iter() + .fold(t.to_string(), |t, (token, like)| t.replace(token, like)) + }; + let wrap_as = |t: &str, w: f64, pt: f64, bold: bool| { + crate::render::report::wrap_with(&fill(t), w.max(1.0), |x| crate::render::report::width_mm(&drawn(x), pt as f32, bold)) + }; + let wrap = |t: &str, w: f64, pt: f64| wrap_as(t, w, pt, false); let pitch = crate::render::layout::line_pitch_mm; let ink = Rgba::rgb(0x2B, 0x26, 0x20); let soft = Rgba::rgb(0x5E, 0x55, 0x47); @@ -479,7 +500,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { around.push(("Frame".into(), (m, m, page_w - 2.0 * m, page_h - 2.0 * m), pub_box(clear, ink, 0.8))); let mut top = m + pad; if let Some(t) = &title { - let lines = wrap(t, iw, title_pt); + let lines = wrap_as(t, iw, title_pt, true); let th = lines.len() as f64 * pitch(title_pt) + 1.5 * k; around.push(("Title".into(), (x0, top, iw, th), pub_text(lines.join("\n"), title_pt, ink, true, TextAlign::Center))); top += th; @@ -508,15 +529,22 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { foot -= nh + 1.5 * k; around.push(("Note".into(), (x0, foot, iw, nh), pub_text(note_lines.join("\n"), body_pt, soft, false, TextAlign::Left))); } + // The columns with something in them, side by side (one alone takes the width). Each one's + // elements keep their names (`Sources`, `Reference`) whatever its heading reads, the heading + // filled and wrapped like the rest. let (gap, inner) = (4.0 * k, 2.5 * k); - let cw = (iw - gap) / 2.0; - let column = |lines: &[String]| lines.iter().flat_map(|t| wrap(t, cw - 2.0 * inner, body_pt)).collect::>(); - // Each column's elements keep their names (`Sources`, `Reference`) whatever its heading - // reads, the heading filled and wrapped like the rest. + let given = [("Sources", heading(0, "Sources"), &sources), ("Reference", heading(1, "Cartographic reference"), &reference)]; + let given: Vec<_> = given.into_iter().filter(|(.., texts)| !texts.is_empty()).collect(); + let n = given.len().max(1) as f64; + let cw = (iw - gap * (n - 1.0)) / n; let tw = cw - 2.0 * inner; - let titled = |i: usize, or: &str| wrap(&fill(&heading(i, or)).to_uppercase(), tw, head_pt); - let columns = - [("Sources", titled(0, "Sources"), column(&sources)), ("Reference", titled(1, "Cartographic reference"), column(&reference))]; + let columns: Vec<_> = given + .into_iter() + .map(|(name, head, texts)| { + let head = wrap_as(&fill(&head).to_uppercase(), tw, head_pt, true); + (name, head, texts.iter().flat_map(|t| wrap(t, tw, body_pt)).collect::>()) + }) + .collect(); let heads = columns.iter().map(|(_, h, _)| h.len()).max().unwrap_or(1); let rows = columns.iter().map(|(.., l)| l.len()).max().unwrap_or(0); if rows > 0 { @@ -553,7 +581,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } } let line = reference.iter().map(|t| fill(t)).collect::>().join(" · "); - let lines = crate::render::report::wrap(&line, page_w, FIGURE_PT as f32); + let lines = wrap(&line, page_w, FIGURE_PT); if lines.len() > 1 { warnings.push("the reference is wider than the figure: it wraps under the map".into()); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index bc13994e36..28f81fb606 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2367,7 +2367,7 @@ fn publication_layouts_fit_their_pages() { let ElementKind::Text { text, size, .. } = &title.kind else { panic!() }; assert!(text.lines().count() >= 2, "{text}"); for line in text.lines() { - assert!(crate::render::report::width_mm(line, *size as f32, false) <= title.w, "{line}"); + assert!(crate::render::report::width_mm(line, *size as f32, true) <= title.w, "{line}: measured bold, as drawn"); } let frame = l.elements.iter().find(|e| e.kind.code() == "mapFrame").unwrap(); assert!(frame.y >= title.y + title.h); @@ -2375,6 +2375,14 @@ fn publication_layouts_fit_their_pages() { assert_eq!(listed.len(), l.elements.len()); assert!(listed.iter().any(|e| e["name"] == "Map Frame" && e["element"] == frame.id && e["kind"] == "mapFrame"), "{r}"); s.project.layouts.pop(); + // With no sources, the reference alone takes the footer's width; no empty box beside it. + s.run("layout.publication", &json!({"extent": piaui})).unwrap(); + let l = s.project.layouts.last().unwrap(); + let frame = l.elements.iter().find(|e| e.kind.code() == "mapFrame").unwrap(); + assert!(l.elements.iter().all(|e| !e.name.starts_with("Sources"))); + let reference = l.elements.iter().find(|e| e.name == "Reference Box").unwrap(); + assert!((reference.x - frame.x).abs() < 1e-9 && (reference.w - frame.w).abs() < 1e-9, "{} of {}", reference.w, frame.w); + s.project.layouts.pop(); // Headings rename what the columns read, filled and wrapped; their elements keep their names. let r = s .run( diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index d520277338..94fe091a54 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -818,8 +818,9 @@ fn legend(pm: &mut Pixmap, r: Rect, map: &Map, title: &str, drawn: Option<&[(u32 } let sw = LEGEND_SWATCH * ppp; for row in legend_rows(map, drawn, &opts) { - // The rectangle's own bottom, which a sum of its top and height can miss by a rounding. - if y + line > r.bottom() { + // The rectangle's own bottom, which a sum of its top and height can miss by a rounding, + // and a thousandth of a row's slack: a legend sized to its rows keeps the last one. + if y + line > r.bottom() + line * 1e-3 { break; } match row { diff --git a/crates/render/src/report.rs b/crates/render/src/report.rs index 86bf10c411..f538904a5d 100644 --- a/crates/render/src/report.rs +++ b/crates/render/src/report.rs @@ -69,16 +69,22 @@ fn style(b: &Block) -> (f32, bool, f64) { /// Splits text into lines no wider than `w` millimetres at `pt` points: whole words, a word wider /// than the line broken across lines. pub fn wrap(s: &str, w: f64, pt: f32) -> Vec { + wrap_with(s, w, |t| width_mm(t, pt, false)) +} + +/// [`wrap`] with the width of a piece of text (in mm) measured by `width`: bold text, or text whose +/// tokens are filled in only when it is drawn. +pub fn wrap_with(s: &str, w: f64, width: impl Fn(&str) -> f64) -> Vec { let mut out = Vec::new(); for para in s.lines().take(2000) { let mut line = String::new(); for word in para.split_whitespace().take(5000) { // A word wider than the line (a long URL…) is broken across lines. let mut word = word.to_string(); - while width_mm(&word, pt, false) > w && word.chars().count() > 1 { + while width(&word) > w && word.chars().count() > 1 { let mut head = String::new(); for ch in word.chars() { - if !head.is_empty() && width_mm(&format!("{head}{ch}"), pt, false) > w { + if !head.is_empty() && width(&format!("{head}{ch}")) > w { break; } head.push(ch); @@ -91,7 +97,7 @@ pub fn wrap(s: &str, w: f64, pt: f32) -> Vec { } let word = word.as_str(); let next = if line.is_empty() { word.to_string() } else { format!("{line} {word}") }; - if !line.is_empty() && width_mm(&next, pt, false) > w { + if !line.is_empty() && width(&next) > w { out.push(std::mem::take(&mut line)); line = word.to_string(); } else { diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index c0c22d7205..5f3f61d3ed 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -14,8 +14,9 @@ the maps; while one is open, its groups lead the Publish tab: - **Publication layouts**: Home › New Layout › **Publication Layout** builds a finished sheet or figure of the map view in one step, with `layout.publication` behind it: - **Sheets** (A4, A3 or A2, portrait or landscape): a frame and margin, the title and subtitle, - the map, and a footer of two boxed columns (sources, and the cartographic reference) with a - note and the authorship under them. Text sizes follow the sheet: an A3's are 1.41 times an + the map, and a footer of two boxed columns (sources, and the cartographic reference; one + with nothing in it is left out, the other taking the width) with a note and the authorship + under them. Text sizes follow the sheet: an A3's are 1.41 times an A4's. - **Figures** for a journal (90, 140 or 190 mm wide, as tall as the map's shape asks) or a thesis (160 × 225 or 160 × 110 mm): the map edge to edge with a line of its projection and From cf40acc6814d241487bcb55bdc855abedbfc31c3 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 09:14:06 -0300 Subject: [PATCH 05/22] Wrapping breaks a word wider than the line by halving, a few measures a line rather than one a character Co-Authored-By: Claude Opus 5.5 --- crates/render/src/report.rs | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/crates/render/src/report.rs b/crates/render/src/report.rs index f538904a5d..a40995ad22 100644 --- a/crates/render/src/report.rs +++ b/crates/render/src/report.rs @@ -79,21 +79,25 @@ pub fn wrap_with(s: &str, w: f64, width: impl Fn(&str) -> f64) -> Vec { for para in s.lines().take(2000) { let mut line = String::new(); for word in para.split_whitespace().take(5000) { - // A word wider than the line (a long URL…) is broken across lines. + // A word wider than the line (a long URL…) is broken across lines: the most of its + // characters that fit, found by halving (a few measures a line, not one a character). let mut word = word.to_string(); while width(&word) > w && word.chars().count() > 1 { - let mut head = String::new(); - for ch in word.chars() { - if !head.is_empty() && width(&format!("{head}{ch}")) > w { - break; + let chars: Vec = word.chars().collect(); + let (mut fits, mut over) = (1, chars.len()); + while over - fits > 1 { + let mid = (fits + over) / 2; + if width(&chars[..mid].iter().collect::()) > w { + over = mid; + } else { + fits = mid; } - head.push(ch); } if !line.is_empty() { out.push(std::mem::take(&mut line)); } - word = word.chars().skip(head.chars().count()).collect(); - out.push(head); + out.push(chars[..fits].iter().collect()); + word = chars[fits..].iter().collect(); } let word = word.as_str(); let next = if line.is_empty() { word.to_string() } else { format!("{line} {word}") }; @@ -456,6 +460,22 @@ mod tests { Doc { title: "Cities".into(), width: 215.9, height: 279.4, blocks } } + /// A word wider than the line breaks into pieces that each fit, nothing lost, found in a few + /// measures a piece rather than one a character (a hostile 2000-character word stays cheap). + #[test] + fn a_long_word_breaks_in_few_measures() { + let word = "x".repeat(2000); + let count = std::cell::Cell::new(0usize); + let lines = wrap_with(&word, 40.0, |t| { + count.set(count.get() + 1); + width_mm(t, 7.0, false) + }); + assert!(lines.len() > 10, "{} lines", lines.len()); + assert!(lines.iter().all(|l| width_mm(l, 7.0, false) <= 40.0), "every piece fits"); + assert_eq!(lines.concat(), word, "nothing lost"); + assert!(count.get() < 20 * lines.len(), "{} measures for {} lines", count.get(), lines.len()); + } + #[test] fn flows_onto_pages_with_repeated_column_headings() { let d = doc(120); From 91935587364df6e4f09177a98ba8c165d27b3f31 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 09:20:25 -0300 Subject: [PATCH 06/22] layout.publication: a heading's live tokens keep their case in capitals, so the layout still fills them Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 24 +++++++++++++++++++++++- crates/engine/src/tests.rs | 6 +++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 96891520f7..fe148c7f74 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -410,6 +410,26 @@ fn aspect(s: &Session, e: &Extent) -> Option { (ext.width() > 0.0 && ext.height() > 0.0).then(|| ext.height() / ext.width()) } +/// `t` in capitals, its `{tokens}` as they are: the layout fills a token (`{date}`) when it draws +/// only in its own case. +fn capitals(t: &str) -> String { + let mut out = String::with_capacity(t.len()); + let mut token = false; + for c in t.chars() { + match c { + '{' => token = true, + '}' => token = false, + _ => {} + } + if token || c == '}' { + out.push(c); + } else { + out.extend(c.to_uppercase()); + } + } + out +} + /// A text element in a publication layout's style: upright, sans, in `align`. fn pub_text(text: String, size: f64, color: Rgba, bold: bool, align: TextAlign) -> ElementKind { ElementKind::Text { text, size, color, bold, italic: false, align, letter_spacing: 0.0, font: FontFamily::Sans } @@ -541,7 +561,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let columns: Vec<_> = given .into_iter() .map(|(name, head, texts)| { - let head = wrap_as(&fill(&head).to_uppercase(), tw, head_pt, true); + // Filled first, so `{projection}` reads in capitals too; the live tokens left keep + // their case (wrap_as fills again, which then finds nothing). + let head = wrap_as(&capitals(&fill(&head)), tw, head_pt, true); (name, head, texts.iter().flat_map(|t| wrap(t, tw, body_pt)).collect::>()) }) .collect(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 28f81fb606..884fc4da21 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2387,13 +2387,17 @@ fn publication_layouts_fit_their_pages() { let r = s .run( "layout.publication", - &json!({"extent": piaui, "sources": "IBGE", "headings": ["Fontes dos dados", "Referência cartográfica na projeção {projection}, a mais longa que se possa imaginar"]}), + &json!({"extent": piaui, "sources": "IBGE", "headings": ["Fontes dos dados, {date}", "Referência cartográfica na projeção {projection}, a mais longa que se possa imaginar"]}), ) .unwrap(); let l = s.project.layouts.last().unwrap(); let heading = l.elements.iter().find(|e| e.name == "Reference Heading").unwrap(); let ElementKind::Text { text, .. } = &heading.kind else { panic!() }; assert!(text.contains("WEB MERCATOR") && !text.contains('{') && text.lines().count() >= 2, "{text}"); + // A live token in a heading keeps its case, so the layout still fills it when it draws. + let sources = l.elements.iter().find(|e| e.name == "Sources Heading").unwrap(); + let ElementKind::Text { text, .. } = &sources.kind else { panic!() }; + assert_eq!(text, "FONTES DOS DADOS, {date}"); assert!(l.elements.iter().any(|e| e.name == "Sources Heading") && l.elements.iter().any(|e| e.name == "Reference"), "{r}"); let body = l.elements.iter().find(|e| e.name == "Reference").unwrap(); assert!(body.y >= heading.y + heading.h - 1e-9, "the reference starts under its wrapped heading"); From fb762df7ad5c4c1e67c58ace1c82d1dfefe2ce0b Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 09:28:28 -0300 Subject: [PATCH 07/22] layout.publication: only a closed {name} keeps its case in a heading's capitals; a lone brace is text Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 28 +++++++++++++++------------- crates/engine/src/tests.rs | 4 +++- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index fe148c7f74..40716295f9 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -411,20 +411,22 @@ fn aspect(s: &Session, e: &Extent) -> Option { } /// `t` in capitals, its `{tokens}` as they are: the layout fills a token (`{date}`) when it draws -/// only in its own case. -fn capitals(t: &str) -> String { +/// only in its own case. A token is a closed `{name}` of letters and digits; a lone brace is text. +pub(crate) fn capitals(t: &str) -> String { let mut out = String::with_capacity(t.len()); - let mut token = false; - for c in t.chars() { - match c { - '{' => token = true, - '}' => token = false, - _ => {} - } - if token || c == '}' { - out.push(c); - } else { - out.extend(c.to_uppercase()); + let mut rest = t; + while let Some(c) = rest.chars().next() { + let token = + (c == '{').then(|| rest.find('}')).flatten().filter(|&end| end > 1 && rest[1..end].chars().all(|c| c.is_ascii_alphanumeric())); + match token { + Some(end) => { + out.push_str(&rest[..=end]); + rest = &rest[end + 1..]; + } + None => { + out.extend(c.to_uppercase()); + rest = &rest[c.len_utf8()..]; + } } } out diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 884fc4da21..b6ea643777 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2406,7 +2406,9 @@ fn publication_layouts_fit_their_pages() { let one = s.project.layouts.iter().find(|l| l.name == "figure-1col").unwrap(); assert!(one.width == 90.0 && one.height > 90.0, "{} × {}", one.width, one.height); // Graticule steps and round scales. - use crate::cmd::layout::{grid_step, round_scale, step_text}; + use crate::cmd::layout::{capitals, grid_step, round_scale, step_text}; + assert_eq!(capitals("Fontes, {date} e {pageName}"), "FONTES, {date} E {pageName}"); + assert_eq!(capitals("Dados {2024 e {só} }"), "DADOS {2024 E {SÓ} }", "a lone or odd brace is text"); assert_eq!(grid_step(&rustgis_geom::Extent::new(10.0, 45.0, 11.0, 46.0)), 0.25); assert_eq!(grid_step(&rustgis_geom::Extent::new(-180.0, -90.0, 180.0, 90.0)), 30.0); assert_eq!((step_text(2.0), step_text(0.25), step_text(0.02)), ("2°".to_string(), "15′".to_string(), "72″".to_string())); From a996d670690c484552bd4a465d3eae1d5a3d3140 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 09:35:21 -0300 Subject: [PATCH 08/22] layout.publication: a figure whose shape had to be guessed says so Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 40716295f9..9c5b559079 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -613,7 +613,11 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let fh = if page_h > 0.0 { page_h - note_h } else { - (page_w * aspect(s, &extent).unwrap_or(0.75)).clamp(0.45 * page_w, 1.3 * page_w).round() + let shape = aspect(s, &extent).unwrap_or_else(|| { + warnings.push("the extent's shape on the map's projection isn't known: the figure is 4 wide by 3 tall".into()); + 0.75 + }); + (page_w * shape).clamp(0.45 * page_w, 1.3 * page_w).round() }; if fh < 40.0 { return Err("the reference leaves the map no room: shorten it".into()); From bc8bb0246e541d2df868a7de31dac2f0b8a0b26e Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 09:39:22 -0300 Subject: [PATCH 09/22] layout.publication: the datum from the projection's definition (a preset on NAD83 says so); the legend sized through the complete-source rows the export draws Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 39 +++++++++++++++++++++++++++------ crates/engine/src/tests.rs | 13 ++++++++++- crates/render/src/layout.rs | 14 +++++++----- 3 files changed, 52 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 9c5b559079..30cdad3fc7 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -369,14 +369,32 @@ pub(crate) fn step_text(step: f64) -> String { } /// The map's projection and datum for a layout's texts: an EPSG name's two halves (`SIRGAS 2000 / -/// UTM zone 23S`), else the projection's name over WGS 84, as the presets take longitudes and -/// latitudes. +/// UTM zone 23S`), else the projection's name and the datum its definition names (a preset's +/// `+datum=NAD83`), WGS 84 when it names none. fn projection_and_datum(s: &Session) -> (String, String) { - let label = s.map().projection.label(); - match label.split_once(" / ") { - Some((datum, projection)) => (projection.trim().to_string(), datum.trim().to_string()), - None => (label, "WGS 84".to_string()), + let projection = &s.map().projection; + let label = projection.label(); + if let Some((datum, name)) = label.split_once(" / ") { + return (name.trim().to_string(), datum.trim().to_string()); } + let datum = rustgis_map::projection::lookup(&projection.code()).ok().and_then(|(def, _)| datum_of(&def)); + (label, datum.unwrap_or_else(|| "WGS 84".to_string())) +} + +/// The datum a PROJ definition names: its `+datum`, else its `+ellps`, else a sphere for `+R`. +pub(crate) fn datum_of(def: &str) -> Option { + let param = |k: &str| def.split_whitespace().find_map(|t| t.strip_prefix(k).map(str::to_string)); + if let Some(d) = param("+datum=") { + return Some(if d == "WGS84" { "WGS 84".into() } else { d }); + } + if let Some(e) = param("+ellps=") { + return Some(match e.as_str() { + "WGS84" => "WGS 84".into(), + "GRS80" => "GRS 1980 ellipsoid".into(), + _ => format!("{e} ellipsoid"), + }); + } + param("+R=").map(|_| "a sphere".into()) } /// Texts given as one or a list (up to 50), each cut to [`MAX_PUBLICATION_TEXT`] characters. @@ -684,7 +702,14 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { }; let lonlat = crate::render::view_lonlat(s.map(), &view); let reading = s.map_mut().sync_sources(&lonlat, render_scale, true); - let (mut cw, mut ch) = crate::render::layout::legend_size_mm(s.map(), render_scale, false, false, &[]); + let (mut cw, mut ch) = match crate::render::layout::legend_size_mm(s.map_mut(), render_scale, false, false, &[]) { + Some(size) => size, + None => { + // A complete source that can't be read: the export says why; the legend is sized by hand. + warnings.push("a layer's source couldn't be read through, so the legend has a fixed size; exporting says why".into()); + (fw * 0.3, fh * 0.25) + } + }; let listed = s.map().layers.iter().any(|l| s.map().shows(l) && !l.graphics && !l.is_raster()); if reading && listed { (cw, ch) = (cw.max(fw * 0.3), ch.max(fh * 0.25)); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9768d5970c..af8500520f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2408,7 +2408,18 @@ fn publication_layouts_fit_their_pages() { let one = s.project.layouts.iter().find(|l| l.name == "figure-1col").unwrap(); assert!(one.width == 90.0 && one.height > 90.0, "{} × {}", one.width, one.height); // Graticule steps and round scales. - use crate::cmd::layout::{capitals, grid_step, round_scale, step_text}; + use crate::cmd::layout::{capitals, datum_of, grid_step, round_scale, step_text}; + assert_eq!(datum_of("+proj=aea +lat_1=29.5 +datum=NAD83 +units=m").as_deref(), Some("NAD83")); + assert_eq!(datum_of("+proj=robin +ellps=WGS84").as_deref(), Some("WGS 84")); + assert_eq!(datum_of("+proj=eqearth +R=6371008.8").as_deref(), Some("a sphere")); + assert_eq!(datum_of("+proj=moll"), None); + // A preset on NAD83 says so, though its name holds no datum. + s.run("map.projection", &json!({"type": "usaAlbers"})).unwrap(); + s.run("layout.publication", &json!({"extent": [-100, 35, -90, 45]})).unwrap(); + let l = s.project.layouts.last().unwrap(); + let ElementKind::Text { text, .. } = &l.elements.iter().find(|e| e.name == "Reference").unwrap().kind else { panic!() }; + assert!(text.contains("Datum: NAD83"), "{text}"); + s.project.layouts.pop(); assert_eq!(capitals("Fontes, {date} e {pageName}"), "FONTES, {date} E {pageName}"); assert_eq!(capitals("Dados {2024 e {só} }"), "DADOS {2024 E {SÓ} }", "a lone or odd brace is text"); assert_eq!(grid_step(&rustgis_geom::Extent::new(10.0, 45.0, 11.0, 46.0)), 0.25); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 5aa66c83ab..19515e3e25 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -939,9 +939,11 @@ fn legend(pm: &mut Pixmap, r: Rect, map: &Map, title: &str, drawn: Option<&[(u32 /// The size a legend with no title takes, in mm (width, height): its rows as [`legend`] draws /// them, the classes a frame shows at the renderer's scale denominator `scale` (as the layout -/// finds it for a frame), or every class with `all_classes`. For sizing a legend to its content. -pub fn legend_size_mm(map: &Map, scale: f64, all_classes: bool, hide_other: bool, exclude: &[String]) -> (f64, f64) { - let drawn = (!all_classes).then(|| shown_legends(map, scale)); +/// finds it for a frame, a complete source read through as [`render`] reads it), or every class +/// with `all_classes`. For sizing a legend to its content. `None` when a complete source can't be +/// read, as [`render`] then draws no page. +pub fn legend_size_mm(map: &mut Map, scale: f64, all_classes: bool, hide_other: bool, exclude: &[String]) -> Option<(f64, f64)> { + let drawn = if all_classes { None } else { Some(complete_shown_legends(map, scale)?) }; let rows = legend_rows(map, drawn.as_deref(), &LegendOptions { hide_other, exclude }); let width = rows .iter() @@ -952,7 +954,7 @@ pub fn legend_size_mm(map: &Map, scale: f64, all_classes: bool, hide_other: bool }) .fold(0.0f32, f32::max); let mm = 25.4 / 96.0; - (f64::from(width) * mm, rows.len() as f64 * f64::from(LEGEND_ROW) * mm) + Some((f64::from(width) * mm, rows.len() as f64 * f64::from(LEGEND_ROW) * mm)) } /// The renderer's scale denominator for a frame showing `map` at paper scale 1:`scale` (the one @@ -1361,11 +1363,11 @@ mod tests { // every class. let row = f64::from(LEGEND_ROW) * 25.4 / 96.0; for (all_classes, ink) in [(false, shown), (true, all)] { - let (w, h) = legend_size_mm(&map, 1e6, all_classes, false, &[]); + let (w, h) = legend_size_mm(&mut map, 1e6, all_classes, false, &[]).unwrap(); let ink = f64::from(ink) * 25.4 / 96.0; assert!(w > 0.0 && ink <= h && h - ink < row, "{ink} mm drawn in {h} mm"); } - assert!((legend_size_mm(&map, 1e6, false, false, &[]).1 - 2.0 * row).abs() < 1e-9); + assert!((legend_size_mm(&mut map, 1e6, false, false, &[]).unwrap().1 - 2.0 * row).abs() < 1e-9); // A layer the legend leaves out (by name, any case) isn't listed, drawn or not. let name = map.layer(pts).unwrap().name.to_uppercase(); assert_eq!(depth_without(&map, Some(&drawn), false, std::slice::from_ref(&name)), 0, "its only drawn layer left out"); From aade8e4286f7243318fadc32e6f5a2d7e79c517d Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 09:44:03 -0300 Subject: [PATCH 10/22] layout.publication: a globe's default extent is the whole Earth; an empty author leaves the line out Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 25 +++++++++++++++++-------- crates/engine/src/tests.rs | 4 ++++ docs/user-guide/layouts.md | 2 +- 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 30cdad3fc7..680ee84c8a 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -29,7 +29,7 @@ pub fn commands() -> Vec { r#"{"name"?: string, "page"?: "letter"|"legal"|"tabloid"|"a5"|"a4"|"a3"|"a2"|"a1"|"a0", "orientation"?: "landscape"|"portrait", "width"?: mm, "height"?: mm, "template"?: "map" (frame, title, legend, north arrow, scale bar; the default)|"blank"}"#, ), C::new("layout.publication", "New Publication Layout", "Publish › Layout", publication).params( - r#"{"profile"?: "a4-portrait" (the default)|"a4-landscape"|"a3-portrait"|"a3-landscape"|"a2-portrait"|"a2-landscape" (a sheet: frame, title, subtitle, the map, a boxed footer)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"), "headings"?: [the sources' heading, the reference's heading]} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, + r#"{"profile"?: "a4-portrait" (the default)|"a4-landscape"|"a3-portrait"|"a3-landscape"|"a2-portrait"|"a2-landscape" (a sheet: frame, title, subtitle, the map, a boxed footer)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"; "" for none), "headings"?: [the sources' heading, the reference's heading]} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, ), C::new("layout.activate", "Open Layout", "Browser", |s, p| { let i = index(s, &by_name(p))?; @@ -472,6 +472,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { })?; let (sheet, page_w, page_h) = (profile.sheet, profile.width, profile.height); let extent = match p.get("extent").filter(|v| !v.is_null()) { + // The view; on a globe the whole Earth, as geoprocessing takes it (the globe camera's flat + // extent means nothing there). + None if s.map().projection.is_globe() => Extent::new(-180.0, -90.0, 180.0, 90.0), None => { let e = super::workspace::view_extent(s); Extent::new(e.min_x.max(-180.0), e.min_y.max(-90.0), e.max_x.min(180.0), e.max_y.min(90.0)) @@ -495,7 +498,11 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let sources = texts_of(p, "sources")?.unwrap_or_default(); let reference = texts_of(p, "reference")?.unwrap_or_else(|| vec!["Projection: {projection}".into(), "Datum: {datum} · Graticule: {grid}".into()]); - let author = one("author")?.unwrap_or_else(|| "Made with RustGIS · {date}".into()); + // An empty author leaves the line out; none given, the default. + let author = match p.get("author") { + Some(Value::String(t)) if t.trim().is_empty() => None, + _ => Some(one("author")?.unwrap_or_else(|| "Made with RustGIS · {date}".into())), + }; let headings = texts_of(p, "headings")?.unwrap_or_default(); let heading = |i: usize, or: &str| headings.get(i).cloned().unwrap_or_else(|| or.to_string()); let (projection, datum) = projection_and_datum(s); @@ -554,14 +561,16 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // The footer, from the bottom up: authorship, the note, then the two boxes side by side, // as tall as the longer column. let bottom = page_h - m - pad; - let author_lines = wrap(&author, iw, small_pt); + let author_lines = author.as_deref().map(|t| wrap(t, iw, small_pt)).unwrap_or_default(); let author_h = author_lines.len() as f64 * pitch(small_pt); let author_y = bottom - author_h; - around.push(( - "Author".into(), - (x0, author_y, iw, author_h), - pub_text(author_lines.join("\n"), small_pt, soft, false, TextAlign::Right), - )); + if !author_lines.is_empty() { + around.push(( + "Author".into(), + (x0, author_y, iw, author_h), + pub_text(author_lines.join("\n"), small_pt, soft, false, TextAlign::Right), + )); + } let note_lines = note.as_deref().map(|t| wrap(t, iw, body_pt)).unwrap_or_default(); let mut foot = author_y; if !note_lines.is_empty() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index af8500520f..5779658a7a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2377,6 +2377,10 @@ fn publication_layouts_fit_their_pages() { assert_eq!(listed.len(), l.elements.len()); assert!(listed.iter().any(|e| e["name"] == "Map Frame" && e["element"] == frame.id && e["kind"] == "mapFrame"), "{r}"); s.project.layouts.pop(); + // An empty author leaves the authorship out. + s.run("layout.publication", &json!({"extent": piaui, "author": ""})).unwrap(); + assert!(s.project.layouts.last().unwrap().elements.iter().all(|e| e.name != "Author")); + s.project.layouts.pop(); // With no sources, the reference alone takes the footer's width; no empty box beside it. s.run("layout.publication", &json!({"extent": piaui})).unwrap(); let l = s.project.layouts.last().unwrap(); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 5f3f61d3ed..e0b6efb6f5 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -31,7 +31,7 @@ the maps; while one is open, its groups lead the Publish tab: so none runs past it, and the footer grows to hold them. `{projection}`, `{datum}` and `{grid}` are filled from the map when the layout is made. `{date}` and the other dynamic text tokens stay live. The reference defaults to the projection, datum and graticule, and the - authorship to "Made with RustGIS · {date}". `headings` renames the two columns. + authorship to "Made with RustGIS · {date}" (`"author": ""` leaves it out). `headings` renames the two columns. - Every element is an ordinary one, to move or restyle afterwards. Running it again with another `profile` makes another layout of the same map. From d511f92219e92350850ee0e167f2ed23f1889823 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 09:48:07 -0300 Subject: [PATCH 11/22] layout.publication: a profile that isn't text is refused, not read as the default Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 5 ++++- crates/engine/src/tests.rs | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 680ee84c8a..caf095ffae 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -465,7 +465,10 @@ fn pub_box(fill: Rgba, outline: Rgba, width: f64) -> ElementKind { /// subtitle and a footer of two boxed columns (sources, cartographic reference) with a note and /// authorship under them, each text wrapped to its box with the layout's own font. fn publication(s: &mut Session, p: &Value) -> CmdResult { - let id = ps(p, "profile").unwrap_or("a4-portrait").trim().to_ascii_lowercase(); + let id = match p.get("profile").filter(|v| !v.is_null()) { + None => "a4-portrait".to_string(), + Some(v) => v.as_str().map(|t| t.trim().to_ascii_lowercase()).ok_or("profile is a profile's name, such as \"a4-portrait\"")?, + }; let profile = PUBLICATION_PROFILES.iter().find(|pr| pr.id == id).ok_or_else(|| { let names: Vec<&str> = PUBLICATION_PROFILES.iter().map(|pr| pr.id).collect(); format!("unknown profile '{id}': {}", names.join(", ")) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5779658a7a..23c60c22b9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2433,6 +2433,7 @@ fn publication_layouts_fit_their_pages() { // Refused: an unknown profile, a malformed extent, a footer that leaves the map no room. for (p, said) in [ (json!({"profile": "a5-portrait"}), "unknown profile"), + (json!({"profile": 5}), "profile is"), (json!({"extent": [10, 0, 5, 1]}), "extent is"), (json!({"extent": [10, 0, 11], "profile": "a4-portrait"}), "extent is"), (json!({"sources": vec![long; 40], "profile": "a4-landscape", "extent": piaui}), "no room"), From 156158dcd1cfb2fc38eb2c706584feb2ca51e0ff Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 09:53:36 -0300 Subject: [PATCH 12/22] layout.publication: the extent fits within the graticule's label strips; an empty author list leaves the line out too; the map sync noted to come after the last refusal Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 20 +++++++++++++------- crates/engine/src/tests.rs | 12 ++++++++---- docs/user-guide/layouts.md | 3 ++- 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index caf095ffae..a4f96e81e8 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -29,7 +29,7 @@ pub fn commands() -> Vec { r#"{"name"?: string, "page"?: "letter"|"legal"|"tabloid"|"a5"|"a4"|"a3"|"a2"|"a1"|"a0", "orientation"?: "landscape"|"portrait", "width"?: mm, "height"?: mm, "template"?: "map" (frame, title, legend, north arrow, scale bar; the default)|"blank"}"#, ), C::new("layout.publication", "New Publication Layout", "Publish › Layout", publication).params( - r#"{"profile"?: "a4-portrait" (the default)|"a4-landscape"|"a3-portrait"|"a3-landscape"|"a2-portrait"|"a2-landscape" (a sheet: frame, title, subtitle, the map, a boxed footer)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"; "" for none), "headings"?: [the sources' heading, the reference's heading]} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, + r#"{"profile"?: "a4-portrait" (the default)|"a4-landscape"|"a3-portrait"|"a3-landscape"|"a2-portrait"|"a2-landscape" (a sheet: frame, title, subtitle, the map, a boxed footer)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"; "" or [] for none), "headings"?: [the sources' heading, the reference's heading]} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, ), C::new("layout.activate", "Open Layout", "Browser", |s, p| { let i = index(s, &by_name(p))?; @@ -502,9 +502,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let reference = texts_of(p, "reference")?.unwrap_or_else(|| vec!["Projection: {projection}".into(), "Datum: {datum} · Graticule: {grid}".into()]); // An empty author leaves the line out; none given, the default. - let author = match p.get("author") { - Some(Value::String(t)) if t.trim().is_empty() => None, - _ => Some(one("author")?.unwrap_or_else(|| "Made with RustGIS · {date}".into())), + let author = match texts_of(p, "author")? { + None => Some("Made with RustGIS · {date}".to_string()), + Some(t) => Some(t.join(" ")).filter(|t| !t.trim().is_empty()), }; let headings = texts_of(p, "headings")?.unwrap_or_default(); let heading = |i: usize, or: &str| headings.get(i).cloned().unwrap_or_else(|| or.to_string()); @@ -660,9 +660,14 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { )); (page_w, h, (0.0, 0.0, page_w, fh)) }; - let (center, scale) = fit_scale(s.map(), &extent, fw, fh).ok_or("the extent can't be drawn on the map's projection")?; - let scale = round_scale(scale); + // The extent fits within the graticule's label strips (drawn inside the frame along its + // labelled edges), on both sides so it stays centred, and its labels cover none of it. let edges = GridEdges { top: sheet, bottom: true, left: true, right: sheet }; + let strip_w = if edges.left || edges.right { 2.0 * LABEL_ROOM_SIDE } else { 0.0 }; + let strip_h = if edges.top || edges.bottom { 2.0 * LABEL_ROOM_END } else { 0.0 }; + let (center, scale) = fit_scale(s.map(), &extent, (fw - strip_w).max(fw / 2.0), (fh - strip_h).max(fh / 2.0)) + .ok_or("the extent can't be drawn on the map's projection")?; + let scale = round_scale(scale); let grid = Grid { step, edges, ..Grid::default() }; let name = unique_name(s, ps(p, "name").unwrap_or("Publication")); let mut l = Layout::new(name.clone(), w, h); @@ -701,7 +706,8 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let (aw, ah) = if sheet { (8.0 * k, 12.0 * k) } else { (5.0, 7.5) }; l.add("North Arrow", (fx + fw - right - aw, fy + top, aw, ah), ElementKind::north_arrow(frame)); // The legend lists what the frame draws: its map synced to the frame's view first, as an - // export does, so a streamed layer has its features there. While one is still reading, the + // export does, so a streamed layer has its features there. (This changes the session's map, + // so it comes after the last refusal: nothing below fails.) While one is still reading, the // classes can't be known: the legend gets a fixed size, to fit by hand. Nothing drawn in the // frame, no legend. let render_scale = crate::render::layout::frame_render_scale(s.map(), center, scale); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 23c60c22b9..4c09ebd5b5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2321,7 +2321,9 @@ fn publication_layouts_fit_their_pages() { let unit = 10f64.powf(scale.log10().floor() - 1.0); assert!(((scale / unit) - (scale / unit).round()).abs() < 1e-6, "{profile}: 1:{scale}"); let extent = rustgis_geom::Extent::new(-46.8, -11.6, -38.5, -2.2); - let (_, fits) = rustgis_map::layout::fit_scale(s.map(), &extent, frame.w, frame.h).unwrap(); + // Fitted within the graticule's label strips (9 mm beside the frame's sides, 6 mm along its + // top and bottom), so the labels cover none of the extent. + let (_, fits) = rustgis_map::layout::fit_scale(s.map(), &extent, frame.w - 18.0, frame.h - 12.0).unwrap(); assert!(fits <= *scale && *scale < fits * 1.1, "{profile}: 1:{scale} for 1:{fits}"); assert_eq!(grid.step, 2.0, "{profile}: Piauí's 9.4° take a 2° graticule"); let text = |name: &str| { @@ -2378,9 +2380,11 @@ fn publication_layouts_fit_their_pages() { assert!(listed.iter().any(|e| e["name"] == "Map Frame" && e["element"] == frame.id && e["kind"] == "mapFrame"), "{r}"); s.project.layouts.pop(); // An empty author leaves the authorship out. - s.run("layout.publication", &json!({"extent": piaui, "author": ""})).unwrap(); - assert!(s.project.layouts.last().unwrap().elements.iter().all(|e| e.name != "Author")); - s.project.layouts.pop(); + for none in [json!(""), json!([]), json!([" "])] { + s.run("layout.publication", &json!({"extent": piaui, "author": none})).unwrap(); + assert!(s.project.layouts.last().unwrap().elements.iter().all(|e| e.name != "Author"), "{none}"); + s.project.layouts.pop(); + } // With no sources, the reference alone takes the footer's width; no empty box beside it. s.run("layout.publication", &json!({"extent": piaui})).unwrap(); let l = s.project.layouts.last().unwrap(); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index e0b6efb6f5..bcac1a7bb9 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -23,7 +23,8 @@ the maps; while one is open, its groups lead the Publish tab: datum under it, at 7 pt. A figure's title and sources belong in its caption, so they are left out, and the result says so. - **The map**: the `extent` given (or the view) fitted at a round scale, two significant - figures, rounded up so it still fits. A graticule has its step picked from the extent, at + figures, rounded up so it still fits within the strips the graticule's labels take inside + the frame. A graticule has its step picked from the extent, at most five lines across (2° for a state, 15′ for a city), and labels on every edge of a sheet. The north arrow, the legend (sized to what it lists) and the scale bar with the numeric scale under it sit in the frame's corners, on pale boxes, clear of the graticule's labels. From ec4c8321a3de6c11be781bfa37eda046ef59f146 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 09:58:12 -0300 Subject: [PATCH 13/22] Tests: layout.publication is undone as one command, the map as it was Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4c09ebd5b5..e0c35cccfd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2379,6 +2379,15 @@ fn publication_layouts_fit_their_pages() { assert_eq!(listed.len(), l.elements.len()); assert!(listed.iter().any(|e| e["name"] == "Map Frame" && e["element"] == frame.id && e["kind"] == "mapFrame"), "{r}"); s.project.layouts.pop(); + // Undone as one command: the layout goes, and the map is as it was (its layers, view and + // projection), the legend's sync of streamed layers included. + let (layouts, map) = (s.project.layouts.len(), s.map().clone()); + s.run("layout.publication", &json!({"extent": piaui})).unwrap(); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!(s.project.layouts.len(), layouts); + let ids = |m: &rustgis_map::Map| m.layers.iter().map(|l| (l.id, l.name.clone(), l.visible)).collect::>(); + assert_eq!(ids(s.map()), ids(&map)); + assert_eq!((s.map().projection.code(), s.map().camera.center), (map.projection.code(), map.camera.center)); // An empty author leaves the authorship out. for none in [json!(""), json!([]), json!([" "])] { s.run("layout.publication", &json!({"extent": piaui, "author": none})).unwrap(); From 775753f8f524df442deabefafe8d2f62bd2e1d24 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 10:03:52 -0300 Subject: [PATCH 14/22] Tests: a publication layout over a streamed layer is undone, the layer streaming as before; the legend's measured width against its ink. Docs: every publication text is measured and wrapped Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests.rs | 20 ++++++++++++++++++++ crates/render/src/layout.rs | 22 ++++++++++++++++++++-- docs/user-guide/layouts.md | 5 +++-- 3 files changed, 43 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e0c35cccfd..cbf0289a49 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5558,6 +5558,26 @@ fn a_streamed_layer_whose_file_goes_away_shows_an_error_not_stale_features() { assert!(l.source.as_ref().unwrap().error.is_some()); } +/// `layout.publication` over a streamed layer: the frame's view is read for its legend, which lists +/// the layer; undone, the layout goes and the layer is streaming from its source as before, +/// reading a view again when one is drawn. +#[test] +fn a_publication_layout_over_a_streamed_layer_is_undone() { + let path = grid_fgb("publication", 30); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path.display().to_string(), "stream": true})).unwrap(); + let r = s.run("layout.publication", &json!({"extent": [0, 0, 20, 20], "author": ""})).unwrap(); + assert!(s.project.layouts[0].elements.iter().any(|e| e.name == "Legend"), "the read layer is listed: {r}"); + s.run("edit.undo", &Value::Null).unwrap(); + assert!(s.project.layouts.is_empty()); + let l = &s.map().layers[0]; + assert!(l.source.as_ref().is_some_and(|src| src.error.is_none()), "still streaming from its source"); + let v = view_of(&mut s, rustgis_geom::Extent::new(0.0, 0.0, 20.0, 20.0)); + crate::render::render_png(s.map_mut(), &v).unwrap(); + assert!(!s.map().layers[0].dataset.features.is_empty(), "it reads the view again"); + let _ = std::fs::remove_file(path); +} + #[test] fn any_command_editing_a_streamed_layer_is_undone() { let path = grid_fgb("guarded", 30); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 19515e3e25..7e26d8564a 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -1362,10 +1362,28 @@ mod tests { // The size a legend takes holds what it draws, to within a row: two rows drawn, six with // every class. let row = f64::from(LEGEND_ROW) * 25.4 / 96.0; - for (all_classes, ink) in [(false, shown), (true, all)] { + // How far right the legend draws, in pixels (points at this scale), as `depth` goes down. + let reach = |map: &Map, drawn: Option<&[(u32, Vec)]>| { + let mut pm = Pixmap::new(300, 400).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + legend( + &mut pm, + Rect::from_xywh(0.0, 0.0, 300.0, 400.0).unwrap(), + map, + "", + drawn, + LegendOptions { hide_other: false, exclude: &[] }, + 1.0, + ); + (0..pm.width()).filter(|&x| (0..pm.height()).any(|y| pm.pixel(x, y).is_some_and(|p| p.red() < 200))).max().unwrap_or(0) + }; + for (all_classes, ink, right) in [(false, shown, reach(&map, Some(&drawn))), (true, all, reach(&map, None))] { let (w, h) = legend_size_mm(&mut map, 1e6, all_classes, false, &[]).unwrap(); - let ink = f64::from(ink) * 25.4 / 96.0; + let (ink, right) = (f64::from(ink) * 25.4 / 96.0, f64::from(right) * 25.4 / 96.0); assert!(w > 0.0 && ink <= h && h - ink < row, "{ink} mm drawn in {h} mm"); + // The widths in the same units as the drawing: the ink ends within the width measured, + // short of it by no more than a glyph's side bearing. + assert!(right <= w + 0.3 && right > w - 1.5, "{right} mm drawn across {w} mm"); } assert!((legend_size_mm(&mut map, 1e6, false, false, &[]).unwrap().1 - 2.0 * row).abs() < 1e-9); // A layer the legend leaves out (by name, any case) isn't listed, drawn or not. diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index bcac1a7bb9..a6e4119c28 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -28,8 +28,9 @@ the maps; while one is open, its groups lead the Publish tab: most five lines across (2° for a state, 15′ for a city), and labels on every edge of a sheet. The north arrow, the legend (sized to what it lists) and the scale bar with the numeric scale under it sit in the frame's corners, on pale boxes, clear of the graticule's labels. - - **Texts**: the footer's lines are measured with the layout's font and wrapped to their box, - so none runs past it, and the footer grows to hold them. `{projection}`, `{datum}` and + - **Texts**: the title, subtitle, footer lines and authorship are measured with the layout's + font (the title and headings bold, as drawn) and wrapped to their box, so none runs past it, + and each box grows to hold them. `{projection}`, `{datum}` and `{grid}` are filled from the map when the layout is made. `{date}` and the other dynamic text tokens stay live. The reference defaults to the projection, datum and graticule, and the authorship to "Made with RustGIS · {date}" (`"author": ""` leaves it out). `headings` renames the two columns. From 64b9b216d38c4e9623da1bf1bfe727d66ff887a9 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 10:08:03 -0300 Subject: [PATCH 15/22] layout.publication: the menu shows the layout's warnings; a frame too small for its label strips says so Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 3 +++ crates/ui-egui/src/ribbon.rs | 8 +++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index a4f96e81e8..02b5827982 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -665,6 +665,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let edges = GridEdges { top: sheet, bottom: true, left: true, right: sheet }; let strip_w = if edges.left || edges.right { 2.0 * LABEL_ROOM_SIDE } else { 0.0 }; let strip_h = if edges.top || edges.bottom { 2.0 * LABEL_ROOM_END } else { 0.0 }; + if fw - strip_w < fw / 2.0 || fh - strip_h < fh / 2.0 { + warnings.push("the frame is too small to keep its graticule's labels off the map's edges: they may cover them".into()); + } let (center, scale) = fit_scale(s.map(), &extent, (fw - strip_w).max(fw / 2.0), (fh - strip_h).max(fh / 2.0)) .ok_or("the extent can't be drawn on the map's projection")?; let scale = round_scale(scale); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index f39f0d47cc..1ba401ec8e 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -952,7 +952,13 @@ fn project_group(app: &mut RustGisApp, ui: &mut Ui) { } // The view's extent may not be known (an empty map): said, and the tab stays. match app.run("layout.publication", p) { - Ok(_) => app.ui.tab = "Publish".into(), + Ok(r) => { + // What the layout couldn't do as asked (a legend clipped, a layer still reading). + for w in r["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str()) { + app.session.notify(w.to_string(), false); + } + app.ui.tab = "Publish".into(); + } Err(e) => app.session.notify(e, true), } ui.close(); From 33fa29dc6c17244dc13726db001e8b72cc3e93fc Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 10:13:34 -0300 Subject: [PATCH 16/22] layout.publication: a figure says it left out an author and headings given to it Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 13 ++++++++++--- crates/engine/src/tests.rs | 6 ++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 02b5827982..3cabb5876c 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -627,9 +627,16 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { (page_w, page_h, (x0, frame_top, iw, frame_bottom - frame_top)) } else { // A figure: the map edge to edge, a line of the projection and datum under it. - for (field, given) in - [("title", title.is_some()), ("subtitle", subtitle.is_some()), ("sources", !sources.is_empty()), ("note", note.is_some())] - { + // Every text a figure leaves to its caption, given anyway, is said to be left out. + let asked = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); + for (field, given) in [ + ("title", title.is_some()), + ("subtitle", subtitle.is_some()), + ("sources", !sources.is_empty()), + ("note", note.is_some()), + ("author", asked("author")), + ("headings", !headings.is_empty()), + ] { if given { warnings.push(format!("{field} goes in the figure's caption, not on it: left out")); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cbf0289a49..33ccbb3235 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2388,6 +2388,12 @@ fn publication_layouts_fit_their_pages() { let ids = |m: &rustgis_map::Map| m.layers.iter().map(|l| (l.id, l.name.clone(), l.visible)).collect::>(); assert_eq!(ids(s.map()), ids(&map)); assert_eq!((s.map().projection.code(), s.map().camera.center), (map.projection.code(), map.camera.center)); + // A figure says it left out an author and headings given to it, as it does a title. + let r = + s.run("layout.publication", &json!({"profile": "figure-1col", "extent": piaui, "author": "Me", "headings": ["A", "B"]})).unwrap(); + let said = r["warnings"].to_string(); + assert!(said.contains("author goes") && said.contains("headings goes"), "{said}"); + s.project.layouts.pop(); // An empty author leaves the authorship out. for none in [json!(""), json!([]), json!([" "])] { s.run("layout.publication", &json!({"extent": piaui, "author": none})).unwrap(); From b7a2b9f640df624c19e7e3d891dcf7dd1ee5f135 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 10:19:49 -0300 Subject: [PATCH 17/22] Publication Layout menu: each profile's name a tl! literal, so the catalogs find it Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/ribbon.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 1ba401ec8e..d1d9ed9d09 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -944,7 +944,22 @@ fn project_group(app: &mut RustGisApp, ui: &mut Ui) { // A finished sheet or figure of the map view, its texts to fill in on the page. ui.menu_button(tl!("Publication Layout"), |ui| { for profile in rustgis_engine::cmd::layout::PUBLICATION_PROFILES { - if ui.button(tl!(profile.label)).clicked() { + // Each profile's name a literal here, so the catalogs find it. + let label = match profile.id { + "a4-portrait" => tl!("A4 portrait sheet"), + "a4-landscape" => tl!("A4 landscape sheet"), + "a3-portrait" => tl!("A3 portrait sheet"), + "a3-landscape" => tl!("A3 landscape sheet"), + "a2-portrait" => tl!("A2 portrait sheet"), + "a2-landscape" => tl!("A2 landscape sheet"), + "figure-1col" => tl!("Journal figure, 1 column (90 mm)"), + "figure-1.5col" => tl!("Journal figure, 1.5 columns (140 mm)"), + "figure-2col" => tl!("Journal figure, 2 columns (190 mm)"), + "thesis-full" => tl!("Thesis figure, full page (160 × 225 mm)"), + "thesis-half" => tl!("Thesis figure, half page (160 × 110 mm)"), + _ => tl!(profile.label), + }; + if ui.button(label).clicked() { // A sheet is titled with the map's name; a figure's title is its caption's. let mut p = json!({"profile": profile.id}); if profile.sheet { From fd56698e3ac7145d4aa9b29f0e483372bc4f8f97 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 10:23:00 -0300 Subject: [PATCH 18/22] Publication Layout menu: the profiles' literal names in one function, tested against the engine's labels Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/ribbon.rs | 44 ++++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index d1d9ed9d09..2d3b8c76e0 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -927,6 +927,25 @@ fn labeling_group(app: &mut RustGisApp, ui: &mut Ui) { }); } +/// A publication profile's name in the menu: a `tl!` literal each, so the catalogs find it (the +/// engine's labels, which it matches in English); `None` for a profile added without one. +fn publication_label(id: &str) -> Option<&'static str> { + Some(match id { + "a4-portrait" => tl!("A4 portrait sheet"), + "a4-landscape" => tl!("A4 landscape sheet"), + "a3-portrait" => tl!("A3 portrait sheet"), + "a3-landscape" => tl!("A3 landscape sheet"), + "a2-portrait" => tl!("A2 portrait sheet"), + "a2-landscape" => tl!("A2 landscape sheet"), + "figure-1col" => tl!("Journal figure, 1 column (90 mm)"), + "figure-1.5col" => tl!("Journal figure, 1.5 columns (140 mm)"), + "figure-2col" => tl!("Journal figure, 2 columns (190 mm)"), + "thesis-full" => tl!("Thesis figure, full page (160 × 225 mm)"), + "thesis-half" => tl!("Thesis figure, half page (160 × 110 mm)"), + _ => return None, + }) +} + fn project_group(app: &mut RustGisApp, ui: &mut Ui) { group(ui, "Project", |ui| { big(ui, app, "new_map", "New\nMap", "Add a new map to the project.", "map.new", Value::Null, false, false); @@ -944,21 +963,7 @@ fn project_group(app: &mut RustGisApp, ui: &mut Ui) { // A finished sheet or figure of the map view, its texts to fill in on the page. ui.menu_button(tl!("Publication Layout"), |ui| { for profile in rustgis_engine::cmd::layout::PUBLICATION_PROFILES { - // Each profile's name a literal here, so the catalogs find it. - let label = match profile.id { - "a4-portrait" => tl!("A4 portrait sheet"), - "a4-landscape" => tl!("A4 landscape sheet"), - "a3-portrait" => tl!("A3 portrait sheet"), - "a3-landscape" => tl!("A3 landscape sheet"), - "a2-portrait" => tl!("A2 portrait sheet"), - "a2-landscape" => tl!("A2 landscape sheet"), - "figure-1col" => tl!("Journal figure, 1 column (90 mm)"), - "figure-1.5col" => tl!("Journal figure, 1.5 columns (140 mm)"), - "figure-2col" => tl!("Journal figure, 2 columns (190 mm)"), - "thesis-full" => tl!("Thesis figure, full page (160 × 225 mm)"), - "thesis-half" => tl!("Thesis figure, half page (160 × 110 mm)"), - _ => tl!(profile.label), - }; + let label = publication_label(profile.id).unwrap_or_else(|| tl!(profile.label)); if ui.button(label).clicked() { // A sheet is titled with the map's name; a figure's title is its caption's. let mut p = json!({"profile": profile.id}); @@ -4348,6 +4353,15 @@ fn language_menu(app: &mut RustGisApp, ui: &mut Ui) { mod tests { use super::*; + /// Every publication profile has its literal name in the menu, the engine's label word for word + /// (the test runs in English), so neither can be renamed without the other. + #[test] + fn every_publication_profile_is_named_by_a_literal() { + for p in rustgis_engine::cmd::layout::PUBLICATION_PROFILES { + assert_eq!(publication_label(p.id), Some(p.label), "{}", p.id); + } + } + #[test] fn saved_hidden_tabs_never_hide_the_fixed_tabs() { let saved = ["Settings", "Help", "Edit", "Share", "Edit"].iter().map(|t| t.to_string()).collect(); From 7c82f9caf682df67a44cf3ac1df2ad5c9ec60760 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 10:28:10 -0300 Subject: [PATCH 19/22] layout.publication: a figure given an empty author doesn't warn it was left out Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 3 ++- crates/engine/src/tests.rs | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 3cabb5876c..0707c28d12 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -634,7 +634,8 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { ("subtitle", subtitle.is_some()), ("sources", !sources.is_empty()), ("note", note.is_some()), - ("author", asked("author")), + // An empty author asks for none: nothing left out. + ("author", asked("author") && author.is_some()), ("headings", !headings.is_empty()), ] { if given { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 33ccbb3235..261df72ef6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2394,6 +2394,9 @@ fn publication_layouts_fit_their_pages() { let said = r["warnings"].to_string(); assert!(said.contains("author goes") && said.contains("headings goes"), "{said}"); s.project.layouts.pop(); + let r = s.run("layout.publication", &json!({"profile": "figure-1col", "extent": piaui, "author": ""})).unwrap(); + assert!(!r["warnings"].to_string().contains("author"), "an empty author asks for none: {r}"); + s.project.layouts.pop(); // An empty author leaves the authorship out. for none in [json!(""), json!([]), json!([" "])] { s.run("layout.publication", &json!({"extent": piaui, "author": none})).unwrap(); From f587d2a1ebd6e42866195137fe08eb6664b86097 Mon Sep 17 00:00:00 2001 From: giswqs Date: Thu, 22 Oct 2026 09:39:18 -0400 Subject: [PATCH 20/22] Tests: read a publication heading's words across its wrapped lines Where the reference heading wraps depends on the font the machine finds: on CI it breaks between WEB and MERCATOR, so the test failed there although the heading was right. --- crates/engine/src/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 261df72ef6..a1db2b4838 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2421,7 +2421,8 @@ fn publication_layouts_fit_their_pages() { let l = s.project.layouts.last().unwrap(); let heading = l.elements.iter().find(|e| e.name == "Reference Heading").unwrap(); let ElementKind::Text { text, .. } = &heading.kind else { panic!() }; - assert!(text.contains("WEB MERCATOR") && !text.contains('{') && text.lines().count() >= 2, "{text}"); + // Where the wrap breaks depends on the font found, so the words are read across the lines. + assert!(text.replace('\n', " ").contains("WEB MERCATOR") && !text.contains('{') && text.lines().count() >= 2, "{text}"); // A live token in a heading keeps its case, so the layout still fills it when it draws. let sources = l.elements.iter().find(|e| e.name == "Sources Heading").unwrap(); let ElementKind::Text { text, .. } = &sources.kind else { panic!() }; From 97383717aab0a6ee95d82d0f790cbbbac0c2f9be Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 10:43:45 -0300 Subject: [PATCH 21/22] layout.publication: a figure's reference a millimetre in from the paper's edges; the menu's warnings in one notice Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 5 +++-- crates/ui-egui/src/ribbon.rs | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 0707c28d12..dbc1151120 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -643,7 +643,8 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } } let line = reference.iter().map(|t| fill(t)).collect::>().join(" · "); - let lines = wrap(&line, page_w, FIGURE_PT); + // A millimetre in from the paper's edges, which a journal may trim. + let lines = wrap(&line, page_w - 2.0, FIGURE_PT); if lines.len() > 1 { warnings.push("the reference is wider than the figure: it wraps under the map".into()); } @@ -663,7 +664,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let h = if page_h > 0.0 { page_h } else { (fh + note_h).ceil() }; around.push(( "Reference".into(), - (0.0, fh + 1.0, page_w, note_h - 1.0), + (1.0, fh + 1.0, page_w - 2.0, note_h - 1.0), pub_text(lines.join("\n"), FIGURE_PT, ink, false, TextAlign::Left), )); (page_w, h, (0.0, 0.0, page_w, fh)) diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 2d3b8c76e0..25db050de8 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -974,8 +974,9 @@ fn project_group(app: &mut RustGisApp, ui: &mut Ui) { match app.run("layout.publication", p) { Ok(r) => { // What the layout couldn't do as asked (a legend clipped, a layer still reading). - for w in r["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str()) { - app.session.notify(w.to_string(), false); + let said: Vec<&str> = r["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str()).collect(); + if !said.is_empty() { + app.session.notify(said.join("\n"), false); } app.ui.tab = "Publish".into(); } From bc0fcc67a341028999c79bec654b77931267593e Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 22 Oct 2026 12:00:58 -0300 Subject: [PATCH 22/22] =?UTF-8?q?layout.publication:=20text=20without=20to?= =?UTF-8?q?kens=20measured=20as=20it=20is;=20a=20graticule=20step=20under?= =?UTF-8?q?=20a=20minute's=20multiple=20in=20minutes=20and=20seconds=20(1?= =?UTF-8?q?=E2=80=B212=E2=80=B3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 9 ++++++++- crates/engine/src/tests.rs | 3 ++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index dbc1151120..3bb8298b45 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -364,7 +364,10 @@ pub(crate) fn step_text(step: f64) -> String { } else if (minutes - minutes.round()).abs() < 1e-9 { format!("{}′", minutes.round()) } else { - format!("{}″", (step * 3600.0).round()) + // Minutes and seconds (1′12″), or seconds alone under a minute. + let seconds = (step * 3600.0).round(); + let (m, sec) = ((seconds / 60.0).floor(), seconds % 60.0); + if m > 0.0 { format!("{m}′{sec}″") } else { format!("{sec}″") } } } @@ -515,6 +518,10 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // draws (`{date}`, `{scale}`…) as wide as a typical value of theirs. let (map_name, crs) = (s.map().name.clone(), s.map().projection.label()); let drawn = move |t: &str| { + // Most text has no token: measured as it is. + if !t.contains('{') { + return t.to_string(); + } [ ("{date}", "0000-00-00"), ("{time}", "00:00"), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1a437c9127..7cf6202592 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2451,7 +2451,8 @@ fn publication_layouts_fit_their_pages() { assert_eq!(capitals("Dados {2024 e {só} }"), "DADOS {2024 E {SÓ} }", "a lone or odd brace is text"); assert_eq!(grid_step(&rustgis_geom::Extent::new(10.0, 45.0, 11.0, 46.0)), 0.25); assert_eq!(grid_step(&rustgis_geom::Extent::new(-180.0, -90.0, 180.0, 90.0)), 30.0); - assert_eq!((step_text(2.0), step_text(0.25), step_text(0.02)), ("2°".to_string(), "15′".to_string(), "72″".to_string())); + assert_eq!((step_text(2.0), step_text(0.25), step_text(0.02)), ("2°".to_string(), "15′".to_string(), "1′12″".to_string())); + assert_eq!(step_text(0.01), "36″"); assert_eq!((round_scale(1_234_567.0), round_scale(4_500_000.0), round_scale(999.0)), (1_300_000.0, 4_500_000.0, 1_000.0)); // Refused: an unknown profile, a malformed extent, a footer that leaves the map no room. for (p, said) in [