diff --git a/crates/assistant/skills/print-layout/SKILL.md b/crates/assistant/skills/print-layout/SKILL.md index e19b32df9a..43b6254f28 100644 --- a/crates/assistant/skills/print-layout/SKILL.md +++ b/crates/assistant/skills/print-layout/SKILL.md @@ -8,7 +8,7 @@ description: Make a printable page layout — map frame, title, legend, north ar 1. Get the map right first: symbology, labels and extent. A layout's map frame shows the map's current view. 2. For a finished sheet or a figure for a paper in one step, use `layout.publication` with a `"profile"` (a page size alone, `"a4"`, `"letter"`, `"legal"`, `"tabloid"`, `"a5"` to `"a0"`, for a sheet turned to the area's shape, or with its orientation, `"a4-portrait"`, `"letter-landscape"`, … to choose; `"figure-1col"`, `"thesis-full"`, … for a figure), the `"extent"` - to fit, and the texts: `"title"`, `"subtitle"`, `"sources"`, `"note"`, a `"locator"` (`"globe"`: the visible polygon layers held in the project, not streamed ones, over the basemap; `"inset"`; `["inset", "globe"]`, both, the globe outlining the inset; or `"none"`; when omitted, `"globe"` on a sheet and `"none"` on a figure), and `"decimal": ","` for a map in a language with a decimal comma. A sheet's `"style"` arranges it: `"classic"` (the default), `"banner"`, `"panel"`, `"editorial"`, `"modular"`, `"poster"` (for a poster-like sheet), `"edge"` (the map from side to side of the page; it also takes `"paper"`, the page colour as `"#RRGGBB"`, `"kicker"`, a short line over the title, and `"figures"`, up to three `{"value", "label"}` under the map, whose texts may hold layer statistics such as `{count:Layer}`; `"panel"` takes `"figures"` too, stacked in its panel) or `"mosaic"` (a key map and 1 to 6 detail maps numbered on it, listed in `"panels"` as `[west, south, east, north]` in degrees; without `"extent"` the key map holds them all), with an `"accent"` colour as `"#RRGGBB"`. Its + to fit, and the texts: `"title"`, `"subtitle"`, `"sources"`, `"note"`, a `"locator"` (`"globe"`: the visible polygon layers held in the project, not streamed ones, over the basemap; `"inset"`; `["inset", "globe"]`, both, the globe outlining the inset; or `"none"`; when omitted, `"globe"` on a sheet and `"none"` on a figure), and `"decimal": ","` for a map in a language with a decimal comma. A sheet's `"style"` arranges it: `"classic"` (the default), `"banner"`, `"panel"`, `"editorial"`, `"modular"`, `"poster"` (for a poster-like sheet), `"edge"` (the map from side to side of the page; it also takes `"paper"`, the page colour as `"#RRGGBB"`, `"kicker"`, a short line over the title, and `"figures"`, up to three `{"value", "label"}` under the map, whose texts may hold layer statistics such as `{count:Layer}`; `"panel"` takes `"figures"` too, stacked in its panel) or `"mosaic"` (a key map and 1 to 6 detail maps numbered on it, listed in `"panels"` as `[west, south, east, north]` in degrees, or as `{"extent": …}` or `{"bookmark": "name"}` of the map, with a `"label"` on its number and a `"scale"` (1:N) if wanted; without `"extent"` the key map holds them all), with an `"accent"` colour as `"#RRGGBB"`. Its surrounds (locator, north arrow, legend, scale bar) start from an `"arrangement"` (`"classic"`, `"mirrored"`, `"legendRight"`, `"legendTop"`, or a corner for each; `"best"`, the default, tries the user's favourite, set with `layout.arrangement`, and the others), and one over the data moves to the freest place in the frame, the largest first (the legend, as a rule); read its `"arrangement"`, `"moved"` and `"warnings"`. It places the frame at a round scale, the graticule, legend (a long one in up to three columns: its own choice, though a legend takes up to six), scale bar and north arrow, and wraps the footer. `"grid"`, `"scaleBar"` and `"northArrow"` take `"none"` to leave that part out, or an object of its options (the grid's `"step"` or `"type"`, the bar's `"units"` or `"style"`, the arrow's `"style"`, `"fill"`, `"outline"` and `"show"`). Its result lists every element's id and name (`"elements"`), so skip to step 5 to adjust them. Otherwise, diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index e980b04523..5da2d96e3c 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -104,7 +104,7 @@ pub fn commands() -> Vec { r#""legend"?: "none" (no legend; a colorbar keeps its box, and the answer's "legendColumns" is null) | {"title"?: text, "columns"?: 1 to 6 (that many; the placement picks 1 to 3 otherwise), "exclude"?: [layer names] (left out besides the context ones)}, "#, r#""legendBox"?: "auto" (the default: over the map, the legend has no box where the map shows nothing under it but its light plain paper or water, with no layer, context, basemap shape or graticule line there and no veil; the answer's "legendBox" says whether it has one) | "always", "#, r#""style"?: "classic" (the default: the title over the map, the footer under it) | "banner" (the title and subtitle in a band of the accent colour across the top) | "panel" (the map at the left, a panel at the right with the title, locator, legend, sources and reference) | "editorial" (the title large in serif, a column at the right with the note, the locator and the legend) | "modular" (cards on a light page: the map, the locator and the legend each in one, the sources and reference in tinted ones) | "poster" (the page in the accent colour, the title in light text, the map in a light card, the footer in darker blocks) | "edge" (the map from one side of the page to the other with no border, a kicker and the title over it, the footer with no boxes under a thin rule) | "mosaic" (the classic sheet with its map area split into a key map, which takes the legend, scale bar, north arrow and locator, and a grid of detail maps that "panels" lists, each numbered as the key map numbers its outline) (a sheet's arrangement; figures leave it to the caption), "#, - r#""panels"?: 1 to 6 [west, south, east, north] in degrees (a mosaic sheet's detail maps, each fitted at a round scale; without "extent" the key map holds them all; "crs" doesn't apply to them), "#, + r#""panels"?: 1 to 6 [west, south, east, north] in degrees, or {"extent": [w, s, e, n] | "bookmark": a bookmark's name, "label"?: text (on the number's plate), "scale"?: N (1:N, centred on the extent)} (a mosaic sheet's detail maps, each fitted at a round scale unless given one; without "extent" the key map holds them all; "crs" doesn't apply to them), "#, r##""paper"?: "#RRGGBB" (an edge sheet's page colour, as layout.page's "color"; white by default; on a dark one its texts are light), "##, r#""kicker"?: text (an edge sheet's short line in spaced capitals over the title, in the accent colour), "#, r#""figures"?: up to three {"value": text, "label"?: text} (a sheet's headline figures: an edge sheet's in columns under the map, a panel sheet's stacked in its panel; a value may hold layer statistics such as {count:Layer}), "#, diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index 9c8695705a..057afd5f48 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -98,9 +98,13 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let (sheet, page_w, page_h) = (profile.sheet, profile.width, profile.height); let whole_globe = shows_whole_globe(s.map(), p); // Its error is raised once the style is known: another style is told panels isn't for it. - let panels = publication_panels(p); + let panels = publication_panels(s, p); let globe = s.map().projection.is_globe(); - let around_panels = panels.as_ref().ok().and_then(|p| p.as_deref()).map(|p| panels_extent(p, globe)); + let around_panels = panels + .as_ref() + .ok() + .and_then(|p| p.as_deref()) + .map(|p| panels_extent(&p.iter().map(|panel| panel.extent).collect::>(), globe)); // An extent in the map's own system (#3322): `plane` is that rectangle, framed as it is, and // `extent` only says how large it is in degrees. let in_own = match crate::cmd::imagery::crs_param(s, p, "crs")? { @@ -246,6 +250,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu .filter_map(|t| t.as_deref()) .chain(sources.iter().chain(&reference).chain(&headings).map(String::as_str)) .chain(headlines.iter().flat_map(|(value, label)| [Some(value), label.as_ref()]).flatten().map(String::as_str)) + .chain(panels.iter().filter_map(|panel| panel.label.as_deref())) .collect(); crate::render::layout::statistic_figures(s.map(), comma, &texts) }; @@ -1099,14 +1104,28 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let (inner_w, inner_h) = inner_frame((fw, fh), (room_side, room_end)); let (center, scale) = fit_frame(s.map(), &extent, rectangle.as_ref(), whole_globe, (inner_w, inner_h)) .ok_or("the extent can't be drawn on the map's projection")?; - let panel_views = panels - .iter() - .zip(&cells) - .enumerate() - .map(|(i, (e, &(.., w, h)))| { - fit_frame(s.map(), e, None, false, (w, h)).ok_or_else(|| format!("panels[{i}] can't be drawn on the map's projection")) - }) - .collect::, _>>()?; + let mut panel_views = Vec::with_capacity(panels.len()); + let mut too_small = Vec::new(); + for (i, (panel, &(.., w, h))) in panels.iter().zip(&cells).enumerate() { + let (panel_center, fitted) = fit_frame(s.map(), &panel.extent, None, false, (w, h)) + .ok_or_else(|| format!("panels[{i}] can't be drawn on the map's projection"))?; + // A scale given is kept, and said where it shows less than the panel's extent: nothing is + // cut without a word (#3579). + if let Some(scale) = panel.scale { + // `fit_scale` keeps a tenth of spare: a scale that shows the extent edge to edge holds it. + let holds = fit_scale(s.map(), &panel.extent, w, h) + .is_none_or(|(_, whole)| scale >= whole / rustgis_map::layout::FIT_MARGIN * (1.0 - 1e-9)); + if !holds { + too_small.push(format!("panels[{i}] at 1:{scale} (1:{fitted:.0} does)")); + } + } + panel_views.push((panel_center, panel.scale.unwrap_or(fitted))); + } + warnings.extend(panels_warning( + &too_small, + "is at a scale that doesn't show its whole extent", + "are at scales that don't show their whole extents", + )); // A name given past the limit is refused, as layout.new refuses it, not cut (#2639). let given = crate::cmd::within("name", "a layout's name", ps(p, "name").unwrap_or(PUBLICATION_NAME).trim(), crate::cmd::MAX_NAME)?; let (name, name_cut) = unique_name(s, "New Publication Layout", "the name given", &given); @@ -1142,7 +1161,8 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu }, ); if mosaic { - add_panels(&mut l, &s.map().name, frame, &cells, &panel_views, k, ink); + let labels: Vec> = panels.iter().map(|panel| panel.label.clone()).collect(); + warnings.extend(add_panels(&mut l, &s.map().name, frame, &cells, &panel_views, &labels, &drawn, k, ink)); } // Over the map, clear of the grid's labels (drawn inside the frame along its labelled // edges): the north arrow, the legend sized to what it lists, the scale bar with the numeric diff --git a/crates/engine/src/cmd/layout/publication/mosaic.rs b/crates/engine/src/cmd/layout/publication/mosaic.rs index 7f3b3a52ee..5ec2422e8f 100644 --- a/crates/engine/src/cmd/layout/publication/mosaic.rs +++ b/crates/engine/src/cmd/layout/publication/mosaic.rs @@ -11,17 +11,79 @@ const MAX_PANELS: usize = 6; pub(super) const KEY_MAP_SHARE: f64 = 0.55; /// What a mosaic sheet given no list of panels, or one of the wrong length, is told. -pub(super) const PANELS_WANTED: &str = "a mosaic sheet takes panels: a list of 1 to 6 extents, each [west, south, east, north] in degrees"; +pub(super) const PANELS_WANTED: &str = "a mosaic sheet takes panels: a list of 1 to 6 extents, each [west, south, east, north] in degrees, or an object with an \"extent\" or a \"bookmark\""; -/// The `"panels"` of a mosaic sheet; `None` when not given. -pub(super) fn publication_panels(p: &Value) -> Result>, String> { +/// The most characters a panel's label takes. +const MAX_LABEL: usize = 80; + +/// One detail map of a mosaic: what it shows, its label, and the scale it is drawn at when given +/// (#3579). +pub(super) struct Panel { + pub(super) extent: Extent, + pub(super) label: Option, + pub(super) scale: Option, +} + +/// The `"panels"` of a mosaic sheet; `None` when not given. Each is an extent `[west, south, east, +/// north]`, or an object with an `"extent"` or a `"bookmark"` (of the map), and a `"label"` and a +/// `"scale"` if it has them. +pub(super) fn publication_panels(s: &Session, p: &Value) -> Result>, String> { let Some(v) = p.get("panels").filter(|v| !v.is_null()) else { return Ok(None) }; let list = v.as_array().filter(|a| (1..=MAX_PANELS).contains(&a.len())).ok_or(PANELS_WANTED)?; - list.iter() - .enumerate() - .map(|(i, v)| degrees_extent(v).ok_or_else(|| format!("panels[{i}] is [west, south, east, north] in degrees"))) - .collect::>() - .map(Some) + list.iter().enumerate().map(|(i, v)| panel_of(s, i, v)).collect::>().map(Some) +} + +fn panel_of(s: &Session, i: usize, v: &Value) -> Result { + let bad_extent = || format!("panels[{i}] is [west, south, east, north] in degrees"); + let Some(o) = v.as_object() else { + return Ok(Panel { extent: degrees_extent(v).ok_or_else(bad_extent)?, label: None, scale: None }); + }; + let given = |key: &str| o.get(key).filter(|v| !v.is_null()); + let extent = match (given("extent"), given("bookmark")) { + (Some(e), None) => degrees_extent(e).ok_or_else(bad_extent)?, + (None, Some(b)) => bookmark_extent(s, i, b)?, + (None, None) => return Err(format!("panels[{i}] takes an \"extent\" or a \"bookmark\"")), + (Some(_), Some(_)) => return Err(format!("panels[{i}] takes an \"extent\" or a \"bookmark\", not both")), + }; + let label = match given("label") { + None => None, + Some(l) => { + let text = l.as_str().ok_or_else(|| format!("panels[{i}].label is text"))?; + // Whitespace, line breaks included, is one space: a break would make the label two lines. + let text = text.split_whitespace().collect::>().join(" "); + let text = crate::cmd::within(&format!("panels[{i}].label"), "a panel's label", &text, MAX_LABEL)?; + (!text.is_empty()).then_some(text) + } + }; + let scale = match given("scale") { + None => None, + Some(x) => { + let (low, high) = (rustgis_map::layout::MIN_FRAME_SCALE, rustgis_map::layout::MAX_FRAME_SCALE); + Some( + x.as_f64() + .filter(|x| (low..=high).contains(x)) + .ok_or_else(|| format!("panels[{i}].scale is a number from {low} to {high} (1:N)"))?, + ) + } + }; + Ok(Panel { extent, label, scale }) +} + +/// What the map's bookmark `name` covers, in degrees: its camera seen at the map view's size. +fn bookmark_extent(s: &Session, i: usize, name: &Value) -> Result { + let name = name.as_str().ok_or_else(|| format!("panels[{i}].bookmark is a bookmark's name"))?; + let map = s.map(); + let Some(mark) = map.bookmarks.iter().find(|b| b.name == name) else { + let there: Vec<&str> = map.bookmarks.iter().map(|b| b.name.as_str()).collect(); + let has = if there.is_empty() { "none".to_string() } else { there.join(", ") }; + return Err(format!("panels[{i}]: the map has no bookmark \"{name}\"; it has {has}")); + }; + let all = crate::cmd::workspace::camera_extent(map, &mark.camera, s.view_size); + let (west, south, east, north) = (all.min_x.max(-180.0), all.min_y.max(-90.0), all.max_x.min(180.0), all.max_y.min(90.0)); + if !(west < east && south < north) { + return Err(format!("panels[{i}]: the bookmark \"{name}\" shows no place on the Earth")); + } + Ok(Extent::new(west, south, east, north)) } /// The box around every panel with a tenth of it more on each side: the key map's extent when none @@ -87,8 +149,19 @@ pub(super) fn mosaic_cells((x, y, w, h): Cell, n: usize, gap: f64) -> (Cell, Vec } /// Adds each panel's frame in its cell at its view, numbers it in its top left corner on a white -/// plate, and has the key map `key` outline them all, numbered in the same order. -pub(super) fn add_panels(l: &mut Layout, map: &str, key: u32, cells: &[Cell], views: &[(Coord, f64)], k: f64, ink: Rgba) { +/// plate (widened to read "1 · label" for a panel with one), and has the key map `key` outline them +/// all, numbered in the same order. The warnings are those of the labels it had to cut or leave out. +pub(super) fn add_panels( + l: &mut Layout, + map: &str, + key: u32, + cells: &[Cell], + views: &[(Coord, f64)], + labels: &[Option], + drawn: &dyn Fn(&str) -> String, + k: f64, + ink: Rgba, +) -> Vec { let outlined: Vec = cells .iter() .zip(views) @@ -122,11 +195,28 @@ pub(super) fn add_panels(l: &mut Layout, map: &str, key: u32, cells: &[Cell], vi let (white, clear) = (Rgba::rgb(0xFF, 0xFF, 0xFF), Rgba::new(0, 0, 0, 0)); let line = crate::render::layout::line_pitch_mm(pt); let (w, h) = (6.0 * k, line + k); - for (i, &(x, y, ..)) in cells.iter().enumerate() { + let (mut cut, mut left_out) = (Vec::new(), Vec::new()); + for (i, &(x, y, cw, _)) in cells.iter().enumerate() { let (x, y, n) = (x + 1.5 * k, y + 1.5 * k, i + 1); - l.add(format!("Panel {n} Box"), (x, y, w, h), pub_box(white, clear, 0.0)); - let number = pub_text(Broken::from(vec![n.to_string()]), pt, ink, true, TextAlign::Center); - l.add(format!("Panel {n} Number"), (x, y + 0.5 * k, w, line), number); + // A label widens the plate to the text, as far as the cell leaves room (1.5 k each side). + let label = labels.get(i).and_then(|l| l.as_deref()); + let (text, plate, align) = match label.map(|l| fit_label(&format!("{n} · {l}"), cw - 3.0 * k, pt, 0.75 * k, drawn)) { + Some(Some((text, width, was_cut))) => { + if was_cut { + cut.push(format!("panels[{i}] \"{text}\"")); + } + (text, width.max(w), TextAlign::Left) + } + Some(None) => { + left_out.push(format!("panels[{i}]")); + (n.to_string(), w, TextAlign::Center) + } + None => (n.to_string(), w, TextAlign::Center), + }; + l.add(format!("Panel {n} Box"), (x, y, plate, h), pub_box(white, clear, 0.0)); + let number = pub_text(Broken::from(vec![text]), pt, ink, true, align); + let pad = if align == TextAlign::Left { 0.75 * k } else { 0.0 }; + l.add(format!("Panel {n} Number"), (x + pad, y + 0.5 * k, plate - 2.0 * pad, line), number); } if let Some(e) = l.element_mut(key) { e.kind.set_extent_indicators(outlined); @@ -134,6 +224,57 @@ pub(super) fn add_panels(l: &mut Layout, map: &str, key: u32, cells: &[Cell], vi *extent_numbers = true; } } + [ + panels_warning(&cut, "has its label cut to fit it", "have their labels cut to fit them"), + panels_warning(&left_out, "has a label that doesn't fit it, left out", "have labels that don't fit them, left out"), + ] + .into_iter() + .flatten() + .collect() +} + +/// One warning for the panels of one kind: how many, what is said of them, and which. +pub(super) fn panels_warning(who: &[String], one: &str, many: &str) -> Option { + match who { + [] => None, + [only] => Some(format!("1 panel {one}: {only}")), + _ => Some(format!("{} panels {many}: {}", who.len(), who.join(", "))), + } +} + +/// The plate text for `text` (measured as its tokens draw, by `drawn`) in bold `pt` points on one line +/// within `room` mm (less `pad` each side), with the width it takes and whether it was cut with "…"; `None` where not even its first +/// characters fit. +fn fit_label(text: &str, room: f64, pt: f64, pad: f64, drawn: &dyn Fn(&str) -> String) -> Option<(String, f64, bool)> { + let wide = room - 2.0 * pad; + let one_line = |s: &str, width: f64| { + crate::render::layout::wrapped_lines(&drawn(s), width, pt, true, rustgis_map::layout::FontFamily::Sans, TextAlign::Left).len() <= 1 + }; + // The narrowest width holding the text on one line, to a tenth of a millimetre. + let narrowest = |s: &str| { + let (mut low, mut high) = (0.0, wide); + while high - low > 0.1 { + let mid = (low + high) / 2.0; + if one_line(s, mid) { high = mid } else { low = mid } + } + high + }; + if wide <= 0.0 { + return None; + } + if one_line(text, wide) { + return Some((text.to_string(), narrowest(text) + 2.0 * pad, false)); + } + // Cut: the most characters that, with the ellipsis, still fit, never ending in half a `{token}`. + let chars: Vec = text.chars().collect(); + (1..chars.len()).rev().find_map(|n| { + let kept: String = chars[..n].iter().collect(); + if kept.rfind('{') > kept.rfind('}') { + return None; + } + let cut = format!("{}…", kept.trim_end()); + one_line(&cut, wide).then(|| (cut.clone(), narrowest(&cut) + 2.0 * pad, true)) + }) } /// The side (mm) of the square a number on the key map takes: a mosaic's one digit, drawn bold at diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index fc34b2fb04..8a8754dd70 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -502,9 +502,16 @@ pub fn view_extent(s: &Session) -> Extent { } /// The longitude/latitude extent a `size` view of map `m` shows. -pub fn view_extent_of(m: &rustgis_map::Map, (w, h): (f64, f64)) -> Extent { +pub fn view_extent_of(m: &rustgis_map::Map, size: (f64, f64)) -> Extent { + camera_extent(m, &m.camera, size) +} + +/// The longitude/latitude extent a `size` view through `camera` of map `m` shows: the places on a +/// grid of 9 × 9 points over it (enough for its footprint on a flat or a curved map), those with no +/// place on the Earth left out. +pub(crate) fn camera_extent(m: &rustgis_map::Map, camera: &rustgis_map::Camera, (w, h): (f64, f64)) -> Extent { let mut ll = Extent::EMPTY; - for c in places_in(m, m.camera.extent(w, h), 8) { + for c in places_in(m, camera.extent(w, h), 8) { ll.expand(c); } ll diff --git a/crates/engine/src/tests/layout_mosaic.rs b/crates/engine/src/tests/layout_mosaic.rs index dce69d7ff1..0685af985f 100644 --- a/crates/engine/src/tests/layout_mosaic.rs +++ b/crates/engine/src/tests/layout_mosaic.rs @@ -440,3 +440,240 @@ fn a_mosaic_with_no_band_clear_of_its_numbers_is_as_an_unveiled_one() { let placed = |s: &Session| elements(s).iter().map(|e| (e.name.clone(), e.x, e.y, e.w, e.h)).collect::>(); assert_eq!(placed(&s), placed(&off)); } + +// --- Panels with a label, a bookmark and a scale each (#3579) --- + +fn text_of(s: &Session, name: &str) -> String { + match &find(s, name).kind { + ElementKind::Text { text, .. } => text.clone(), + k => panic!("{name}: {k:?}"), + } +} + +/// The ground a panel's frame shows, in longitude/latitude: west, south, east, north. +fn shown_by(s: &Session, name: &str) -> [f64; 4] { + let e = find(s, name); + let ElementKind::MapFrame { center, scale, .. } = &e.kind else { panic!("{name} is no frame") }; + let pt = rustgis_map::layout::PT_PER_MM; + let cam = rustgis_map::layout::frame_camera(s.map(), *center, *scale, 0.0, 0.0); + let (w, h) = (e.w * pt, e.h * pt); + let (a, b) = (cam.to_map(0.0, 0.0, w, h), cam.to_map(w, h, w, h)); + let (a, b) = (s.map().to_lonlat(a).unwrap(), s.map().to_lonlat(b).unwrap()); + [a.x, b.y, b.x, a.y] +} + +fn same_frames(a: &Session, b: &Session) { + let frames = + |s: &Session| elements(s).iter().map(|e| (e.name.clone(), e.x, e.y, e.w, e.h, format!("{:?}", e.kind))).collect::>(); + assert_eq!(frames(a), frames(b)); +} + +#[test] +fn a_panel_given_as_an_object_with_its_extent_is_the_same_as_the_list() { + let (by_list, _) = sheet(json!({})); + let objects: Vec = PANELS.iter().map(|p| json!({"extent": p})).collect(); + let (by_object, _) = sheet(json!({"panels": objects})); + same_frames(&by_list, &by_object); +} + +#[test] +fn a_label_widens_its_panels_plate_and_follows_the_number() { + let (s, r) = sheet(json!({"panels": [{"extent": PANELS[0], "label": "Providencia"}, PANELS[1], PANELS[2]]})); + assert_eq!(text_of(&s, "Panel 1 Number"), "1 · Providencia"); + assert_eq!(text_of(&s, "Panel 2 Number"), "2"); + let (one, two) = (find(&s, "Panel 1 Box"), find(&s, "Panel 2 Box")); + assert!(one.w > two.w + 5.0 && (one.h - two.h).abs() < 1e-9, "{one:?} {two:?}"); + assert!(inside(one, find(&s, "Panel 1")) && inside(find(&s, "Panel 1 Number"), one)); + assert!(warnings(&r).iter().all(|w| !w.contains("label")), "{r}"); +} + +#[test] +fn a_label_wider_than_its_panel_is_cut_and_said() { + let long = "A very long place name ".repeat(3); + let (s, r) = sheet(json!({"panels": [{"extent": PANELS[0], "label": long}, PANELS[1]]})); + let text = text_of(&s, "Panel 1 Number"); + assert!(text.starts_with("1 · A very") && text.ends_with('…') && text.len() < long.len(), "{text}"); + assert!(inside(find(&s, "Panel 1 Box"), find(&s, "Panel 1"))); + assert!(warnings(&r).iter().any(|w| w.contains("panels[0]") && w.contains("label")), "{r}"); +} + +#[test] +fn an_empty_label_is_no_label() { + let (plain, _) = sheet(json!({})); + let objects: Vec = PANELS.iter().map(|p| json!({"extent": p, "label": " "})).collect(); + let (blank, _) = sheet(json!({"panels": objects})); + same_frames(&plain, &blank); + assert_eq!(text_of(&blank, "Panel 1 Number"), "1"); +} + +#[test] +fn a_bad_panel_object_is_named() { + let bad = [ + (json!({"label": "no place"}), "takes an \"extent\" or a \"bookmark\""), + (json!({"extent": PANELS[1], "bookmark": "Home"}), "not both"), + (json!({"extent": PANELS[1], "scale": 0}), "scale is a number from 0.5 to"), + (json!({"extent": PANELS[1], "scale": -5}), "scale is a number from 0.5 to"), + (json!({"extent": PANELS[1], "scale": "big"}), "scale is a number from 0.5 to"), + (json!({"extent": PANELS[1], "scale": 0.1}), "scale is a number from 0.5 to"), + (json!({"extent": PANELS[1], "scale": 1e20}), "scale is a number from 0.5 to"), + (json!({"extent": PANELS[1], "label": 5}), "label is text"), + (json!({"extent": PANELS[1], "label": "x".repeat(81)}), "81 characters"), + (json!({"extent": [0, 0, 0, 1]}), "is [west, south, east, north] in degrees"), + (json!({"bookmark": 7}), "bookmark is a bookmark's name"), + ]; + for (panel, said) in bad { + let mut s = world(); + let err = publish(&mut s, json!({"panels": [PANELS[0], panel]})).unwrap_err(); + assert!(err.contains("panels[1]") && err.contains(said), "{panel}: {err}"); + assert!(s.project.layouts.is_empty()); + } +} + +#[test] +fn a_bookmark_is_a_panel_showing_what_it_covers() { + let mut s = world(); + s.run("map.zoomToExtent", &json!({"extent": PANELS[0]})).unwrap(); + s.run("bookmark.add", &json!({"name": "Isla"})).unwrap(); + s.run("map.zoomToExtent", &json!({"extent": [-60.0, -30.0, -30.0, 5.0]})).unwrap(); + publish(&mut s, json!({"panels": [{"bookmark": "Isla"}, PANELS[1]]})).unwrap(); + let [w, so, e, n] = shown_by(&s, "Panel 1"); + let [pw, ps, pe, pn] = PANELS[0]; + assert!(w <= pw && so <= ps && e >= pe && n >= pn, "the panel shows {w} {so} {e} {n}, not all of the bookmark's place"); + // And not the whole map the view had when the sheet was made. + assert!(e - w < 20.0, "{w} {e}"); + assert_outlines(&s, 2); +} + +#[test] +fn a_bookmark_that_is_not_there_lists_the_ones_that_are() { + let mut s = world(); + s.run("bookmark.add", &json!({"name": "Isla"})).unwrap(); + s.run("bookmark.add", &json!({"name": "Puerto"})).unwrap(); + let err = publish(&mut s, json!({"panels": [PANELS[0], {"bookmark": "Playa"}]})).unwrap_err(); + assert!(err.contains("panels[1]") && err.contains("Playa") && err.contains("Isla") && err.contains("Puerto"), "{err}"); + assert!(s.project.layouts.is_empty()); +} + +#[test] +fn a_scale_puts_the_panel_at_that_scale_centred_on_its_extent() { + let (s, r) = sheet(json!({"panels": [{"extent": PANELS[0], "scale": 12_000_000}, PANELS[1], PANELS[2]]})); + assert_eq!(scale_of(find(&s, "Panel 1")), 12_000_000.0); + let [w, so, e, n] = shown_by(&s, "Panel 1"); + let [pw, ps, pe, pn] = PANELS[0]; + assert!(((w + e) / 2.0 - (pw + pe) / 2.0).abs() < 0.1 && ((so + n) / 2.0 - (ps + pn) / 2.0).abs() < 0.3, "{w} {so} {e} {n}"); + assert!(!warnings(&r).iter().any(|w| w.contains("panels[0]")), "{r}"); + // The others keep the scale they fit. + assert_ne!(scale_of(find(&s, "Panel 2")), 12_000_000.0); +} + +#[test] +fn a_scale_that_does_not_hold_the_extent_is_kept_and_said() { + let (s, r) = sheet(json!({"panels": [{"extent": PANELS[0], "scale": 100_000}, PANELS[1], PANELS[2]]})); + assert_eq!(scale_of(find(&s, "Panel 1")), 100_000.0); + assert!(warnings(&r).iter().any(|w| w.contains("panels[0]") && w.contains("1:100000")), "{r}"); +} + +#[test] +fn lists_objects_and_bookmarks_mix_in_order() { + let mut s = world(); + s.run("bookmark.add", &json!({"name": "Isla"})).unwrap(); + let r = publish( + &mut s, + json!({"panels": [PANELS[0], {"extent": PANELS[1], "label": "Dos"}, {"bookmark": "Isla", "label": "Tres", "scale": 30_000_000}]}), + ) + .unwrap(); + assert_outlines(&s, 3); + let texts: Vec = (1..=3).map(|i| text_of(&s, &format!("Panel {i} Number"))).collect(); + assert_eq!(texts, ["1", "2 · Dos", "3 · Tres"], "{r}"); + assert_eq!(scale_of(find(&s, "Panel 3")), 30_000_000.0); +} + +#[test] +fn objects_in_panels_of_another_style_get_the_error_of_a_list() { + let err = publish(&mut world(), json!({"style": "classic", "panels": [{"extent": PANELS[0]}]})).unwrap_err(); + assert!(err.contains("panels is for a sheet with \"style\": \"mosaic\""), "{err}"); +} + +#[test] +fn panels_with_a_cut_label_are_one_warning() { + let long = "A very long place name ".repeat(3); + let (_, r) = sheet(json!({"panels": [{"extent": PANELS[0], "label": long}, {"extent": PANELS[1], "label": long}, PANELS[2]]})); + let cut: Vec = warnings(&r).into_iter().filter(|w| w.contains("label")).collect(); + assert_eq!(cut.len(), 1, "{r}"); + assert!( + cut[0].starts_with("2 panels have their labels cut") && cut[0].contains("panels[0]") && cut[0].contains("panels[1]"), + "{cut:?}" + ); +} + +#[test] +fn panels_at_a_scale_that_does_not_hold_are_one_warning() { + let (_, r) = sheet(json!({"panels": [{"extent": PANELS[0], "scale": 100_000}, PANELS[1], {"extent": PANELS[2], "scale": 200_000}]})); + let said: Vec = warnings(&r).into_iter().filter(|w| w.contains("whole extent")).collect(); + assert_eq!(said.len(), 1, "{r}"); + assert!( + said[0].starts_with("2 panels are at scales") + && said[0].contains("panels[0] at 1:100000") + && said[0].contains("panels[2] at 1:200000"), + "{said:?}" + ); +} + +#[test] +fn a_label_with_a_line_break_is_one_line() { + let (s, r) = sheet(json!({"panels": [{"extent": PANELS[0], "label": "Ab\n cd"}, PANELS[1]]})); + assert_eq!(text_of(&s, "Panel 1 Number"), "1 · Ab cd"); + assert!(warnings(&r).iter().all(|w| !w.contains("panels[0]")), "{r}"); +} + +#[test] +fn a_scale_below_one_is_written_as_it_is() { + let (_, r) = sheet(json!({"panels": [{"extent": PANELS[0], "scale": 0.5}, PANELS[1]]})); + assert!(warnings(&r).iter().any(|w| w.contains("panels[0] at 1:0.5 (")), "{r}"); +} + +#[test] +fn a_scale_that_shows_the_extent_with_no_spare_is_not_said_not_to() { + let (first, _) = sheet(json!({})); + let cell = find(&first, "Panel 1"); + let [w, so, e, n] = PANELS[0]; + let (_, fit) = rustgis_map::layout::fit_scale(first.map(), &rustgis_geom::Extent::new(w, so, e, n), cell.w, cell.h).unwrap(); + // fit_scale keeps a tenth of spare: a scale a little under it still shows the extent whole. + let scale = (fit * 0.95).floor(); + let (s, r) = sheet(json!({"panels": [{"extent": PANELS[0], "scale": scale}, PANELS[1], PANELS[2]]})); + assert_eq!(scale_of(find(&s, "Panel 1")), scale); + assert!(!warnings(&r).iter().any(|w| w.contains("panels[0]")), "{scale} shows the whole extent: {r}"); +} + +#[test] +fn a_labels_tokens_are_measured_as_they_draw() { + // "{center}" is eight characters and draws nineteen: two of them are too wide for the panel. + let (s, r) = sheet(json!({"panels": [{"extent": PANELS[0], "label": "{center} {center}"}, PANELS[1], PANELS[2]]})); + assert!(warnings(&r).iter().any(|w| w.contains("panels[0]") && w.contains("cut")), "{r}"); + assert!(inside(find(&s, "Panel 1 Box"), find(&s, "Panel 1"))); + // Short enough as it draws: kept as typed. + let (s, r) = sheet(json!({"panels": [{"extent": PANELS[0], "label": "{center}"}, PANELS[1], PANELS[2]]})); + assert_eq!(text_of(&s, "Panel 1 Number"), "1 · {center}"); + assert!(!warnings(&r).iter().any(|w| w.contains("panels[0]")), "{r}"); +} + +#[test] +fn a_labels_layer_statistic_is_measured_as_the_figure_it_draws() { + // Three statistics are fifty-odd characters as typed and a few digits each as drawn. + let label = "{count:Countries} {count:Countries} {count:Countries}"; + let (s, r) = sheet(json!({"panels": [{"extent": PANELS[0], "label": label}, PANELS[1], PANELS[2]]})); + assert_eq!(text_of(&s, "Panel 1 Number"), format!("1 · {label}")); + assert!(!warnings(&r).iter().any(|w| w.contains("panels[0]")), "{r}"); +} + +#[test] +fn a_cut_label_never_ends_in_half_a_token() { + // Every cut of this label that the panel's width allows could land inside a "{center}". + for label in ["{center} {center} {center}", "ab{center}cd{center}{center}", "{count:Countries}{center}{center}", "a} {center} {center}"] + { + let (s, _) = sheet(json!({"panels": [{"extent": PANELS[0], "label": label}, PANELS[1], PANELS[2]]})); + let text = text_of(&s, "Panel 1 Number"); + // No `{` is left open: the last brace of the displayed text isn't an opening one. + assert!(text.rfind('{') <= text.rfind('}'), "{label}: {text}"); + } +} diff --git a/crates/map/src/layout/frame.rs b/crates/map/src/layout/frame.rs index c66fcf3f23..25bd01bef0 100644 --- a/crates/map/src/layout/frame.rs +++ b/crates/map/src/layout/frame.rs @@ -9,6 +9,9 @@ pub const MIN_FRAME_SCALE: f64 = 0.5; /// The smallest: the whole world many times over. pub const MAX_FRAME_SCALE: f64 = 1e10; +/// The spare [`fit_scale`] leaves around what it fits: a tenth more ground than the extent's. +pub const FIT_MARGIN: f64 = 1.1; + /// The outline of a map frame. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub enum FrameShape { @@ -161,7 +164,7 @@ pub fn fit_scale_plane(map: &Map, ext: &rustgis_geom::Extent, w_mm: f64, h_mm: f // A lone point gets a metre around it; anything larger fits as it is, down to a find a // millimetre across (#902). Ground metres, whatever the projection's units. let floor_m = if ext.width() > 0.0 || ext.height() > 0.0 { 1e-3 } else { 1.0 }; - let (gw, gh) = ((ext.width() * per).max(floor_m) * 1.1, (ext.height() * per).max(floor_m) * 1.1); + let (gw, gh) = ((ext.width() * per).max(floor_m) * FIT_MARGIN, (ext.height() * per).max(floor_m) * FIT_MARGIN); let scale = (gw / (w_mm / 1000.0)).max(gh / (h_mm / 1000.0)); Some((center, scale.clamp(MIN_FRAME_SCALE, MAX_FRAME_SCALE))) } diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 2b14605d88..8fc0c2a8b6 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -294,10 +294,18 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu **Extent indicators**). Without `"extent"` the key map holds every panel with a little room around them; the panels whose middle lies outside what the key map shows, which it can't number, are named in one warning. Panels stay in degrees where `"extent"` is given with `"crs"`. + A panel may also be an object: `{"extent": [w, s, e, n]}` or `{"bookmark": "name"}` (what that + bookmark of the map covers, as a map view of the app's size shows it: the sheet can differ + where the view's size does), with a `"label"` and a `"scale"` if it + has them. A label widens the number's plate to read "1 · Name" (cut with "…", and said, where + the panel has no room for it all), and a scale puts the panel at 1:N, centred on its extent + (kept, and said, where it doesn't show the whole extent). A bad one is an error naming + `panels[i]`. ``` layout.publication={"profile": "a4-landscape", "style": "mosaic", "title": "Three study areas", - "panels": [[-46, -11, -43, -8], [-42, -8, -39, -5], [-45, -5, -42, -2]]} + "panels": [[-46, -11, -43, -8], {"extent": [-42, -8, -39, -5], "label": "Delta"}, + {"bookmark": "Port", "scale": 5000000}]} ``` - Every element is an ordinary one, to move or restyle afterwards. The command returns element IDs for `layout.update`, and `warnings`. Running it again with another `profile` makes