diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index b9a8191e73..514bbab786 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -310,9 +310,94 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // A later pass failing where an earlier one held (its shorter page leaving the texts too // little room) settles on the last that held: only the first pass's failure is the request's. let (mut held, mut settled) = (0.0f64, false); - // The least a panel with headline figures is cut to: a shorter one fails the next pass, and the - // sheet would be left uncut. - let mut panel_needs = 0.0f64; + // A panel's height down to its locator, and what the sources and reference take from the map + // once under it. + let mut panel_head = None; + // Context around the data (neighbouring borders, the states around in one colour), which the + // placement already sets aside, is left out of the legend too, unless "contextInLegend" (#1379). + // It is judged again at each other scale the search below draws the map at, as the placement + // judges it there, and the legend takes the one at the scale settled on. + // Those "legend" already asks to leave out aren't among them, so the warning doesn't offer to + // list them; without a legend there are none. + let context_at = |map: &rustgis_map::Map, center: Coord, scale: f64, frame: (f64, f64)| { + let Some(legend) = legend.as_ref().filter(|_| !context_in_legend) else { return Vec::new() }; + let mut context = legend_context(map, center, scale, frame); + context.retain(|c| !legend.exclude.iter().any(|n| n.eq_ignore_ascii_case(c))); + context + }; + // The legend's sizes at a render scale: nothing without one. + let legend_sizes = |map: &mut rustgis_map::Map, scale: f64, context: &[String]| match &legend { + None => Some([(0.0, 0.0); PUBLICATION_LEGEND_COLUMNS]), + Some(legend) => legend.sizes(map, scale, context, legend_pt), + }; + // The room inside the legend's box, round its rows and colorbar. + let legend_pad = 2.0; + // What the legend of a frame `fw` × `fh` mm shows and the room it asks for, in `column` or over + // the map, `map` read for that frame (`reading`: a read still running). The one measure of it: + // the placement's, and the check of a panel's cut. + let legend_content = + |map: &mut rustgis_map::Map, center: Coord, scale: f64, (fw, fh): (f64, f64), column: Option, reading: bool| { + let mut said = Vec::new(); + let render_scale = crate::render::layout::frame_render_scale(map, center, scale); + let context = context_at(map, center, scale, (fw, fh)); + let mut sizes = legend_sizes(map, render_scale, &context); + let (mut cw, mut ch) = match sizes { + Some(sizes) => sizes[0], + None => { + // A complete source that can't be read: the export says why; the legend is sized by hand. + said.push("a layer's source couldn't be read through, so the legend has a fixed size; exporting says why".to_string()); + (fw * 0.3, fh * 0.25) + } + }; + // Of the layers the legend lists, or may list once read (a raster still without its style): + // whether one is still reading, and whether a raster's read failed, leaving it no classes to + // measure. Those it leaves out, asked or as context, count for neither. + let (listed_reading, listed_failed) = legend.as_ref().map_or((false, false), |legend| { + let out = legend.left_out(&context); + map.layers.iter().filter(|l| map.draws_at(l, render_scale) && !out.iter().any(|n| n.eq_ignore_ascii_case(&l.name))).fold( + (false, false), + |(reading, failed), l| { + let lists = crate::render::layout::legend_lists(l); + let raster = l.raster.as_ref(); + ( + reading + || raster.is_some_and(|r| r.is_reading() && (lists || r.awaits_style())) + || (lists && l.source.as_ref().is_some_and(|src| src.is_pending())), + failed || (lists && raster.is_some_and(|r| r.error.is_some() && r.data.is_none() && !r.is_reading())), + ) + }, + ) + }); + let unread = if reading && listed_reading { + Some("the legend's classes aren't known yet (a layer still reading): it has a fixed size to fit by hand") + } else if listed_failed { + Some("a layer the legend lists couldn't be read, so the legend has a fixed size to fit by hand") + } else { + None + }; + if let Some(why) = unread { + (cw, ch) = (cw.max(fw * 0.3), ch.max(fh * 0.25)); + sizes = None; + said.push(why.into()); + } else if legend.as_ref().is_some_and(|l| crate::render::layout::tile_legends_pending(map, render_scale, &l.exclude)) { + // Not waited for: a slow legend server would hold the command up. + (cw, ch) = (cw.max(fw * 0.3), ch.max(fh * 0.25)); + sizes = None; + said.push("a WMS or WMTS layer's legend picture is still loading: the legend has a fixed size to fit by hand".into()); + } + let bar = colorbar_top(map, colorbar).filter(|l| has_color_scale(l)).map(|l| l.name.clone()); + // The colorbar's title is the raster's name, over the bar. The box is as wide as the title, up + // to the legend's cap (in a side column, the column's width, a card's on a page of cards); a + // longer title wraps there, each line past the first making the colorbar taller (#2493). + let title_room = match column { + Some(c) => c.w + if style == Style::Modular { 5.0 * k } else { 0.0 } - 2.0 * legend_pad, + None => fw * 0.45 - 2.0 * legend_pad, + }; + let base_w = if sheet { 50.0 * k } else { 40.0 }; + let bar_w = base_w.max(bar.as_deref().map_or(0.0, crate::render::layout::colorbar_title_width_mm).min(title_room)); + let bar_measured = bar.as_deref().map_or(COLORBAR_MM, |title| colorbar_mm(title, bar_w.min(title_room))); + LegendContent { context, sizes, rows: (cw, ch), bar, base_w, bar_w, bar_measured, said } + }; let warned = warnings.len(); let (w, h, (fx, fy, fw, fh), column) = loop { around.clear(); @@ -727,12 +812,9 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu } y += if i + 1 < headlines.len() { 2.0 * k } else { 3.0 * k }; } - if !under && !headlines.is_empty() { - // The height down to here, the 30·k the check below asks for the locator and - // the legend with 1·k to spare (a pass may land 0.5 mm short), and what the - // sources and reference take from the map once under it. + if !under { let moved = foot - footer(&mut Vec::new(), &plain, true, true); - panel_needs = y - top + ip + 31.0 * k + moved; + panel_head = Some((y - top + ip, moved)); } // The sources and the reference, stacked up from the panel's foot. let mut yb = panel_bottom - ip; @@ -889,20 +971,67 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu } }; let (_, _, (_, _, lw, lh), _) = laid; - // The frame's height for the area at its width, with a seventh more of its surroundings; - // worked out on the first pass (the width doesn't change), aimed at on the others, whose + // Worked out on the first pass (the width doesn't change), aimed at on the others, whose // footer can grow (a panel's sources move under the map) and so need a pass or two more. if passes == 0 { - target = (sheet && matches!(style, Style::Panel | Style::Editorial)) + // The frame's height for the area at its width, with a seventh more of its surroundings. + let area = (sheet && matches!(style, Style::Panel | Style::Editorial)) .then(|| aspect(s, &extent)) .flatten() - .map(|a| (((lw - 2.0 * room_side).max(1.0) * a + 2.0 * room_end) * 1.15).max(40.0 * k).max(panel_needs)) - // Only a frame clearly too tall is cut. - .filter(|n| *n < 0.97 * lh); + .map(|a| (((lw - 2.0 * room_side).max(1.0) * a + 2.0 * room_end) * 1.15).max(40.0 * k)); + // The least a panel is cut to, with 1·k to spare (a pass may land 0.5 mm short): its + // texts down to the locator and the 30·k the panel's check asks for, or the 40·k the + // map's frame needs. A shorter one fails the next pass and leaves the sheet uncut. + let least = panel_head.map_or(0.0, |(head, _)| (head + 31.0 * k).max(41.0 * k)); + // Only a frame clearly too tall is cut, and one the page can give up with what moves + // under the map. + target = area.map(|cut| cut.max(least)).filter(|n| *n < 0.97 * lh && *n + moved_under(panel_head) < lh); } passes += 1; + let reached = target.is_none_or(|n| (lh - n).abs() <= 0.5); match target { - Some(n) if !settled && (lh - n).abs() > 0.5 && passes < 5 => (held, freed) = (freed, (freed + lh - n).max(0.0)), + Some(n) if !settled && !reached && passes < 5 => { + // The first cut's frame also loses what moves under the map; the later ones have + // given it back already. + let moving = if freed > 0.0 { 0.0 } else { moved_under(panel_head) }; + (held, freed) = (freed, (freed + lh - n - moving).max(0.0)); + } + // A panel's cut is taken only with its legend whole in the column the frame leaves: else + // it is cut less, or, with no pass or no cut left for that, not at all. + _ if freed > 0.0 && style == Style::Panel => { + // The height the frame must grow to for its legend: none when the column holds it. + let short = laid.3.filter(|_| legend.is_some() || colorbar).and_then(|c| { + let inner = inner_frame((lw, lh), (room_side, room_end)); + let (center, scale) = fit_frame(s.map(), &extent, whole_globe, inner)?; + // Read on a copy: the session's map is only changed after the last refusal. + let mut map = s.map().clone(); + let at = crate::render::layout::frame_render_scale(&map, center, scale); + let reading = sync_to_frame(&mut map, center, scale, (lw, lh), at); + let content = legend_content(&mut map, center, scale, (lw, lh), Some(c), reading); + // A legend of unknown size gets a fixed one, which no cut is raised for: said. + if !content.said.is_empty() { + return None; + } + let count = locators.len() as f64; + let under = if locators.is_empty() { 0.0 } else { column_side(c, count, k) + 3.0 * k }; + if column_holds(&content, c.w, c.h - under, legend_pad) { + return None; + } + let need = (content.column_height() + 2.0 * legend_pad).max(MIN_LEGEND_MM); + // The locator shrinks to 0.45 of the column before the legend under it does. + let full = column_side(Column { h: f64::INFINITY, ..c }, count.max(1.0), k); + let tall = if locators.is_empty() { need } else { ((3.0 * k + need) / 0.55).min(full + 3.0 * k + need) }; + Some(lh - c.h + tall + 1.0 * k) + }); + let uncut = lh + freed + moved_under(panel_head); + match short { + None => break laid, + Some(n) if !settled && passes < 5 && n < 0.97 * uncut && freed + lh > n => { + (target, held, freed) = (Some(n), freed, freed + lh - n); + } + Some(_) => (freed, settled) = (0.0, true), + } + } _ => break laid, } }; @@ -922,26 +1051,16 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu if fw - strip_w < fw / 2.0 || fh - strip_h < fh / 2.0 { warnings.push("the frame is too small to keep its grid's labels off the map's edges: they may cover them".into()); } - let (inner_w, inner_h) = ((fw - strip_w).max(fw / 2.0), (fh - strip_h).max(fh / 2.0)); - let (center, scale) = if whole_globe { - // The globe seen whole fills the frame, centred where the view looks (#2337): fitting the - // whole Earth's flat footprint instead drew it a fraction of the frame, around 0°, 0°. - // Its size at a scale is the same at any latitude, so it is worked out on the equator, - // where the probe stays within the camera's resolutions. - let view = s.map().center_lonlat(); - let scale = round_scale(globe_scale(s.map(), Coord::new(view.x, 0.0), inner_w.min(inner_h) * WHOLE_GLOBE_FILL)); - let center = drawable_globe_center(s.map(), view, scale); - if center != view { - warnings.push(format!( - "the globe is centred at {:.1}° rather than the view's {:.1}° of latitude: nearer the pole, the frame can't draw it small enough to fit", - center.y, view.y - )); - } - (center, scale) - } else { - fit_scale(s.map(), &extent, inner_w, inner_h).ok_or("the extent can't be drawn on the map's projection")? - }; - let scale = round_scale(scale); + let (inner_w, inner_h) = inner_frame((fw, fh), (room_side, room_end)); + let (center, scale) = + fit_frame(s.map(), &extent, whole_globe, (inner_w, inner_h)).ok_or("the extent can't be drawn on the map's projection")?; + if whole_globe && center != s.map().center_lonlat() { + warnings.push(format!( + "the globe is centred at {:.1}° rather than the view's {:.1}° of latitude: nearer the pole, the frame can't draw it small enough to fit", + center.y, + s.map().center_lonlat().y + )); + } // 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").trim(), crate::cmd::MAX_NAME)?; let (name, name_cut) = unique_name(s, "New Publication Layout", "the name given", &given); @@ -1000,10 +1119,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // Two locators sit side by side, each `side` square. let (locator_count, locator_gap) = (locators.len().max(1) as f64, 3.0 * k); let side = match column { - // In a column, its width (shared by two) up to an A4 portrait column's (a landscape - // sheet's wider column doesn't make it larger), leaving the legend most of the height - // under it. - Some(c) => ((c.w - (locator_count - 1.0) * locator_gap) / locator_count).min(52.0 * k).min(0.45 * c.h).max(0.0), + Some(c) => column_side(c, locator_count, k), None if sheet => (0.24 * fw.min(fh)).clamp(25.0 * k, 70.0 * k), None => (0.3 * fw.min(fh)).clamp(18.0, 45.0), }; @@ -1159,82 +1275,13 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // classes can't be known: the legend gets a fixed size, to fit by hand. Nothing drawn in the // frame, no legend. let render_scale = crate::render::layout::frame_render_scale(s.map(), center, scale); - let view = crate::render::View { - width: fw * rustgis_map::layout::PT_PER_MM, - height: fh * rustgis_map::layout::PT_PER_MM, - pixels_per_point: 1.0, - camera: rustgis_map::layout::frame_camera(s.map(), center, scale, 0.0, 0.0), - sky: false, - }; - let lonlat = crate::render::view_lonlat(s.map(), &view); - let own = crate::render::view_own(s.map(), &view); - let reading = s.map_mut().sync_sources_in(&lonlat, own.as_ref(), render_scale, true, &rustgis_data::query::Env::default()); - // Context around the data (neighbouring borders, the states around in one colour), which the - // placement already sets aside, is left out of the legend too, unless "contextInLegend" (#1379). - // It is judged again at each other scale the search below draws the map at, as the placement - // judges it there, and the legend takes the one at the scale settled on. - // Those "legend" already asks to leave out aren't among them, so the warning doesn't offer to - // list them; without a legend there are none. - let context_at = |s: &Session, center: Coord, scale: f64| { - let Some(legend) = legend.as_ref().filter(|_| !context_in_legend) else { return Vec::new() }; - let mut context = legend_context(s.map(), center, scale, (fw, fh)); - context.retain(|c| !legend.exclude.iter().any(|n| n.eq_ignore_ascii_case(c))); - context - }; - // The legend's sizes at a render scale: nothing without one. - let legend_sizes = |s: &mut Session, scale: f64, context: &[String]| match &legend { - None => Some([(0.0, 0.0); PUBLICATION_LEGEND_COLUMNS]), - Some(legend) => legend.sizes(s.map_mut(), scale, context, legend_pt), - }; + let reading = sync_to_frame(s.map_mut(), center, scale, (fw, fh), render_scale); // Whether a legend picture still loading keeps its size at a render scale unknown. let pictures_pending = |s: &Session, scale: f64| legend.as_ref().is_some_and(|l| crate::render::layout::tile_legends_pending(s.map(), scale, &l.exclude)); - let mut context = context_at(s, center, scale); - let mut sizes = legend_sizes(s, render_scale, &context); - let (mut cw, mut ch) = match sizes { - Some(sizes) => sizes[0], - None => { - // A complete source that can't be read: the export says why; the legend is sized by hand. - warnings.push("a layer's source couldn't be read through, so the legend has a fixed size; exporting says why".into()); - (fw * 0.3, fh * 0.25) - } - }; - // Of the layers the legend lists, or may list once read (a raster still without its style): - // whether one is still reading, and whether a raster's read failed, leaving it no classes to - // measure. Those it leaves out, asked or as context, count for neither. - let (listed_reading, listed_failed) = legend.as_ref().map_or((false, false), |legend| { - let out = legend.left_out(&context); - s.map().layers.iter().filter(|l| s.map().draws_at(l, render_scale) && !out.iter().any(|n| n.eq_ignore_ascii_case(&l.name))).fold( - (false, false), - |(reading, failed), l| { - let lists = crate::render::layout::legend_lists(l); - let raster = l.raster.as_ref(); - ( - reading - || raster.is_some_and(|r| r.is_reading() && (lists || r.awaits_style())) - || (lists && l.source.as_ref().is_some_and(|src| src.is_pending())), - failed || (lists && raster.is_some_and(|r| r.error.is_some() && r.data.is_none() && !r.is_reading())), - ) - }, - ) - }); - let unread = if reading && listed_reading { - Some("the legend's classes aren't known yet (a layer still reading): it has a fixed size to fit by hand") - } else if listed_failed { - Some("a layer the legend lists couldn't be read, so the legend has a fixed size to fit by hand") - } else { - None - }; - if let Some(why) = unread { - (cw, ch) = (cw.max(fw * 0.3), ch.max(fh * 0.25)); - sizes = None; - warnings.push(why.into()); - } else if pictures_pending(s, render_scale) { - // Not waited for: a slow legend server would hold the command up. - (cw, ch) = (cw.max(fw * 0.3), ch.max(fh * 0.25)); - sizes = None; - warnings.push("a WMS or WMTS layer's legend picture is still loading: the legend has a fixed size to fit by hand".into()); - } + let LegendContent { mut context, mut sizes, rows: (mut cw, mut ch), bar, base_w, bar_w, bar_measured, said } = + legend_content(s.map_mut(), center, scale, (fw, fh), column, reading); + warnings.extend(said); // A scale bar given a larger text than the sheet's gets the height for it. let text_growth = match &scale_kind { Some(ElementKind::ScaleBar { text_size, .. }) => (text_size / bar_pt).max(1.0), @@ -1259,7 +1306,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let ground_per_pt = |s: &Session, center: Coord, scale: f64| { s.map().ground_res_at(&rustgis_map::layout::frame_camera(s.map(), center, scale, 0.0, 0.0)) }; - let pad = 2.0; + let pad = legend_pad; // The surrounds to place: what each is and its size (the arrangement gives its corner). let mut surrounds: Vec<(Surround, f64, f64)> = Vec::new(); if !locator_maps.is_empty() && column.is_none() { @@ -1283,10 +1330,8 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // "none"` leaves it out, and its room in the box with it (#1680). // One on top whose pixels aren't read yet has no scale to show: no colorbar, rather than the // scale of a raster under it under its name. - let top_raster = colorbar.then(|| rustgis_map::layout::colorbar_layer(s.map(), None)).flatten(); - let scaled = |l: &&rustgis_map::Layer| l.raster.as_ref().is_some_and(|r| rustgis_map::layout::color_scale(r).is_some()); - let bar = top_raster.filter(scaled).map(|l| l.name.clone()); - if let Some(l) = top_raster.filter(|l| !scaled(l)) { + let top_raster = colorbar_top(s.map(), colorbar); + if let Some(l) = top_raster.filter(|l| !has_color_scale(l)) { let why = if l.raster.as_ref().is_some_and(|r| r.error.is_some()) { "couldn't be read" } else { "is still reading" }; warnings.push(format!( "{} {why}, so its colour scale isn't known and the layout has no colorbar for it; add one with layout.addElement once it has read", @@ -1303,16 +1348,6 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // under it one as wide. let card = style == Style::Modular && column.is_some(); let (card_r, card_pad) = (3.0 * k, 2.5 * k); - // The colorbar's title is the raster's name, over the bar. The box is as wide as the title, up - // to the legend's cap (in a side column, the column's width); a longer title wraps there, each - // line past the first making the colorbar taller (#2493). - let title_room = match column { - Some(c) => c.w + if card { 2.0 * card_pad } else { 0.0 } - 2.0 * pad, - None => fw * 0.45 - 2.0 * pad, - }; - let base_w = if sheet { 50.0 * k } else { 40.0 }; - let bar_w = base_w.max(bar.as_deref().map_or(0.0, crate::render::layout::colorbar_title_width_mm).min(title_room)); - let bar_measured = bar.as_deref().map_or(COLORBAR_MM, |title| colorbar_mm(title, bar_w.min(title_room))); let bar_gap = if ch > 0.0 { 2.0 } else { 0.0 }; // Over the map the box is never placed taller than 60% of the frame, so the title's lines // count only up to that, less the rows of the legend beside them (a colorbar's own height, as @@ -1483,7 +1518,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let own = crate::render::view_own(s.map(), &view); let reading = s.map_mut().sync_sources_in(&lonlat, own.as_ref(), render_scale, true, &rustgis_data::query::Env::default()); - let here_context = if tried == asked_scale { context.clone() } else { context_at(s, centred, tried) }; + let here_context = if tried == asked_scale { context.clone() } else { context_at(s.map(), centred, tried, (fw, fh)) }; let here = if reading || (tried != asked_scale && pictures_pending(s, render_scale)) { unknown_at.get_or_insert(tried); None @@ -1492,7 +1527,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu } else { // A legend that can't be measured there (a source that can't be read // through) leaves that scale untried too, which is said. - let measured = legend_sizes(s, render_scale, &here_context); + let measured = legend_sizes(s.map_mut(), render_scale, &here_context); if measured.is_none() { unknown_at.get_or_insert(tried); } @@ -1573,12 +1608,12 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu (own.clone(), *own_sizes, own_context.clone()) } else { let Some(own) = crate::render::layout::frame_coverage(s.map_mut(), there, tried, fw, fh, 384) else { continue }; - let own_context = context_at(s, there, tried); + let own_context = context_at(s.map(), there, tried, (fw, fh)); let own_sizes = if own_context == *here_context { *here } else { let at_there = crate::render::layout::frame_render_scale(s.map(), there, tried); - let measured = legend_sizes(s, at_there, &own_context); + let measured = legend_sizes(s.map_mut(), at_there, &own_context); // A legend that can't be measured there leaves that move untried, which is // said, as at a scale. let Some(measured) = measured else { @@ -2142,6 +2177,102 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu ) } +/// What a publication's legend shows on a frame, and the room it asks for. +struct LegendContent { + context: Vec, + /// Its rows' sizes in one to the most columns; none where it takes a fixed size. + sizes: Option<[(f64, f64); PUBLICATION_LEGEND_COLUMNS]>, + rows: (f64, f64), + /// The raster the colorbar under the rows is of. + bar: Option, + base_w: f64, + bar_w: f64, + bar_measured: f64, + /// Why its size is a fixed one rather than its rows'. + said: Vec, +} + +impl LegendContent { + /// The height of its rows and colorbar in a side column, which takes the colorbar's whole. + fn column_height(&self) -> f64 { + let gap = if self.rows.1 > 0.0 { 2.0 } else { 0.0 }; + self.rows.1 + if self.bar.is_some() { self.bar_measured + gap } else { 0.0 } + } +} + +/// The room of a frame `w` × `h` mm inside its grid's label strips, `side` and `end` mm along each +/// of its sides and ends, half the frame at the least. +fn inner_frame((w, h): (f64, f64), (side, end): (f64, f64)) -> (f64, f64) { + ((w - 2.0 * side).max(w / 2.0), (h - 2.0 * end).max(h / 2.0)) +} + +/// What a panel's frame loses to the sources and reference once they move under the map. +fn moved_under(panel_head: Option<(f64, f64)>) -> f64 { + panel_head.map_or(0.0, |(_, moved)| moved) +} + +/// A side column's locator, `count` of them sharing its width up to an A4 portrait column's (a +/// landscape sheet's wider column doesn't make it larger), leaving the legend most of the height +/// under it. +fn column_side(c: Column, count: f64, k: f64) -> f64 { + ((c.w - (count - 1.0) * 3.0 * k) / count).min(52.0 * k).min(0.45 * c.h).max(0.0) +} + +/// Whether the legend's box in a side column `w` wide, `room` mm tall at most, holds `content`'s +/// rows and colorbar: what the placement then draws whole there. +fn column_holds(content: &LegendContent, w: f64, room: f64, pad: f64) -> bool { + let height = content.column_height(); + if height <= 0.0 { + return true; + } + let (cw, ch) = content.rows; + let gap = if ch > 0.0 { 2.0 } else { 0.0 }; + let (iw, ih) = (w - 2.0 * pad, (height + 2.0 * pad).min(room) - 2.0 * pad); + let need = content.bar.as_deref().map_or(0.0, |title| colorbar_mm(title, iw)); + let fit = colorbar_fit(need, ih, ch + gap, false); + let rows = (ih - fit - if content.bar.is_some() { gap } else { 0.0 }).max(0.0); + room >= MIN_LEGEND_MM && !overflows((cw, ch), (iw, rows)).1 && need <= fit + LEGEND_FIT_MM +} + +/// The topmost visible raster a colorbar may be of, none where none is asked for. +fn colorbar_top(map: &rustgis_map::Map, colorbar: bool) -> Option<&rustgis_map::Layer> { + colorbar.then(|| rustgis_map::layout::colorbar_layer(map, None)).flatten() +} + +fn has_color_scale(l: &rustgis_map::Layer) -> bool { + l.raster.as_ref().is_some_and(|r| rustgis_map::layout::color_scale(r).is_some()) +} + +/// The centre and scale of a frame of `map` with `inner` mm (width, height) inside its grid's label +/// strips: `extent` fitted in it, or the whole globe filling it, centred where the view looks. +fn fit_frame(map: &rustgis_map::Map, extent: &Extent, whole_globe: bool, (w, h): (f64, f64)) -> Option<(Coord, f64)> { + if !whole_globe { + return fit_scale(map, extent, w, h).map(|(center, scale)| (center, round_scale(scale))); + } + // The globe seen whole fills the frame, centred where the view looks (#2337): fitting the + // whole Earth's flat footprint instead drew it a fraction of the frame, around 0°, 0°. + // Its size at a scale is the same at any latitude, so it is worked out on the equator, + // where the probe stays within the camera's resolutions. + let view = map.center_lonlat(); + let scale = round_scale(globe_scale(map, Coord::new(view.x, 0.0), w.min(h) * WHOLE_GLOBE_FILL)); + Some((drawable_globe_center(map, view, scale), scale)) +} + +/// Reads `map`'s streamed layers as a frame `size` (mm) at 1:`scale` around `center` draws them, +/// waiting for them as an export does; whether a read is still running. +fn sync_to_frame(map: &mut rustgis_map::Map, center: Coord, scale: f64, (w, h): (f64, f64), render_scale: f64) -> bool { + let view = crate::render::View { + width: w * rustgis_map::layout::PT_PER_MM, + height: h * rustgis_map::layout::PT_PER_MM, + pixels_per_point: 1.0, + camera: rustgis_map::layout::frame_camera(map, center, scale, 0.0, 0.0), + sky: false, + }; + let lonlat = crate::render::view_lonlat(map, &view); + let own = crate::render::view_own(map, &view); + map.sync_sources_in(&lonlat, own.as_ref(), render_scale, true, &rustgis_data::query::Env::default()) +} + /// Whether the publication gives the top shown raster with a colour scale a colorbar: `"auto"` (the /// default) or `"none"`. pub(in crate::cmd::layout) fn publication_colorbar(p: &Value) -> Result { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 49fd20805d..51a89a6de6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -129,6 +129,9 @@ mod layout_edge; #[path = "tests/layout_panel_figures.rs"] mod layout_panel_figures; +#[path = "tests/layout_panel_cut.rs"] +mod layout_panel_cut; + #[path = "tests/layout_chart_notices.rs"] mod layout_chart_notices; diff --git a/crates/engine/src/tests/layout_panel_cut.rs b/crates/engine/src/tests/layout_panel_cut.rs new file mode 100644 index 0000000000..d53c0b0230 --- /dev/null +++ b/crates/engine/src/tests/layout_panel_cut.rs @@ -0,0 +1,328 @@ +//! The cut of `layout.publication`'s panel sheet for an area much wider than tall (#3266): cut as +//! far as the panel allows, rather than not at all. + +use super::*; +use rustgis_map::layout::{Element, ElementKind, Layout}; + +/// West, east and north of the areas; each test picks the south. +fn area(south: f64) -> Value { + json!([-60.0, south, -30.0, -2.0]) +} + +/// Taller than any frame: never cut. +const TALL: [f64; 4] = [-46.8, -30.0, -38.5, -2.2]; + +/// A panel sheet with a title, a subtitle and sources, `extra`'s parameters over these. +fn panel(extra: Value) -> Result { + panel_of(&mut world(), extra).map(|(l, _)| l) +} + +/// The same over `s`'s map, with the command's warnings. +fn panel_of(s: &mut Session, extra: Value) -> Result<(Layout, String), String> { + let mut p = json!({"profile": "a4-portrait", "style": "panel", "extent": area(-3.0), "title": "Piauí", + "subtitle": "Vegetation trend, 2001–2025", "sources": ["Boundaries: IBGE 2022"]}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.run("layout.publication", &p)?; + Ok((s.project.layouts.last().unwrap().clone(), r["warnings"].to_string())) +} + +/// What a legend with more rows than its box takes is warned with. +const LEGEND_CUT: &str = "the legend lists more than fits its box"; + +/// A cut sheet whose legend is whole. +fn assert_cut_whole(extra: Value, uncut: f64, what: &str) -> Layout { + let (l, warnings) = panel_of(&mut world(), extra).unwrap_or_else(|e| panic!("{what}: {e}")); + assert_cut(&l, uncut, what); + assert!(!warnings.contains(LEGEND_CUT), "{what}: {warnings}"); + l +} + +fn named<'a>(l: &'a Layout, name: &str) -> &'a Element { + l.elements.iter().find(|e| e.name == name).unwrap_or_else(|| panic!("no {name}")) +} + +fn frame(l: &Layout) -> f64 { + named(l, "Map Frame").h +} + +/// The height left to the locator and the legend, from the first of them to the panel's foot. +fn column(l: &Layout) -> f64 { + let panel = named(l, "Panel Box"); + let top = l + .elements + .iter() + .filter(|e| e.name.starts_with("Locator") || e.name.starts_with("Legend")) + .map(|e| e.y) + .fold(f64::INFINITY, f64::min); + panel.y + panel.h - top +} + +/// Cut well short of the uncut frame, the locator and the legend still with their 30 mm (on A4). +fn assert_cut(l: &Layout, uncut: f64, what: &str) { + assert!(frame(l) < 0.97 * uncut, "{what}: a frame of {} mm is not cut from {uncut}", frame(l)); + assert!(column(l) >= 30.0, "{what}: {} mm for the locator and the legend", column(l)); +} + +#[test] +fn a_panel_of_a_very_wide_area_is_cut_rather_than_left_whole() { + let uncut = frame(&panel(json!({"extent": TALL})).unwrap()); + assert_cut(&panel(json!({"extent": area(-16.0)})).unwrap(), uncut, "the issue's area"); +} + +#[test] +fn a_wider_area_never_takes_a_taller_frame() { + let uncut = frame(&panel(json!({"extent": TALL})).unwrap()); + let mut last = uncut; + for south in [-20.0, -18.0, -16.0, -14.0, -10.0, -6.0, -3.0] { + let l = panel(json!({"extent": area(south)})).unwrap(); + assert_cut(&l, uncut, &format!("south {south}")); + assert!(frame(&l) <= last + 0.5, "south {south}: {} after {last}", frame(&l)); + last = frame(&l); + } +} + +#[test] +fn a_panel_with_no_title_is_cut_further() { + let uncut = frame(&panel(json!({"extent": TALL})).unwrap()); + let titled = panel(json!({})).unwrap(); + let bare = panel(json!({"title": null, "subtitle": null})).unwrap(); + assert_cut(&titled, uncut, "titled"); + assert_cut(&bare, uncut, "no title"); + assert!(frame(&bare) < frame(&titled), "{} and {}", frame(&bare), frame(&titled)); +} + +#[test] +fn a_panels_tall_sources_never_fail_a_wide_area() { + let uncut = frame(&panel(json!({"extent": TALL})).unwrap()); + let long = "Boundaries and statistics of the municipalities, revised edition ".repeat(3); + let mut cut = 0; + for n in 1..=20 { + let texts = json!({"sources": vec![long.clone(); n], "reference": long}); + // Sources an uncut sheet has no room for are the request's own failure. + let mut tall = texts.clone(); + tall["extent"] = json!(TALL); + if let Err(e) = panel(tall) { + assert!(e.contains("no room"), "{n} sources: {e}"); + continue; + } + let l = panel(texts).unwrap_or_else(|e| panic!("{n} sources: {e}")); + assert!(column(&l) >= 30.0, "{n} sources: {}", column(&l)); + if frame(&l) < 0.97 * uncut { + cut += 1; + } + } + assert!(cut > 0); +} + +#[test] +fn a_wide_area_is_cut_on_every_page_size() { + for profile in crate::cmd::layout::PUBLICATION_PROFILES.iter().filter(|p| p.sheet) { + let id = profile.id; + let uncut = frame(&panel(json!({"profile": id, "extent": TALL})).unwrap()); + let l = panel(json!({"profile": id})).unwrap_or_else(|e| panic!("{id}: {e}")); + assert!(frame(&l) < 0.97 * uncut, "{id}: {} from {uncut}", frame(&l)); + // The sheet's sizes are A4's, scaled by its short side. + let k = l.width.min(l.height) / 210.0; + assert!(column(&l) >= 30.0 * k, "{id}: {} mm for the locator and the legend", column(&l)); + } +} + +#[test] +fn a_cut_panel_keeps_its_legend_whole() { + let uncut = frame(&panel(json!({"extent": TALL})).unwrap()); + // -20 was cut already, its legend short of its last layer; -3 is a band 1° tall. + for south in [-20.0, -16.0, -3.0] { + assert_cut_whole(json!({"extent": area(south)}), uncut, &format!("south {south}")); + } +} + +#[test] +fn the_cut_leaves_room_for_the_legend_asked_for() { + let uncut = frame(&panel(json!({"extent": TALL})).unwrap()); + let all = frame(&assert_cut_whole(json!({}), uncut, "every layer")); + let fewer = assert_cut_whole(json!({"legend": {"exclude": ["Countries"]}}), uncut, "a layer left out"); + assert!(frame(&fewer) < all, "{} and {all}", frame(&fewer)); + let (none, _) = panel_of(&mut world(), json!({"legend": "none"})).unwrap(); + assert!(frame(&none) < frame(&fewer), "{} and {}", frame(&none), frame(&fewer)); + assert_cut_whole(json!({"legend": {"columns": 2}}), uncut, "two columns"); + assert_cut_whole(json!({"locator": ["inset", "globe"]}), uncut, "two locators"); + assert_cut_whole(json!({"locator": "none"}), uncut, "no locator"); +} + +#[test] +fn a_legend_no_cut_sheet_could_hold_leaves_the_sheet_whole() { + let mut s = world(); + s.run("layer.symbology", &json!({"layer": "Countries", "type": "unique", "field": "name"})).unwrap(); + let uncut = frame(&panel(json!({"extent": TALL})).unwrap()); + let (l, warnings) = panel_of(&mut s, json!({})).unwrap(); + assert!(frame(&l) >= 0.97 * uncut, "{} from {uncut}", frame(&l)); + assert!(warnings.contains(LEGEND_CUT), "{warnings}"); +} + +#[test] +fn a_tall_area_stays_whole() { + let tall = panel(json!({"extent": TALL})).unwrap(); + // A4's margin and padding put an uncut panel's top at 15 mm. + assert!((named(&tall, "Panel Box").y - 15.0).abs() < 1e-6); +} + +#[test] +fn the_cut_counts_the_layers_the_final_frame_lists() { + // One-colour layers running past the frame are left out of the legend as context: a frame the + // legend makes taller can take them whole, and its legend lists them. + for half in [8.0, 9.0, 10.0, 11.0, 12.0, 14.0, 16.0] { + let mut s = world(); + let (w, so, e, n) = (-55.0, -9.0 - half, -35.0, -9.0 + half); + let ring = json!([[[w, so], [e, so], [e, n], [w, n], [w, so]]]); + let fc = json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": ring}}]}); + let path = std::env::temp_dir().join(format!("rustgis-3266-{}-{half}.geojson", std::process::id())); + std::fs::write(&path, fc.to_string()).unwrap(); + for i in 0..3 { + s.run("layer.addData", &json!({"path": path.display().to_string(), "name": format!("Block {i}")})).unwrap(); + } + let _ = std::fs::remove_file(path); + let (_, warnings) = panel_of(&mut s, json!({"extent": area(-16.0)})).unwrap(); + assert!(!warnings.contains(LEGEND_CUT), "half {half}: {warnings}"); + } +} + +#[test] +fn the_cut_counts_a_streamed_layers_classes() { + let features: Vec = (0..200) + .map(|i| { + let at = [-58.0 + f64::from(i % 25), -15.0 + f64::from(i / 25)]; + json!({"type": "Feature", "properties": {"k": format!("class {}", i % 6)}, "geometry": {"type": "Point", "coordinates": at}}) + }) + .collect(); + let path = std::env::temp_dir().join(format!("rustgis-3266-{}-streamed.geojson", std::process::id())); + std::fs::write(&path, json!({"type": "FeatureCollection", "features": features}).to_string()).unwrap(); + let streamed = || { + let mut s = world(); + s.run("layer.addData", &json!({"path": path.display().to_string(), "stream": true, "name": "Streamed"})).unwrap(); + s + }; + // The classes are taken from the rows, so from a map that has read them; the sheets under + // test get them on a layer not read yet. + let mut read = streamed(); + read.map_mut().sync_sources(&rustgis_data::Extent::new(-60.0, -20.0, -30.0, -2.0), 1e7, true); + read.run("layer.symbology", &json!({"layer": "Streamed", "type": "unique", "field": "k"})).unwrap(); + let renderer = read.map().layers.iter().find(|l| l.name == "Streamed").unwrap().renderer.clone(); + assert!(matches!(&renderer, rustgis_map::Renderer::Unique { classes, .. } if classes.len() == 6), "{renderer:?}"); + for south in [-20.0, -16.0, -3.0] { + let mut s = streamed(); + s.map_mut().layers.iter_mut().find(|l| l.name == "Streamed").unwrap().renderer = renderer.clone(); + let (l, warnings) = panel_of(&mut s, json!({"extent": area(south)})).unwrap(); + assert!(!warnings.contains(LEGEND_CUT), "south {south}: {warnings}"); + // The rows as drawn: a row left out for room isn't written. + let svg = path.with_extension("svg"); + s.run("layout.export", &json!({"path": svg.display().to_string()})).unwrap(); + let drawn = std::fs::read_to_string(&svg).unwrap(); + let _ = std::fs::remove_file(svg); + for i in 0..6 { + assert!(drawn.contains(&format!("aria-label=\"class {i}\"")), "south {south}: no row for class {i}"); + } + let legend = l.elements.iter().find_map(|e| match &e.kind { + ElementKind::Legend { exclude, .. } => Some(exclude), + _ => None, + }); + let exclude = legend.unwrap_or_else(|| panic!("south {south}: no legend")); + assert!(!exclude.iter().any(|n| n == "Streamed"), "south {south}: {exclude:?}"); + } + let _ = std::fs::remove_file(path); +} + +#[test] +fn a_cut_panel_of_the_whole_globe_keeps_a_long_legend_whole() { + // More rows from layers with short labels: a long one doesn't fit the column's width in every + // font, which the same warning says. + for copies in [4, 6, 8] { + let mut s = world(); + s.run("map.projection", &json!({"type": "globe"})).unwrap(); + let cities = s.map().layers.iter().find(|l| l.name == "Cities").unwrap().clone(); + for i in 0..copies { + let mut copy = cities.clone(); + (copy.id, copy.name) = (1000 + i, format!("Cities {i}")); + s.map_mut().layers.push(copy); + } + let (_, warnings) = panel_of(&mut s, json!({"extent": null})).unwrap(); + assert!(!warnings.contains(LEGEND_CUT), "{copies} copies: {warnings}"); + } +} + +fn matrix_raster() -> std::path::PathBuf { + std::env::temp_dir().join(format!("rustgis-3266-{}-matrix.tif", std::process::id())) +} + +#[test] +fn no_cut_sheet_clips_its_legend() { + type Setup = fn(&mut Session); + let plain: Setup = |_| {}; + let globe: Setup = |s| { + s.run("map.projection", &json!({"type": "globe"})).unwrap(); + }; + // Layers drawn at some scales alone, which a frame of another height can cross. + let scaled: Setup = |s| { + s.run("map.projection", &json!({"type": "globe"})).unwrap(); + for (i, l) in s.map_mut().layers.iter_mut().enumerate() { + l.min_scale = Some([4e8, 2e8, 1e8, 6e7][i % 4]); + } + }; + // The raster is read from its file by each sheet: kept until the last. + let raster: Setup = |s| { + std::fs::write(matrix_raster(), rustgis_data::raster::cog::example(256, 128)).unwrap(); + s.run("layer.addData", &json!({"path": matrix_raster().display().to_string()})).unwrap(); + }; + let cases: [(&str, Setup, Value); 9] = [ + ("plain", plain, json!({})), + ("globe", globe, json!({"extent": null})), + ("globe, scale limited", scaled, json!({"extent": null})), + ("raster colorbar", raster, json!({})), + ("two locators", plain, json!({"locator": ["inset", "globe"]})), + ("no locator", plain, json!({"locator": "none"})), + ("no legend", raster, json!({"legend": "none"})), + ("no key", plain, json!({"legend": "none", "colorbar": "none"})), + ("context listed", plain, json!({"contextInLegend": true})), + ]; + let mut cut = 0; + for profile in crate::cmd::layout::PUBLICATION_PROFILES.iter().filter(|p| p.sheet) { + for (name, setup, extra) in &cases { + for south in [-20.0, -3.0] { + let mut p = json!({"profile": profile.id, "extent": area(south)}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let mut s = world(); + setup(&mut s); + let what = format!("{} {name} {south}", profile.id); + let (l, warnings) = panel_of(&mut s, p).unwrap_or_else(|e| panic!("{what}: {e}")); + // An uncut panel starts at the page's margin and padding: 15 mm on A4. + let whole = named(&l, "Panel Box").y <= 15.0 * l.width.min(l.height) / 210.0 + 0.5; + if !whole { + cut += 1; + if *name == "raster colorbar" { + assert!(l.elements.iter().any(|e| e.kind.code() == "colorbar"), "{what}: no colorbar"); + } + for lost in [LEGEND_CUT, "leaves the legend no room", "colorbar of"] { + assert!(!warnings.contains(lost), "{what}: {warnings}"); + } + } + } + } + } + let _ = std::fs::remove_file(matrix_raster()); + assert!(cut > 100, "{cut} cut sheets"); +} + +#[test] +fn a_very_wide_area_is_cut_down_to_what_the_panel_needs() { + // No legend: under the locator's top, the 30 mm the panel asks for, its 1 mm spare and the + // panel's 3 mm padding; the room the sources take under the map is given once. + for sources in [1, 4] { + let texts = vec!["Boundaries: IBGE 2022"; sources]; + let l = panel(json!({"legend": "none", "sources": texts})).unwrap(); + let room = column(&l); + assert!((33.0..=35.0).contains(&room), "{sources} sources: {room} mm under the locator's top"); + } +}