diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index f05d793b9f..d5853c2bb4 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -32,7 +32,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).inputs(publication_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"profile"?: "a4" (the default) | "a3" | "a2" (a sheet turned to portrait or landscape, whichever the area's map comes out larger on: its extent east to west against north to south, on the map's projection) | "a4-portrait"|"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, an editorial column's heading], "locator"?: "globe" (a globe with the area outlined; the default on sheets) | "inset" (the surrounding region, the area outlined) | "none" (the default on figures), "decimal"?: "." (the default) | "," (graticule, scale bar and colorbar numbers and {scale} with a decimal comma: 0,05 and 1:6.300.000), "colorbar"?: "auto" (the default: the top visible raster with a colour scale, not drawn by classes, gets one, under the legend in its box; a raster drawn by classes has them in the legend's rows instead) | "none" (no colorbar, and the legend's box has no room for one), "veil"?: true (the default: when no shape of the legend fits, a map that runs on past the extent, with a long legend, has what is outside the extent veiled and its surrounds grouped there, at up to half the scale on a sheet) | false (never veiled, and drawn at its scale; the map may still move aside), "contextInLegend"?: false (the default: layers the placement takes as context around the data, polygons only outlined or, beside a layer drawn by classes or a raster, in one colour and running on past the frame, are left out of the legend, which a warning names) | true (the legend lists them), "northArrow"?: "auto" (the default: none when the extent spans 20° or more on its longer side, where the graticule gives north, which a warning says) | "always" | "none", "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) (a sheet's arrangement; figures leave it to the caption), "accent"?: a colour as #RRGGBB (the style's colour: its band, panel tint, headings and rules, a poster's page), "arrangement"?: "best" (the default: the favourite, each arrangement by name and each saved with layout.arrangement laid out, the one moving the least area off its corners kept, then the one leaving the least over the data, the favourite on a tie) | "favourite" (layout.arrangement's) | an arrangement by name (built in or saved) or corner by corner, as layout.arrangement takes (the corners the locator, north arrow, legend and scale bar are at home in; one covering what the map draws there still moves), "coverage"?: "*.png" (writes the coverage grid the placement searched, as it settled on it, three pixels a cell: what the map draws dark, the free cells white, both tinted blue in the strips the graticule's labels keep, the surrounds placed over the map outlined in red; the answer gives its path)} → 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" (the default) | "a3" | "a2" (a sheet turned to portrait or landscape, whichever the area's map comes out larger on: its extent east to west against north to south, on the map's projection) | "a4-portrait"|"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, an editorial column's heading], "locator"?: "globe" (a globe with the area outlined; the default on sheets) | "inset" (the surrounding region, the area outlined) | "none" (the default on figures), "decimal"?: "." (the default) | "," (graticule, scale bar and colorbar numbers and {scale} with a decimal comma: 0,05 and 1:6.300.000), "colorbar"?: "auto" (the default: the top visible raster with a colour scale, not drawn by classes, gets one, under the legend in its box; a raster drawn by classes has them in the legend's rows instead) | "none" (no colorbar, and the legend's box has no room for one), "veil"?: true (the default: when no shape of the legend fits, a map that runs on past the extent, with a long legend, has what is outside the extent veiled and its surrounds grouped there, at up to half the scale on a sheet) | false (never veiled, and drawn at its scale; the map may still move aside), "contextInLegend"?: false (the default: layers the placement takes as context around the data, polygons only outlined or, beside a layer drawn by classes or a raster, in one colour and running on past the frame, are left out of the legend, which a warning names) | true (the legend lists them), "northArrow"?: "auto" (the default: none when the extent spans 20° or more on its longer side, where the graticule gives north, which a warning says) | "always" | "none", "legendBox"?: "auto" (the default: over the map, the legend has no box where the map shows nothing under it but its 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", "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) (a sheet's arrangement; figures leave it to the caption), "accent"?: a colour as #RRGGBB (the style's colour: its band, panel tint, headings and rules, a poster's page), "arrangement"?: "best" (the default: the favourite, each arrangement by name and each saved with layout.arrangement laid out, the one moving the least area off its corners kept, then the one leaving the least over the data, the favourite on a tie) | "favourite" (layout.arrangement's) | an arrangement by name (built in or saved) or corner by corner, as layout.arrangement takes (the corners the locator, north arrow, legend and scale bar are at home in; one covering what the map draws there still moves), "coverage"?: "*.png" (writes the coverage grid the placement searched, as it settled on it, three pixels a cell: what the map draws dark, the free cells white, both tinted blue in the strips the graticule's labels keep, the surrounds placed over the map outlined in red; the answer gives its path)} → 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.arrangement", "Favourite Arrangement", "Publish › Layout", arrangement).roles(&[]).effects(crate::policy::Effects::NONE).view().params( r#"{"favourite"?: "classic" (the locator top left, the north arrow top right, the legend bottom left, the scale bar bottom right) | "mirrored" | "legendRight" | "legendTop" | {"locator", "northArrow", "legend", "scaleBar": "top-left"|"top-right"|"bottom-left"|"bottom-right", each a corner of its own} | a saved arrangement's name, "save"?: a name (1 to 40 characters, not a built-in one nor "best", "favourite", "custom" or "veil"; one saved under it already, case aside, is replaced) to save "arrangement" under (at most 20 saved), "arrangement"?: what "save" saves: an arrangement by name, or a corner for each surround as "favourite" takes them (refused without "save"), "remove"?: a saved arrangement's name (a favourite named after it keeps its corners, unless "favourite" gives another)} → the favourite arrangement of publication layouts and those saved by name (kept with the app's preferences), the favourite's corners, the arrangements by name and the saved ones' corners; a removal, then a save, then the favourite; with none of them given, they are only shown"#, @@ -616,6 +616,15 @@ fn pub_card(fill: Rgba, outline: Rgba, width: f64, radius: f64) -> ElementKind { ElementKind::Rectangle { fill, outline, width, radius, dash: None } } +/// Where a page's visual centre sits down it, as a share of its height: a little above its middle, +/// where the eye takes a page's centre to be. +const VISUAL_CENTRE_DOWN: f64 = 0.45; + +/// How far `at` (page mm) is from the visual centre of a page `page` (mm) wide and tall. +fn visual_centre_offset(at: (f64, f64), (w, h): (f64, f64)) -> f64 { + (at.0 - w / 2.0).hypot(at.1 - h * VISUAL_CENTRE_DOWN) +} + /// The surrounds a publication layout places in the map frame's corners. #[derive(Clone, Copy, PartialEq)] pub(crate) enum Surround { @@ -1197,6 +1206,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let may_veil = publication_veil(p)?; let context_in_legend = publication_flag(p, "contextInLegend")?.unwrap_or(false); let north_arrow = publication_north_arrow(p)?; + let legend_box_always = publication_legend_box(p)?; // A style or an accent that isn't text is refused, as an unknown one is, rather than left out. for k in ["style", "accent"] { if p.get(k).is_some_and(|v| !v.is_null() && !v.is_string()) { @@ -2122,8 +2132,10 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let (cw, ch) = largest_free_cells(gw, cells, (col(area.0), row(area.1), col(area.2), row(area.3))); (cw as f64 * fw / gw as f64, ch as f64 * fh / gh as f64) }; - // When no shape of the legend fits the room the map leaves, the map moves as far as the asked - // extent stays in the frame, towards the edge that joins the room on both its sides. Failing + // When no shape of the legend fits the room the map leaves, the map moves towards an edge, so + // the room on both its sides joins, by part or all of the way the asked extent can go and stay + // in the frame: of the moves that make room, the one keeping it nearest the page's visual + // centre. Failing // that, on a continuous map (drawn over most of the extent and running on past it) with a long // legend (a short one sits over the map as well as ever), what is outside the extent is veiled, // and counts as room; and failing that, the map is drawn at up to half the scale, for a band of @@ -2263,8 +2275,32 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let need = |sizes: &[(f64, f64); MAX_LEGEND_COLUMNS], room: (f64, f64)| { sizes.iter().position(|size| whole(*size).0 <= room.0 && whole(*size).1 <= room.1) }; - let mut found: Option<(usize, f64)> = None; - for (dx, dy) in [(0.0, 0.0), (to_right, 0.0), (-to_left, 0.0), (0.0, to_bottom), (0.0, -to_top)] { + // Of the places with the fewest columns, the one leaving the extent nearest the + // page's visual centre (a little above its middle) is kept, a move away from that + // centre as short as makes room, one towards it as far as stays nearest it; within a + // millimetre of the nearest, the one with the most room (#1379). + // Each place that fits: its columns, its distance from that centre, its room, and the + // map's centre, coverage, move, veil and legend there. + type Fit = ( + usize, + f64, + f64, + Coord, + (u32, u32, Vec), + (f64, f64), + Option, + [(f64, f64); MAX_LEGEND_COLUMNS], + Vec, + ); + let mut fits: Vec = Vec::new(); + // Each way a quarter, half, three quarters and all of the way the extent can go, so + // a move can stop short of the edge. A way with no room to go is left out (its moves + // are the centred place, tried first). + let moves = [(to_right, 0.0), (-to_left, 0.0), (0.0, to_bottom), (0.0, -to_top)] + .into_iter() + .filter(|&(x, y)| x != 0.0 || y != 0.0) + .flat_map(|(x, y)| [0.25, 0.5, 0.75, 1.0].map(|f| (x * f, y * f))); + for (dx, dy) in std::iter::once((0.0, 0.0)).chain(moves) { // Centred with no veil at the asked scale is what has no room; a shift of nothing // is centred. let still = dx == 0.0 && dy == 0.0; @@ -2340,14 +2376,21 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // as drawn there. let in_group = |s: &Session| grouped(clip, n, &legend_sizes, scale_box(ground_per_pt(s, there, tried), tried)); let Some(n) = (if veil { in_group(s).map(|(i, _)| i) } else { Some(n) }) else { continue }; - if found.is_none_or(|(fewest, most)| n < fewest || (n == fewest && room.0 * room.1 > most)) { - found = Some((n, room.0 * room.1)); - (center, scale, coverage, map_shift) = (there, tried, Some(moved), (dx, dy)); - veiled = veil.then_some(clip); - (chosen, chosen_context) = (legend_sizes, legend_context); - } + let off = visual_centre_offset((clip.0 + clip.2 / 2.0, clip.1 + clip.3 / 2.0), (w, h)); + fits.push((n, off, room.0 * room.1, there, moved, (dx, dy), veil.then_some(clip), legend_sizes, legend_context)); } - if found.is_some() { + // The fewest columns; of those, the nearest that centre, and within a millimetre of + // the nearest, the most room (the first tried on a tie). + let Some(fewest) = fits.iter().map(|f| f.0).min() else { continue }; + let nearest = fits.iter().filter(|f| f.0 == fewest).map(|f| f.1).fold(f64::INFINITY, f64::min); + let best = fits + .into_iter() + .filter(|f| f.0 == fewest && f.1 <= nearest + 1.0) + .reduce(|kept, f| if f.2 > kept.2 { f } else { kept }); + if let Some((_, _, _, there, moved, shift, clip, legend_sizes, legend_context)) = best { + (center, scale, coverage, map_shift) = (there, tried, Some(moved), shift); + veiled = clip; + (chosen, chosen_context) = (legend_sizes, legend_context); break; } } @@ -2662,12 +2705,26 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { Some(_) => None, None => spot_of(Surround::Legend).inspect(|&r| placed.push(("legend", r))), }; + // Over the map, where it shows nothing under the legend but its plain paper or water (no layer, + // context, basemap shape or graticule line, and no veil), the legend needs no box to be read: + // the box is kept, clear, unless "legendBox": "always" (#1379). A card is the style's look, + // and stays. + let legend_bare = + legend_rect.filter(|_| column.is_none() && !style.cards() && veiled.is_none() && !legend_box_always).is_some_and(|r| { + covered(r) == 0.0 + && !graticule_crosses(s, center, scale, (fw, fh), (r.0 - fx, r.1 - fy, r.2, r.3), step) + && crate::render::layout::frame_plain_under(s.map_mut(), center, scale, (fw, fh), (r.0 - fx, r.1 - fy, r.2, r.3), 384) + }); if let Some(r) = legend_rect { let (lw, lh) = (r.2, r.3); l.add( "Legend Box", r, - if card { pub_card(Rgba::rgb(0xFF, 0xFF, 0xFF), Rgba::new(0x2B, 0x26, 0x20, 60), 0.4, card_r) } else { surround_box(paper) }, + if card { + pub_card(Rgba::rgb(0xFF, 0xFF, 0xFF), Rgba::new(0x2B, 0x26, 0x20, 60), 0.4, card_r) + } else { + surround_box(if legend_bare { clear } else { paper }) + }, ); // The colorbar at the bottom of the box, as tall as the box allows; the legend's rows in // what is left above it. Each says when it doesn't fit, rather than one blaming the other. @@ -2779,7 +2836,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { s.active_layout = Some(i); let locator = locator_map.map(|(map, ..)| map); Ok( - json!({"layout": i, "name": name, "profile": profile.id, "page": [w, h], "scale": scale, "grid": step, "locator": locator, "style": style.code(), "arrangement": arrangement_used, "legendColumns": legend_cols, "mapShift": [map_shift.0, map_shift.1], "veiled": veiled.is_some(), "elements": elements, "moved": moved, "coverage": coverage_written, "warnings": warnings}), + json!({"layout": i, "name": name, "profile": profile.id, "page": [w, h], "scale": scale, "grid": step, "locator": locator, "style": style.code(), "arrangement": arrangement_used, "legendColumns": legend_cols, "mapShift": [map_shift.0, map_shift.1], "veiled": veiled.is_some(), "legendBox": legend_rect.is_some() && !legend_bare, "elements": elements, "moved": moved, "coverage": coverage_written, "warnings": warnings}), ) } @@ -5469,6 +5526,42 @@ pub(crate) fn extent_span_deg(e: &Extent) -> f64 { e.height().max(e.width() * mid.cos()) } +/// Whether a publication's legend always has its box: `true` for "always", `false` for "auto" +/// (the default: none where the map shows nothing under it but its plain background, #1379). +fn publication_legend_box(p: &Value) -> Result { + match p.get("legendBox").filter(|v| !v.is_null()) { + None => Ok(false), + Some(v) => match v.as_str().map(str::trim) { + Some("auto") => Ok(false), + Some("always") => Ok(true), + _ => Err("legendBox is \"auto\" or \"always\"".into()), + }, + } +} + +/// Whether a line of a graticule every `step` degrees crosses `under` (mm from the top left of a +/// frame `size` mm wide and tall showing the active map at 1:`scale` around `center`): the +/// rectangle's longitudes or latitudes, read on a grid of points over it, run past a multiple of +/// the step. A point off the projection, or longitudes over half the globe apart, count as +/// crossed. +fn graticule_crosses(s: &Session, center: Coord, scale: f64, (fw, fh): (f64, f64), under: Rect, step: f64) -> bool { + const N: usize = 8; + let flat = s.map().flat(); + let Some(at) = flat.forward_checked(center) else { return true }; + let mm = 1000.0 * flat.ground_per_unit(at) * s.map().body().ratio() / scale; + let (mut lon, mut lat) = ((f64::INFINITY, f64::NEG_INFINITY), (f64::INFINITY, f64::NEG_INFINITY)); + for i in 0..=N { + for j in 0..=N { + let x = under.0 + under.2 * i as f64 / N as f64 - fw / 2.0; + let y = under.1 + under.3 * j as f64 / N as f64 - fh / 2.0; + let Some(ll) = flat.inverse(Coord::new(at.x + x / mm, at.y - y / mm)) else { return true }; + (lon, lat) = ((lon.0.min(ll.x), lon.1.max(ll.x)), (lat.0.min(ll.y), lat.1.max(ll.y))); + } + } + let crossed = |(lo, hi): (f64, f64)| (lo / step).floor() != (hi / step).floor() || (lo / step).fract() == 0.0; + !step.is_finite() || step <= 0.0 || lon.1 - lon.0 > 180.0 || crossed(lon) || crossed(lat) +} + /// Whether the publication may veil what lies outside the extent when nothing else leaves its /// legend room: `true` (the default) or `false`. fn publication_veil(p: &Value) -> Result { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1441ebca4b..90eaa869af 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -50170,6 +50170,80 @@ fn layout_no_data_legend_is_optional_and_saved() { assert!(matches!(old.element(3).unwrap().kind, ElementKind::Legend { show_no_data: false, .. })); } +/// Over the map, a legend with nothing under it but the blank paper (no layer, no graticule line) +/// has a clear box; one over data or a graticule line, or with "legendBox": "always", a white one +/// (#1379). +#[test] +fn a_publication_legend_over_plain_paper_has_no_box() { + let dir = std::env::temp_dir().join(format!("rustgis-legend-box-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("a_layer_name.geojson"); + let json = json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": + {"type": "Polygon", "coordinates": [[[0.0, 0.0], [15.0, 0.0], [15.0, 10.0], [0.0, 10.0], [0.0, 0.0]]]}}]}); + std::fs::write(&path, json.to_string()).unwrap(); + let laid = |profile: &str, extent: Value, legend_box: Value| { + let mut s = Session::new(Project::default()); + s.run("map.basemap", &json!({"name": "blank"})).unwrap(); + for _ in 0..2 { + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + } + let p = json!({"profile": profile, "extent": extent, "author": "", "locator": "none", "legendBox": legend_box}); + let r = s.run("layout.publication", &p).unwrap(); + let l = s.project.layouts.last().unwrap(); + let fill = l.elements.iter().find(|e| e.name == "Legend Box").map(|e| match &e.kind { + rustgis_map::layout::ElementKind::Rectangle { fill, .. } => fill.0[3], + _ => panic!("the legend's box is a rectangle"), + }); + (r["legendBox"].as_bool().unwrap(), fill.expect("the box is kept as an element, clear or not")) + }; + assert_eq!(laid("figure-2col", json!([-8, -6, 23, 16]), Value::Null), (false, 0), "clear over the paper"); + assert_eq!(laid("figure-2col", json!([-8, -6, 23, 16]), json!("auto")), (false, 0), "\"auto\" is the default"); + let (boxed, alpha) = laid("figure-2col", json!([-8, -6, 23, 16]), json!("always")); + assert!(boxed && alpha > 0, "\"always\" keeps it white"); + // At this extent a graticule line runs under the legend's corner. + let (boxed, alpha) = laid("a4-landscape", json!([-5, -5, 20, 15]), Value::Null); + assert!(boxed && alpha > 0, "a line under it keeps the box"); + // In a side column (panel) or on a card (modular), the legend keeps its box, by default too. + for style in ["panel", "modular"] { + let mut s = Session::new(Project::default()); + s.run("map.basemap", &json!({"name": "blank"})).unwrap(); + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + let p = json!({"profile": "a4-landscape", "extent": [-8, -6, 23, 16], "author": "", "style": style}); + let r = s.run("layout.publication", &p).unwrap(); + let l = s.project.layouts.last().unwrap(); + let filled = l.elements.iter().any(|e| { + e.name == "Legend Box" && matches!(&e.kind, rustgis_map::layout::ElementKind::Rectangle { fill, .. } if fill.0[3] > 0) + }); + assert!(r["legendBox"] == json!(true) && filled, "{style}: {r}"); + } + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + let bad = s.run("layout.publication", &json!({"legendBox": "never"})).unwrap_err(); + assert!(bad.contains("legendBox is"), "{bad}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A map moved aside for its legend stays nearest the page's visual centre: moved away from it (down, +/// here, the frame's centre being under the page's), it goes less than all of the way the extent +/// can go when part of it is enough (#1379). +#[test] +fn a_publication_map_moved_aside_stays_nearest_the_visual_centre() { + let mut s = Session::new(Project::default()); + for name in ["Other countries", "Area"] { + s.run("layer.addSample", &json!({"name": "countries"})).unwrap(); + s.run("layer.rename", &json!({"layer": "Countries", "name": name})).unwrap(); + } + s.run("layer.definitionQuery", &json!({"layer": "Area", "where": "continent = 'Europe'"})).unwrap(); + s.run("layer.symbology", &json!({"layer": "Area", "type": "unique", "field": "name"})).unwrap(); + let p = json!({"profile": "a4-portrait", "extent": [-25, 34, 45, 72], "author": "", "title": "Europe"}); + let r = s.run("layout.publication", &p).unwrap(); + let dy = r["mapShift"][1].as_f64().unwrap(); + // All of the way down is 36 mm here (what the move was before #1379's item 8). + assert!(dy > 1.0 && dy < 35.0, "moved down, less than all the way: {r}"); + let said = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).any(|w| w.contains(&format!("{:.0} mm down", dy))); + assert!(said, "{r}"); +} + /// #2139: a name or text over its limit is refused with its length and the limit, and nothing /// changes; one at the limit is taken whole. #[test] diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 4ca5377dcb..fb87609e7e 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -2531,6 +2531,68 @@ pub fn frame_coverage_judged_on( Some((gw, gh, drawn)) } +/// Whether a frame showing `map` at 1:`scale` around `center`, `size` (mm) wide and tall, shows +/// one plain colour under `under` (mm from the frame's top left), the basemap's water or land +/// colour, and nothing else: no layer, label or context layer, no outline of the basemap's. Drawn as the map is, on a +/// grid of about `cells` cells across the frame's longer side, its label lock set aside (and put +/// back) as [`frame_coverage`] does. Web tiles aren't fetched for it, so a map with any is not +/// plain anywhere; nor is a frame that can't be drawn. For a publication's legend, which needs no +/// box there (#1379). +pub fn frame_plain_under( + map: &mut Map, + center: Coord, + scale: f64, + (w_mm, h_mm): (f64, f64), + under: (f64, f64, f64, f64), + cells: u32, +) -> bool { + if !map.tiles.is_empty() || !(w_mm > 0.0 && h_mm > 0.0) { + return false; + } + let (w, h) = (w_mm * PT_PER_MM, h_mm * PT_PER_MM); + let ppp = f64::from(cells.clamp(8, 1024)) / w.max(h); + let view = View { width: w, height: h, pixels_per_point: ppp, camera: frame_camera(map, center, scale, 0.0, 0.0), sky: false }; + // The background as the map draws it: on another body, the land's grey (Map::palette). + let (water, land, ..) = map.palette(); + struct Lock<'a> { + lock: Option>, + anchors: std::collections::HashMap, + map: &'a mut Map, + } + impl Drop for Lock<'_> { + fn drop(&mut self) { + self.map.label_lock = self.lock.take(); + self.map.label_lock_line_anchors = std::mem::take(&mut self.anchors); + } + } + let lock = Lock { lock: map.label_lock.take(), anchors: std::mem::take(&mut map.label_lock_line_anchors), map }; + let Some(img) = crate::render(&mut *lock.map, &view) else { return false }; + drop(lock); + // A streamed layer still reading, or a raster read in place whose tiles are on their way or + // were drawn from less than the view needs: what lies under the rectangle isn't known yet. + if img.data_pending || !img.pending_in_place.is_empty() || !img.partial.is_empty() { + return false; + } + // The labels are drawn apart from the features, as the frame draws them over its map. + let crate::Rendered { pixmap, labels, unplaced, label_layers, .. } = img; + let mut canvas = Canvas::from_pixmap(pixmap); + crate::draw_labels(&mut canvas, (&unplaced, &labels, &label_layers), ppp as f32); + let pm = canvas.into_pixmap(); + let (gw, gh) = (pm.width() as usize, pm.height() as usize); + // Every cell the rectangle touches, partly too. + let cell = |v: f64, size: f64, n: usize, round: fn(f64) -> f64| (round(v / size * n as f64).max(0.0) as usize).min(n); + let (c0, c1) = (cell(under.0, w_mm, gw, f64::floor), cell(under.0 + under.2, w_mm, gw, f64::ceil)); + let (r0, r1) = (cell(under.1, h_mm, gh, f64::floor), cell(under.1 + under.3, h_mm, gh, f64::ceil)); + let px = pm.pixels(); + let mut seen = (r0..r1).flat_map(|r| (c0..c1).map(move |c| r * gw + c)).map(|i| px[i]); + // One colour, and that the basemap's water or land: a polygon filling the whole rectangle in + // one colour, data or context, isn't the background. + let rgba = |p: tiny_skia::PremultipliedColorU8| (p.red(), p.green(), p.blue(), p.alpha()); + let Some(first) = seen.next().map(rgba) else { return false }; + let background = [water, land].iter().any(|c| (c.0[0], c.0[1], c.0[2], 255) == first); + background && seen.all(|p| rgba(p) == first) +} + /// A legend entry's symbol `s` of the layer `l` in the box (`x`, `y`, `w`, `h`): a point as /// [`point_swatch`] draws it with `strokes`, or a line or a filled box a swatch wide, in the middle /// of the box. @@ -3326,6 +3388,55 @@ mod tests { assert_eq!(red(&map, 300.0, &[], 1e6).0, 0, "hidden"); } + /// Plain under a rectangle is nothing drawn there but the background: the basemap's paper, not a + /// layer or its label, not an outline that coverage takes as context, and never with web tiles + /// (#1379). + #[test] + fn frame_plain_under_counts_everything_drawn_but_the_background() { + use rustgis_data::{Dataset, Geometry}; + let square = |name: &str, half: f64| { + let mut d = Dataset::new(name, GeometryType::Polygon, Vec::new()); + let ring = [(-half, -half), (half, -half), (half, half), (-half, half), (-half, -half)]; + d.push(Some(Geometry::Polygon(vec![vec![ring.map(|(x, y)| Coord::new(x, y)).to_vec()]])), Vec::new()); + d + }; + let mut map = Map::new("m"); + (map.basemap, map.graticule) = (rustgis_map::Basemap::Blank, false); + map.add_dataset(square("data", 0.1)); + // A 100 mm frame at 1:1,000,000 shows about 0.9° across: the square sits in its middle. + let plain = |map: &mut Map, under| frame_plain_under(map, Coord::new(0.0, 0.0), 1_000_000.0, (100.0, 100.0), under, 128); + assert!(plain(&mut map, (2.0, 70.0, 25.0, 25.0)), "a corner is the blank paper"); + assert!(!plain(&mut map, (40.0, 40.0, 20.0, 20.0)), "the data in the middle"); + assert!(!plain(&mut map, (48.0, 48.0, 4.0, 4.0)), "one colour all over, but the data's, not the background"); + map.graticule = true; + assert!(!plain(&mut map, (2.0, 2.0, 96.0, 96.0)), "the map's own graticule is drawn in the frame too"); + map.graticule = false; + let border = map.add_dataset(square("border", 0.3)); + if let Some(l) = map.layers.iter_mut().find(|l| l.id == border) { + let outline = rustgis_map::Symbol::default_for(GeometryType::Polygon, 0); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { fill: Rgba::new(0, 0, 0, 0), ..outline }); + } + assert!(plain(&mut map, (2.0, 86.0, 12.0, 12.0)), "the outline (17 to 83 mm) runs clear of that corner"); + assert!(!plain(&mut map, (2.0, 2.0, 96.0, 96.0)), "an outline coverage leaves out still counts here"); + // A point left of the rectangle, its label running into it: the label counts. + let mut d = Dataset::new("named", GeometryType::Point, vec![rustgis_data::Field::new("name", rustgis_data::FieldType::Text)]); + d.push(Some(Geometry::Point(Coord::new(-0.2, -0.25))), vec![rustgis_data::Value::Text("A long place name".into())]); + let named = map.add_dataset(d); + let right_of_it = (31.0, 63.0, 67.0, 33.0); + map.layer_mut(border).unwrap().visible = false; + assert!(plain(&mut map, right_of_it), "the point itself lies outside it"); + map.layer_mut(named).unwrap().labels.enabled = true; + assert!(!plain(&mut map, right_of_it), "its label lies inside it"); + map.layer_mut(named).unwrap().labels.enabled = false; + // On another body the background is drawn in the land's grey (Map::palette), not the + // Earth basemap's water: that grey is the background there. + (map.body, map.basemap) = ("mars".into(), rustgis_map::Basemap::Paper); + assert!(plain(&mut map, (2.0, 86.0, 12.0, 12.0)), "Mars's plain grey is its background"); + (map.body, map.basemap) = ("earth".into(), rustgis_map::Basemap::Blank); + map.tiles.push(rustgis_map::TileLayer::new("tiles", rustgis_map::TileKind::Raster, "https://example.invalid/{z}/{x}/{y}.png")); + assert!(!plain(&mut map, (2.0, 86.0, 12.0, 12.0)), "web tiles aren't fetched for it, so nothing is plain"); + } + /// A layer that only outlines its polygons isn't counted as drawn, unless nothing else is shown, /// and it is shown again after; one with labels is more than an outline. #[test] diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index f8c7922db5..f27d744693 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -85,9 +85,14 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu fill and no labels, such as neighbouring borders, don't count as what the map draws here, unless nothing else is shown, nor do polygon layers in one colour with no labels that run on past the frame, such as neighbouring states, beside a layer drawn by classes or a raster. When no shape - of the legend fits, the map is first moved towards an edge, as far as the asked extent stays in - the frame, so the room on both its sides joins (the answer's `mapShift`, in mm right and down, - and a warning). Where the projection stretches, as Web Mercator does away from the equator, the + of the legend fits, the map is first moved towards an edge, by a quarter, a half, three quarters + or all of the way the asked extent can go and stay in the frame, so the room on both its sides + joins (the answer's `mapShift`, in mm right and down, and a warning). Of the moves that need the + fewest legend columns, the one that leaves the extent's centre nearest the page's visual centre + (in the middle across, 45% of the way down) is kept: a move away from that centre goes only as + far as makes room, one towards it as far as keeps it nearest. Of the moves within 1 mm of the + nearest, the one with the most room is kept. Where the projection stretches, as Web Mercator + does away from the equator, the moved frame is drawn at its new centre's ground scale, and the extent has to stay whole at that scale. Only when no move makes room for it, a continuous map with a long legend is veiled: at the asked scale, at least 80% of the extent's part of the frame and 30% of the rest are drawn @@ -111,6 +116,12 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu latitude), the layout has no north arrow: the graticule gives north there, and one arrow can't point north across the whole frame. A warning says so; `"northArrow": "always"` draws one, and `"none"` leaves it out at any span. + - **Legend box**: over the map, the legend's box is left clear where the map shows nothing under + it but its plain paper or water: no layer, label, context layer, basemap shape or graticule + line, no web tiles, and no veil. Its text then sits on the page as on open sea. The answer's + `legendBox` says whether it has one; the clear box is still an element, to fill by hand, and + `"legendBox": "always"` keeps it white. A legend in a side column or on a card keeps its box + (`legendBox` is `true`). - **Decimal comma**: `"decimal": ","` prints the graticule, scale bar and colorbar numbers and `{scale}` with a decimal comma and points between thousands (`0,05`, `1:6.300.000`). `layout.page={"decimal": ","}` sets it on any layout; `"."` restores decimal points.