diff --git a/crates/assistant/skills/print-layout/SKILL.md b/crates/assistant/skills/print-layout/SKILL.md index dc333973c8..dc50a1f281 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) or `"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), 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; 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/command-surface.txt b/crates/engine/command-surface.txt index 2b08e43ad5..0d773b1749 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -298,7 +298,7 @@ layout.import path? text? layout.move name? layout? to layout.new name? page? orientation? width? height? template? layout.page layout? page? orientation? width? height? decimal? color? -layout.publication profile? extent? crs? name? title? subtitle? sources? reference? note? author? headings? locator? decimal? colorbar? veil? contextInLegend? northArrow? grid? scaleBar? legend? legendBox? style? paper? kicker? figures? accent? arrangement? coverage? +layout.publication profile? extent? crs? name? title? subtitle? sources? reference? note? author? headings? locator? decimal? colorbar? veil? contextInLegend? northArrow? grid? scaleBar? legend? legendBox? style? panels? paper? kicker? figures? accent? arrangement? coverage? layout.remove name? layout? layout.removeElement layout? element layout.rename name? layout? newName diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 2a230aa271..2905f920ae 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -102,7 +102,8 @@ pub fn commands() -> Vec { r#""scaleBar"?: "none" | {a scale bar's options as layout.update takes them: style, units, divisions, color, fill, textSize, decimals, subdivisions, divisionsBeforeZero, labelPosition, unitLabel, unitLabelPosition, fit; textSize in points as given, not scaled with the sheet} (none on a globe shown whole, whatever is asked), "#, 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) (a sheet's arrangement; figures leave it to the caption), "#, + 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##""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/area.rs b/crates/engine/src/cmd/layout/publication/area.rs index 2c38ae8ba0..ff0ffc608c 100644 --- a/crates/engine/src/cmd/layout/publication/area.rs +++ b/crates/engine/src/cmd/layout/publication/area.rs @@ -51,6 +51,14 @@ pub(super) fn in_map_system(s: &Session, extent: Option<&Value>, crs: Crs) -> Re Ok((size_in_degrees(map, plane, center, &places), plane)) } +/// An extent in degrees: four numbers, west of east and south of north, within the world's. +pub(super) fn degrees_extent(v: &Value) -> Option { + match four_sides(v) { + Some([w, so, e, n]) if w < e && so < n && w >= -180.0 && e <= 180.0 && so >= -90.0 && n <= 90.0 => Some(Extent::new(w, so, e, n)), + _ => None, + } +} + /// The four numbers of an `extent`, when it is a list of four finite ones. pub(super) fn four_sides(extent: &Value) -> Option<[f64; 4]> { let sides: Vec = extent.as_array()?.iter().map(|x| x.as_f64().filter(|x| x.is_finite())).collect::>()?; diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index 6d72deb26f..2ebe40df51 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -8,6 +8,8 @@ mod arrangement; pub use arrangement::*; mod coverage; pub(in crate::cmd::layout) use coverage::*; +mod mosaic; +use mosaic::*; mod parts; use parts::*; mod placement; @@ -64,6 +66,12 @@ pub(in crate::cmd::layout) fn landscape_suits(aspect: f64, short: f64, long: f64 let sides = if style == Style::Edge { 0.0 } else { 30.0 * k }; let (iw, ih) = (w - sides, h - texts); let fw = if style.has_column() { 0.68 * iw } else { iw }; + // A mosaic's map is its key map, which takes a share of the area's longer side. + let (fw, ih) = match style { + Style::Mosaic if fw >= ih => (KEY_MAP_SHARE * fw, ih), + Style::Mosaic => (fw, KEY_MAP_SHARE * ih), + _ => (fw, ih), + }; let (fw, fh) = (fw - 2.0 * LABEL_ROOM_SIDE * k, ih - 2.0 * LABEL_ROOM_END * k); fw.min(fh / aspect.max(1e-6)) }; @@ -89,18 +97,24 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let (auto, profile) = publication_profile(p)?; 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 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)); // 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")? { Some(crs) => Some(in_map_system(s, p.get("extent"), crs)?), None => None, }; - let extent = match (in_own, p.get("extent").filter(|v| !v.is_null())) { - (Some((size, _)), _) => size, + let extent = match (in_own, p.get("extent").filter(|v| !v.is_null()), around_panels) { + (Some((size, _)), ..) => size, + // A mosaic's key map: all its panels. + (None, None, Some(around)) => around, // The view; on a globe the whole Earth, as geoprocessing takes it (the globe camera's flat // extent means nothing there). - (None, None) if whole_globe => Extent::new(-180.0, -90.0, 180.0, 90.0), - (None, None) => { + (None, None, None) if whole_globe => Extent::new(-180.0, -90.0, 180.0, 90.0), + (None, None, None) => { let e = crate::cmd::workspace::view_extent(s); let e = 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)); if !(e.width() > 0.0 && e.height() > 0.0) { @@ -108,10 +122,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu } e } - (None, Some(v)) => match four_sides(v) { - 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()), - }, + (None, Some(v), _) => degrees_extent(v).ok_or("extent is [west, south, east, north] in degrees")?, }; let rectangle = in_own.map(|(_, plane)| plane); // Where the area lies on the map's projection, which shapes the page and the veil: the rectangle @@ -146,7 +157,9 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu None => Style::Classic, Some(raw) => Style::parse(raw).ok_or_else(|| { let x = raw.trim(); - format!("style is \"classic\", \"banner\", \"panel\", \"editorial\", \"modular\", \"poster\" or \"edge\", not \"{x}\"") + format!( + "style is \"classic\", \"banner\", \"panel\", \"editorial\", \"modular\", \"poster\", \"edge\" or \"mosaic\", not \"{x}\"" + ) })?, }; let accent = color(p, "accent", style.accent())?; @@ -164,6 +177,16 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu if !(edge || sheet && style == Style::Panel) && given("figures") { return Err("figures is for a sheet with \"style\": \"edge\" or \"panel\"".into()); } + let mosaic = sheet && style == Style::Mosaic; + if !mosaic && given("panels") { + return Err( + if sheet { "panels is for a sheet with \"style\": \"mosaic\"" } else { "panels is for a sheet: a figure takes none" }.into() + ); + } + let panels = match panels? { + None if mosaic => return Err(PANELS_WANTED.into()), + panels => panels.unwrap_or_default(), + }; // White is the page's own colour, kept as none, as `layout.page` keeps it. let page_colour = crate::cmd::opaque_color(p, "paper")?.flatten().filter(|c| *c != Rgba::rgb(0xFF, 0xFF, 0xFF)); let kicker = one("kicker")?; @@ -517,7 +540,8 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let (card_r, card_pad) = (3.0 * k, 2.5 * k); let card_line = Rgba::new(0x2B, 0x26, 0x20, 60); match style { - Style::Classic => { + // A mosaic is a classic sheet whose map area is split once it is laid out. + Style::Classic | Style::Mosaic => { let mut top = m + pad; if let Some(t) = &title { let lines = broken(t, iw, title_pt, true, TextAlign::Center, FontFamily::Sans); @@ -1062,6 +1086,10 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu } else { (fy, column, h) }; + // A mosaic's key map takes part of the map's area, and all that follows places the surrounds + // on it; its panels take the rest. + let ((fx, fy, fw, fh), cells) = + if mosaic { mosaic_cells((fx, fy, fw, fh), panels.len(), 3.0 * k) } else { ((fx, fy, fw, fh), Vec::new()) }; // The extent fits within the grid'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 (strip_w, strip_h) = (2.0 * room_side, 2.0 * room_end); @@ -1071,6 +1099,14 @@ 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::, _>>()?; // 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); @@ -1105,6 +1141,9 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu pitch: 0.0, }, ); + if mosaic { + add_panels(&mut l, &s.map().name, frame, &cells, &panel_views, 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 // scale under it, and the locator, each on a pale box. Each takes the corner where it covers @@ -1735,6 +1774,8 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // and size, each surround's place, the ones moved, and the area (mm²) of those moved and of what // still covers the drawing. type Laid = (Option<(usize, f64, f64)>, Vec<(Surround, Rect)>, Vec<&'static str>, (f64, f64)); + // Where a mosaic's key map numbers its panels: taken before any surround is placed. + let numbers = number_zones(s.map(), center, scale, (fx, fy, fw, fh), &cells, &panel_views); let lay_out = |homes: Homes, legend: (f64, f64)| -> Laid { let corner_of = |what: Surround| { surrounds.iter().find(|(kind, ..)| *kind == what).map(|&(kind, w, h)| { @@ -1760,7 +1801,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let mut order: Vec = (0..spots.len()).collect(); order.sort_by(|&a, &b| (spots[b].1.2 * spots[b].1.3).total_cmp(&(spots[a].1.2 * spots[a].1.3))); let mut moved: Vec<&'static str> = Vec::new(); - let mut settled: Vec = Vec::new(); + let mut settled: Vec = numbers.iter().map(|n| n.1).collect(); for i in order { let (kind, home) = spots[i]; let here = covered(home); @@ -1790,7 +1831,9 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let cut = if lost > 1.0 { fw * fh / 2.0 + 10.0 * lost } else { 0.0 }; // Surrounds left over each other (nowhere clear for one a larger one's corner took) cost ten // times their overlap, so an arrangement that keeps them apart wins. - let clash = 10.0 * overlap_area(&spots.iter().map(|(_, r)| *r).collect::>()); + // A panel's number left under one costs the same. + let hidden: f64 = numbers.iter().flat_map(|n| spots.iter().map(|(_, r)| overlap_area(&[n.1, *r]))).sum(); + let clash = 10.0 * (overlap_area(&spots.iter().map(|(_, r)| *r).collect::>()) + hidden); (legend_at, spots, moved, (shifted + dropped + cut + clash, over)) }; // Each arrangement tried laid out, and one picked ([`pick_arrangement`]): the least area moved @@ -1847,10 +1890,20 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // it no room. let mut arrangement_used = tries.iter().find(|(_, h)| *h == homes).map_or_else(|| arrangement_name(homes).to_string(), |(n, _)| n.clone()); - if let (Some(clip), Some(known)) = (veiled, sizes) - && let Some((i, (legend_place, locator_place, arrow_place, scale_place))) = - grouped(clip, 0, &known, scale_box(ground_per_pt(s, center, scale), scale)) + let mut group = veiled + .zip(sizes) + .and_then(|(clip, known)| grouped(clip, 0, &known, scale_box(ground_per_pt(s, center, scale), scale)).map(|g| (g, known))); + // A group that would hide a panel's number isn't taken, nor the map veiled for it: the corners, + // which keep off the numbers, stay. + if let Some(((_, (legend_place, locator_place, arrow_place, scale_place)), _)) = &group + && [Some(*legend_place), *locator_place, *arrow_place, Some(*scale_place)] + .iter() + .flatten() + .any(|place| numbers.iter().any(|n| overlap_area(&[n.1, *place]) > 0.0)) { + (group, veiled) = (None, None); + } + if let Some(((i, (legend_place, locator_place, arrow_place, scale_place)), known)) = group { legend_cols = i + 1; (cw, ch) = known[i]; for (kind, place) in [ @@ -1908,6 +1961,10 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu } l.add("Extent Outline", (x0, y0, x1 - x0, y1 - y0), pub_card(Rgba::new(0, 0, 0, 0), Rgba::rgb(0x2B, 0x26, 0x20), 0.8, 0.0)); } + // A surround with nowhere else to go may still hide one: said. + let covers: Vec<(&str, Rect)> = spots.iter().map(|(kind, r)| (named(*kind), *r)).collect(); + warnings.extend(covered_numbers_warning(&numbers, &covers)); + warnings.extend(unnumbered_panels_warning(&numbers, panels.len())); if surrounds.iter().any(|x| x.0 == Surround::Legend) && !spots.iter().any(|(kind, _)| *kind == Surround::Legend) { warnings.push( "the frame leaves the legend no room beside the locator, so it is left out: give the map more room, or set \"locator\": \"none\"" @@ -2401,7 +2458,8 @@ pub(in crate::cmd::layout) fn publication_veil(p: &Value) -> Result bool { - map.projection.is_globe() && p.get("extent").is_none_or(Value::is_null) + // A mosaic's panels say what its key map shows, as an extent does. + map.projection.is_globe() && ["extent", "panels"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) } /// How much of the frame, inside its graticule's label strips, a globe seen whole spans: a little diff --git a/crates/engine/src/cmd/layout/publication/mosaic.rs b/crates/engine/src/cmd/layout/publication/mosaic.rs new file mode 100644 index 0000000000..2c4c94ce7f --- /dev/null +++ b/crates/engine/src/cmd/layout/publication/mosaic.rs @@ -0,0 +1,227 @@ +//! A mosaic sheet (#3513): its map area split into a key map and a grid of detail frames, each +//! numbered as the key map numbers its outline. + +use super::*; +use rustgis_map::layout::ExtentIndicator; + +/// The most panels a mosaic takes: past six, A4's cells are too small to read. +const MAX_PANELS: usize = 6; + +/// The share of the map area's longer side the key map takes. +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"; + +/// The `"panels"` of a mosaic sheet; `None` when not given. +pub(super) fn publication_panels(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) +} + +/// The box around every panel with a tenth of it more on each side: the key map's extent when none +/// is given. On the globe, whose far side is hidden, its longitudes are the shortest run holding +/// every panel, which may go on past 180°. +pub(super) fn panels_extent(panels: &[Extent], globe: bool) -> Extent { + let mut all = Extent::EMPTY; + for e in panels { + all.expand(Coord::new(e.min_x, e.min_y)); + all.expand(Coord::new(e.max_x, e.max_y)); + } + // A run starting at a panel's west edge, those west of it taken a turn of the globe on. + let run = |from: f64| { + let east = panels.iter().map(|e| if e.min_x < from { e.max_x + 360.0 } else { e.max_x }).fold(from, f64::max); + (from, east) + }; + let across = panels.iter().map(|e| run(e.min_x)).min_by(|a, b| (a.1 - a.0).total_cmp(&(b.1 - b.0))); + let (west, east, limit) = match across { + // Not cut: past 360° it still centres the run. + Some((west, east)) if globe && east - west < all.width() => (west, east, f64::INFINITY), + _ => (all.min_x, all.max_x, 180.0), + }; + let (x, y) = ((east - west) / 10.0, all.height() / 10.0); + Extent::new((west - x).max(-limit), (all.min_y - y).max(-90.0), (east + x).min(limit), (all.max_y + y).min(90.0)) +} + +/// A rectangle on the page: x, y, width and height in millimetres. +type Cell = (f64, f64, f64, f64); + +/// The map area split for `n` panels, `gap` mm apart: the key map at its left on a wide area, at its +/// top on a tall one, and the panels in the rest, in rows. The grid is the one whose cells are the +/// nearest to square, weighed by the cells it would leave empty; a last row with fewer panels shares +/// its width among them, so none of the area is left blank. +pub(super) fn mosaic_cells((x, y, w, h): Cell, n: usize, gap: f64) -> (Cell, Vec) { + let (key, (rx, ry, rw, rh)) = if w >= h { + let kw = KEY_MAP_SHARE * w; + ((x, y, kw, h), (x + kw + gap, y, w - kw - gap, h)) + } else { + let kh = KEY_MAP_SHARE * h; + ((x, y, w, kh), (x, y + kh + gap, w, h - kh - gap)) + }; + let width = |cols: usize| (rw - gap * (cols - 1) as f64) / cols as f64; + let height = |cols: usize| { + let rows = n.div_ceil(cols); + (rh - gap * (rows - 1) as f64) / rows as f64 + }; + // How far from square (the longer side over the shorter), by the grid's cells per panel. + let cost = |cols: usize| { + let (w, h) = (width(cols), height(cols)); + let oblong = if w > 0.0 && h > 0.0 { (w / h).max(h / w) } else { f64::INFINITY }; + oblong * (cols * n.div_ceil(cols)) as f64 / n as f64 + }; + let cols = (1..=n.max(1)).min_by(|&a, &b| cost(a).total_cmp(&cost(b))).unwrap_or(1); + let ch = height(cols); + let cells = (0..n) + .map(|i| { + let in_row = cols.min(n - i / cols * cols); + let cw = width(in_row); + (rx + (i % cols) as f64 * (cw + gap), ry + (i / cols) as f64 * (ch + gap), cw, ch) + }) + .collect(); + (key, cells) +} + +/// 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) { + let outlined: Vec = cells + .iter() + .zip(views) + .enumerate() + .map(|(i, (&cell, &(center, scale)))| { + let of = l.add( + format!("Panel {}", i + 1), + cell, + ElementKind::MapFrame { + map: map.to_string(), + center, + scale, + shape: FrameShape::Rectangle, + grid: None, + sections: Vec::new(), + extent_of: None, + extent_color: rustgis_map::layout::INDICATOR_COLOR, + extent_width: rustgis_map::layout::INDICATOR_WIDTH, + more_extents: Vec::new(), + extent_numbers: false, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }, + ); + ExtentIndicator { of, color: rustgis_map::layout::INDICATOR_COLOR, width: rustgis_map::layout::INDICATOR_WIDTH } + }) + .collect(); + let pt = 10.0 * k; + 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 (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); + } + if let Some(e) = l.element_mut(key) { + e.kind.set_extent_indicators(outlined); + if let ElementKind::MapFrame { extent_numbers, .. } = &mut e.kind { + *extent_numbers = true; + } + } +} + +/// The side (mm) of the square a number on the key map takes: a mosaic's one digit, drawn bold at +/// about 13 points, with its halo. +const NUMBER_ZONE_MM: f64 = 6.0; + +/// The square around each panel's number on the key map, in page millimetres, with the panel's +/// number: no surround goes there. The key map is at `center` and `scale`, in `key` on the page. +pub(super) fn number_zones( + map: &rustgis_map::Map, + center: Coord, + scale: f64, + (x, y, w, h): Cell, + cells: &[Cell], + views: &[(Coord, f64)], +) -> Vec<(usize, Cell)> { + cells + .iter() + .zip(views) + .enumerate() + .filter_map(|(i, (&(.., cw, ch), &(at, of)))| { + let (nx, ny) = crate::render::layout::extent_number_mm(map, center, scale, (w, h), (at, of, (cw, ch)))?; + let half = NUMBER_ZONE_MM / 2.0; + Some((i + 1, (x + nx - half, y + ny - half, NUMBER_ZONE_MM, NUMBER_ZONE_MM))) + }) + .collect() +} + +/// The warning for the numbers a surround still covers, having found no other place: one, naming +/// their panels and what covers them. `covers` are the surrounds, by name and place. +pub(super) fn covered_numbers_warning(numbers: &[(usize, Cell)], covers: &[(&str, Cell)]) -> Option { + let over = |zone: Cell| covers.iter().filter(move |(_, r)| overlap_area(&[zone, *r]) > 0.0); + let hidden: Vec = numbers.iter().filter(|n| over(n.1).next().is_some()).map(|n| n.0.to_string()).collect(); + let by: Vec<&str> = + covers.iter().filter(|(_, r)| numbers.iter().any(|n| overlap_area(&[n.1, *r]) > 0.0)).map(|(name, _)| *name).collect(); + let (by, named) = (by.join(" and the "), hidden.join(", ")); + match hidden.len() { + 0 => None, + 1 => Some(format!("1 panel number on the key map is covered by the {by}, which found no other place: panel {named}")), + n => Some(format!("{n} panel numbers on the key map are covered by the {by}, which found no other place: panels {named}")), + } +} + +/// The warning naming the panels the key map draws no number for, their middle off what it shows +/// (past its edges, or on the globe's far side). `numbers` are the ones it draws. +pub(super) fn unnumbered_panels_warning(numbers: &[(usize, Cell)], panels: usize) -> Option { + let out: Vec = (1..=panels).filter(|n| numbers.iter().all(|drawn| drawn.0 != *n)).map(|n| n.to_string()).collect(); + let named = out.join(", "); + match out.len() { + 0 => None, + 1 => Some(format!("1 panel isn't numbered on the key map, its middle outside what the key map shows: panel {named}")), + n => Some(format!("{n} panels aren't numbered on the key map, their middles outside what the key map shows: panels {named}")), + } +} + +#[cfg(test)] +mod tests { + use super::super::{Style, landscape_suits}; + use super::{Extent, covered_numbers_warning, panels_extent}; + + #[test] + fn the_globes_run_of_longitudes_past_180_is_kept_whole() { + // The shortest run holding both starts at 170 and ends at 460, a tenth more on each side. + let panels = [Extent::new(-170.0, 70.0, 100.0, 80.0), Extent::new(170.0, 70.0, 179.0, 80.0)]; + let around = panels_extent(&panels, true); + assert_eq!((around.min_x, around.max_x), (141.0, 489.0)); + } + + #[test] + fn a_page_turns_to_suit_a_mosaics_key_map() { + // A wide row of panels: a classic sheet gains from landscape, a mosaic's key map doesn't. + assert!(landscape_suits(0.1, 210.0, 297.0, Style::Classic)); + assert!(!landscape_suits(0.1, 210.0, 297.0, Style::Mosaic)); + } + + #[test] + fn the_covered_numbers_share_one_counted_warning() { + let numbers = [(1, (0.0, 0.0, 6.0, 6.0)), (2, (20.0, 0.0, 6.0, 6.0)), (3, (60.0, 0.0, 6.0, 6.0))]; + let said = |covers: &[(&str, (f64, f64, f64, f64))]| covered_numbers_warning(&numbers, covers); + assert_eq!(said(&[("legend", (40.0, 0.0, 10.0, 10.0))]), None); + assert_eq!( + said(&[("legend", (22.0, 2.0, 10.0, 10.0))]).as_deref(), + Some("1 panel number on the key map is covered by the legend, which found no other place: panel 2") + ); + // Two surrounds, one of them over two numbers, the other over one of those again. + assert_eq!( + said(&[("legend", (0.0, 0.0, 30.0, 10.0)), ("scale bar", (1.0, 1.0, 2.0, 2.0))]).as_deref(), + Some("2 panel numbers on the key map are covered by the legend and the scale bar, which found no other place: panels 1, 2") + ); + } +} diff --git a/crates/engine/src/cmd/layout/publication/sheet.rs b/crates/engine/src/cmd/layout/publication/sheet.rs index 0a75733da1..baef58e8f9 100644 --- a/crates/engine/src/cmd/layout/publication/sheet.rs +++ b/crates/engine/src/cmd/layout/publication/sheet.rs @@ -118,6 +118,10 @@ pub(in crate::cmd::layout) enum Style { /// the title over it, up to three headline figures under it, the footer unboxed under a thin /// rule. Edge, + /// A classic sheet whose map area holds a key map and detail frames numbered on it (#3513). + /// Not in [`PUBLICATION_STYLES`], which lists the styles that need no more than their name: + /// this one takes `"panels"`. + Mosaic, } impl Style { @@ -130,6 +134,7 @@ impl Style { "modular" => Some(Style::Modular), "poster" => Some(Style::Poster), "edge" => Some(Style::Edge), + "mosaic" => Some(Style::Mosaic), _ => None, } } @@ -143,6 +148,7 @@ impl Style { Style::Modular => "modular", Style::Poster => "poster", Style::Edge => "edge", + Style::Mosaic => "mosaic", } } @@ -150,7 +156,7 @@ impl Style { /// edge sheet's brick red, the same on a light paper and on a dark one. pub(in crate::cmd::layout) fn accent(self) -> Rgba { match self { - Style::Classic => Rgba::rgb(0x2B, 0x26, 0x20), + Style::Classic | Style::Mosaic => Rgba::rgb(0x2B, 0x26, 0x20), Style::Banner => Rgba::rgb(0x4A, 0x34, 0x26), Style::Panel => Rgba::rgb(0x2E, 0x5E, 0x3A), Style::Editorial => Rgba::rgb(0x1F, 0x2D, 0x4D), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 01f12864e8..14396ad38f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -205,6 +205,10 @@ mod layout_north_font; #[path = "tests/layout_scale_font.rs"] mod layout_scale_font; +/// A mosaic publication sheet (#3513). +#[path = "tests/layout_mosaic.rs"] +mod layout_mosaic; + #[path = "tests/sde_connections.rs"] mod sde_connections; diff --git a/crates/engine/src/tests/layout_mosaic.rs b/crates/engine/src/tests/layout_mosaic.rs new file mode 100644 index 0000000000..1bb5dd7659 --- /dev/null +++ b/crates/engine/src/tests/layout_mosaic.rs @@ -0,0 +1,404 @@ +//! `layout.publication`'s mosaic style (#3513): a key map and detail frames numbered on it. + +use super::*; +use rustgis_map::layout::{Element, ElementKind}; + +const PANELS: [[f64; 4]; 3] = [[-46.0, -11.0, -43.0, -8.0], [-42.0, -8.0, -39.0, -5.0], [-45.0, -5.0, -42.0, -2.0]]; + +fn publish(s: &mut Session, parts: Value) -> Result { + let mut p = json!({"profile": "a4-portrait", "style": "mosaic", "panels": PANELS}); + p.as_object_mut().unwrap().extend(parts.as_object().unwrap().clone()); + p.as_object_mut().unwrap().retain(|_, v| !v.is_null()); + s.run("layout.publication", &p).map_err(|e| e.to_string()) +} + +fn sheet(parts: Value) -> (Session, Value) { + let mut s = world(); + let r = publish(&mut s, parts).unwrap(); + (s, r) +} + +fn elements(s: &Session) -> &[Element] { + &s.project.layouts.last().unwrap().elements +} + +fn find<'a>(s: &'a Session, name: &str) -> &'a Element { + elements(s).iter().find(|e| e.name == name).unwrap_or_else(|| panic!("no {name}")) +} + +fn panel_names(s: &Session) -> Vec<&str> { + elements(s).iter().filter(|e| e.name.starts_with("Panel ")).map(|e| e.name.as_str()).collect() +} + +/// The panels' frames, in order. +fn panels(s: &Session, n: usize) -> Vec<&Element> { + (1..=n).map(|i| find(s, &format!("Panel {i}"))).collect() +} + +fn apart(a: &Element, b: &Element) -> bool { + a.x + a.w <= b.x + 1e-6 || b.x + b.w <= a.x + 1e-6 || a.y + a.h <= b.y + 1e-6 || b.y + b.h <= a.y + 1e-6 +} + +fn inside(a: &Element, b: &Element) -> bool { + a.x >= b.x - 1e-6 && a.y >= b.y - 1e-6 && a.x + a.w <= b.x + b.w + 1e-6 && a.y + a.h <= b.y + b.h + 1e-6 +} + +fn scale_of(e: &Element) -> f64 { + match &e.kind { + ElementKind::MapFrame { scale, .. } => *scale, + k => panic!("{k:?}"), + } +} + +fn warnings(r: &Value) -> Vec { + r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect() +} + +/// The guide outlines the panels in order, numbered. +fn assert_outlines(s: &Session, n: usize) { + let guide = &find(s, "Map Frame").kind; + let outlined: Vec = guide.extent_indicators().iter().map(|i| i.of).collect(); + assert_eq!(outlined, panels(s, n).iter().map(|p| p.id).collect::>()); + assert!(guide.numbers_extents()); +} + +#[test] +fn a_mosaic_has_a_key_map_outlining_its_numbered_panels() { + let (s, r) = sheet(json!({})); + assert_eq!(r["style"], "mosaic", "{r}"); + assert_eq!( + panel_names(&s), + [ + "Panel 1", + "Panel 2", + "Panel 3", + "Panel 1 Box", + "Panel 1 Number", + "Panel 2 Box", + "Panel 2 Number", + "Panel 3 Box", + "Panel 3 Number" + ] + ); + assert_outlines(&s, 3); + for (i, panel) in panels(&s, 3).into_iter().enumerate() { + let (plate, number) = (find(&s, &format!("Panel {} Box", i + 1)), find(&s, &format!("Panel {} Number", i + 1))); + assert!(inside(plate, panel) && inside(number, plate), "{plate:?} {panel:?}"); + assert!(plate.x - panel.x < panel.w / 4.0 && plate.y - panel.y < panel.h / 4.0, "{plate:?} {panel:?}"); + assert!(matches!(&number.kind, ElementKind::Text { text, .. } if *text == (i + 1).to_string()), "{number:?}"); + assert!(matches!(&panel.kind, ElementKind::MapFrame { grid: None, .. }), "{panel:?}"); + } +} + +#[test] +fn one_panel_is_enough() { + let (s, _) = sheet(json!({"panels": [PANELS[0]]})); + assert_outlines(&s, 1); + assert!(apart(find(&s, "Map Frame"), find(&s, "Panel 1"))); +} + +#[test] +fn six_panels_lie_apart_on_the_map_area() { + for profile in ["a5-portrait", "a4-portrait", "a4-landscape", "a0-landscape"] { + let six = [PANELS[0], PANELS[1], PANELS[2], PANELS[0], PANELS[1], PANELS[2]]; + let (s, _) = sheet(json!({"profile": profile, "panels": six})); + assert_outlines(&s, 6); + let layout = s.project.layouts.last().unwrap(); + let mut frames = panels(&s, 6); + frames.push(find(&s, "Map Frame")); + for (i, a) in frames.iter().enumerate() { + assert!(a.x >= 0.0 && a.y >= 0.0 && a.x + a.w <= layout.width && a.y + a.h <= layout.height, "{profile}: {a:?}"); + assert!(a.w > 0.0 && a.h > 0.0, "{profile}: {a:?}"); + for b in &frames[i + 1..] { + assert!(apart(a, b), "{profile}: {a:?} {b:?}"); + } + } + } +} + +#[test] +fn a_mosaic_takes_one_to_six_panels() { + for panels in [json!(null), json!([]), json!(vec![PANELS[0]; 7]), json!("all"), json!({})] { + let err = publish(&mut world(), json!({"panels": panels})).unwrap_err(); + assert!(err.contains("1 to 6"), "{panels}: {err}"); + } +} + +#[test] +fn a_malformed_panel_is_named() { + let bad = [ + json!([1, 2, 3]), + json!([3, 0, 3, 1]), + json!([0, 1, 1, 0]), + json!([0, 0, 1, 91]), + json!([-181, 0, 1, 1]), + json!("here"), + json!(null), + ]; + for panel in bad { + let mut s = world(); + let err = publish(&mut s, json!({"panels": [PANELS[0], panel]})).unwrap_err(); + assert!(err.contains("panels[1] is [west, south, east, north] in degrees"), "{panel}: {err}"); + assert!(s.project.layouts.is_empty()); + } +} + +#[test] +fn panels_are_for_a_mosaic_sheet() { + for parts in [json!({"style": null}), json!({"style": "classic"}), json!({"style": "panel"})] { + let mut s = world(); + let err = publish(&mut s, parts.clone()).unwrap_err(); + assert!(err.contains("panels is for a sheet with \"style\": \"mosaic\""), "{parts}: {err}"); + assert!(s.project.layouts.is_empty()); + } + // Whatever their shape: the style is what is wrong. + for panels in [json!([]), json!("all"), json!([[1, 2, 3]])] { + let err = publish(&mut world(), json!({"style": "classic", "panels": panels})).unwrap_err(); + assert!(err.contains("panels is for a sheet with \"style\": \"mosaic\""), "{panels}: {err}"); + } +} + +#[test] +fn a_figure_is_told_it_takes_no_panels() { + for style in [json!("mosaic"), json!("classic"), json!(null)] { + let mut s = world(); + let err = publish(&mut s, json!({"profile": "figure-1col", "style": style})).unwrap_err(); + assert!(err.contains("panels is for a sheet: a figure takes none"), "{style}: {err}"); + assert!(s.project.layouts.is_empty()); + } +} + +#[test] +fn a_figure_leaves_the_mosaic_to_its_caption() { + let (s, r) = sheet(json!({"profile": "figure-1col", "panels": null})); + assert!(warnings(&r).iter().any(|w| w.starts_with("style \"mosaic\" arranges a sheet's texts")), "{r}"); + assert!(panel_names(&s).is_empty()); +} + +#[test] +fn panels_stay_in_degrees_beside_an_extent_in_the_maps_system() { + // Web Mercator metres around the three panels. + let (s, r) = sheet(json!({"crs": "EPSG:3857", "extent": [-5_300_000, -1_400_000, -4_200_000, -100_000]})); + assert_outlines(&s, 3); + assert!(!warnings(&r).iter().any(|w| w.contains("what the key map shows")), "{r}"); + let (degrees, _) = sheet(json!({})); + for (a, b) in panels(&s, 3).into_iter().zip(panels(°rees, 3)) { + assert_eq!(scale_of(a), scale_of(b)); + } +} + +#[test] +fn without_an_extent_the_key_map_holds_every_panel() { + let (s, r) = sheet(json!({})); + assert!(!warnings(&r).iter().any(|w| w.contains("what the key map shows")), "{r}"); + let guide = find(&s, "Map Frame"); + let union = rustgis_geom::Extent::new(-46.0, -11.0, -39.0, -2.0); + let (_, fitted) = rustgis_map::layout::fit_scale(s.map(), &union, guide.w, guide.h).unwrap(); + assert!(scale_of(guide) >= fitted, "{} {fitted}", scale_of(guide)); +} + +#[test] +fn a_panel_outside_the_extent_given_is_warned_about() { + let far = [20.0, 10.0, 23.0, 13.0]; + let (s, r) = sheet(json!({"extent": [-47, -12, -38, -1], "panels": [PANELS[0], far]})); + assert_outlines(&s, 2); + let said: Vec<_> = warnings(&r).into_iter().filter(|w| w.contains("what the key map shows")).collect(); + assert_eq!(said, ["1 panel isn't numbered on the key map, its middle outside what the key map shows: panel 2"]); +} + +#[test] +fn the_panels_outside_the_extent_given_are_warned_about_once() { + let (far, further) = ([20.0, 10.0, 23.0, 13.0], [60.0, 10.0, 63.0, 13.0]); + let (_, r) = sheet(json!({"extent": [-47, -12, -38, -1], "panels": [far, PANELS[0], further]})); + let said: Vec<_> = warnings(&r).into_iter().filter(|w| w.contains("what the key map shows")).collect(); + assert_eq!(said, ["2 panels aren't numbered on the key map, their middles outside what the key map shows: panels 1, 3"]); +} + +#[test] +fn the_panels_sit_under_the_key_map_on_a_tall_sheet_and_beside_it_on_a_wide_one() { + let (tall, _) = sheet(json!({})); + let guide = find(&tall, "Map Frame"); + for p in panels(&tall, 3) { + assert!(p.y >= guide.y + guide.h && guide.h > p.h, "{guide:?} {p:?}"); + } + let (wide, _) = sheet(json!({"profile": "a3-landscape"})); + let guide = find(&wide, "Map Frame"); + for p in panels(&wide, 3) { + assert!(p.x >= guide.x + guide.w && guide.w > p.w, "{guide:?} {p:?}"); + } +} + +#[test] +fn each_panel_fits_its_extent_at_a_round_scale() { + let (s, _) = sheet(json!({})); + for ([w, so, e, n], panel) in PANELS.into_iter().zip(panels(&s, 3)) { + let (_, fitted) = rustgis_map::layout::fit_scale(s.map(), &rustgis_geom::Extent::new(w, so, e, n), panel.w, panel.h).unwrap(); + assert_eq!(scale_of(panel), crate::cmd::layout::round_scale(fitted)); + } +} + +#[test] +fn the_surrounds_sit_on_the_key_map() { + let (s, _) = sheet(json!({"northArrow": "always"})); + let guide = find(&s, "Map Frame"); + for name in ["Legend Box", "Scale Box", "North Arrow", "Locator"] { + assert!(inside(find(&s, name), guide), "{name}: {:?} {guide:?}", find(&s, name)); + } +} + +#[test] +fn texts_that_leave_the_map_no_room_are_refused() { + let err = publish(&mut world(), json!({"profile": "a5-portrait", "title": "word ".repeat(380)})).unwrap_err(); + assert!(err.contains("the texts leave the map no room"), "{err}"); +} + +#[test] +fn one_undo_removes_the_whole_mosaic() { + let (mut s, _) = sheet(json!({})); + s.run("edit.undo", &Value::Null).unwrap(); + assert!(s.project.layouts.is_empty()); +} + +#[test] +fn a_saved_mosaic_opens_with_its_numbered_outlines() { + let (s, _) = sheet(json!({})); + let text = serde_json::to_string(&s.project).unwrap(); + let opened = crate::Project::from_json(&text).unwrap(); + assert_eq!(serde_json::to_value(&opened.layouts).unwrap(), serde_json::to_value(&s.project.layouts).unwrap()); + let requires = opened.required_capabilities(); + assert!(requires.contains(&"layout-extent-numbers") && requires.contains(&"layout-extent-indicators"), "{requires:?}"); +} + +#[test] +fn on_the_globe_the_key_map_shows_its_panels_not_the_whole_earth() { + let mut s = world(); + s.run("map.projection", &json!({"type": "globe"})).unwrap(); + let (whole, r) = { + let mut other = world(); + other.run("map.projection", &json!({"type": "globe"})).unwrap(); + let r = other.run("layout.publication", &json!({"profile": "a4-portrait"})).unwrap(); + (scale_of(find(&other, "Map Frame")), r) + }; + assert!(r["locator"].is_null(), "{r}"); + let r = publish(&mut s, json!({})).unwrap(); + assert!(scale_of(find(&s, "Map Frame")) < whole / 2.0, "{r}"); + assert!(r["locator"].is_string(), "{r}"); +} + +#[test] +fn every_row_of_panels_reaches_the_end_of_their_area() { + for profile in ["a4-portrait", "a3-landscape"] { + for n in 1..=6 { + let some: Vec<[f64; 4]> = PANELS.into_iter().cycle().take(n).collect(); + let (s, _) = sheet(json!({"profile": profile, "panels": some})); + let frames = panels(&s, n); + let end = frames.iter().map(|p| p.x + p.w).fold(0.0, f64::max); + for row in &frames { + let reaches = frames.iter().filter(|p| (p.y - row.y).abs() < 1e-6).map(|p| p.x + p.w).fold(0.0, f64::max); + assert!((reaches - end).abs() < 1e-6, "{profile} {n}: {reaches} {end}"); + } + } + } +} + +#[test] +fn on_the_globe_panels_on_both_sides_of_180_are_on_the_side_the_key_map_faces() { + let mut s = world(); + s.run("map.projection", &json!({"type": "globe"})).unwrap(); + // Together, then with a third that makes the shortest run start west of the seam. + for (panels, middle) in [ + (json!([[178, -1, 179, 1], [-179, -1, -178, 1]]), 180.0), + (json!([[-179, -1, -178, 1], [150, -1, 152, 1], [178, -1, 179, 1]]), 166.0), + ] { + publish(&mut s, json!({"panels": panels})).unwrap(); + let ElementKind::MapFrame { center, .. } = &find(&s, "Map Frame").kind else { panic!("no frame") }; + let off = (center.x - middle + 180.0_f64).rem_euclid(360.0) - 180.0; + assert!(off.abs() < 1.0, "{panels}: {center:?}"); + } +} + +#[test] +fn no_surround_covers_a_panels_number_on_the_key_map() { + // Open sea: with nothing to cover, each surround stays in its home corner. + let base = json!({"extent": [-30, -30, -20, -22], "northArrow": "always", "panels": [[-25.5, -26.5, -24.5, -25.5]]}); + let (plain, _) = sheet(base.clone()); + let guide = find(&plain, "Map Frame"); + let ElementKind::MapFrame { center, scale, .. } = &guide.kind else { panic!("no frame") }; + let cam = rustgis_map::layout::frame_camera(plain.map(), *center, *scale, 0.0, 0.0); + let pt = rustgis_map::layout::PT_PER_MM; + let names = ["Locator", "North Arrow", "Legend Box", "Scale Box"]; + for home in names { + // A panel around the place the surround takes with none there. + let r = find(&plain, home); + let (x, y) = (r.x + r.w / 2.0 - guide.x, r.y + r.h / 2.0 - guide.y); + let at = plain.map().to_lonlat(cam.to_map(x * pt, y * pt, guide.w * pt, guide.h * pt)).unwrap(); + let mut parts = base.clone(); + parts["panels"] = json!([[at.x - 0.2, at.y - 0.2, at.x + 0.2, at.y + 0.2]]); + let (s, r) = sheet(parts); + let (px, py) = (guide.x + x, guide.y + y); + for name in names { + let Some(e) = elements(&s).iter().find(|e| e.name == name) else { continue }; + let covers = px > e.x - 2.0 && px < e.x + e.w + 2.0 && py > e.y - 2.0 && py < e.y + e.h + 2.0; + assert!(!covers, "{home}: {name} covers the number at {px} {py}: {e:?} {r}"); + } + assert!(has_all(&s, &names), "{home}: a surround is left out: {r}"); + } +} + +fn has_all(s: &Session, names: &[&str]) -> bool { + names.iter().all(|n| elements(s).iter().any(|e| e.name == *n)) +} + +#[test] +fn a_panel_the_key_map_cant_number_is_warned_about_on_any_view() { + // The globe's far side, then a flat panel half on the key map with its middle off it. + for (globe, panel) in [(true, [140, -35, 150, -25]), (false, [-20, 35, 130, 40])] { + let mut s = world(); + if globe { + s.run("map.projection", &json!({"type": "globe"})).unwrap(); + } + let r = publish(&mut s, json!({"extent": [-10, 35, 12, 60], "panels": [[0, 45, 5, 50], panel]})).unwrap(); + let said: Vec<_> = warnings(&r).into_iter().filter(|w| w.contains("what the key map shows")).collect(); + assert_eq!(said, ["1 panel isn't numbered on the key map, its middle outside what the key map shows: panel 2"], "globe {globe}"); + } +} + +#[test] +fn a_veiled_key_maps_group_covers_no_panels_number() { + let path = std::env::temp_dir().join(format!("rustgis-mosaic-veil-{}.geojson", std::process::id())); + let ring = json!([[[0.0, 0.0], [15.0, 0.0], [15.0, 10.0], [0.0, 10.0], [0.0, 0.0]]]); + let feature = json!({"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": ring}}); + std::fs::write(&path, json!({"type": "FeatureCollection", "features": [feature]}).to_string()).unwrap(); + // A map running on past a narrow extent, with a long legend: veiled, the surrounds in a band. + let veiled = |panels: Value| { + let mut s = Session::new(Project::default()); + for _ in 0..12 { + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + } + let parts = json!({"profile": "a4-landscape", "extent": [7, 4, 9, 6], "author": "", "locator": "none", "panels": panels}); + let r = publish(&mut s, parts).unwrap(); + (s, r) + }; + let (plain, r) = veiled(json!([[7.9, 4.9, 8.1, 5.1]])); + assert_eq!(r["veiled"], json!(true), "{r}"); + // A second panel where the group's legend went, outside the extent. + let (guide, legend) = (find(&plain, "Map Frame"), find(&plain, "Legend Box")); + let ElementKind::MapFrame { center, scale, .. } = &guide.kind else { panic!("no frame") }; + let cam = rustgis_map::layout::frame_camera(plain.map(), *center, *scale, 0.0, 0.0); + let pt = rustgis_map::layout::PT_PER_MM; + let (x, y) = (legend.x + legend.w / 2.0 - guide.x, legend.y + legend.h / 2.0 - guide.y); + let at = plain.map().to_lonlat(cam.to_map(x * pt, y * pt, guide.w * pt, guide.h * pt)).unwrap(); + let (s, r) = veiled(json!([[7.9, 4.9, 8.1, 5.1], [at.x - 0.05, at.y - 0.05, at.x + 0.05, at.y + 0.05]])); + std::fs::remove_file(&path).unwrap(); + let guide = find(&s, "Map Frame"); + let ElementKind::MapFrame { center, scale, .. } = &guide.kind else { panic!("no frame") }; + let cam = rustgis_map::layout::frame_camera(s.map(), *center, *scale, 0.0, 0.0); + let (nx, ny) = cam.to_screen(s.map().to_map(at).unwrap(), guide.w * pt, guide.h * pt); + let (px, py) = (guide.x + nx / pt, guide.y + ny / pt); + for name in ["Legend Box", "Scale Box", "North Arrow"] { + let Some(e) = elements(&s).iter().find(|e| e.name == name) else { continue }; + let covers = px > e.x - 2.0 && px < e.x + e.w + 2.0 && py > e.y - 2.0 && py < e.y + e.h + 2.0; + assert!(!covers, "{name} covers the number at {px} {py}: {e:?} {r}"); + } + assert!(!warnings(&r).iter().any(|w| w.contains("is covered by")), "{r}"); +} diff --git a/crates/render/src/layout/frame.rs b/crates/render/src/layout/frame.rs index b936be56e0..9984999954 100644 --- a/crates/render/src/layout/frame.rs +++ b/crates/render/src/layout/frame.rs @@ -671,6 +671,27 @@ pub(super) fn outline_lonlat(pm: &mut Canvas, map: &Map, view: &View, ring: &[Op } } +/// Where a map frame of `map` at `center` and `scale`, `size` mm large and facing north, draws the +/// number of its outline of another such frame of the same map, `of` its centre, scale and size +/// (#3394): in mm from the frame's top left. `None` where it draws none. +pub fn extent_number_mm( + map: &Map, + center: Coord, + scale: f64, + (w, h): (f64, f64), + (of_center, of_scale, (of_w, of_h)): (Coord, f64, (f64, f64)), +) -> Option<(f64, f64)> { + let pt = rustgis_map::layout::PT_PER_MM; + let camera = |center, scale| rustgis_map::layout::frame_camera(map, center, scale, 0.0, 0.0); + let view = View { width: w * pt, height: h * pt, pixels_per_point: 1.0, camera: camera(center, scale), sky: false }; + let of = camera(of_center, of_scale); + let ring = frame_outline_lonlat(map, &of, of_w * pt, of_h * pt); + let middle = map.to_lonlat(of.center).filter(|_| ring.iter().any(Option::is_some))?; + let (x, y) = place_lonlat(map, &view, middle, &ring, map.projection.is_globe())?; + let (x, y) = (f64::from(x) / pt, f64::from(y) / pt); + ((0.0..w).contains(&x) && (0.0..h).contains(&y)).then_some((x, y)) +} + /// Where a frame's map shows `c` (longitude, latitude), the middle of the frame outlined by /// `ring`, in pixels of its drawing: moved and cut as [`outline_lonlat`] moves and cuts that ring, /// so it falls with the outline, on the piece holding it. `None` where the map can't show it. diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 9a40dc66ee..e1bf198f87 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -281,9 +281,23 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu deep brown, green or blue by default, a brick red on an edge sheet). Where the accent would be hard to read on an edge sheet's paper (under 4.5:1 contrast), the kicker takes it lightened or darkened toward the texts' colour, as the sheet is made. - A figure leaves the style to its caption. In the menu, each sheet opens a list of the seven + A figure leaves the style to its caption. In the menu, each sheet opens a list of those seven styles, each saying what it looks like, in its default accent (`"accent"` in the command picks another). + - **A mosaic** (`"style": "mosaic"`, from a script or the assistant; not in the menu) is a + classic sheet whose map area holds a key map and 1 to 6 detail maps of the same map, listed in + `"panels"` as `[west, south, east, north]` in degrees. The key map takes the left of a wide + area, or the top of a tall one, with the grid, legend, scale bar, north arrow and locator; the + detail maps sit in rows in the rest, each fitted at a round scale, with no grid. Each is + numbered in its top left corner, and the key map outlines it with the same number (see + **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"`. + + ``` + layout.publication={"profile": "a4-landscape", "style": "mosaic", "title": "Three study areas", + "panels": [[-46, -11, -43, -8], [-42, -8, -39, -5], [-45, -5, -42, -2]]} + ``` - 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 another layout of the same map.