From 70fcc926dc0848bd1177d002220ae602a4311903 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 21:44:55 -0500 Subject: [PATCH] refactor(render): split layout.rs into a layout module (#3068) --- crates/render/src/layout.rs | 11640 +-------------------- crates/render/src/layout/chart.rs | 395 + crates/render/src/layout/colorbar.rs | 275 + crates/render/src/layout/coverage.rs | 221 + crates/render/src/layout/dynamic_text.rs | 185 + crates/render/src/layout/frame.rs | 552 + crates/render/src/layout/grid.rs | 502 + crates/render/src/layout/legend.rs | 789 ++ crates/render/src/layout/losses.rs | 423 + crates/render/src/layout/north.rs | 60 + crates/render/src/layout/scale_bar.rs | 646 ++ crates/render/src/layout/swatch.rs | 257 + crates/render/src/layout/table.rs | 71 + crates/render/src/layout/tests.rs | 6820 ++++++++++++ crates/render/src/layout/textbox.rs | 226 + 15 files changed, 11519 insertions(+), 11543 deletions(-) create mode 100644 crates/render/src/layout/chart.rs create mode 100644 crates/render/src/layout/colorbar.rs create mode 100644 crates/render/src/layout/coverage.rs create mode 100644 crates/render/src/layout/dynamic_text.rs create mode 100644 crates/render/src/layout/frame.rs create mode 100644 crates/render/src/layout/grid.rs create mode 100644 crates/render/src/layout/legend.rs create mode 100644 crates/render/src/layout/losses.rs create mode 100644 crates/render/src/layout/north.rs create mode 100644 crates/render/src/layout/scale_bar.rs create mode 100644 crates/render/src/layout/swatch.rs create mode 100644 crates/render/src/layout/table.rs create mode 100644 crates/render/src/layout/tests.rs create mode 100644 crates/render/src/layout/textbox.rs diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 035f0e4264..c3ef60a3fa 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -18,6 +18,34 @@ use tiny_skia::{FillRule, Mask, PathBuilder, Pixmap, PixmapPaint, Rect, Stroke, use crate::{View, paint, point_marks, text}; +mod chart; +mod colorbar; +mod coverage; +mod dynamic_text; +mod frame; +mod grid; +mod legend; +mod losses; +mod north; +mod scale_bar; +mod swatch; +mod table; +mod textbox; + +pub use chart::*; +pub use colorbar::*; +pub use coverage::*; +pub use dynamic_text::*; +pub use frame::*; +pub use grid::*; +pub use legend::*; +pub use losses::*; +use north::*; +pub use scale_bar::*; +use swatch::*; +use table::*; +pub use textbox::*; + /// Page values for dynamic text. #[derive(Clone, Debug, Default)] pub struct PageInfo { @@ -251,426 +279,6 @@ pub(crate) fn page_geometry(layout: &Layout, dpi: f64) -> (u32, u32, f64) { (w as u32, h as u32, k.min(w / layout.width).min(h / layout.height)) } -/// Visible text elements (and legend and colorbar titles) whose ink crosses the page boundary, -/// or whose lines the text renderer omits at its box's vertical limit or its 200-line limit. -/// Text is not clipped horizontally to its element: a line wider than its box alone is not a -/// loss. Dynamic text uses this page and its first frame, rotated text is checked after its -/// turn, and a wrapped text (a colorbar's title too) by the lines it is broken into. -pub fn clipped_text(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo) -> Vec<(u32, String)> { - text_losses(layout, maps, dpi, info).into_iter().map(|l| (l.id, l.name)).collect() -} - -/// A text element (or a legend's title) [`clipped_text`] finds cut off, with the lines of it -/// left out of the page (#2346). -#[derive(Debug, Clone, PartialEq)] -pub struct TextLoss { - pub id: u32, - pub name: String, - /// Its lines with ink that aren't drawn: below its box, or past the 200 a text draws. 0 when - /// only its ink crosses the page's edge. - pub left_out: usize, - /// It has more lines left out than `left_out` counts: a wrapped text is broken only up to - /// the line past the 200 drawn ([`wrapped`]). - pub at_least: bool, - /// Some of them are left out below its box, among the first 200: a taller box or a smaller - /// text draws them. For a scale bar, its box is too small for its labels and bar - /// ([`BarLayout::cramped`]): its bar drawn below it, or its end label past its side or over - /// its first label. For a colorbar, also set, with no line counted, when its labels would - /// spill out of its box ([`colorbar_plan`]). - pub below_box: bool, - /// Some of them come past the 200 lines a text draws, whatever its box: only splitting the - /// text draws them. - pub past_limit: bool, - /// Some of its ink crosses the page's edge: a text's drawn lines, or a scale bar's labels. - pub off_page: bool, - /// A scale bar's unit label shortened with an ellipsis to fit its room, or left out with no - /// room for even its first character; `None` for a text, or a unit label drawn whole. - pub unit_label: Option, -} - -/// How a scale bar's unit label is cut to fit its room ([`TextLoss::unit_label`]). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum UnitLabelCut { - /// Shortened with an ellipsis. - Shortened, - /// Left out: not even its first character fits. - LeftOut, -} - -/// [`clipped_text`], with how many of each text's lines are left out of its box ([`TextLoss`]): -/// what the layout view, an export and the commands say, so they never tell it apart. -pub fn text_losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo) -> Vec { - losses(layout, maps, dpi, info, None) -} - -/// [`text_losses`] for the element `id` alone, measuring no other: `None` when it isn't cut off. -pub fn text_loss(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, id: u32) -> Option { - losses(layout, maps, dpi, info, Some(id)).pop() -} - -/// Whether a scale bar `e` drawn in `r` puts a label's ink past the page's `size` in pixels, and -/// whether its box is too small for its labels and bar ([`BarLayout::cramped`]), its labels placed -/// by [`bar_layout`] as the drawing places them: their line's middle at `label_y`, each centred on -/// its advance as `text_at` draws it, and its unit label where it is drawn; and whether that unit -/// label is shortened or left out to fit ([`BarLayout::unit_cut`]). `None` when it draws no bar. -fn bar_labels_cut( - layout: &Layout, - maps: &[Map], - e: &rustgis_map::layout::Element, - r: Rect, - ppp: f32, - size: (f32, f32), -) -> Option<(bool, bool, Option)> { - let ElementKind::ScaleBar { frame, .. } = &e.kind else { return None }; - let ElementKind::MapFrame { map, center, scale, bearing, pitch, .. } = &layout.element(*frame)?.kind else { return None }; - let m = maps.get(map_index(maps, map)?)?; - let ground = m.ground_res_at(&frame_camera(m, *center, *scale, *bearing, *pitch)); - let bar = bar_layout(r, ground, &BarOptions::of(&e.kind)?, f64::from(ppp), layout.decimal_comma)?; - let (w, h) = size; - // Its labels, centred on their divisions, and its unit label where it is drawn. - let unit = bar.unit.as_ref().map(|u| (u.x, u.y, u.text.as_str(), matches!(u.align, text::Align::Center))); - let drawn = bar.labels.iter().map(|(x, s)| (*x, bar.label_y, s.as_str(), true)).chain(unit); - let off_page = drawn.into_iter().any(|(x, y, s, centred)| { - let pen = if centred { x - text::measure(s, bar.px / 1.33, false) / 2.0 } else { x }; - text::styled_bounds(s, bar.px, text::Face::default(), 0.0) - .is_some_and(|ink| pen + ink.left() < 0.0 || y + ink.top() < 0.0 || pen + ink.right() > w || y + ink.bottom() > h) - }); - Some((off_page, bar.cramped, bar.unit_cut)) -} - -/// The texts cut off, of the whole page or of the element `only`. A text's lines are the ones the -/// page draws ([`drawn_text`]), placed as [`text_block`] places them: its block shifted down its -/// box by its alignment and stepped by its spaced pitch. A block taller than its box starts at its -/// top whatever its alignment, so the same trailing lines are left out and counted as for a text -/// at the top. -fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option) -> Vec { - let (w, h, k) = page_geometry(layout, dpi); - let ppp = (k / PT_PER_MM) as f32; - let first = layout.first_frame().and_then(|id| layout.element(id)).and_then(|e| { - let ElementKind::MapFrame { map, center, scale, bearing, pitch, .. } = &e.kind else { return None }; - let m = maps.get(map_index(maps, map)?)?; - Some((m, frame_camera(m, *center, *scale, *bearing, *pitch))) - }); - layout - .elements - .iter() - .filter(|e| e.visible && only.is_none_or(|id| id == e.id)) - .filter_map(|e| { - // At least a pixel each way, as the page draws it. - let r = Rect::from_xywh((e.x * k) as f32, (e.y * k) as f32, ((e.w * k) as f32).max(1.0), ((e.h * k) as f32).max(1.0))?; - // A scale bar's labels where it draws them, at their size (#2581); a bar drawn without - // ink draws none, as a text without ink. - if let ElementKind::ScaleBar { color, .. } = &e.kind { - if color.a() == 0 { - return None; - } - let (off_page, cramped, unit_label) = bar_labels_cut(layout, maps, e, r, ppp, (w as f32, h as f32))?; - return (off_page || cramped || unit_label.is_some()).then(|| TextLoss { - id: e.id, - name: e.name.clone(), - left_out: 0, - at_least: false, - below_box: cramped, - past_limit: false, - off_page, - unit_label, - }); - } - // A colorbar's labels left out for want of height, said with its title (#2638). - let mut labels_cut = false; - // `fits`: how many of its lines the element draws, when it decides that itself. - let (s, size, face, align, spacing, rotation, title, broken, fits, block) = match &e.kind { - ElementKind::Text { - text: t, - size, - color, - bold, - italic, - align, - letter_spacing, - font, - font_name, - rotation, - wrap, - valign, - line_spacing, - case, - .. - } if color.a() > 0 => { - let style = - text_style(*bold, *italic, *font, font_name.as_deref(), *align, *letter_spacing).with_block(*valign, *line_spacing); - // Its lines as they are drawn: in its case, a wrapped text's broken to its box. - let s = drawn_text(expand(t, layout, info, first), *case, *wrap, e.w, *size, style); - ( - s, - *size as f32, - style.face, - *align, - *letter_spacing as f32, - *rotation as f32, - false, - *wrap, - None, - (style.valign, style.line_spacing), - ) - } - // Its title at the size it is drawn at, its legend's text size (#2581). - ElementKind::Legend { title, frame, text_size, .. } => { - let ElementKind::MapFrame { map, .. } = &layout.element(*frame)?.kind else { return None }; - map_index(maps, map)?; - let size = LEGEND_TITLE_PT * legend_size(*text_size); - ( - title.clone(), - size, - text::Face { bold: true, ..Default::default() }, - TextAlign::Left, - 0.0, - 0.0, - true, - false, - None, - (TextVAlign::Top, USUAL_LINE_SPACING), - ) - } - // A colorbar's title in the lines it is drawn in (#2493), when it draws one: its - // frame's map has a raster with a colour scale (else it draws a placeholder). - // Its labels, too, when they would spill out of the element (#2638), as the colorbar - // lays them out ([`colorbar_plan`]). - ElementKind::Colorbar { frame, layer, title, orientation, ticks, tick_side, reverse, .. } => { - let ElementKind::MapFrame { map, .. } = &layout.element(*frame)?.kind else { return None }; - let m = maps.get(map_index(maps, map)?)?; - let scale = rustgis_map::layout::colorbar_layer(m, layer.as_deref()) - .and_then(|l| l.raster.as_ref()) - .and_then(rustgis_map::layout::color_scale)?; - let bar = Bar { - title, - orientation: *orientation, - ticks: *ticks, - side: *tick_side, - reverse: *reverse, - comma: layout.decimal_comma, - ink: INK, - }; - let plan = colorbar_plan(r, &scale, &bar, ppp); - let lines = if title.is_empty() { Vec::new() } else { colorbar_title_lines(title, e.w) }; - let fits = plan.title.len(); - labels_cut = plan.spilled > 0; - if lines.is_empty() && !labels_cut { - return None; - } - let s = lines.join("\n"); - ( - s, - COLORBAR_TITLE_PT as f32, - colorbar_title_style().face, - TextAlign::Left, - 0.0, - 0.0, - false, - true, - Some(fits), - (TextVAlign::Top, USUAL_LINE_SPACING), - ) - } - _ => return None, - }; - let px = size.clamp(2.0, 400.0) * 1.33 * ppp; - // A legend's title sits in the middle of its first row, which grows with its size. - // A text's first line, where its block alignment puts it ([`block_shift`]). - let mut cy = if title { - r.y() + LEGEND_ROW * (size / LEGEND_TITLE_PT) * ppp / 2.0 - } else { - let shift = text_shift(block.0, f64::from(r.height()), f64::from(px), &s, f64::from(block.1)) as f32; - r.y() + shift + px * 0.6 - }; - let turn = Transform::from_rotate_at(rotation, r.x() + r.width() / 2.0, r.y() + r.height() / 2.0); - // Legend titles are drawn on one line, unlike text elements' explicit line breaks. - let lines = std::iter::once(s.as_str()).filter(|_| title).chain(s.lines().filter(|_| !title)); - let (mut cut, mut left_out, mut below_box, mut past_limit, mut off_page) = (false, 0, false, false, false); - for (i, line) in lines.enumerate() { - let drawn = match fits { - Some(n) => i < n, - None => i < 200 && (title || cy <= r.bottom() + px), - }; - // A line not drawn is only looked at for a letter, as a wrapped text tells its - // ink ([`crate::report::wrap_lines`]): a long text isn't shaped past its box. - if !drawn { - if line.chars().any(|c| !c.is_whitespace()) { - (cut, left_out) = (true, left_out + 1); - if i < 200 { - below_box = true; - } else { - past_limit = true; - } - } - continue; - } - let ink = text::styled_bounds(line, px, face, spacing * 1.33 * ppp); - off_page |= ink.is_some_and(|ink| { - let left = match align { - TextAlign::Left => r.x(), - TextAlign::Center => r.x() + (r.width() - ink.width()) / 2.0 - ink.left(), - TextAlign::Right => r.right() - ink.width() - ink.left(), - }; - let mut corners = [ - tiny_skia::Point::from_xy(left + ink.left(), cy + ink.top()), - tiny_skia::Point::from_xy(left + ink.right(), cy + ink.top()), - tiny_skia::Point::from_xy(left + ink.left(), cy + ink.bottom()), - tiny_skia::Point::from_xy(left + ink.right(), cy + ink.bottom()), - ]; - turn.map_points(&mut corners); - corners.iter().any(|p| p.x < 0.0 || p.y < 0.0 || p.x > w as f32 || p.y > h as f32) - }); - cy += px * 1.25 * block.1; - } - // A wrapped text ends at the line past the 200 drawn ([`wrapped`]): it may go on. - let at_least = broken && s.lines().nth(200).is_some(); - below_box |= labels_cut; - (cut || off_page || labels_cut).then(|| TextLoss { - id: e.id, - name: e.name.clone(), - left_out, - at_least, - below_box, - past_limit, - off_page, - unit_label: None, - }) - }) - .collect() -} - -/// One counted notice per kind, naming the affected elements by their stable address. Exports -/// can merge repeated element IDs across series pages before calling this, so a PDF's fallback -/// rendering and repeated pages never multiply the count. Its advice fits the texts of `layout` -/// named: breaking lines by hand or wrapping them for a text not wrapped (#2346), only the box or -/// the size when all are wrapped to their boxes, and line breaks without the wrap for a legend's -/// title, which has none. -pub fn clipped_text_notice(layout: &Layout, clipped: &[(u32, String)]) -> Option { - if clipped.is_empty() { - return None; - } - let mut names = clipped.iter().take(10).map(|(id, name)| format!("{name} ({id})")).collect::>().join(", "); - if clipped.len() > 10 { - names.push_str(&format!(" and {} more", clipped.len() - 10)); - } - // Each text's wrap; `None` for a legend's or a colorbar's title, or an element gone since, - // which keep the advice they always had. - let wraps = clipped - .iter() - .map(|(id, _)| match layout.element(*id).map(|e| &e.kind) { - Some(ElementKind::Text { wrap, .. }) => Some(*wrap), - _ => None, - }) - .collect::>(); - // Scale bars alone: their labels are no text to break (#2581). - let bars = clipped.iter().all(|(id, _)| matches!(layout.element(*id).map(|e| &e.kind), Some(ElementKind::ScaleBar { .. }))); - // Colorbars alone: their titles already wrap, and a tick label isn't fixed by a line break - // (#2638). - let colorbars = clipped.iter().all(|(id, _)| matches!(layout.element(*id).map(|e| &e.kind), Some(ElementKind::Colorbar { .. }))); - let advice = if bars && clipped.len() == 1 { - "move it inside the page or make its box larger, or reduce its text size" - } else if bars { - "move them inside the page or make their boxes larger, or reduce their text size" - } else if colorbars { - "make the colorbar larger or its title shorter, so its title lines and tick labels fit" - } else if wraps.contains(&Some(false)) { - "resize or move the text, reduce its size, add line breaks, or turn on Wrap to the box" - } else if wraps.iter().all(|w| *w == Some(true)) { - "resize or move the text, or reduce its size" - } else { - "resize or move the text, reduce its size, or add line breaks" - }; - Some(format!("Text is cut off in {} layout element(s): {names}; {advice}", clipped.len())) -} - -/// What scale bars whose labels don't fit are told (#2581), from their [`TextLoss`]es: one notice -/// a kind, with the bars' count and names. Their boxes too small for their labels and bars (a bar -/// drawn below its box, or an end label past its side), a label off the page, and a unit label -/// shortened or left out to fit ([`UnitLabelCut`]), each said of every bar it is true of. -pub fn scale_bar_fit_notices(losses: &[TextLoss]) -> Vec { - let said = |small: bool| { - let kind = |l: &&TextLoss| if small { l.below_box } else { l.off_page }; - let names: Vec = losses.iter().filter(kind).map(|l| format!("\"{}\"", l.name)).collect(); - let (n, names) = (names.len(), names.join(", ")); - match (n, small) { - (0, _) => None, - (1, true) => Some(format!( - "Scale bar {names}: its box is too small for its labels at their size, so they or its bar run past it; make it larger or reduce its text size" - )), - (1, false) => Some(format!("Scale bar {names}: a label runs off the page; move it inside the page or reduce its text size")), - (_, true) => Some(format!( - "{n} scale bars ({names}): their boxes are too small for their labels at their size, so they or their bars run past them; make them larger or reduce their text size" - )), - (_, false) => { - Some(format!("{n} scale bars ({names}): a label runs off the page; move them inside the page or reduce their text size")) - } - } - }; - // A unit label shortened to fit, or left out with no room for it. - let unit_said = |cut: UnitLabelCut| { - let names: Vec = losses.iter().filter(|l| l.unit_label == Some(cut)).map(|l| format!("\"{}\"", l.name)).collect(); - let (n, names) = (names.len(), names.join(", ")); - match (n, cut) { - (0, _) => None, - (1, UnitLabelCut::Shortened) => Some(format!( - "Scale bar {names}: its unit label is shortened to fit; make its box larger, reduce its text size or shorten the unit label" - )), - (1, UnitLabelCut::LeftOut) => Some(format!( - "Scale bar {names}: its unit label is left out, as there is no room for it; make its box larger, reduce its text size or shorten the unit label" - )), - (_, UnitLabelCut::Shortened) => Some(format!( - "{n} scale bars ({names}): their unit labels are shortened to fit; make their boxes larger, reduce their text size or shorten the unit labels" - )), - (_, UnitLabelCut::LeftOut) => Some(format!( - "{n} scale bars ({names}): their unit labels are left out, as there is no room for them; make their boxes larger, reduce their text size or shorten the unit labels" - )), - } - }; - [said(true), said(false), unit_said(UnitLabelCut::Shortened), unit_said(UnitLabelCut::LeftOut)].into_iter().flatten().collect() -} - -/// What a text that loses lines is told (#2346), from its [`TextLoss`]: `None` when none of its -/// lines is left out. Lines below its box want a taller box or a smaller text; lines past the 200 -/// a text draws, splitting the text, as no box draws them. -pub fn lines_left_out_notice(loss: &TextLoss) -> Option { - let n = loss.left_out; - if n == 0 && !loss.at_least { - return None; - } - let (count, one) = match (n, loss.at_least) { - (1, false) => ("1 line".to_string(), true), - (n, false) => (format!("{n} lines"), false), - (n, true) => (format!("{} or more lines", n.max(1)), false), - }; - let said = match (loss.below_box, loss.past_limit) { - (_, false) => { - let verbs = if one { "doesn't fit its box and isn't" } else { "don't fit its box and aren't" }; - format!("{verbs} drawn; make the box taller or the text smaller") - } - (false, true) => { - format!("{} drawn: a text draws at most 200 lines; split it into more than one text", if one { "isn't" } else { "aren't" }) - } - (true, true) => format!( - "{} drawn: make the box taller or the text smaller, and split it, as a text draws at most 200 lines", - if one { "isn't" } else { "aren't" } - ), - }; - Some(format!("{count} of the text \"{}\" ({}) {said}", loss.name, loss.id)) -} - -/// What a text whose ink crosses the page's edge is told (#2703), from its [`TextLoss`]: `None` -/// when none does. Its lines left out below its box are [`lines_left_out_notice`]'s: a text can -/// have both, and each is said. -pub fn off_page_notice(loss: &TextLoss) -> Option { - loss.off_page.then(|| { - format!( - "The text \"{}\" ({}) runs off the page, so part of it isn't drawn; move it inside the page, resize it or reduce its size", - loss.name, loss.id - ) - }) -} - /// One element on transparency, allocating only its on-page pixel bounds. /// Outer `None` means rendering failed; inner `None` means the element is off-page. /// A fatal source error is retained for the composed SVG's revision check and error report. @@ -1097,291 +705,6 @@ fn draw_page( Some(pm) } -/// A map frame's map, `w` × `h` points at `ppp` pixels a point, labels and attribution included: -/// what a frame shows before its grid, indicator and outline. It waits for the map's tiles, as a -/// page needs them all. Refuses a linked archive changed during the complete frame. -pub fn frame_map(map: &mut Map, camera: rustgis_map::Camera, w: f64, h: f64, ppp: f64) -> Result { - let revisions = crate::archive_revisions([&*map]); - let mut failed_source = None; - let view = View { width: w, height: h, pixels_per_point: ppp, camera, sky: false }; - let result = frame_canvas(map, &view, false, &mut false, None, &mut failed_source, &Env::default()).map(Canvas::into_pixmap); - revisions.finish(map, failed_source, result, "could not draw the map frame") -} - -/// [`frame_map`] on a canvas: one that records (see [`crate::canvas`]) when `record` and the -/// frame can be kept as vectors (flat, north up, without view effects), else its pixels; with -/// `grid` (and whether the layout writes a decimal comma) drawn on it under the attribution. -/// `pending` is set when some of its tiles, or a read of its streamed layers or rasters, were -/// still on their way (in the browser, which doesn't wait for them). -fn frame_canvas( - map: &mut Map, - view: &View, - record: bool, - pending: &mut bool, - grid: Option<(&Grid, bool)>, - failed_source: &mut Option, - env: &Env, -) -> Option { - // Why its layers were drawn without their cast shadows is kept for the page's caller (see - // `crate::shadows_said`). - let (img, shadows) = crate::frame_with_shadows_to_come(|| crate::complete(map, view, record, failed_source, env)); - let img = img?; - *pending |= img.tiles_pending || img.data_pending || shadows; - Some(finish_frame(img, view.pixels_per_point, grid.map(|(g, comma)| (&*map, view, g, comma)))) -} - -/// [`frame_map`] without waiting for tiles still on their way, for a preview drawn while the -/// interface waits: a pan's preview, whose size is more than the frame's for the overscan slid -/// under the pointer. -pub fn frame_map_preview(map: &mut Map, camera: rustgis_map::Camera, w: f64, h: f64, ppp: f64) -> Option { - frame_map_preview_with(map, camera, w, h, ppp, &Env::default()) -} - -/// Map preview during a layout pan, using the same expression context as its page. -pub fn frame_map_preview_with(map: &mut Map, camera: rustgis_map::Camera, w: f64, h: f64, ppp: f64, env: &Env) -> Option { - let view = View { width: w, height: h, pixels_per_point: ppp, camera, sky: false }; - crate::render_cpu(map, &view, false, false, &mut None, env).map(|img| finish_frame(img, ppp, None).into_pixmap()) -} - -/// A rendered frame map with its labels, its `grid` (drawn on `map` in `view`, with a decimal -/// comma or not) and its attribution drawn on it: on its recording when it was recorded, else on -/// its pixels. The attribution keeps clear of the grid's labels. -fn finish_frame(img: crate::Rendered, ppp: f64, grid: Option<(&Map, &View, &Grid, bool)>) -> Canvas { - let crate::Rendered { pixmap, recorded, labels, unplaced, label_layers, attribution, .. } = img; - let mut pm = recorded.unwrap_or_else(|| Canvas::from_pixmap(pixmap)); - crate::draw_labels(&mut pm, (&unplaced, &labels, &label_layers), ppp as f32); - // The grid is a layer of its own (#1815). - pm.layer(grid.is_some().then_some("Grid")); - let grid_labels = grid.map(|(map, view, g, comma)| draw_grid(&mut pm, map, view, g, comma)).unwrap_or_default(); - pm.layer(None); - let (w, h) = (pm.width() as f32 / ppp as f32, pm.height() as f32 / ppp as f32); - let inset = crate::attribution_text(&attribution).map_or((0.0, 0.0), |(_, tw)| attribution_inset((w, h), tw, &grid_labels)); - crate::draw_attribution(&mut pm, &attribution, ppp as f32, inset); - pm -} - -/// How far further in (up from the bottom, in from the right, in points) the attribution `tw` -/// points wide goes on a frame `w` × `h` points, so it covers none of the grid's bottom and right -/// `labels` (each one's edge, and its box in points: left, top, right, bottom). It goes above a -/// bottom label under it. Beside a right label, it goes left of it when it still fits in the frame -/// there, else above it; when neither fits, as far left as the frame holds it. Where none is in -/// the way, it stays in the corner. -fn attribution_inset((w, h): (f32, f32), tw: f32, labels: &[(Edge, [f32; 4])]) -> (f32, f32) { - let size = crate::ATTRIBUTION_SIZE; - // Half the credit's height, its halo included, and the gap it keeps from a label. - let (half, gap) = (size * 0.8, 2.0); - let (mut bottom, mut right) = (0.0f32, 0.0f32); - // The credit's foot set `gap` above a label's top `y`: how far up from the bottom that is. - let above = |y: f32| h - size * 0.9 + half - y + gap; - // Each move clears the label for good (the credit only goes up and left), so each label is - // met once at most; the last resort ends the search. - for _ in 0..=labels.len() { - // Its whole width, where it is drawn: a credit wider than the frame runs past both edges. - let (cx, cy) = (crate::attribution_center(w, tw, right), h - bottom - size * 0.9); - let (x0, x1, y0, y1) = (cx - tw / 2.0, cx + tw / 2.0, cy - half, cy + half); - let hit = labels - .iter() - .filter(|(e, _)| matches!(e, Edge::Bottom | Edge::Right)) - .find(|(_, b)| x0 < b[2] && b[0] < x1 && y0 < b[3] && b[1] < y1); - match hit { - // Left of the label, its right end `gap` short of it, when all of it stays in. - Some((Edge::Right, b)) if b[0] - gap - tw >= 0.0 => right += x1 - (b[0] - gap), - // Above the label, when all of it stays in. - Some((Edge::Right, b)) if b[1] - gap - 2.0 * half >= 0.0 => bottom = above(b[1]), - // Neither: as far left as the frame holds it (a credit wider than the frame stays put). - Some((Edge::Right, _)) => { - right += x0.max(0.0); - break; - } - Some((_, b)) => bottom = above(b[1]), - None => break, - } - } - (bottom, right) -} - -/// A scale as `{scale}` prints it: `1:6,300,000`, or `1:6.300.000` with a decimal comma. -pub fn scale_ratio_text(scale: f64, comma: bool) -> String { - let ratio = rustgis_map::graphics::scale_ratio(scale); - if comma { decimal(ratio, true) } else { ratio } -} - -/// Expands layout text tokens: the page ones here, the map ones from the first frame. -pub fn expand(t: &str, layout: &Layout, info: &PageInfo, frame: Option<(&Map, rustgis_map::Camera)>) -> String { - // The frame's scale, worked out once for both its forms below. - let scale = frame.map(|(m, cam)| m.ground_res_at(&cam) / rustgis_map::layout::PAPER_M_PER_PT); - // The layer statistics first, read from the text as written: a page or layout name put in - // below isn't read as one. - let t = statistics(t, layout.decimal_comma, frame.map(|(m, _)| m)); - // A layout with a decimal comma prints its scale with points between thousands: put in first, - // so a page or layout name holding "{scale}" isn't read as the token. - let t = match scale { - Some(scale) if layout.decimal_comma => t.replace("{scale}", &scale_ratio_text(scale, true)), - _ => t, - }; - let t = t - .replace("{page}", &info.page.max(1).to_string()) - .replace("{pages}", &info.pages.max(1).to_string()) - .replace("{pageName}", &info.page_name) - .replace("{layout}", &layout.name); - let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); - let v = match frame { - Some((m, cam)) => rustgis_map::graphics::TokenValues { - map: m.name.clone(), - scale: scale.unwrap_or(0.0), - crs: m.projection.label(), - layers: m.layers.iter().filter(|l| !l.graphics).count(), - center: m.to_lonlat(cam.center).unwrap_or_default(), - now, - }, - None => rustgis_map::graphics::TokenValues { - map: String::new(), - scale: 0.0, - crs: String::new(), - layers: 0, - center: Coord::default(), - now, - }, - }; - rustgis_map::graphics::expand(&t, &v) -} - -/// What the layer statistics in `text` (#2853) are missing, one line per token, each once: no map -/// frame, the first frame's map not in the project, no such layer in it, or what -/// [`rustgis_map::layout::layer_statistic`] finds missing (each drawn as written by [`expand`]); and -/// a figure over a layer read in place, which covers only the features loaded, has a line for that -/// as well. -pub fn statistic_notices(layout: &Layout, maps: &[Map], text: &str) -> Vec { - let map = layout.first_frame().and_then(|f| match &layout.element(f)?.kind { - ElementKind::MapFrame { map, .. } => maps.get(map_index(maps, map)?), - _ => None, - }); - let no_map = match layout.first_frame() { - Some(_) => "the map of the layout's first frame is not in the project", - None => "the layout has no map frame whose map it would read", - }; - notices_over(map.ok_or(no_map), "the map of the layout's first frame", text) -} - -/// [`statistic_notices`] for a text whose figures are read from `map`, which the notices call -/// `whose`: a presentation map page's title, drawn over that page's own map. -pub fn map_statistic_notices(map: &Map, whose: &str, text: &str) -> Vec { - notices_over(Ok(map), whose, text) -} - -/// The notices of `text`'s figures over `map`, or why there is none to read. -fn notices_over(map: Result<&Map, &str>, whose: &str, text: &str) -> Vec { - use rustgis_map::layout::StatMissing; - let mut said: Vec = Vec::new(); - let tokens = distinct_stat_tokens(text, true); - // Each layer's figures in one pass, whatever their number. - let figures: Vec)>>> = match map { - Ok(m) => figures_of(m, &tokens).into_iter().map(Some).collect(), - Err(_) => vec![None; tokens.len()], - }; - for (t, found) in tokens.iter().zip(figures) { - let (layer, field) = (t.layer, t.field.unwrap_or_default()); - // A layer read in place holds only what is loaded, so its figure is partial, and one with - // no number yet gets some as more is loaded. - if let Some(Some((true, Ok(_) | Err(StatMissing::NoValue)))) = found { - said.push(format!("{} covers only the features of '{layer}' that are loaded: it is read in place", t.token)); - } - let why = match found.map(|l| l.map(|(_, figure)| figure)) { - None => map.err().unwrap_or_default().to_string(), - Some(None) => format!("{whose} has no layer named '{layer}'"), - Some(Some(Ok(_))) => continue, - Some(Some(Err(StatMissing::Raster))) => format!("'{layer}' is a raster layer, which has no features"), - Some(Some(Err(StatMissing::Field))) if t.field.is_none() => { - format!("a {} takes a field: write {{{}:{layer}:field}}", t.stat.code(), t.stat.code()) - } - Some(Some(Err(StatMissing::Field))) => format!("'{layer}' has no field named '{field}'"), - Some(Some(Err(StatMissing::NotNumeric))) => format!("'{field}' of '{layer}' holds no numbers"), - Some(Some(Err(StatMissing::NoValue))) => { - format!( - "no feature of '{layer}' its definition query keeps has a number in '{field}', or the figure is past a number's range" - ) - } - }; - said.push(format!("{} shows as written: {why}", t.token)); - } - said -} - -/// `t` with its layer statistics (#2853) from `map`, the first frame's, written as a chart writes -/// its values ([`rustgis_map::layout::chart_value_text`]) with `comma` the decimal mark; a token -/// with no figure stays as written ([`statistic_notices`] says why). -fn statistics(t: &str, comma: bool, map: Option<&Map>) -> String { - let Some(m) = map else { return t.to_string() }; - let mut out = t.to_string(); - // `replace` below puts in every occurrence, so a repeated token is worked out once, and the - // figures of one layer in one pass over it. - let tokens = distinct_stat_tokens(t, false); - for (s, figure) in tokens.iter().zip(figures_of(m, &tokens)) { - if let Some((_, Ok(v))) = figure { - out = out.replace(s.token, &decimal(rustgis_map::layout::chart_value_text(v, None), comma)); - } - } - out -} - -/// The layer statistics of `texts` (#2853) as the page draws them from `map`, as (token, figure) -/// pairs for the tokens that have a figure, each token once: what a publication measures its texts -/// with, so a box is sized for the figures it will show, not for the tokens written. -pub fn statistic_figures(map: &Map, comma: bool, texts: &[&str]) -> Vec<(String, String)> { - let mut pairs: Vec<(String, String)> = Vec::new(); - for text in texts { - let tokens = distinct_stat_tokens(text, false); - for (s, figure) in tokens.iter().zip(figures_of(map, &tokens)) { - if let Some((_, Ok(v))) = figure - && !pairs.iter().any(|(token, _)| token == s.token) - { - pairs.push((s.token.to_string(), decimal(rustgis_map::layout::chart_value_text(v, None), comma))); - } - } - } - pairs -} - -/// The statistic tokens of `text`, each once, in the order they come; with `gaps`, the figures -/// written without their field too. -fn distinct_stat_tokens(text: &str, gaps: bool) -> Vec> { - let mut tokens: Vec> = Vec::new(); - let read = if gaps { rustgis_map::layout::stat_tokens_and_gaps(text) } else { rustgis_map::layout::stat_tokens(text) }; - for t in read { - if !tokens.iter().any(|seen| seen.token == t.token) { - tokens.push(t); - } - } - tokens -} - -/// The figure of each of `tokens` in `map`, with whether its layer is read in place; none for a token -/// whose layer the map lacks. The figures of one layer are worked out in one pass over its rows -/// ([`rustgis_map::layout::layer_statistics`]), so a text with many figures costs a pass for each -/// layer, not for each figure. -fn figures_of( - map: &Map, - tokens: &[rustgis_map::layout::StatToken<'_>], -) -> Vec)>> { - let mut out = vec![None; tokens.len()]; - let mut done = vec![false; tokens.len()]; - for i in 0..tokens.len() { - if done[i] { - continue; - } - let same: Vec = (i..tokens.len()).filter(|j| !done[*j] && tokens[*j].layer.eq_ignore_ascii_case(tokens[i].layer)).collect(); - for j in &same { - done[*j] = true; - } - let Some(layer) = map.layer_by_name(tokens[i].layer) else { continue }; - let wanted: Vec<_> = same.iter().map(|j| (tokens[*j].stat, tokens[*j].field)).collect(); - for (j, figure) in same.iter().zip(rustgis_map::layout::layer_statistics(layer, &wanted)) { - out[*j] = Some((layer.is_streamed(), figure)); - } - } - out -} - /// `stroke` dashed along `path` by an element's pattern (points, at `ppp` pixels a point), as a /// line layer's stroke is ([`crate::dash_steps`]): solid when it has none, or when the pattern is /// under a pixel a round or would cut the path into too many dashes. @@ -1449,10860 +772,91 @@ fn decimal(s: String, comma: bool) -> String { .collect() } -fn shape_path(shape: &FrameShape, r: Rect) -> Option { - match shape { - FrameShape::Rectangle => Some(PathBuilder::from_rect(r)), - FrameShape::Circle => { - let d = r.width().min(r.height()); - PathBuilder::from_oval(Rect::from_xywh(r.x() + (r.width() - d) / 2.0, r.y() + (r.height() - d) / 2.0, d, d)?) - } - FrameShape::Ellipse => PathBuilder::from_oval(r), - FrameShape::Polygon(_) => { - let mut pb = PathBuilder::new(); - for (i, (u, v)) in shape.outline().into_iter().enumerate() { - let (px, py) = (r.x() + u as f32 * r.width(), r.y() + v as f32 * r.height()); - if i == 0 { pb.move_to(px, py) } else { pb.line_to(px, py) } - } - pb.close(); - pb.finish() - } - } +/// A grey box with `label` in it, where a frame's map can't be drawn. +fn placeholder(pm: &mut Canvas, r: Rect, label: &str, ppp: f64) { + pm.fill_rect(r, &paint(Rgba::rgb(0xF0, 0xF1, 0xF3), 1.0), Transform::identity(), None); + let p = PathBuilder::from_rect(r); + pm.stroke_path( + &p, + &paint(Rgba::rgb(0xA0, 0xA4, 0xAA), 1.0), + &Stroke { width: ppp as f32, ..Stroke::default() }, + Transform::identity(), + None, + ); + text::text_at( + pm, + label, + r.x() + r.width() / 2.0, + r.y() + r.height() / 2.0, + 10.0 * 1.33 * ppp as f32, + Rgba::rgb(0x70, 0x74, 0x7A), + false, + text::Align::Center, + false, + ); } -/// The lon/lat outline of what a frame shows, `None` where an edge has no place on the Earth (off -/// the disc of a frame on the globe, or outside a custom projection's domain): the outline breaks -/// there rather than cutting across the map it is drawn on, and reaches the place where the edge -/// leaves it (#2369). -fn frame_outline_lonlat(map: &Map, cam: &rustgis_map::Camera, w: f64, h: f64) -> Vec> { - let n = 16; - let edge = |t: f64, side: usize| match side { - 0 => (t * w, 0.0), - 1 => (w, t * h), - 2 => ((1.0 - t) * w, h), - _ => (0.0, (1.0 - t) * h), - }; - // A frame on the globe is read through the globe as it draws it (#2348), with a gap where an - // edge runs off the disc: one that shows the globe whole has no edge on it, and no outline. - let globe = map.projection.is_globe().then(|| rustgis_map::globe::Globe::new(cam, w, h)); - let at = |(sx, sy): (f64, f64)| match &globe { - Some(g) => g.inverse(sx, sy), - None => map.to_lonlat(cam.to_map(sx, sy, w, h)), - }; - // A frame on the globe has its longitudes kept continuous, a turn added or taken where they - // cross ±180°, so on a flat frame the outline doesn't jump across the map there. A flat - // frame's are drawn where they are. - let mut last: Option = None; - let mut ring = Vec::with_capacity(4 * n + 8); - let mut push = |c: Option| { - let c = match (globe.is_some(), c, last) { - (true, Some(c), Some(p)) => Some(Coord::new(c.x + 360.0 * ((p - c.x) / 360.0).round(), c.y)), - _ => c, - }; - if let Some(c) = c { - last = Some(c.x); - } - ring.push(c); - }; - let mut first = None; - let mut prev: Option<((f64, f64), Option)> = None; - // Every side's samples, and the first again to close the ring. - for i in 0..=4 * n { - let p = edge((i % n) as f64 / n as f64, (i / n) % 4); - let c = match first { - Some(f) if i == 4 * n => f, - _ => at(p), - }; - first.get_or_insert(c); - // Between a sample with a place and one without, the place where the edge leaves the - // Earth, found by bisecting (24 halvings take a sixteenth of the edge to well under a - // millionth of it): without it the outline stops up to a sample short of it. - if let Some((q, b)) = prev - && b.is_some() != c.is_some() - { - let (mut inside, mut outside, mut found) = if b.is_some() { (q, p, b) } else { (p, q, c) }; - for _ in 0..24 { - let mid = ((inside.0 + outside.0) / 2.0, (inside.1 + outside.1) / 2.0); - match at(mid) { - Some(m) => (inside, found) = (mid, Some(m)), - None => outside = mid, - } - } - push(found); - } - push(c); - prev = Some((p, c)); +/// Fills `pts` with `fill` and outlines it with `outline`. +fn shape(pm: &mut Canvas, pts: &[(f32, f32)], fill: Rgba, outline: Rgba, width: f32) { + let mut pb = PathBuilder::new(); + for (i, (x, y)) in pts.iter().enumerate() { + if i == 0 { pb.move_to(*x, *y) } else { pb.line_to(*x, *y) } } - ring -} - -/// The map frames of a page georeferenced for a PDF ([`frame_viewports`], #1191). -#[derive(Debug, Default)] -pub struct Georeferenced { - /// The georeferenced frames, in drawing order, each in the rectangles no frame drawn over it - /// covers (`uncovered`): no two overlap, so a reader never has two to choose from. - pub viewports: Vec, - /// The frames that couldn't be, by id and name, with why. - pub left_out: Vec<(u32, String, &'static str)>, - /// The frames whose coordinate system can't be written as WKT (a grid shift, or a projection - /// WKT1 has no name for), by id and name: - /// georeferenced by their corners in longitude/latitude, which put the places of a 9 × 9 grid - /// over the frame within [`MAX_CORNER_FIT_MM`] of where they are drawn (`corner_fit_mm`). - pub by_corners: Vec<(u32, String)>, -} - -/// How far, on paper, a frame georeferenced by its corners in longitude/latitude may put a place -/// from where the frame draws it: past it, the frame is left out (#1191). -pub const MAX_CORNER_FIT_MM: f64 = 0.5; - -/// Each visible map frame of `layout` as a PDF viewport ([`crate::pdf::Viewport`]): its place on -/// the page as a page drawn at `dpi` places it, its corners' latitude and longitude, and its -/// map's coordinate system as WKT. A frame on the globe or tilted shows no flat map to measure -/// on, so it is left out, as is one on another body than the Earth, one whose map is missing, -/// one with a corner off the Earth, one across its projection's edge (the 180° meridian) and one -/// whose system has no WKT and whose corners alone would misplace it. A frame drawn over another, -/// left out or not, is cut out of the other's viewport, so that the other's coordinates don't show -/// through it: a viewport without coordinates would do it by the standard (the last viewport -/// holding a point is taken, ISO 32000-1, 12.9.2), but Acrobat Reader doesn't take one. -pub fn frame_viewports(layout: &Layout, maps: &[Map], dpi: f64) -> Georeferenced { - let mut out = Georeferenced::default(); - // A frame is drawn from a whole pixel of the page ([`draw_page`]), whose pixels are stretched - // over its paper: the viewport is that box, in millimetres. - let (wpx, hpx, k) = page_geometry(layout, dpi); - let (sx, sy) = (layout.width / f64::from(wpx.max(1)), layout.height / f64::from(hpx.max(1))); - let frames: Vec<_> = layout - .elements - .iter() - .filter(|e| e.visible && matches!(e.kind, ElementKind::MapFrame { .. })) - // Rounded as `draw_page` rounds them, in single precision, so the box is the drawn one. - .map(|e| (e, [f64::from(((e.x * k) as f32).round()) * sx, f64::from(((e.y * k) as f32).round()) * sy, e.w * k * sx, e.h * k * sy])) - .collect(); - for (i, (e, placed)) in frames.iter().enumerate() { - let ElementKind::MapFrame { map, center, scale, bearing, pitch, shape, .. } = &e.kind else { continue }; - // A viewport is a rectangle: one for a shaped frame over another would give its places - // where the page shows the other's map, around the shape. (It still cuts the other.) - let over = - |[x, y, w, h]: [f64; 4]| x < placed[0] + placed[2] && placed[0] < x + w && y < placed[1] + placed[3] && placed[1] < y + h; - if *shape != rustgis_map::layout::FrameShape::Rectangle && frames[..i].iter().any(|(_, r)| over(*r)) { - out.left_out.push(( - e.id, - e.name.clone(), - "it isn't a rectangle and is drawn over another frame, whose map shows around its shape", - )); - continue; - } - let Some(m) = map_index(maps, map).and_then(|i| maps.get(i)) else { - out.left_out.push((e.id, e.name.clone(), "its map is missing")); - continue; - }; - if !placed.iter().all(|v| v.is_finite()) { - out.left_out.push((e.id, e.name.clone(), "its place on the page isn't a number")); - continue; - } - // What the frames drawn over it leave of it. - let mut shown = vec![*placed]; - for (_, over) in &frames[i + 1..] { - shown = shown.into_iter().flat_map(|r| uncovered(r, *over)).collect(); - // Past the most, it is left out: cutting on would only make more. - if shown.len() > MAX_VIEWPORTS_A_FRAME { - break; - } - } - if shown.is_empty() { - out.left_out.push((e.id, e.name.clone(), "the frames drawn over it cover all of it")); - continue; - } - if shown.len() > MAX_VIEWPORTS_A_FRAME { - out.left_out.push((e.id, e.name.clone(), "too many frames are drawn over it")); - continue; - } - match frame_viewport(e, *placed, &shown, m, rustgis_map::layout::frame_camera(m, *center, *scale, *bearing, *pitch)) { - Ok((v, exact)) => { - if !exact { - out.by_corners.push((e.id, e.name.clone())); - } - out.viewports.extend(v); - } - Err(why) => out.left_out.push((e.id, e.name.clone(), why)), - } + pb.close(); + if let Some(p) = pb.finish() { + pm.fill_path(&p, &paint(fill, 1.0), FillRule::Winding, Transform::identity(), None); + pm.stroke_path(&p, &paint(outline, 1.0), &Stroke { width, ..Stroke::default() }, Transform::identity(), None); } - out } -/// The most rectangles a frame's viewport is cut into by the frames drawn over it; past it, the -/// frame is left out. -const MAX_VIEWPORTS_A_FRAME: usize = 64; - -/// A strip narrower than this, in millimetres, left of a frame beside one drawn over it, is -/// dropped: no one points into it. -const MIN_STRIP_MM: f64 = 0.01; - -/// Rectangle `r` (x, y, width, height) without `cut`: up to four rectangles, the bands above and -/// below the cut, and beside it between them. -fn uncovered(r: [f64; 4], cut: [f64; 4]) -> Vec<[f64; 4]> { - let (x0, y0, x1, y1) = (r[0], r[1], r[0] + r[2], r[1] + r[3]); - let (cx0, cy0, cx1, cy1) = (cut[0].max(x0), cut[1].max(y0), (cut[0] + cut[2]).min(x1), (cut[1] + cut[3]).min(y1)); - if cx0 >= cx1 || cy0 >= cy1 { - return vec![r]; +/// A box filled with `colour`; none where it has no size. +fn fill(pm: &mut Canvas, colour: Rgba, x: f32, y: f32, w: f32, h: f32) { + if let Some(b) = Rect::from_xywh(x, y, w, h) { + pm.fill_rect(b, &paint(colour, 1.0), Transform::identity(), None); } - [(x0, y0, x1, cy0), (x0, cy1, x1, y1), (x0, cy0, cx0, cy1), (cx1, cy0, x1, cy1)] - .into_iter() - .filter(|(a, b, c, d)| c - a >= MIN_STRIP_MM && d - b >= MIN_STRIP_MM) - .map(|(a, b, c, d)| [a, b, c - a, d - b]) - .collect() } -/// How far, in millimetres on paper, a reader that fits a frame's corners in longitude/latitude -/// (`corners`, latitude then longitude, clockwise from the top-left) puts the places on a 9 × 9 -/// grid over it, its edges included, from where the frame, `w` × `h` points seen by `cam`, draws -/// them: the worst of them, the fit being exact at the corners. `None` when one of them isn't on -/// the map. -fn corner_fit_mm(corners: &[(f64, f64); 4], map: &Map, cam: &rustgis_map::Camera, w: f64, h: f64) -> Option { - let [tl, tr, br, bl] = *corners; - let mut worst: f64 = 0.0; - // A 9 × 9 grid over the frame, its edges included (the corners are exact). - let grid = (0..=8).flat_map(|i| (0..=8).map(move |j| (f64::from(i) / 8.0, f64::from(j) / 8.0))); - for (u, t) in grid { - // Between the corners, as the unit square's (`/LPTS`) is filled: bilinearly. - let mix = |a: f64, b: f64, c: f64, d: f64| (1.0 - u) * (1.0 - t) * a + u * (1.0 - t) * b + u * t * c + (1.0 - u) * t * d; - let (lat, lon) = (mix(tl.0, tr.0, br.0, bl.0), mix(tl.1, tr.1, br.1, bl.1)); - let at = map.to_map(Coord::new((lon + 540.0).rem_euclid(360.0) - 180.0, lat))?; - let (x, y) = cam.try_to_screen(at, w, h)?; - // `f64::max` ignores NaN: a sample that isn't a number is no fit. - let off = (x - u * w).hypot(y - t * h); - if !off.is_finite() { - return None; - } - worst = worst.max(off); - } - (worst.is_finite()).then_some(worst / PT_PER_MM) +/// The first case-insensitive frame-map name match; a missing reference renders no map. +pub fn map_index(maps: &[rustgis_map::Map], name: &str) -> Option { + maps.iter().position(|map| map.name.eq_ignore_ascii_case(name)) } -/// Frame `e` of `map`, placed at `placed` (millimetres: x, y, width, height) and seen by `cam`, as -/// a viewport for each rectangle of it in `shown`, and whether it is in the map's own coordinate -/// system (else in longitude/latitude, by its corners). -fn frame_viewport( - e: &rustgis_map::layout::Element, - placed: [f64; 4], - shown: &[[f64; 4]], - map: &Map, - cam: rustgis_map::Camera, -) -> Result<(Vec, bool), &'static str> { - use rustgis_data::raster::{crs, wkt}; - if map.projection.is_globe() { - return Err("it shows the globe"); - } - // Its coordinates are another body's, which an Earth system would misplace. - if !map.body().is_earth() { - return Err("it is on another body than the Earth"); - } - if cam.pitch.abs() > 1e-9 { - return Err("it is tilted"); - } - // The map's coordinate system: its WKT and EPSG code, and its PROJ definition (whose datum - // the corners are given on). - let (system, def) = match &map.projection { - rustgis_map::Projection::Custom(code) => { - let (def, label) = rustgis_map::projection::lookup(code).map_err(|_| "its projection can't be read")?; - let lower = code.trim().to_ascii_lowercase(); - let digits = lower.strip_prefix("epsg").map_or(lower.as_str(), |r| r.trim_start_matches([':', ' '])); - let epsg = digits.parse::().ok().filter(|_| digits.bytes().all(|b| b.is_ascii_digit())); - let text = match epsg { - Some(c) => wkt::to_wkt(crs::Crs::Epsg(c)), - None => wkt::proj4_to_wkt(&def, &label), - }; - (text.map(|t| (t, epsg)), Some(def)) - } - _ => (wkt::to_wkt(crs::Crs::WebMercator).map(|t| (t, Some(3857))), None), - }; - let (w, h) = (e.w * PT_PER_MM, e.h * PT_PER_MM); - // The latitude and longitude of the frame's point `(sx, sy)` (points from its top-left). - let place = |sx: f64, sy: f64| -> Result<(f64, f64), &'static str> { - let m = cam.try_to_map(sx, sy, w, h).ok_or("a corner is off the Earth")?; - let c = map.to_lonlat(m).ok_or("a corner is off the Earth")?; - // A corner past the projection's edge (Web Mercator's world repeated across 180°) is at a - // longitude past ±180°, or comes back elsewhere: a reader, which takes longitudes within - // ±180°, would put it on the other side of the world. (In longitude/latitude, below, the - // corners are kept within half a turn of each other instead.) - let back = map.to_map(c).ok_or("a corner is off the Earth")?; - let elsewhere = (back.x - m.x).abs() > 1e-6 * m.x.abs().max(1.0) || (back.y - m.y).abs() > 1e-6 * m.y.abs().max(1.0); - if elsewhere || (system.is_some() && c.x.abs() > 180.0) { - return Err("it crosses its projection's edge (the 180° meridian)"); - } - // On the system's own datum, as a reader that takes its WKT reads them. - let c = match (&system, &def) { - (Some(_), Some(def)) => crs::lonlat_on_datum_of(def, c).ok_or("its corners can't be moved onto its datum")?, - _ => c, - }; - // A value no PDF number can be (from a hostile project) is no place. - if !(c.x.is_finite() && c.y.is_finite()) { - return Err("a corner is off the Earth"); - } - Ok((c.y, c.x)) - }; - // Clockwise from the top-left, as `/LPTS` takes them. - let corners_of = |[x0, y0, x1, y1]: [f64; 4]| -> Result<[(f64, f64); 4], &'static str> { - Ok([place(x0, y0)?, place(x1, y0)?, place(x1, y1)?, place(x0, y1)?]) +/// Pages of one text each with none of the block settings, in the combinations main draws: each +/// alignment, wrapped or not, turned 0, 90, -90 or 33 degrees, spaced 0 or 3 points (bold, and +/// italic when turned 33), in a box that holds its lines and one that cuts them; and two texts +/// across the page's right and bottom edges. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn plain_text_pages() -> Vec { + let text = "Population counts\nfrom the 2020 census; boundaries simplified for print\nPage {page} of {pages}"; + let page = |at: (f64, f64, f64, f64), f: &dyn Fn(&mut ElementKind)| { + let mut l = Layout::new("Plain", 120.0, 80.0); + let mut kind = ElementKind::text(text, 11.0, Rgba::rgb(0, 0, 0), false); + f(&mut kind); + l.add("Note", at, kind); + l }; - let mut corners = corners_of([0.0, 0.0, w, h])?; - let exact = system.is_some(); - let (wkt, epsg) = match &system { - Some((text, code)) => (text.clone(), *code), - None => { - // In longitude/latitude the corners are fitted as they are: across 180° they are kept - // within half a turn of the first, so that the frame isn't taken to span the world. - let first = corners[0].1; - for c in &mut corners { - c.1 = first + ((c.1 - first + 540.0).rem_euclid(360.0) - 180.0); - } - // A reader is right at the corners only: the frame is written if, between them, it - // puts no place more than half a millimetre on paper from where the frame draws it. - match corner_fit_mm(&corners, map, &cam, w, h) { - Some(off) if off <= MAX_CORNER_FIT_MM => {} - Some(_) => { - return Err( - "its coordinate system can't be written as WKT, and its corners alone would put places more than 0.5 mm off", - ); + let mut pages = Vec::new(); + for align in TextAlign::ALL { + for wrap in [false, true] { + for turn in [0.0, 90.0, -90.0, 33.0] { + for spacing in [0.0, 3.0] { + for h in [40.0, 9.0] { + pages.push(page((10.0, 10.0, 60.0, h), &|k| { + if let ElementKind::Text { align: a, wrap: w, rotation, letter_spacing, italic, bold, .. } = k { + (*a, *w, *rotation, *letter_spacing) = (align, wrap, turn, spacing); + (*italic, *bold) = (turn == 33.0, spacing > 0.0); + } + })); + } } - None => return Err("its coordinate system can't be written as WKT, and a place between its corners is off the map"), } - (wkt::to_wkt(crs::Crs::LonLat).ok_or("its projection can't be read")?, Some(4326)) } - }; - let first = corners[0].1; - let mut viewports = Vec::with_capacity(shown.len()); - for r in shown { - // The rectangle's corners in the frame's points, the frame being `placed` on the page. - let to = |mm: f64, from: f64, size: f64, pts: f64| (mm - from) / size * pts; - let (x0, y0) = (to(r[0], placed[0], placed[2], w), to(r[1], placed[1], placed[3], h)); - let (x1, y1) = (to(r[0] + r[2], placed[0], placed[2], w), to(r[1] + r[3], placed[1], placed[3], h)); - let mut corners = if *r == placed { corners } else { corners_of([x0, y0, x1, y1])? }; - if !exact { - for c in &mut corners { - c.1 = first + ((c.1 - first + 540.0).rem_euclid(360.0) - 180.0); - } - } - let measure = crate::pdf::GeoMeasure { corners, wkt: wkt.clone(), projected: exact, epsg }; - viewports.push(crate::pdf::Viewport { name: e.name.clone(), rect_mm: *r, measure }); - } - Ok((viewports, exact)) -} - -/// A ring (longitude, latitude), broken at each `None`, placed on a flat map for drawing: where its -/// points go on the map's world, whose middle (its camera's centre) is at `mid`. `from_globe`: the -/// ring is a frame on the globe's, its longitudes run on across ±180° rather than kept in a world. -/// -/// A frame on the globe has its whole ring shifted a turn east or west if that brings the middle -/// of its longitudes nearer the map's middle, as they run on from its first point (#2348), which -/// can be on the other side of ±180° from it: one shift for all keeps it in one piece on a map -/// that doesn't wrap. A flat frame's ring is placed where it is. Then a ring that a map can't show in one piece -/// is cut at the map's edge as the map cuts features (#209), each piece brought into the map's -/// world and running to the edge (#2369): any ring on a world projection, which wraps at its edge -/// (on Robinson centred on 150°E at -30°, with its datum's margin), and on Web Mercator, which -/// doesn't, a globe frame's around a pole, which runs a whole turn, at ±180°. -fn ring_on_flat(map: &Map, mid: Option, ring: &[Option], from_globe: bool) -> Vec> { - use rustgis_data::Geometry; - let (west, east) = ring.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(w, e), c| (w.min(c.x), e.max(c.x))); - let around_pole = from_globe && east - west >= 360.0 - 1e-6; - let shift = match (from_globe && !around_pole && west <= east, mid) { - (true, Some(mid)) => 360.0 * ((mid.x - (west + east) / 2.0) / 360.0).round(), - _ => 0.0, - }; - let shifted = ring.iter().map(|c| c.map(|c| Coord::new(c.x + shift, c.y))); - let flat = map.flat(); - let edge = match &flat { - rustgis_map::projection::Flat::Custom(p) => p.edge().copied(), - rustgis_map::projection::Flat::Mercator => None, - }; - if edge.is_none() && !around_pole { - return shifted.collect(); } - let shifted: Vec> = shifted.collect(); - let runs = shifted.split(Option::is_none).map(|r| r.iter().flatten().copied().collect()).collect(); - let (lon0, margin) = edge.map_or((0.0, None), |e| (e.lon - 180.0, Some(e))); - let margin = |lat: f64| margin.map_or(0.0, |e| e.stray_at(lat)); - // A line cut is a line: the `else` is never taken. - let Geometry::Line(pieces) = rustgis_map::antimeridian::cut_with_margin(&Geometry::Line(runs), lon0, &margin) else { - return shifted; - }; - pieces.into_iter().flat_map(|p| p.into_iter().map(Some).chain([None])).collect() + pages.push(page((90.0, 10.0, 60.0, 30.0), &|_| {})); + pages.push(page((10.0, 74.0, 60.0, 30.0), &|_| {})); + pages } -/// Strokes the ring `ring` (longitude, latitude) on a frame's map `width` points wide: another -/// frame's extent, as an extent indicator shows it, broken at each `None`. `from_globe`: the ring -/// is a frame on the globe's, its longitudes run on across ±180° rather than kept in a world. -fn outline_lonlat(pm: &mut Canvas, map: &Map, view: &View, ring: &[Option], from_globe: bool, color: Rgba, width: f32) { - let ppp = view.pixels_per_point as f32; - // On a globe, through the globe as the frame draws it, breaking behind its horizon (#2348): - // through the flat camera the outline lands off the area once it is away from the centre. - let globe = map.projection.is_globe().then(|| rustgis_map::globe::Globe::new(&view.camera, view.width, view.height)); - let placed; - let ring = match globe { - Some(_) => ring, - None => { - placed = ring_on_flat(map, map.to_lonlat(view.camera.center), ring, from_globe); - &placed[..] - } - }; - let project = |c: Coord| match &globe { - Some(g) => g.forward(c), - // A tilted frame's outline breaks where it passes behind the eye, and any frame's where - // its projection can't show the place (#2369). - None => map.to_map(c).and_then(|m| view.camera.try_to_screen(m, view.width, view.height)), - }; - let mut pb = PathBuilder::new(); - let mut first = true; - let mut push = |at: Option<(f64, f64)>| { - let Some((x, y)) = at else { - first = true; - return; - }; - let (x, y) = (x as f32 * ppp, y as f32 * ppp); - if first { - pb.move_to(x, y); - first = false; - } else { - pb.line_to(x, y); - } - }; - let mut previous: Option<(Coord, Option<(f64, f64)>)> = None; - for &c in ring { - let at = c.and_then(project); - if globe.is_none() - && let (Some((last, last_at)), Some(c)) = (previous, c) - && last_at.is_some() != at.is_some() - { - // Reach the overview's projection boundary, rather than stop at the last sample - // inside it (#2433). Keep the valid side of 24 halvings, as frame_outline_lonlat - // does for the source frame's boundary. An explicit gap never enters this search. - let (mut inside, mut outside, mut found) = if last_at.is_some() { (last, c, last_at) } else { (c, last, at) }; - for _ in 0..24 { - // Samples can straddle ±180° on a regional projection without a wrapping edge: - // follow their short arc rather than bisect across the other side of the map. - let lon = inside.x + ((outside.x - inside.x + 540.0).rem_euclid(360.0) - 180.0) / 2.0; - let mid = Coord::new(lon, (inside.y + outside.y) / 2.0); - match project(mid) { - Some(point) => (inside, found) = (mid, Some(point)), - None => outside = mid, - } - } - push(found); - } - push(at); - previous = c.map(|c| (c, at)); - } - if let Some(p) = pb.finish() { - pm.stroke_path(&p, &paint(color, 1.0), &Stroke { width: width * ppp, ..Stroke::default() }, Transform::identity(), None); - } -} - -/// A graticule label as [`Grid::label`] writes it, with plain `'` and `"` for minutes and seconds -/// when the label font has no prime marks. -fn grid_label(g: &Grid, v: f64, lon: bool, step: f64) -> String { - let s = g.label(v, lon, step); - if text::covers(&s, false) { s } else { s.replace('′', "'").replace('″', "\"") } -} - -/// A graticule's lines over `ext` (longitude/latitude), each with its label. -fn graticule_lines(g: &Grid, ext: Extent, comma: bool, lines: &mut Vec<(Vec, String, bool)>) { - if ext.is_empty() { - return; - } - let span = ext.width().max(ext.height()); - let step = if g.step > 0.0 { - g.step.max(0.001) - } else { - *[0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 15.0, 30.0, 45.0].iter().find(|s| span / **s <= 8.0).unwrap_or(&60.0) - }; - // Lines run a little past the frame so they cross its edges rather than end on them. - let pad = span * 0.02; - let (lat0, lat1) = ((ext.min_y - pad).max(-89.9), (ext.max_y + pad).min(89.9)); - let (lon0, lon1) = (ext.min_x - pad, ext.max_x + pad); - let mut n = 0; - let mut lon = (ext.min_x / step).floor() * step; - while lon <= ext.max_x + step * 1e-9 && n < 200 { - let pts = (0..=48).map(|i| Coord::new(lon, lat0 + (lat1 - lat0) * i as f64 / 48.0)).collect(); - lines.push((pts, decimal(grid_label(g, lon, true, step), comma), true)); - lon += step; - n += 1; - } - let mut lat = (ext.min_y / step).floor() * step; - while lat <= ext.max_y + step * 1e-9 && n < 400 { - if lat.abs() <= 90.0 { - let pts = (0..=48).map(|i| Coord::new(lon0 + (lon1 - lon0) * i as f64 / 48.0, lat)).collect(); - lines.push((pts, decimal(grid_label(g, lat, false, step), comma), false)); - } - lat += step; - n += 1; - } -} - -/// The most lines a measured grid draws each way: past them its step is widened to draw at most -/// [`WIDENED_LINES`]. -const MAX_MEASURED_LINES: f64 = 100.0; -/// About how many lines a step too fine for the frame is widened to. -const WIDENED_LINES: f64 = 50.0; - -/// A measured grid's lines over the frame whose edges are `lonlats`, in the coordinate system of -/// `tr`: eastings (north–south) and northings, each back in longitude/latitude, with its label. -pub(crate) fn measured_lines( - g: &Grid, - tr: &rustgis_data::raster::Transformer, - lonlats: &[Coord], - comma: bool, - lines: &mut Vec<(Vec, String, bool)>, -) { - let mut ext = Extent::EMPTY; - for c in lonlats.iter().filter_map(|c| tr.from_lonlat(*c)) { - ext.expand(c); - } - if ext.is_empty() || !(ext.width().is_finite() && ext.height().is_finite()) { - return; - } - let span = ext.width().max(ext.height()); - let given = g.step.clamp(0.0, rustgis_map::layout::MAX_MEASURED_STEP); - let step = if given > 0.0 { - given.max(rustgis_map::layout::MIN_MEASURED_STEP) - } else if g.mgrs { - // (At most 100 km apart, so MGRS's squares are drawn whole.) - nice_step(span, rustgis_map::layout::MIN_MEASURED_STEP).min(100_000.0) - } else { - nice_step(span, rustgis_map::layout::MIN_MEASURED_STEP) - }; - // A step too fine for the frame (a 1 m grid over a country) is widened, not drawn as a blur. - let step = if span / step > MAX_MEASURED_LINES { nice_step(span * 8.0 / WIDENED_LINES, step) } else { step }; - let pad = span * 0.02; - let (x0, x1, y0, y1) = (ext.min_x - pad, ext.max_x + pad, ext.min_y - pad, ext.max_y + pad); - let back = |x: f64, y: f64| tr.to_lonlat(Coord::new(x, y)); - // Counted too: at coordinates far larger than the step, adding it may not move a line on. - let most = 2 * MAX_MEASURED_LINES as usize; - let first = |min: f64| (min / step).floor() * step; - for (i, x) in - std::iter::successors(Some(first(ext.min_x)), |x| Some(x + step)).take_while(|x| *x <= ext.max_x + step * 1e-9).enumerate() - { - if i >= most { - break; - } - // (A point that doesn't convert is left out.) - let pts: Vec = (0..=48).filter_map(|i| back(x, y0 + (y1 - y0) * f64::from(i) / 48.0)).collect(); - lines.push((pts, decimal(g.measured_label(x, step), comma), true)); - } - for (i, y) in - std::iter::successors(Some(first(ext.min_y)), |y| Some(y + step)).take_while(|y| *y <= ext.max_y + step * 1e-9).enumerate() - { - if i >= most { - break; - } - let pts: Vec = (0..=48).filter_map(|i| back(x0 + (x1 - x0) * f64::from(i) / 48.0, y)).collect(); - lines.push((pts, decimal(g.measured_label(y, step), comma), false)); - } -} - -/// Where a polyline (in pixels) crosses the edges of a `w` × `h` frame, as (edge, position along -/// it): the top and bottom edges give x, the left and right ones y. -fn edge_crossings(pts: &[(f32, f32)], w: f32, h: f32) -> Vec<(Edge, f32)> { - let mut out = Vec::new(); - for pair in pts.windows(2) { - let &[(x0, y0), (x1, y1)] = pair else { continue }; - for (edge, a, b, at) in [(Edge::Top, y0, y1, 0.0), (Edge::Bottom, y0, y1, h), (Edge::Left, x0, x1, 0.0), (Edge::Right, x0, x1, w)] { - let (da, db) = (a - at, b - at); - // Counted once where a vertex sits on the edge, and never along it. - if !((da <= 0.0 && db > 0.0) || (da > 0.0 && db <= 0.0)) { - continue; - } - let t = da / (da - db); - let (along, limit) = match edge { - Edge::Top | Edge::Bottom => (x0 + (x1 - x0) * t, w), - Edge::Left | Edge::Right => (y0 + (y1 - y0) * t, h), - }; - if along.is_finite() && (0.0..=limit).contains(&along) { - out.push((edge, along)); - } - } - } - out -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Edge { - Top, - Bottom, - Left, - Right, -} - -/// The coordinate system of a measured grid on `map`: the grid's own, else the map's when it is -/// projected, else the WGS 84 UTM zone at `center` (longitude/latitude). With MGRS labels, only a -/// WGS 84 UTM zone: the one named, else the map's when it is one, else MGRS's zone at `center`. -/// `None` for one that can't be read or isn't projected. -pub fn measured_crs(g: &Grid, map: &Map, center: Coord) -> Option { - use rustgis_data::raster::Crs; - use rustgis_map::layout::utm_zone_of; - let utm = |(zone, north): (u8, bool)| Crs::from_epsg(if north { 32_600 } else { 32_700 } + u32::from(zone)); - let named = g.crs.as_deref().map(str::trim).filter(|c| !c.is_empty()); - let crs = match named { - // (One longer than a command keeps, from a crafted project, isn't read each frame.) - Some(c) if c.chars().count() > rustgis_map::layout::MAX_GRID_CRS => return None, - Some(c) if g.mgrs => utm(utm_zone_of(c)?)?, - Some(c) => Crs::parse(c).ok()?, - // The map's own: its code (a preset, EPSG:, ESRI: or local:) as its PROJ definition. - None => match &map.projection { - rustgis_map::Projection::Custom(code) if g.mgrs => utm_zone_of(code).and_then(utm), - rustgis_map::Projection::Custom(code) => rustgis_map::projection::lookup(code) - .ok() - .and_then(|(def, _)| Crs::parse(&def).ok()) - .or_else(|| Crs::parse(code).ok()) - .filter(|c| !c.is_geographic()), - _ => None, - } - .map_or_else( - || { - // MGRS's zone at the centre keeps southern Norway's and Svalbard's wider zones. - let c = Coord::new((center.x + 180.0).rem_euclid(360.0) - 180.0, center.y); - match rustgis_geom::utm::utm_zone(c).filter(|_| g.mgrs) { - Some(zone) => utm((zone, center.y >= 0.0)), - None => Crs::from_epsg(rustgis_map::layout::utm_epsg(center.x, center.y)), - } - }, - Some, - )?, - }; - (!crs.is_geographic()).then_some(crs) -} - -/// A step that draws about eight lines across `span`: 1, 2 or 5 times a power of ten. -pub(crate) fn nice_step(span: f64, smallest: f64) -> f64 { - let rough = (span / 8.0).max(smallest); - let p = 10f64.powf(rough.log10().floor()); - [1.0, 2.0, 5.0, 10.0].iter().map(|k| k * p).find(|s| *s >= rough).unwrap_or(10.0 * p) -} - -/// A grid over a frame: lines across it, ticks along its edges or both, labelled at the edges the -/// grid names. A graticule's lines are latitudes and longitudes; a measured grid's are eastings and -/// northings in its coordinate system, bent through it onto the map. Gives the labels drawn: each -/// one's edge and its box in points (left, top, right, bottom). -fn draw_grid(pm: &mut Canvas, map: &Map, view: &View, g: &Grid, comma: bool) -> Vec<(Edge, [f32; 4])> { - let ppp = view.pixels_per_point as f32; - // Its labels' size against the default (#2581): their room from the edge and between them, - // and MGRS squares' names, follow in proportion, a point at the default being `unit` pixels. - let k = layout_text_scale(g.label_size, GRID_LABEL_PT) as f32; - let unit = ppp * k; - let (w, h) = (view.width, view.height); - // On a globe, through the globe as the frame draws it (#2337): through the flat camera the - // lines would be laid out as a flat world around it. - let globe = map.projection.is_globe().then(|| rustgis_map::globe::Globe::new(&view.camera, w, h)); - let lonlat_at = |sx: f64, sy: f64| crate::mapgrid::at(map, view, globe.as_ref(), sx, sy); - // The frame's edges in longitude/latitude: its corners and points along each side. - let mut edge_points = Vec::new(); - for i in 0..=8 { - let t = f64::from(i) / 8.0; - edge_points.extend([(w * t, 0.0), (w * t, h), (0.0, h * t), (w, h * t)]); - } - let mut lonlats: Vec = edge_points.iter().filter_map(|&(sx, sy)| lonlat_at(sx, sy)).collect(); - // A frame with an edge past the globe's rim sees the globe's limb: its graticule is the whole - // Earth's, the lines behind the globe left out where they are drawn. A measured grid takes its - // bounds from the part of the globe inside the frame too, the edges missing it. - let rim = globe.is_some() && lonlats.len() < edge_points.len(); - if rim { - for i in 0..=16 { - for j in 0..=16 { - lonlats.extend(lonlat_at(w * f64::from(i) / 16.0, h * f64::from(j) / 16.0)); - } - } - } - let world = Extent::new(-180.0, -90.0, 180.0, 90.0); - let mut ext = if rim { world } else { Extent::EMPTY }; - for c in &lonlats { - ext.expand(*c); - } - if ext.is_empty() { - return Vec::new(); - } - // Each line: its points in longitude/latitude, its label, and whether it runs north–south - // (labelled along the top and bottom first). - let mut lines: Vec<(Vec, String, bool)> = Vec::new(); - // A measured grid's MGRS squares: each one's name and middle, in the frame's points. - let mut squares = Vec::new(); - match g.kind { - GridKind::Graticule => { - // Over the extent of the frame's corners and midpoints, as it always was (its step and - // lines unchanged for the layouts made before measured grids). - let mut corners = if rim { world } else { Extent::EMPTY }; - for (sx, sy) in [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h), (w / 2.0, 0.0), (w / 2.0, h), (0.0, h / 2.0), (w, h / 2.0)] { - if let Some(c) = lonlat_at(sx, sy) { - corners.expand(c); - } - } - graticule_lines(g, corners, comma, &mut lines); - } - GridKind::Measured => { - let center = lonlat_at(w / 2.0, h / 2.0).unwrap_or_else(|| ext.center()); - let Some(crs) = measured_crs(g, map, center) else { return Vec::new() }; - let Ok(tr) = crs.transformer() else { return Vec::new() }; - measured_lines(g, &tr, &lonlats, comma, &mut lines); - if g.mgrs - && g.labels - && let Some((zone, _)) = rustgis_map::layout::utm_zone_of(&crs.epsg().to_string()) - { - let size = |s: &str| (text::measure(s, MGRS_LABEL_PT * k, true), MGRS_LABEL_PT * k * 1.33 * 1.2); - squares = mgrs_squares(map, view, globe.as_ref(), zone, &tr, size); - } - } - } - // A tilted frame's lines break where they pass behind the eye, a globe's behind its horizon. - let to_px = |c: Coord| { - match &globe { - Some(on) => on.forward(c), - None => map.to_map(c).and_then(|m| view.camera.try_to_screen(m, w, h)), - } - .map(|(x, y)| (x as f32 * ppp, y as f32 * ppp)) - .filter(|(x, y)| x.is_finite() && y.is_finite()) - }; - let (pw, ph) = (pm.width() as f32, pm.height() as f32); - let paint_line = paint(g.color, 1.0); - let stroke = Stroke { width: g.width.max(0.0) as f32 * ppp, ..Stroke::default() }; - let tick = if g.style.ticks() { (g.tick_length * PT_PER_MM) as f32 * ppp } else { 0.0 }; - let label_px = GRID_LABEL_PT as f32 * 1.33 * unit; - let label_color = Rgba::rgb(0x20, 0x20, 0x20); - let vertical = g.label_orientation == Orientation::Vertical; - let mut pb = PathBuilder::new(); - // Each label's edge, place along it, text, and whether it is a meridian's. - let mut labels: Vec<(Edge, f32, String, bool)> = Vec::new(); - let mut draw_line = |pb: &mut PathBuilder, pts: Vec, label: String, lon: bool| { - let px: Vec> = pts.into_iter().map(to_px).collect(); - // Runs of points that projected, so a line breaks where its projection does. - for run in px.split(|p| p.is_none()) { - let run: Vec<(f32, f32)> = run.iter().flatten().copied().collect(); - if g.style.lines() { - for (i, (x, y)) in run.iter().enumerate() { - if i == 0 { pb.move_to(*x, *y) } else { pb.line_to(*x, *y) } - } - } - for (edge, at) in edge_crossings(&run, pw, ph) { - if tick > 0.0 { - let (a, b) = match edge { - Edge::Top => ((at, 0.0), (at, tick)), - Edge::Bottom => ((at, ph), (at, ph - tick)), - Edge::Left => ((0.0, at), (tick, at)), - Edge::Right => ((pw, at), (pw - tick, at)), - }; - pb.move_to(a.0, a.1); - pb.line_to(b.0, b.1); - } - let shown = match edge { - Edge::Top => g.edges.top, - Edge::Bottom => g.edges.bottom, - Edge::Left => g.edges.left, - Edge::Right => g.edges.right, - }; - if g.labels && shown { - labels.push((edge, at, label.clone(), lon)); - } - } - } - }; - for (pts, label, lon) in lines { - draw_line(&mut pb, pts, label, lon); - } - if let Some(p) = pb.finish() { - pm.stroke_path(&p, &paint_line, &stroke, Transform::identity(), None); - } - for (s, x, y) in squares { - text::text_at(pm, &s, x * ppp, y * ppp, MGRS_LABEL_PT * 1.33 * unit, label_color, true, text::Align::Center, true); - } - // Labels sit just inside the frame, past the ticks. - let inset = tick + 3.0 * unit; - let along = |edge: Edge, s: &str| match edge { - Edge::Left | Edge::Right if !vertical => label_px, - _ => text::measure(s, label_px / 1.33, false), - }; - // How far a label reaches in from its edge: past the inset, its height, or a side's flat - // label its width. - let across = |edge: Edge, s: &str| { - inset - + match edge { - Edge::Left | Edge::Right if !vertical => text::measure(s, label_px / 1.33, false), - _ => label_px, - } - }; - let mut drawn = Vec::new(); - for (edge, at, s) in kept_labels(labels, (pw, ph), (along, across), label_px, unit) { - let tw = text::measure(&s, label_px / 1.33, false); - // Its centre, and half its size across and down (its halo and descenders included). - let (flat, upright) = ((tw / 2.0, label_px * 0.6), (label_px * 0.6, tw / 2.0)); - let (cx, cy, (hw, hh)) = match edge { - Edge::Top => (at, inset + label_px * 0.4, flat), - Edge::Bottom => (at, ph - inset - label_px * 0.4, flat), - Edge::Left if vertical => (inset + label_px * 0.4, at, upright), - Edge::Right if vertical => (pw - inset - label_px * 0.4, at, upright), - Edge::Left => (inset + tw / 2.0, at, flat), - Edge::Right => (pw - inset - tw / 2.0, at, flat), - }; - if matches!(edge, Edge::Left | Edge::Right) && vertical { - rotated_text(pm, &s, cx, cy, label_px, label_color); - } else { - text::text_at(pm, &s, cx, cy, label_px, label_color, false, text::Align::Center, true); - } - drawn.push((edge, [(cx - hw) / ppp, (cy - hh) / ppp, (cx + hw) / ppp, (cy + hh) / ppp])); - } - drawn -} - -/// The size of a measured grid's MGRS square labels, in points. -const MGRS_LABEL_PT: f32 = 10.0; -/// The places across and down a frame where [`mgrs_squares`] looks which square shows. -const MGRS_SAMPLES: u32 = 32; - -/// Where a measured grid in UTM zone `zone` (`tr` its transformer) names its MGRS 100 km squares on -/// a frame showing `map` in `view` (through `globe` on a globe, as its lines): each square of the -/// zone, and of each latitude band, that shows, by its grid zone designation and letters -/// (`32T MT`), at the middle of what shows of it, in the frame's points. Only where all of the -/// label, `size(text)` points across and down, stays in its square and well inside the frame, -/// clear of the edge labels. Squares the zone's eastings reach past its edges (a frame across two -/// zones) are named in the other zone, so not here. -fn mgrs_squares( - map: &Map, - view: &View, - globe: Option<&rustgis_map::globe::Globe>, - zone: u8, - tr: &rustgis_data::raster::Transformer, - size: impl Fn(&str) -> (f32, f32), -) -> Vec<(String, f32, f32)> { - use rustgis_geom::utm; - let (w, h) = (view.width, view.height); - // The square, and band, a place on the frame is in: none outside the zone. On a globe, the - // place the globe draws there, as the grid's lines (#2337). - let square = |sx: f64, sy: f64| -> Option<(i64, i64, char)> { - let c = crate::mapgrid::at(map, view, globe, sx, sy)?; - // (A copy of the world past ±180° is the same place.) - let c = Coord::new((c.x + 180.0).rem_euclid(360.0) - 180.0, c.y); - if utm::utm_zone(c)? != zone { - return None; - } - let band = utm::latitude_band(c.y)?; - let p = tr.from_lonlat(c)?; - // Across the Equator from the grid's hemisphere, the northing MGRS gives there: the other - // hemisphere's, 10,000 km apart. - let y = match (c.y < 0.0, p.y) { - (true, y) if y < 0.0 => y + 10_000_000.0, - (false, y) if y >= 10_000_000.0 => y - 10_000_000.0, - (_, y) => y, - }; - let (e, n) = ((p.x / 100_000.0).floor(), (y / 100_000.0).floor()); - (e.is_finite() && n.is_finite()).then_some((e as i64, n as i64, band)) - }; - // Each square's samples: their sum across and down, and how many. - let mut seen: std::collections::BTreeMap<(i64, i64, char), (f64, f64, u32)> = std::collections::BTreeMap::new(); - for i in 0..MGRS_SAMPLES { - for j in 0..MGRS_SAMPLES { - let (sx, sy) = (w * (f64::from(i) + 0.5) / f64::from(MGRS_SAMPLES), h * (f64::from(j) + 0.5) / f64::from(MGRS_SAMPLES)); - if let Some(k) = square(sx, sy) { - let e = seen.entry(k).or_default(); - *e = (e.0 + sx, e.1 + sy, e.2 + 1); - } - } - } - let mut out = Vec::new(); - for ((e, n, band), (sx, sy, count)) in seen { - let mid = |k: i64| (k as f64 + 0.5) * 100_000.0; - let Some((column, row)) = utm::square_letters(zone, mid(e), mid(n)) else { continue }; - let text = format!("{zone:02}{band} {column}{row}"); - let (tw, th) = size(&text); - let (cx, cy) = (sx / f64::from(count), sy / f64::from(count)); - let (hw, hh) = (f64::from(tw) / 2.0 + 2.0, f64::from(th) / 2.0 + 2.0); - // Clear of the edges' labels: three label heights in from each edge. - let margin = 3.0 * f64::from(th); - if cx - hw < margin || cx + hw > w - margin || cy - hh < margin || cy + hh > h - margin { - continue; - } - let corners = [(cx - hw, cy - hh), (cx + hw, cy - hh), (cx - hw, cy + hh), (cx + hw, cy + hh)]; - if corners.iter().all(|&(x, y)| square(x, y) == Some((e, n, band))) { - out.push((text, cx as f32, cy as f32)); - } - } - out -} - -/// The graticule labels drawn, of those at each edge crossing (`labels`: edge, place along it, -/// text, a meridian's or not) on a frame `size` pixels, `label_h` tall: away from the corners (all -/// of a label, `along` its edge, fits, and none at a side's ends by a top or bottom label), within -/// the frame across (how far it reaches in from its edge, `across`, at most the frame's other side: -/// one reaching further in is left out, at any size, rather than cut by the frame), and none over -/// another. Meridians are labelled along the top and bottom and parallels along the sides first; a -/// line that leaves the frame through the other edges (a slanting meridian on a projected map) is -/// labelled there only well clear of the labels already set on that edge. Their room from the -/// corners and between them is in `unit`s, a point at the labels' default size in pixels, so it -/// follows their size. -/// A label left out for want of room is thinning, as on any map, not a loss to report: the grid -/// still shows its lines, and the user guide says labels go where there is room. -fn kept_labels( - mut labels: Vec<(Edge, f32, String, bool)>, - (pw, ph): (f32, f32), - (along, across): (impl Fn(Edge, &str) -> f32, impl Fn(Edge, &str) -> f32), - label_h: f32, - unit: f32, -) -> Vec<(Edge, f32, String)> { - let own_edge = |edge: Edge, lon: bool| matches!(edge, Edge::Top | Edge::Bottom) == lon; - labels.sort_by_key(|(edge, _, _, lon)| !own_edge(*edge, *lon)); - let mut taken: Vec<(Edge, f32, f32)> = Vec::new(); - let mut kept = Vec::new(); - for (edge, at, s, lon) in labels { - let length = along(edge, &s); - let side = matches!(edge, Edge::Left | Edge::Right); - let (limit, room) = if side { (ph, pw) } else { (pw, ph) }; - if across(edge, &s) > room { - continue; - } - // A side's labels keep two label heights from the corners, below the top's labels and - // above the bottom's, so a corner holds no two. - let margin = (length / 2.0 + 3.0 * unit).max(12.0 * unit).max(if side { 2.0 * label_h } else { 0.0 }); - if at < margin || at > limit - margin { - continue; - } - let (a, z) = (at - length / 2.0 - 2.0 * unit, at + length / 2.0 + 2.0 * unit); - // Off its own edge, a label keeps a further length of its own clear of the others, so - // it doesn't read as one of theirs. - let clear = if own_edge(edge, lon) { 0.0 } else { length }; - if taken.iter().any(|(e, ta, tz)| *e == edge && a - clear < *tz && *ta < z + clear) { - continue; - } - taken.push((edge, a, z)); - kept.push((edge, at, s)); - } - kept -} - -/// One line of haloed text centred on (`cx`, `cy`), turned to read from bottom to top. -fn rotated_text(pm: &mut Canvas, s: &str, cx: f32, cy: f32, px: f32, color: Rgba) { - // Whole pixels throughout, so the quarter turn moves pixels without resampling them. - let tw = (text::measure(s, px / 1.33, false) + px * 0.4).ceil().max(1.0); - let th = (px * 1.6).ceil().max(1.0); - let (x, y) = ((cx - th / 2.0).round(), (cy + tw / 2.0).round()); - let t = Transform::from_row(0.0, -1.0, 1.0, 0.0, x, y); - if pm.is_recording() { - pm.with_transform(t, |c| text::text_at(c, s, tw / 2.0, th / 2.0, px, color, false, text::Align::Center, true)); - return; - } - let Some(mut tmp) = Canvas::new(tw as u32, th as u32) else { return }; - text::text_at(&mut tmp, s, tw / 2.0, th / 2.0, px, color, false, text::Align::Center, true); - pm.draw_pixmap( - 0, - 0, - tmp.pixmap().as_ref(), - &PixmapPaint { quality: tiny_skia::FilterQuality::Nearest, ..PixmapPaint::default() }, - t, - None, - ); -} - -/// A grey box with `label` in it, where a frame's map can't be drawn. -fn placeholder(pm: &mut Canvas, r: Rect, label: &str, ppp: f64) { - pm.fill_rect(r, &paint(Rgba::rgb(0xF0, 0xF1, 0xF3), 1.0), Transform::identity(), None); - let p = PathBuilder::from_rect(r); - pm.stroke_path( - &p, - &paint(Rgba::rgb(0xA0, 0xA4, 0xAA), 1.0), - &Stroke { width: ppp as f32, ..Stroke::default() }, - Transform::identity(), - None, - ); - text::text_at( - pm, - label, - r.x() + r.width() / 2.0, - r.y() + r.height() / 2.0, - 10.0 * 1.33 * ppp as f32, - Rgba::rgb(0x70, 0x74, 0x7A), - false, - text::Align::Center, - false, - ); -} - -/// Fills `pts` with `fill` and outlines it with `outline`. -fn shape(pm: &mut Canvas, pts: &[(f32, f32)], fill: Rgba, outline: Rgba, width: f32) { - let mut pb = PathBuilder::new(); - for (i, (x, y)) in pts.iter().enumerate() { - if i == 0 { pb.move_to(*x, *y) } else { pb.line_to(*x, *y) } - } - pb.close(); - if let Some(p) = pb.finish() { - pm.fill_path(&p, &paint(fill, 1.0), FillRule::Winding, Transform::identity(), None); - pm.stroke_path(&p, &paint(outline, 1.0), &Stroke { width, ..Stroke::default() }, Transform::identity(), None); - } -} - -/// A north arrow in `style`, with an `N` above it, pointing north on a map turned to `bearing` -/// (degrees clockwise from north): turned about the middle of `r`, the `N` kept upright. -fn north_arrow(pm: &mut Canvas, r: Rect, style: ArrowStyle, fill: Rgba, outline: Rgba, ppp: f64, bearing: f64) { - let white = Rgba::rgb(0xFF, 0xFF, 0xFF); - let sw = 0.8 * ppp as f32; - let (cx, top) = (r.x() + r.width() / 2.0, r.y()); - let label_h = (r.height() * 0.25).min(14.0 * ppp as f32); - let (tip, base) = (top + label_h + 2.0, r.y() + r.height()); - // North lies `bearing` anticlockwise of the page's up. - let (sin, cos) = if bearing.is_finite() { (-bearing.to_radians()).sin_cos() } else { (0.0, 1.0) }; - let (sin, cos) = (sin as f32, cos as f32); - let (mx, my) = (cx, r.y() + r.height() / 2.0); - let turn = |(x, y): (f32, f32)| { - let (dx, dy) = (x - mx, y - my); - (mx + dx * cos - dy * sin, my + dx * sin + dy * cos) - }; - let shape = |pm: &mut Canvas, pts: &[(f32, f32)], fill: Rgba, outline: Rgba, sw: f32| { - let pts: Vec<(f32, f32)> = pts.iter().map(|p| turn(*p)).collect(); - shape(pm, &pts, fill, outline, sw) - }; - match style { - ArrowStyle::Classic => { - let s = (r.width() * 0.5).min(r.height() * 0.32); - let mid = tip + (base - tip) * 0.68; - shape(pm, &[(cx, tip), (cx - s, base), (cx, mid)], fill, fill, sw); - shape(pm, &[(cx, tip), (cx + s, base), (cx, mid)], white, outline, sw); - } - ArrowStyle::Triangle => { - let s = (r.width() * 0.4).min(r.height() * 0.25); - shape(pm, &[(cx, tip), (cx + s, base), (cx - s, base)], fill, outline, sw); - } - ArrowStyle::Compass | ArrowStyle::Star => { - let cy = (tip + base) / 2.0; - let rad = (r.width() / 2.0).min((base - tip) / 2.0); - let arm = |pm: &mut Canvas, angle: f32, len: f32, half: f32| { - // An arm from the centre, split down its length: one half filled, one light. - let (dx, dy) = (angle.sin(), -angle.cos()); - let end = (cx + dx * len, cy + dy * len); - let (lx, ly) = (cx + dy * half, cy - dx * half); - let (rx, ry) = (cx - dy * half, cy + dx * half); - shape(pm, &[(cx, cy), end, (lx, ly)], fill, outline, sw); - shape(pm, &[(cx, cy), end, (rx, ry)], white, outline, sw); - }; - if style == ArrowStyle::Star { - for k in 0..4 { - arm(pm, std::f32::consts::FRAC_PI_4 + k as f32 * std::f32::consts::FRAC_PI_2, rad * 0.6, rad * 0.14); - } - } - for k in 0..4 { - arm(pm, k as f32 * std::f32::consts::FRAC_PI_2, rad, rad * 0.2); - } - } - } - let (nx, ny) = turn((cx, top + label_h / 2.0)); - text::text_at(pm, "N", nx, ny, label_h * 1.1, outline, true, text::Align::Center, false); -} - -/// A scale bar label for `v`, a multiple of `step`: with the decimals the step needs (up to 6), so -/// 0.0125 km stays 0.0125 rather than rounding to 0.01. A step with no exact decimal (a third) -/// keeps two significant digits of it. -fn scale_number(v: f64, step: f64) -> String { - let places = (0..6usize) - .find(|&n| { - let k = step * 10f64.powi(n as i32); - (k - k.round()).abs() < 1e-9 * k.abs().max(1.0) - }) - .unwrap_or_else(|| { - let mag = if step.is_finite() && step > 0.0 { step.log10().floor() } else { 0.0 }; - (1.0 - mag).clamp(0.0, 6.0) as usize - }); - let s = format!("{v:.prec$}", prec = places); - if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s } -} - -/// A scale bar's number for `v`, a multiple of `step`, with a decimal comma when `comma`. With no -/// `decimals` (auto), as [`scale_number`] prints it and no thousands separators, as bars always -/// printed; with 0 to [`MAX_SCALE_DECIMALS`](rustgis_map::layout::MAX_SCALE_DECIMALS), that many -/// places and the thousands apart. A minus only in front of a digit other than zero; NaN and -/// infinity print 0. -fn bar_number(v: f64, step: f64, decimals: Option, comma: bool) -> String { - let v = if v.is_finite() { v } else { 0.0 }; - let body = match decimals { - None => decimal(scale_number(v.abs(), step), comma), - Some(d) => { - let places = d.min(rustgis_map::layout::MAX_SCALE_DECIMALS); - let s = format!("{:.*}", places, v.abs()); - let (whole, part) = s.split_once('.').unwrap_or((s.as_str(), "")); - let whole = rustgis_map::graphics::thousands(whole.parse().unwrap_or(0.0)); - if part.is_empty() { decimal(whole, comma) } else { decimal(format!("{whole}.{part}"), comma) } - } - }; - if v < 0.0 && body.chars().any(|c| matches!(c, '1'..='9')) { format!("-{body}") } else { body } -} - -/// The share of its element's width a scale bar's length may take. -const BAR_SHARE: f64 = 0.85; -/// How far a scale bar starts in from the element's left edge at its labels' default size, in -/// pixels. [`scale_bar_width_pt`] counts that inset as as many points: when a point is a pixel or -/// more, a pixel is no larger than a point, so the box is never too narrow. It follows the labels' -/// size, as their room does (#2581). -const BAR_INSET: f32 = 2.0; -/// How far a scale bar label's digits rise above the middle of their line, in label sizes: what -/// the room over the bar holds. -const BAR_LABEL_RISE: f32 = 0.5; -/// How far the middle of a scale bar's labels' line sits over the bar's top, in label sizes. -const BAR_LABEL_MID: f32 = 0.7; - -/// What a scale bar counts: its whole length in its unit, that unit in metres and its abbreviation. -#[derive(Clone, Copy, Debug, PartialEq)] -struct BarPlan { - total: f64, - unit_m: f64, - abbr: &'static str, -} - -/// The bar a scale bar draws in an element `width_pt` points wide at `ground_per_pt` ground metres -/// a point: the roundest length within [`BAR_SHARE`] of the width. `None` when it draws none. -fn bar_plan(ground_per_pt: f64, width_pt: f64, units: ScaleUnits) -> Option { - if !(ground_per_pt.is_finite() && ground_per_pt > 0.0 && width_pt.is_finite()) { - return None; - } - let room_m = ground_per_pt * width_pt * BAR_SHARE; - let (unit_m, abbr) = units.resolve(rustgis_geom::nice_distance(room_m)); - let total = rustgis_geom::nice_distance(room_m / unit_m); - (total > 0.0).then_some(BarPlan { total, unit_m, abbr }) -} - -/// A scale bar's label at division `i` of `divisions`, the last with the unit. -fn bar_label(total: f64, divisions: usize, i: usize, abbr: &str, comma: bool) -> String { - let v = decimal(scale_number(total * i as f64 / divisions as f64, total / divisions as f64), comma); - if i == divisions { format!("{v} {abbr}") } else { v } -} - -/// The narrowest element, in points, in which a scale bar draws the same bar as in one `width_pt` -/// wide (its length, unit and divisions), its last label at its `text_size` and `pad_pt` after it -/// included, so a box can be the size of its bar (#1379). `width_pt` when no narrower one draws -/// that bar; `None` when it draws none. -pub fn scale_bar_width_pt(ground_per_pt: f64, width_pt: f64, bar: (ScaleUnits, usize, f64), comma: bool, pad_pt: f64) -> Option { - let (units, divisions, text_size) = bar; - let k = layout_text_scale(text_size, SCALE_BAR_TEXT_PT); - let plan = bar_plan(ground_per_pt, width_pt, units)?; - let divisions = divisions.clamp(1, rustgis_map::layout::MAX_SCALE_DIVISIONS); - let len = plan.total * plan.unit_m / ground_per_pt; - let last = bar_label(plan.total, divisions, divisions, plan.abbr, comma); - let half = f64::from(text::measure(&last, (SCALE_BAR_TEXT_PT * k) as f32, false)) / 2.0; - let inset = f64::from(bar_inset(&bar_label(plan.total, divisions, 0, plan.abbr, comma), k as f32, 1.0)); - // A little over the share the bar takes, so the f32 rectangle an export rebuilds the width - // from (its error growing with the element's place on the page) doesn't pick the next shorter - // length: a ten-thousandth, 0.003 mm on a 30 mm box. - let w = (len / BAR_SHARE * (1.0 + 1e-4)).max(inset + len + half + pad_pt); - Some(if w < width_pt && bar_plan(ground_per_pt, w, units) == Some(plan) { w } else { width_pt }) -} - -/// [`scale_bar_width_pt`] for the scale bar `bar` as it is set: the narrowest element, in points, -/// in which it draws the same bar as in one `width_pt` wide, with every setting it has (its -/// subdivisions, divisions before zero, labels, unit label and where it sits, decimals, fit and -/// text size), its ink and `pad_pt` after it included, as [`bar_layout`] places it for the -/// drawing. A bar without the details is measured as [`scale_bar_width_pt`] measures it, so its -/// box is the one it always had. `width_pt` when no narrower one draws that bar; `None` when it -/// draws none, or `bar` is no scale bar. -pub fn scale_bar_box_width_pt(ground_per_pt: f64, width_pt: f64, bar: &ElementKind, comma: bool, pad_pt: f64) -> Option { - let options = BarOptions::of(bar)?; - if !bar.scale_bar_uses_details() { - return scale_bar_width_pt(ground_per_pt, width_pt, (options.units, options.divisions, options.text_size), comma, pad_pt); - } - // At a point a pixel; the height leaves the width as it is. - let place = |w: f64| Rect::from_xywh(0.0, 0.0, w as f32, 60.0).and_then(|r| bar_layout(r, ground_per_pt, &options, 1.0, comma)); - let wide = place(width_pt)?; - let unit = |b: &BarLayout| b.unit.as_ref().map(|u| u.text.clone()); - let labels = |b: &BarLayout| b.labels.iter().map(|(_, s)| s.clone()).collect::>(); - // The same bar: its length and divisions, each label and its unit label written in full as - // they are in the wider box, and its ink and padding inside the box. - let same = |w: f64| { - place(w).is_some_and(|b| { - b.total == wide.total - && b.divs == wide.divs - && labels(&b) == labels(&wide) - && unit(&b) == unit(&wide) - && f64::from(b.right) + pad_pt <= w - }) - }; - if !same(width_pt) { - return Some(width_pt); - } - // A narrower box draws a bar no longer: the narrowest one that draws this one, halved for, to - // a hundredth of a point: a frame dragged measures its box on every move, so no further. - let (mut lo, mut hi) = (0.0, width_pt); - for _ in 0..48 { - if hi - lo <= 0.01 { - break; - } - let mid = (lo + hi) / 2.0; - if same(mid) { hi = mid } else { lo = mid } - } - // A little over, as for a plain bar, so the f32 rectangle an export rebuilds the width from - // doesn't pick the next shorter length. - let w = hi * (1.0 + 1e-4); - Some(if w < width_pt && same(w) { w } else { width_pt }) -} - -/// How far a scale bar starts in from its box's left side, in pixels, for its first label `first` -/// at `k` times the default size (#2581): [`BAR_INSET`] in proportion, or more, so that label -/// reaches no further past the side than it does at the default size, as the bar moves down to -/// keep its labels from reaching higher. At the default size, [`BAR_INSET`]: pixels, as the -/// drawing has always placed the bar, not following `ppp`, which only the labels' widths do. -fn bar_inset(first: &str, k: f32, ppp: f32) -> f32 { - let half = |k: f32| text::measure(first, SCALE_BAR_TEXT_PT as f32 * k * ppp, false) / 2.0; - (BAR_INSET * k).max(half(k) - (half(1.0) - BAR_INSET).max(0.0)) -} - -/// A scale bar's look: the fields of [`ElementKind::ScaleBar`] but its frame and colours. -#[derive(Clone, Copy, Debug)] -struct BarOptions<'a> { - units: ScaleUnits, - divisions: usize, - style: ScaleBarStyle, - subdivisions: usize, - divisions_before_zero: usize, - label_position: ScaleLabelPosition, - unit_label: Option<&'a str>, - unit_label_position: UnitLabelPosition, - decimals: Option, - text_size: f64, - fit: ScaleBarFit, -} - -impl<'a> BarOptions<'a> { - /// A scale bar element's look; `None` for any other element. - fn of(kind: &'a ElementKind) -> Option> { - let ElementKind::ScaleBar { - units, - divisions, - style, - subdivisions, - divisions_before_zero, - label_position, - unit_label, - unit_label_position, - decimals, - text_size, - fit, - .. - } = kind - else { - return None; - }; - Some(BarOptions { - units: *units, - divisions: *divisions, - style: *style, - subdivisions: *subdivisions, - divisions_before_zero: *divisions_before_zero, - label_position: *label_position, - unit_label: unit_label.as_deref(), - unit_label_position: *unit_label_position, - decimals: *decimals, - text_size: *text_size, - fit: *fit, - }) - } -} - -/// A new scale bar's look. +#[expect(clippy::disallowed_methods, reason = "a thread the system refuses fails the test, as it should")] #[cfg(test)] -impl Default for BarOptions<'_> { - fn default() -> Self { - static PLAIN: std::sync::LazyLock = std::sync::LazyLock::new(|| ElementKind::scale_bar(0)); - BarOptions::of(&PLAIN).expect("a scale bar") - } -} - -/// How long a scale bar is and how it divides: its whole length in its unit, any divisions before -/// zero included, and its divisions after zero. -#[derive(Clone, Copy, Debug, PartialEq)] -struct BarFit { - total: f64, - after: usize, -} - -/// A scale bar of `before` divisions before zero and `after` after it, counting in a unit `unit_m` -/// metres long, fitted to `room_m` ground metres by `fit`: the roundest length divided as asked -/// (`AdjustDivisionValue`, the length [`bar_plan`] takes), as many round divisions as fit -/// (`AdjustDivision`), or the asked divisions each a round length (`AdjustWidth`); under every fit -/// at most ten in all, the divisions before zero included. `None` when it draws none. -fn bar_fit(room_m: f64, unit_m: f64, fit: ScaleBarFit, before: usize, after: usize) -> Option { - // Ten in all under every fit, the divisions before zero among them, and at least one after zero. - let most = rustgis_map::layout::MAX_SCALE_DIVISIONS.saturating_sub(before).max(1); - let after = after.clamp(1, most); - let count = (before + after) as f64; - let (total, after) = match fit { - ScaleBarFit::AdjustDivisionValue => (rustgis_geom::nice_distance(room_m / unit_m), after), - ScaleBarFit::AdjustDivision => { - let most = most as f64; - let fits = |value: f64| (room_m / unit_m / value + 1e-9).floor() - before as f64; - // More than ten would fit: the next round division (1, 2, 5, 10 …) until ten do, so - // the bar fills its room as far as a round value allows rather than stopping short. - let mut value = rustgis_geom::nice_distance(room_m / unit_m / count); - for _ in 0..64 { - if !(fits(value) > most && value.is_finite() && value > 0.0) { - break; - } - value = rustgis_geom::nice_distance(value * 2.5); - } - let after = fits(value).clamp(1.0, most) as usize; - (value * (before + after) as f64, after) - } - ScaleBarFit::AdjustWidth => (rustgis_geom::nice_distance(room_m / unit_m / count) * count, after), - }; - (total.is_finite() && total > 0.0).then_some(BarFit { total, after }) -} - -/// Where a scale bar draws its bar and labels, from [`bar_layout`]. -struct BarLayout { - /// Where the bar starts, its top, its length and its height, in pixels. - x0: f32, - y0: f32, - len: f32, - bar_h: f32, - /// Its labels' size in pixels, the middle of their line, and each drawn: its centre across - /// and its text. One that would touch its neighbour is left out, never the ends. - px: f32, - label_y: f32, - labels: Vec<(f32, String)>, - /// Its divisions before zero, all its divisions, the parts the first after zero is cut - /// into, and its whole length in its unit: what it draws. - before: usize, - divs: usize, - parts: usize, - total: f64, - /// Its unit label when it isn't the last label's: after the bar or on a line of its own. - unit: Option, - /// The furthest right its ink reaches, in pixels: its bar, its last label or its unit label. - right: f32, - /// Its unit label shortened with an ellipsis or left out to fit its room: said, as a cut text. - unit_cut: Option, - /// Its box is too small for its labels and bar: too short, the bar drawn below it or its - /// lines below the bar past its foot, or too narrow, an end label reaching past its side - /// further than the default size's does or, above the default size, over its first label. - cramped: bool, -} - -/// A scale bar's unit label on a line of its own or after the bar: the middle of its line, its -/// place across (its start or its centre, as `align` says) and its text. -struct BarUnit { - x: f32, - y: f32, - text: String, - align: text::Align, -} - -/// Where a scale bar in `r` draws as `bar` asks, at `ground_per_pt` ground metres a point of -/// paper: the drawing and the text-cut check ([`losses`]) take the same, so they agree. `None` -/// when it draws no bar. A label that would touch its neighbour is left out, as on any map: the -/// ends always show, and the user guide says each step is labelled where there is room. That is -/// thinning, not a loss to report. -/// -/// Its labels, their room and its unit label follow its text size (#2581). Its lines above the -/// bar reach no higher than the box's top, or than a plain bar's labels reach at the default size -/// when that is higher (a publication's short box): the bar moves down to give them room. Its -/// lines below the bar reach no lower than the box's foot, the bar moving up as far as its lines -/// above leave it room. A box too short for its lines and bar is [`BarLayout::cramped`], which is -/// said, rather than any line drawn smaller. A bar with none of the details draws where it always -/// was at the default size. -fn bar_layout(r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, ppp: f64, comma: bool) -> Option { - use rustgis_map::layout::{ - MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DECIMALS, MAX_SCALE_DIVISIONS, MAX_SCALE_SUBDIVISIONS, MAX_UNIT_LABEL_CHARS, - }; - if !(ground_per_pt.is_finite() && ground_per_pt > 0.0 && ppp.is_finite() && ppp > 0.0) { - return None; - } - let p = ppp as f32; - let k = layout_text_scale(bar.text_size, SCALE_BAR_TEXT_PT) as f32; - let after = bar.divisions.clamp(1, MAX_SCALE_DIVISIONS); - let before = bar.divisions_before_zero.min(MAX_SCALE_BEFORE_ZERO); - // One part is the division whole. - let parts = bar.subdivisions.clamp(1, MAX_SCALE_SUBDIVISIONS); - let width_pt = f64::from(r.width()) / ppp; - let BarPlan { unit_m, abbr, .. } = bar_plan(ground_per_pt, width_pt, bar.units)?; - let decimals = bar.decimals.map(|d| usize::from(d).min(MAX_SCALE_DECIMALS)); - // The unit's words: its abbreviation unless the bar names it, on one line. - let unit: String = match bar.unit_label { - None => abbr.to_string(), - Some(t) => t.chars().take(MAX_UNIT_LABEL_CHARS).map(|c| if matches!(c, '\n' | '\r') { ' ' } else { c }).collect(), - }; - let has_unit = !unit.trim().is_empty(); - let unit_at = bar.unit_label_position; - let rows = bar_rows(bar.label_position, unit_at, has_unit); - let bar_h = (r.height() * 0.28).min(6.0 * p); - // Its labels' size, and the default's, in pixels. - let (px, px8) = (SCALE_BAR_TEXT_PT as f32 * k * 1.33 * p, SCALE_BAR_TEXT_PT as f32 * 1.33 * p); - let measure_at = |s: &str, px: f32| text::measure(s, px / 1.33, false); - let measure = |s: &str| measure_at(s, px); - let half = |s: &str| measure(s) / 2.0; - let gap = 3.0 * k * p; - // The pixels a unit after the bar takes from it, at most half the bar's room. - let beside = if has_unit && unit_at == UnitLabelPosition::AfterBar { - (measure(&unit) + gap + p).min(r.width() * BAR_SHARE as f32 * 0.5) - } else { - 0.0 - }; - // Division `k` from zero of a bar `total` long in `divs` divisions. - let number = |total: f64, divs: usize, k: isize| bar_number(total * k as f64 / divs as f64, total / divs as f64, decimals, comma); - // Left of zero the first label is a negative one, centred on the bar's end: the bar starts far - // enough in for it, at labels `px` high and `k` times the default. It takes at most half the - // bar's room, as a unit after the bar does: a wider one reaches left of the box rather than - // leave the bar a sliver. - let most_pad = ((r.width() * BAR_SHARE as f32 - beside) * 0.5).max(0.0); - let pad_at = |f: &BarFit, px: f32, k: f32| { - if before > 0 { - let first = number(f.total, before + f.after, -(before as isize)); - (measure_at(&first, px) / 2.0 - BAR_INSET * k).clamp(0.0, most_pad) - } else { - 0.0 - } - }; - let pad_of = |f: &BarFit| pad_at(f, px, k); - // The bar in what's left of its room once `taken` pixels of the box are its labels'. - let fitted = |taken: f32| { - let taken_pt = f64::from(taken) / ppp; - let room_m = ground_per_pt * width_pt * BAR_SHARE - ground_per_pt * taken_pt; - bar_fit(room_m, unit_m, bar.fit, before, after) - }; - let first = fitted(beside)?; - // The room left of zero follows the bar's length: fitted again with the first label's, and once - // more if the shorter bar's first label is wider ("-1.25" for "-1"). Where a refit leaves no - // room, the fit before it draws, its first label perhaps starting a little left of the box. - let (fit, pad) = if before > 0 { - let reserved = pad_of(&first); - match fitted(beside + reserved) { - Some(f) if pad_of(&f) > reserved => match fitted(beside + pad_of(&f)) { - // A refit whose own first label is wider still would start past the room it was - // fitted to: the fit before it draws instead. - Some(g) if pad_of(&g) <= pad_of(&f) => (g, pad_of(&g)), - _ => (f, reserved), - }, - Some(f) => (f, pad_of(&f)), - None => (first, 0.0), - } - } else { - (first, 0.0) - }; - let BarFit { total, after } = fit; - let divs = before + after; - let len = (total * unit_m / ground_per_pt * ppp) as f32; - // How far in the bar starts for labels `k` times the default size: past a first label before - // zero, or as far as the first label at zero needs ([`bar_inset`]). - let zero = number(total, divs, 0); - let inset_at = |k: f32, pad: f32| if before > 0 { BAR_INSET * k + pad } else { bar_inset(&zero, k, p) }; - let x0 = r.x() + inset_at(k, pad); - // The box less the insets the bar keeps. - let (inner_left, inner_right) = (r.x() + BAR_INSET, r.right() - BAR_INSET); - // Division `j` counts `j - before` from zero. Its label, the last with the unit when it follows - // the labels: a unit the bar names shortened so the label, centred on the bar's end, ends - // inside the box, and left out when not even a letter of it fits. The abbreviation, short, - // follows the number as it always has. - let label = |j: usize| { - let v = number(total, divs, j as isize - before as isize); - if j == divs && has_unit && unit_at == UnitLabelPosition::AfterLabels { - // Centred on the bar's end: half of it each side, inside the nearer edge. - let room = 2.0 * (inner_right - (x0 + len)).min((x0 + len) - inner_left); - if bar.unit_label.is_some() { last_label(&v, &unit, room, measure) } else { (format!("{v} {unit}"), None) } - } else { - (v, None) - } - }; - // Each line above the bar moves it down, each below up; labels over it alone leave it where it - // always was. - let centre = 0.62 + 0.12 * (rows.up as f32 - 1.0 - rows.down as f32); - let at = r.y() + r.height() * centre - bar_h / 2.0; - // How far `n` lines of labels `px` high reach out from the bar: the middle of the last, and - // its digits past it. - let reach = |n: usize, px: f32| if n == 0 { 0.0 } else { px * (BAR_LABEL_MID + 1.25 * (n - 1) as f32 + BAR_LABEL_RISE) }; - // The highest its lines may reach: the box's top, or where a plain bar's labels reach at the - // default size when that is higher (a publication's short box), as they always have. Below - // the bar, the box's foot. - let plain_at = r.y() + r.height() * 0.62 - bar_h / 2.0; - let (top, foot) = (r.y().min(plain_at - reach(1, px8)), r.bottom()); - let highest = top + reach(rows.up, px); - let mut y0 = at.max(highest); - if rows.down > 0 { - y0 = y0.min(foot - bar_h - reach(rows.down, px)).max(highest); - } - // The middle of text line `n` out from the bar. - let row = |n: usize| (BAR_LABEL_MID + 1.25 * n as f32) * px; - let seg = len / divs as f32; - let label_y = if bar.label_position == ScaleLabelPosition::Below { y0 + bar_h + row(0) } else { y0 - row(0) }; - // The last label's unit, cut to fit or not. - let mut unit_cut = None; - let all: Vec<(f32, String)> = (0..=divs) - .map(|j| { - let (s, cut) = label(j); - unit_cut = unit_cut.or(cut); - (x0 + seg * j as f32, s) - }) - .collect(); - let last = all.last().map(|(x, s)| x - half(s)).unwrap_or(f32::MAX); - let mut right_label = f32::MIN; - let mut labels = Vec::new(); - for (i, (x, s)) in all.into_iter().enumerate() { - let end = i == divs; - if !end && (x - half(&s) < right_label + gap || x + half(&s) + gap > last) && i != 0 { - continue; - } - right_label = x + half(&s); - labels.push((x, s)); - } - // The unit after the bar, level with its middle, or centred over or under it on a line of its - // own: after the bar in the room kept for it; on a line of its own in the box's width, moved - // in as far as it must be to stay inside it. Shortened with an ellipsis, or left out when not - // even its first character fits. - let place_unit = || { - let mid = x0 + len / 2.0; - let (x, y, align) = match unit_at { - UnitLabelPosition::AfterLabels => return (None, None), - UnitLabelPosition::AfterBar => (x0 + len + gap + p, y0 + bar_h / 2.0, text::Align::Left), - UnitLabelPosition::Above => (mid, y0 - row(rows.unit_row), text::Align::Center), - UnitLabelPosition::Below => (mid, y0 + bar_h + row(rows.unit_row), text::Align::Center), - }; - let room = if unit_at == UnitLabelPosition::AfterBar { beside - gap - p } else { inner_right - inner_left }; - let Some(text) = shortened(&unit, room, measure) else { return (None, Some(UnitLabelCut::LeftOut)) }; - let cut = (text != unit).then_some(UnitLabelCut::Shortened); - let x = if matches!(align, text::Align::Center) { - let w = measure(&text) / 2.0; - x.min(inner_right - w).max(inner_left + w) - } else { - x - }; - (Some(BarUnit { x, y, text, align }), cut) - }; - let (unit, placed_cut) = if has_unit { place_unit() } else { (None, None) }; - let unit_cut = unit_cut.or(placed_cut); - let unit_right = - unit.as_ref().map_or(f32::MIN, |u| if matches!(u.align, text::Align::Left) { u.x + measure(&u.text) } else { u.x + half(&u.text) }); - let right = (x0 + len).max(right_label).max(unit_right); - // Sideways the bar keeps its length: its first label is kept within its reach by the inset, - // and its last reaches no further past the box's right side than the default size's does, or - // than the side itself; further out, the box is too narrow for it, as it is too short when the - // bar is below it. - let half8 = |s: &str| measure_at(s, px8) / 2.0; - let x8 = r.x() + inset_at(1.0, pad_at(&fit, px8, 1.0)); - let past_side = labels.last().is_some_and(|(x, s)| x + half(s) > r.right().max(x8 + (x - x0) + half8(s)) + 0.01); - let low = y0 + bar_h + reach(rows.down, px) > foot + 0.01; - // Its end label is drawn as its first is, whatever the room: above the default size, running - // into the first, the box is too narrow for them too. - let clash = k > 1.0 - && match (labels.first(), labels.last()) { - (Some((fx, fs)), Some((ex, es))) if labels.len() > 1 => ex - half(es) < fx + half(fs), - _ => false, - }; - let cramped = low || past_side || clash; - Some(BarLayout { x0, y0, len, bar_h, px, label_y, labels, before, divs, parts, total, unit, right, unit_cut, cramped }) -} - -/// A scale bar filling most of the element's width as `bar` asks, placed by [`bar_layout`]: its -/// divisions after zero (and any before it) labelled, the first after zero split into its -/// subdivisions. `ground_per_pt` is ground metres per logical point of paper; `colors` are its -/// lines, dark divisions and labels, then the alternating bar's light divisions. -fn scale_bar(pm: &mut Canvas, r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, colors: (Rgba, Rgba), ppp: f64, comma: bool) { - let Some(BarLayout { x0, y0, len, bar_h, px, label_y, labels, before, divs, parts, unit, .. }) = - bar_layout(r, ground_per_pt, bar, ppp, comma) - else { - return; - }; - let (dark, light) = colors; - let seg = len / divs as f32; - let zero_x = x0 + seg * before as f32; - // Where the first division after zero is cut into its subdivisions. - let cuts: Vec = (1..parts).map(|p| zero_x + seg * p as f32 / parts as f32).collect(); - let dark_at = |j: usize| (j as isize - before as isize).rem_euclid(2) == 0; - // An alternating bar's fills alternate from zero, the cut division's parts counted one by one: - // the first part dark, the divisions after them going on from the last part. - let filled_dark = |j: usize| if j < before { dark_at(j) } else { (parts - 1 + (j - before)).is_multiple_of(2) }; - let line = Stroke { width: 0.6 * ppp as f32, ..Stroke::default() }; - let stroke = |pm: &mut Canvas, pts: &[(f32, f32)], w: &Stroke| { - let mut pb = PathBuilder::new(); - for (i, (x, y)) in pts.iter().enumerate() { - if i == 0 { pb.move_to(*x, *y) } else { pb.line_to(*x, *y) } - } - if let Some(p) = pb.finish() { - pm.stroke_path(&p, &paint(dark, 1.0), w, Transform::identity(), None); - } - }; - match bar.style { - ScaleBarStyle::Alternating => { - for j in 0..divs { - let x = x0 + seg * j as f32; - if j == before && parts > 1 { - // Alternating parts from zero, the first dark. - let part = seg / parts as f32; - for p in 0..parts { - let c = if p.is_multiple_of(2) { dark } else { light }; - if let Some(b) = Rect::from_xywh(x + part * p as f32, y0, part, bar_h) { - pm.fill_rect(b, &paint(c, 1.0), Transform::identity(), None); - } - } - } else if let Some(b) = Rect::from_xywh(x, y0, seg, bar_h) { - let c = if filled_dark(j) { dark } else { light }; - pm.fill_rect(b, &paint(c, 1.0), Transform::identity(), None); - } - } - if let Some(b) = Rect::from_xywh(x0, y0, len, bar_h) { - pm.stroke_path(&PathBuilder::from_rect(b), &paint(dark, 1.0), &line, Transform::identity(), None); - } - } - ScaleBarStyle::Stepped => { - let mut pts = vec![(x0, y0 + bar_h)]; - // Its upper steps are an alternating bar's dark divisions; the cut division is upper. - for j in 0..divs { - let y = if j == before || filled_dark(j) { y0 } else { y0 + bar_h }; - let (a, b) = (x0 + seg * j as f32, x0 + seg * (j + 1) as f32); - pts.extend([(a, y), (b, y)]); - } - pts.push((x0 + len, y0 + bar_h)); - stroke(pm, &pts, &Stroke { width: 1.0 * ppp as f32, ..Stroke::default() }); - // The first division after zero is on the upper step: its ticks hang from it. - for &x in &cuts { - stroke(pm, &[(x, y0), (x, y0 + bar_h * 0.5)], &line); - } - } - ScaleBarStyle::Line => { - let base = y0 + bar_h; - stroke(pm, &[(x0, base), (x0 + len, base)], &Stroke { width: 1.0 * ppp as f32, ..Stroke::default() }); - // Tall ticks at the ends and at zero. - for j in 0..=divs { - let tall = if j == 0 || j == divs || j == before { bar_h } else { bar_h * 0.6 }; - let x = x0 + seg * j as f32; - stroke(pm, &[(x, base), (x, base - tall)], &line); - } - for &x in &cuts { - stroke(pm, &[(x, base), (x, base - bar_h * 0.3)], &line); - } - } - } - // Labels at the divisions, over or under the bar, and the unit label where it is asked. - for (x, s) in &labels { - text::text_at(pm, s, *x, label_y, px, dark, false, text::Align::Center, false); - } - if let Some(BarUnit { x, y, text: shown, align }) = unit { - text::text_at(pm, &shown, x, y, px, dark, false, align, false); - } -} - -/// The last label of a scale bar, its number `v` followed by `unit`, as it fits `room` pixels -/// measured by `measure`: the unit shortened with an ellipsis, never the number, and left out when -/// not even its first character fits, with how it was cut. -fn last_label(v: &str, unit: &str, room: f32, measure: impl Fn(&str) -> f32) -> (String, Option) { - let whole = format!("{v} {unit}"); - if measure(&whole) <= room { - return (whole, None); - } - let after = measure(&format!("{v} ")); - match shortened(unit, room - after, &measure) { - Some(u) => (format!("{v} {u}"), Some(UnitLabelCut::Shortened)), - None => (v.to_string(), Some(UnitLabelCut::LeftOut)), - } -} - -/// `t` as it fits `room` pixels measured by `measure`: whole, or cut a character at a time and -/// ended with an ellipsis, keeping at least one character. `None` when not even that fits. A -/// longer prefix measures no less, so the longest that fits is found by halving. -fn shortened(t: &str, room: f32, measure: impl Fn(&str) -> f32) -> Option { - if measure(t) <= room { - return Some(t.to_string()); - } - let chars: Vec = t.chars().collect(); - let cut = |n: usize| format!("{}…", chars.iter().take(n).collect::().trim_end()); - // The fewest characters, from 1, that don't fit: `chars.len()` when all shorter ones do. - let (mut lo, mut hi) = (1, chars.len()); - while lo < hi { - let mid = lo + (hi - lo) / 2; - if measure(&cut(mid)) <= room { lo = mid + 1 } else { hi = mid } - } - (lo > 1).then(|| cut(lo - 1)) -} - -/// The text lines a scale bar has above and below it, and the line its unit takes on its side -/// (0 next to the bar, 1 past its labels). -#[derive(Clone, Copy, Debug, PartialEq)] -struct BarRows { - up: usize, - down: usize, - unit_row: usize, -} - -/// The lines of a scale bar with its labels at `labels` and its unit (if `has_unit`) at `unit`. -fn bar_rows(labels: ScaleLabelPosition, unit: UnitLabelPosition, has_unit: bool) -> BarRows { - let labels_up = labels == ScaleLabelPosition::Above; - // The side the unit has a line of its own on: true above. - let unit_up = match unit { - UnitLabelPosition::Above if has_unit => Some(true), - UnitLabelPosition::Below if has_unit => Some(false), - _ => None, - }; - BarRows { - up: usize::from(labels_up) + usize::from(unit_up == Some(true)), - down: usize::from(!labels_up) + usize::from(unit_up == Some(false)), - unit_row: usize::from(unit_up == Some(labels_up)), - } -} - -/// Each visible layer's legend for what it draws at a scale denominator (#207), by layer id; a -/// layer that draws nothing there isn't listed. The scale is the one the renderer draws the frame -/// at (the one its layers' scale ranges and display filters see), not the paper scale `{scale}` -/// prints, so the legend follows what the frame actually shows. -fn shown_legends(map: &Map, scale: f64, show_no_data: bool, env: &Env) -> Vec<(u32, Vec)> { - map.layers - .iter() - .filter(|l| map.draws_at(l, scale) && legend_lists(l)) - .filter_map(|l| layer_shown(l, scale, show_no_data, env).map(|entries| (l.id, entries))) - .collect() -} - -/// Whether a legend can list a layer: a vector layer, by its symbols, or a raster drawn by classes -/// (a colour table, unique values, class breaks), by its classes (#1679). Not a graphics layer, -/// nor a raster on a ramp or in RGB bands, which a colorbar keys or nothing does. -pub fn legend_lists(l: &rustgis_map::Layer) -> bool { - !l.graphics && l.raster.as_ref().is_none_or(|r| r.style.renderer.draws_classes()) -} - -/// What a layer a legend lists draws at 1:`scale` ([`rustgis_map::Layer::shown_legend`]); for a -/// classified raster, the classes it holds ([`raster_classes`]). `None` when it draws nothing -/// there. -fn layer_shown(l: &rustgis_map::Layer, scale: f64, show_no_data: bool, env: &Env) -> Option> { - if l.is_raster() { - return raster_classes(l, false).filter(|classes| l.in_scale_range(scale) && !classes.is_empty()); - } - let mut entries = l.shown_legend_with(scale, env)?; - if show_no_data { - entries.extend(l.renderer.no_data_legend(&l.dataset, Some(&l.drawn_rows_with(scale, env)))); - } - Some(entries) -} - -/// A classified raster's classes as legend rows (#1679), as the Layers pane draws them -/// ([`rustgis_map::RasterLayer::legend_classes`]): a filled swatch with a thin outline, and its -/// label. `None` for a raster on a ramp or in RGB bands, and for a vector layer. -fn raster_classes(l: &rustgis_map::Layer, all_classes: bool) -> Option> { - let classes = l.raster.as_ref()?.legend_classes(all_classes)?; - let symbol = |fill| rustgis_map::Symbol { fill, stroke: RASTER_SWATCH_EDGE, stroke_width: 0.5, size: 0.0, marker: Default::default() }; - Some(classes.into_iter().map(|(fill, label)| LegendEntry::plain(label, symbol(fill))).collect()) -} - -/// Names only the source whose read stopped this page, leaving unrelated failures generic. -fn failed_source_error(map: &Map, failed_source: Option) -> Option { - let id = failed_source?; - let layer = map.layers.iter().find(|layer| layer.instance_id() == id)?; - layer.source.as_ref()?.read_error().map(|why| format!("{}: {why}", layer.name)) -} - -/// Complete-source legends retain one minimal value per used class, never its geometry. -/// A failed traversal returns its live layer identity for the page's source-error report. -fn complete_shown_legends( - map: &mut Map, - scale: f64, - show_no_data: bool, - failed_source: &mut Option, - env: &Env, -) -> Option)>> { - *failed_source = None; - if !map.layers.iter().any(|l| l.source.as_ref().and_then(|s| s.chunk_source()).is_some()) { - return Some(shown_legends(map, scale, show_no_data, env)); - } - let style_env = env.at_scale(Some(scale)); - let wanted: Vec = - map.layers.iter().enumerate().filter(|(_, l)| map.draws_at(l, scale) && legend_lists(l)).map(|(i, _)| i).collect(); - let mut out = Vec::new(); - for index in wanted { - let layer = map.layers.get_mut(index)?; - let Some(source) = layer.source.as_ref().and_then(|s| s.chunk_source()) else { - if let Some(entries) = layer_shown(layer, scale, show_no_data, env) { - out.push((layer.id, entries)); - } - continue; - }; - let unique = match &layer.renderer { - rustgis_map::Renderer::Unique { field, classes, .. } => Some((field, classes)), - _ => None, - }; - // By expression: a feature of each class seen is kept whole, for the legend to class again. - let by_expression = layer.renderer.expression().is_some(); - let fi = unique.filter(|_| !by_expression).and_then(|(field, _)| layer.dataset.field_index(field)); - let fields = if by_expression { - layer.dataset.fields.clone() - } else { - unique - .filter(|_| fi.is_some()) - .map_or_else(Vec::new, |(field, _)| vec![rustgis_data::Field::new(field, rustgis_data::FieldType::Text)]) - }; - let mut sample = rustgis_data::Dataset::new("legend", layer.geometry_type(), fields); - let mut used = std::collections::HashSet::new(); - let mut any = false; - let mut no_data = None; - let mut chunk = layer.clone(); - chunk.source = None; - // Its chunks come in the source's own system. - chunk.dataset.held_in = source.coord_crs(); - chunk.clear_cache(); - let result = crate::visit_complete(source.as_ref(), &mut |features| { - chunk.dataset.features = features.into(); - let rows = chunk.drawn_rows_with(scale, env); - if show_no_data && no_data.is_none() { - no_data = chunk.renderer.no_data_legend(&chunk.dataset, Some(&rows)); - } - let classer = by_expression.then(|| chunk.renderer.classer_with(&chunk.dataset, style_env.clone())); - for row in rows.iter().enumerate().filter_map(|(row, keep)| keep.then_some(row)) { - any = true; - if let Some(c) = &classer { - let key = chunk.renderer.unique_class(&chunk.dataset, row, c).unwrap_or(usize::MAX); - // Kept with its id ($id), without its geometry. - if used.insert(key) - && let Some(f) = chunk.dataset.features.get(row) - { - let mut f = f.clone(); - f.geometry = None; - sample.features.push(f); - } - } else if let Some((_, classes)) = unique { - let value = fi.map(|fi| chunk.dataset.value(row, fi).to_string()); - let key = value.as_ref().and_then(|v| classes.iter().position(|(k, _)| k == v)).unwrap_or(classes.len()); - if used.insert(key) { - sample.push(None, value.map_or_else(Vec::new, |v| vec![rustgis_data::Value::Text(v)])); - } - } - } - chunk.dataset.features = Vec::new().into(); - Ok(()) - }); - if let Err(e) = result { - if let Some(source) = &mut layer.source { - source.error = Some(e.to_string()); - } - *failed_source = Some(layer.instance_id()); - return None; - } - if let Some(source) = &mut layer.source { - source.clear_error(); - } - if any { - // (A sample of the classes seen: classed again at this scale, by expression.) - let mut entries = layer.with_size_legend(layer.renderer.legend_with(&sample, &[], style_env.clone())); - entries.extend(no_data); - out.push((layer.id, entries)); - } - } - Some(out) -} - -/// What a legend leaves out: ``, and layers by name; the labels it shows for -/// layers instead of their names; the scale denominator whose legend pictures a WMS or WMTS -/// layer shows; and how many times its default size its text is ([`legend_size`]). -#[derive(Clone, Copy)] -struct LegendOptions<'a> { - hide_other: bool, - show_no_data: bool, - exclude: &'a [String], - labels: &'a BTreeMap, - scale: f64, - size: f32, -} - -/// How many times the default a legend of `text_size` points draws its text, rows, swatches and -/// gaps (#2581): 1 at [`rustgis_map::layout::LEGEND_TEXT_PT`], as legends have always been drawn. -/// A point symbol keeps the size the map draws it at, so a legend of sizes still matches the map. -fn legend_size(text_size: f64) -> f32 { - layout_text_scale(text_size, rustgis_map::layout::LEGEND_TEXT_PT) as f32 -} - -impl<'a> LegendOptions<'a> { - /// What the legend shows for the layer named `name`: its label (by name, any case), or the - /// name when it has none (#1654). - fn shown(&self, name: &'a str) -> &'a str { - let label = self.labels.get(name).or_else(|| self.labels.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, l)| l)); - label.map(String::as_str).filter(|l| !l.trim().is_empty()).unwrap_or(name) - } -} - -/// A row of a legend: a layer drawn in one symbol (its swatch and name), a layer's name over its -/// classes, or one of them, or a WMS or WMTS layer's legend picture (under its name). The name is -/// the one the legend shows: the layer's label, if the legend gives it one. -enum LegendRow<'a> { - Plain(&'a rustgis_map::Layer, &'a str), - Head(&'a str), - Class(&'a rustgis_map::Layer, LegendEntry), - Picture(std::sync::Arc), -} - -impl LegendRow<'_> { - /// The side of the square its point symbol takes at 1:`scale`, in points, as far as its marks - /// reach ([`point_marks::reach`]); 0 for any other row. No larger than a legend picture. - fn symbol_side(&self, scale: f64) -> f32 { - let (LegendRow::Plain(l, _) | LegendRow::Class(l, _)) = self else { return 0.0 }; - if l.geometry_type() != GeometryType::Point { - return 0.0; - } - let (s, strokes) = match self { - LegendRow::Class(_, en) => (en.symbol, row_strokes(l, en)), - _ => (l.renderer.symbol_for(&l.dataset, 0), l.line_strokes.as_slice()), - }; - (2.0 * point_marks::reach(&s, strokes) * l.size_factor(scale)).min(MAX_LEGEND_SIDE as f32) - } - - /// Its height at 1:`scale` in a legend `size` times the default ([`legend_size`]), in points: - /// a picture's a pixel a point at the default size, as the Layers pane shows it; a row grows to - /// hold its point symbol. - fn height(&self, scale: f64, size: f32) -> f32 { - match self { - LegendRow::Picture(p) => picture_size(p).1 * size, - _ => (LEGEND_ROW * size).max(self.symbol_side(scale)), - } - } - - /// Its width beside a column of swatches `column` points wide ([`swatch_column`]) in a legend - /// `size` times the default, in points. - fn width(&self, column: f32, size: f32) -> f32 { - match self { - LegendRow::Plain(_, name) => column + LEGEND_INDENT * size + text::measure(name, LEGEND_NAME_PT * size, false), - LegendRow::Head(name) => text::measure(name, LEGEND_NAME_PT * size, true), - LegendRow::Class(_, en) => column + LEGEND_LABEL_INDENT * size + text::measure(&en.label, LEGEND_LABEL_PT * size, false), - LegendRow::Picture(p) => (LEGEND_INDENT + picture_size(p).0) * size, - } - } -} - -/// Rows at 1:`scale` in a legend `size` times the default laid into at most `columns` columns -/// `limit` points high: the row each column starts at, and whether they all fit. A layer's name -/// stays with the row under it; a row taller than `limit` has a column to itself, and the last -/// column takes what is left. -fn flow(rows: &[LegendRow], columns: usize, limit: f32, (scale, size): (f64, f32)) -> (Vec, bool) { - // A thousandth of a row's slack, as the rows have when drawn. - let limit = limit + LEGEND_ROW * size * 1e-3; - let (mut starts, mut used, mut fits, mut i) = (vec![0], 0.0f32, true, 0); - while i < rows.len() { - let end = if matches!(rows[i], LegendRow::Head(_)) { (i + 2).min(rows.len()) } else { i + 1 }; - let part: f32 = rows[i..end].iter().map(|row| row.height(scale, size)).sum(); - if used > 0.0 && used + part > limit && starts.len() < columns { - starts.push(i); - used = 0.0; - } - used += part; - fits &= used <= limit; - i = end; - } - (starts, fits) -} - -/// The rows at 1:`scale` in a legend `size` times the default laid into at most `columns` columns -/// as evenly as they go: where each starts ([`flow`]), and the height of the tallest, in points. -fn balanced(rows: &[LegendRow], columns: usize, at: (f64, f32)) -> (Vec, f32) { - let (scale, size) = at; - let total: f32 = rows.iter().map(|row| row.height(scale, size)).sum(); - let (mut low, mut high) = (total / columns as f32, total); - for _ in 0..24 { - let middle = (low + high) / 2.0; - if flow(rows, columns, middle, at).1 { - high = middle; - } else { - low = middle; - } - } - let starts = flow(rows, columns, high, at).0; - let tallest = column_parts(rows, &starts).map(|part| part.iter().map(|row| row.height(scale, size)).sum()).fold(0.0f32, f32::max); - (starts, tallest) -} - -/// The rows of each column, from where they start. -fn column_parts<'r, 'a>(rows: &'r [LegendRow<'a>], starts: &'r [usize]) -> impl Iterator]> { - starts.iter().enumerate().map(|(k, &start)| &rows[start..starts.get(k + 1).copied().unwrap_or(rows.len())]) -} - -/// The widest of a column's `rows` at 1:`scale` in a legend `size` times the default, in points. -fn widest(rows: &[LegendRow], at: (f64, f32)) -> f32 { - let column = swatch_column(rows, at); - rows.iter().map(|row| row.width(column, at.1)).fold(0.0, f32::max) -} - -/// The stacked strokes a legend's class row draws: its class's own, else its layer's, as -/// [`rustgis_map::Layer::strokes`] finds them for a feature. -fn row_strokes<'a>(l: &'a rustgis_map::Layer, en: &'a LegendEntry) -> &'a [rustgis_map::LineStroke] { - if en.strokes.is_empty() { &l.line_strokes } else { &en.strokes } -} - -/// The stacked fills a legend's class row draws: its class's own, else its layer's, as -/// [`rustgis_map::Layer::fills`] finds them for a feature. -fn row_fills<'a>(l: &'a rustgis_map::Layer, en: &'a LegendEntry) -> &'a [rustgis_map::fills::FillLayer] { - if en.fills.is_empty() { &l.fill_layers } else { &en.fills } -} - -/// The width of a legend's column of swatches at 1:`scale` in a legend `size` times the default, -/// in points: it grows to hold the widest point symbol, so the labels line up. -fn swatch_column(rows: &[LegendRow], (scale, size): (f64, f32)) -> f32 { - rows.iter().map(|row| row.symbol_side(scale)).fold(LEGEND_SWATCH * size, f32::max) -} - -/// A legend picture's size in points (a pixel a point). -fn picture_size(p: &rustgis_tiles::cache::Payload) -> (f32, f32) { - match p { - rustgis_tiles::cache::Payload::Image(pm) => (pm.width() as f32, pm.height() as f32), - _ => (0.0, 0.0), - } -} - -/// Whether a legend lists a WMS or WMTS layer: drawn, and with a legend. -fn tile_listed(t: &rustgis_map::TileLayer) -> bool { - t.draws() && t.opacity > 0.0 && !t.legends.is_empty() -} - -/// A WMS or WMTS layer's legend picture for the map at 1:`scale`, as the Layers pane shows it: -/// the first of its legends there that is a picture. `None` while the one to show is still on -/// its way (`pending` then set), or when none can be shown. The addresses come from a service or -/// a project, so they are checked as the layer's own are. -fn tile_legend(t: &rustgis_map::TileLayer, scale: f64, pending: &mut bool) -> Option> { - use rustgis_tiles::cache::{self, Payload, State, Want}; - for l in rustgis_data::ogc::legends_at(&t.legends, scale) { - if rustgis_tiles::address::check(&l.url, Some(&t.url)).is_err() { - continue; - } - match cache::get(&l.url, Want::Image) { - // No larger than the Layers pane shows one. - State::Ready(p) if matches!(&*p, Payload::Image(pm) if pm.width() <= MAX_LEGEND_SIDE && pm.height() <= MAX_LEGEND_SIDE) => { - return Some(p); - } - State::Pending => { - *pending = true; - return None; - } - // The next, if there is one. - _ => {} - } - } - None -} - -/// Whether a legend picture `map`'s WMS and WMTS layers show at 1:`scale` is still on its way -/// (asking for those not yet asked for); those `exclude` names aren't listed, so aren't waited for. -pub fn tile_legends_pending(map: &Map, scale: f64, exclude: &[String]) -> bool { - let mut pending = false; - for t in map.tiles.iter().filter(|t| tile_listed(t) && !exclude.iter().any(|n| n.eq_ignore_ascii_case(&t.name))) { - let _ = tile_legend(t, scale, &mut pending); - } - pending -} - -/// Whether an element lies at least partly on `layout`'s page. The page's drawing and the redraw -/// gate ([`legends_pending`]) share this one test, in millimetres, so no drawing resolution can make -/// them disagree about a legend at the page's edge. -fn on_page(layout: &Layout, e: &rustgis_map::layout::Element) -> bool { - e.x + e.w > 0.0 && e.y + e.h > 0.0 && e.x < layout.width && e.y < layout.height -} - -/// Whether a legend on the page `layout` lists a WMS or WMTS layer whose legend picture is still -/// on its way, at its frame's scale. The interactive page is drawn again once it lands. A legend -/// wholly off the page shows none of its pictures, so it is not waited for. -pub fn legends_pending(layout: &Layout, maps: &[Map]) -> bool { - layout.elements.iter().filter(|e| e.visible && on_page(layout, e)).any(|e| { - let ElementKind::Legend { frame, exclude, .. } = &e.kind else { return false }; - let Some(ElementKind::MapFrame { map, center, scale, bearing, pitch, .. }) = layout.element(*frame).map(|f| &f.kind) else { - return false; - }; - let Some(m) = maps.iter().find(|m| m.name.eq_ignore_ascii_case(map)) else { return false }; - let cam = frame_camera(m, *center, *scale, *bearing, *pitch); - tile_legends_pending(m, m.ground_res_at(&cam) / rustgis_geom::PIXEL_M, exclude) - }) -} - -/// Refuses an export stopped during a legend wait, or that drew a legend whose picture was still -/// on its way: it stays refused if the picture lands afterwards, as the file would still lack it. -/// The browser cannot wait; it asks the caller to export again once the pictures land. -pub(crate) fn finish_legends() -> Result<(), String> { - rustgis_data::progress::check().map_err(|e| e.to_string())?; - if crate::cancel::requested() { - return Err(rustgis_data::DataError::Cancelled.to_string()); - } - if LEGEND_MISSING.get() { - return Err( - "legend pictures were still on their way when the export stopped waiting for them; export again once they arrive".into() - ); - } - Ok(()) -} - -/// How long an export waits, natively, for all the legend pictures it shows. -const LEGEND_WAIT: web_time::Duration = web_time::Duration::from_secs(30); - -thread_local! { - /// While an export draws on this thread: `Some`, holding the deadline for its legend pictures - /// once its first legend has waited. Every page, element and fallback picture of that export - /// shares it. - static LEGEND_BUDGET: std::cell::Cell>> = const { std::cell::Cell::new(None) }; - /// Whether a legend of the export drawing on this thread was drawn without a picture. - static LEGEND_MISSING: std::cell::Cell = const { std::cell::Cell::new(false) }; - /// A shorter [`LEGEND_WAIT`] for a test to reach. - #[cfg(test)] - static TEST_LEGEND_WAIT: std::cell::Cell> = const { std::cell::Cell::new(None) }; -} - -/// Ends the budget [`legend_budget`] opened when dropped, even by a panic. -pub(crate) struct LegendBudget(bool); - -impl Drop for LegendBudget { - fn drop(&mut self) { - if self.0 { - LEGEND_BUDGET.set(None); - LEGEND_MISSING.set(false); - } - } -} - -/// Opens one legend-wait budget for the export drawing on this thread, unless one is open (an -/// export of several pages or elements, each drawn through its own call, shares it). -pub(crate) fn legend_budget() -> LegendBudget { - let opened = LEGEND_BUDGET.get().is_none(); - if opened { - LEGEND_BUDGET.set(Some(None)); - LEGEND_MISSING.set(false); - } - LegendBudget(opened) -} - -/// When the open budget's legend wait ends, started by the first legend that waits. -fn legend_deadline() -> web_time::Instant { - #[cfg(test)] - let wait = TEST_LEGEND_WAIT.get().unwrap_or(LEGEND_WAIT); - #[cfg(not(test))] - let wait = LEGEND_WAIT; - let fresh = web_time::Instant::now() + wait; - match LEGEND_BUDGET.get() { - Some(Some(deadline)) => deadline, - Some(None) => { - LEGEND_BUDGET.set(Some(Some(fresh))); - fresh - } - None => fresh, - } -} - -/// Waits (natively, until `deadline`) for the legend pictures a legend of `map` at 1:`scale` -/// shows, as a frame waits for its tiles: a page needs them all. Only for those: not for the -/// cache's other fetches, nor for a layer the legend leaves out (`exclude`). `None` when the -/// run was cancelled meanwhile. -fn wait_for_tile_legends(map: &Map, scale: f64, exclude: &[String], deadline: web_time::Instant) -> Option<()> { - // In the browser, which can't wait, the page draws what has arrived. - while cfg!(not(target_arch = "wasm32")) && web_time::Instant::now() < deadline && tile_legends_pending(map, scale, exclude) { - if crate::cancel::requested() || rustgis_data::progress::check().is_err() { - return None; - } - std::thread::sleep(std::time::Duration::from_millis(15)); - } - Some(()) -} - -/// The widest and tallest legend picture shown, in pixels, as in the Layers pane, and the largest -/// side of a legend's point symbol, in points. -const MAX_LEGEND_SIDE: u32 = 2048; - -/// The outline of a raster class's swatch in a legend, as the Layers pane draws one around it. -const RASTER_SWATCH_EDGE: Rgba = Rgba::rgb(0x80, 0x80, 0x80); -/// A legend row's height, in points. -const LEGEND_ROW: f32 = 15.0; -/// A legend's title, layers' names and classes' labels, in points, at its default text size; the -/// room its title takes, in rows; and how far a class's swatch and a name's or label's text sit -/// in, in points. Measuring and drawing a legend both take them, times its size ([`legend_size`]). -const LEGEND_TITLE_PT: f32 = 12.0; -const LEGEND_NAME_PT: f32 = 9.0; -const LEGEND_LABEL_PT: f32 = 8.5; -const LEGEND_TITLE_ROWS: f32 = 1.3; -const LEGEND_INDENT: f32 = 6.0; -const LEGEND_LABEL_INDENT: f32 = 12.0; -/// A legend swatch's width, in points. -const LEGEND_SWATCH: f32 = 16.0; -/// The room between a legend's columns, in points. -const LEGEND_COLUMN_GAP: f32 = 10.0; - -/// The rows of the legend of a frame's map. With `drawn` (from [`shown_legends`]) it shows what the -/// frame draws: only the layers listed there, with their classes. Without, every class of every -/// visible layer. `opts` leaves out `` and the layers it names, either way. -fn legend_rows<'a>(map: &'a Map, drawn: Option<&[(u32, Vec)]>, opts: &LegendOptions<'a>) -> Vec> { - legend_rows_missing(map, drawn, opts).0 -} - -/// [`legend_rows`], and whether a WMS or WMTS legend picture was still on its way when the lookup -/// that makes its rows was made (the row is then left out). -fn legend_rows_missing<'a>( - map: &'a Map, - drawn: Option<&[(u32, Vec)]>, - opts: &LegendOptions<'a>, -) -> (Vec>, bool) { - let mut missing = false; - let excluded = |name: &str| opts.exclude.iter().any(|n| n.eq_ignore_ascii_case(name)); - let mut rows = Vec::new(); - // In the order the map draws them and the Layers pane lists them, top first. - for item in map.stack() { - let l = match item { - rustgis_map::Drawn::Layer(i) => match map.layers.get(i) { - Some(l) => l, - None => continue, - }, - // A WMS or WMTS layer's legend is its service's picture, whatever the frame draws of it. - rustgis_map::Drawn::Tile(i) => { - if let Some(t) = map.tiles.get(i).filter(|t| tile_listed(t) && !excluded(&t.name)) - && let Some(p) = tile_legend(t, opts.scale, &mut missing) - { - rows.push(LegendRow::Head(opts.shown(&t.name))); - rows.push(LegendRow::Picture(p)); - } - continue; - } - }; - if !(map.shows(l) && legend_lists(l) && !excluded(&l.name)) { - continue; - } - let mut entries = match drawn { - Some(d) => match d.iter().find(|(id, _)| *id == l.id) { - Some((_, entries)) => entries.clone(), - None => continue, - }, - // A classified raster's every class (#1679). - None if l.is_raster() => raster_classes(l, true).unwrap_or_default(), - None => l.with_size_legend(l.renderer.legend()), - }; - if drawn.is_none() && opts.show_no_data { - entries.extend(l.renderer.no_data_legend(&l.dataset, None)); - } - // The fallback row only (a class that happens to bear its name stays). - if opts.hide_other && entries.iter().any(|e| e.fallback) { - entries.retain(|e| !e.fallback); - // Nothing left to show for this layer: leave it out rather than draw its plain swatch - // (unless a diagram lists its categories below). - if entries.is_empty() && l.diagram.is_none() { - continue; - } - } - // A layer with a diagram lists its categories under its classes. - if let Some(d) = &l.diagram { - entries.extend(d.legend(l.geometry_type())); - } - if entries.is_empty() { - // A Unique Values layer that lists nothing draws nothing visible (#207); a raster has - // no symbol of its own to show. - if !l.is_raster() && !matches!(l.renderer, rustgis_map::Renderer::Unique { .. }) { - rows.push(LegendRow::Plain(l, opts.shown(&l.name))); - } - continue; - } - rows.push(LegendRow::Head(opts.shown(&l.name))); - rows.extend(entries.into_iter().map(|en| LegendRow::Class(l, en))); - } - (rows, missing) -} - -/// The legend of a frame's map: its title, and its rows ([`legend_rows`]) under it in `columns` -/// columns, each as wide as its widest row. As even as they go in the height the box leaves; in -/// less, each is filled in turn and the last rows are left out. In a box too narrow they close up, -/// so that none is left out for it: long labels run into the next, and the last column's past the -/// box, as a long label does in one column. -fn legend_missing( - pm: &mut Canvas, - r: Rect, - map: &Map, - (title, columns): (&str, usize), - drawn: Option<&[(u32, Vec)]>, - opts: LegendOptions, - ink: Rgba, - ppp: f64, -) -> bool { - let ppp = ppp as f32; - let at = (opts.scale, opts.size); - let mut y = r.y(); - if !title.is_empty() { - let line = LEGEND_ROW * opts.size * ppp; - text::text_at(pm, title, r.x(), y + line / 2.0, LEGEND_TITLE_PT * opts.size * 1.33 * ppp, ink, true, text::Align::Left, false); - y += line * LEGEND_TITLE_ROWS; - } - let (rows, missing) = legend_rows_missing(map, drawn, &opts); - let columns = columns.clamp(1, MAX_LEGEND_COLUMNS); - let starts = flow(&rows, columns, balanced(&rows, columns, at).1.min((r.bottom() - y) / ppp), at).0; - let gap = LEGEND_COLUMN_GAP * opts.size; - let across = (column_parts(&rows, &starts).map(|part| widest(part, at)).sum::() + gap * (starts.len() - 1) as f32) * ppp; - let close_up = if across > r.width() { r.width() / across } else { 1.0 }; - let mut x = r.x(); - for (k, part) in column_parts(&rows, &starts).enumerate() { - // The last has the rest of the box's width. - let right = if k + 1 < starts.len() { x + widest(part, at) * ppp * close_up } else { r.right() }; - let Some(column) = Rect::from_ltrb(x, y, right, r.bottom()) else { break }; - // The room left of it that holds nothing: none at the box's edge, the gap between columns - // as drawn after it. - let lead = if k == 0 { 0.0 } else { gap * ppp * close_up }; - legend_column(pm, column, part, (columns > 1, lead), map, &opts, ink, ppp); - x = right + gap * ppp * close_up; - } - missing -} - -/// [`legend_missing`], for a legend whose missing pictures nobody asks about. -#[cfg(test)] -fn legend( - pm: &mut Canvas, - r: Rect, - map: &Map, - title_columns: (&str, usize), - drawn: Option<&[(u32, Vec)]>, - opts: LegendOptions, - ppp: f64, -) { - legend_missing(pm, r, map, title_columns, drawn, opts, INK, ppp); -} - -/// A column of a legend: its rows from the top of `r`, as many as fit. With `name_with_class`, a -/// layer's name only with room for the class under it, as [`flow`] keeps them together. `lead` -/// pixels left of it hold nothing, which its swatches may reach into. -fn legend_column( - pm: &mut Canvas, - r: Rect, - rows: &[LegendRow], - (name_with_class, lead): (bool, f32), - map: &Map, - opts: &LegendOptions, - dark: Rgba, - ppp: f32, -) { - let mut y = r.y(); - let size = opts.size; - let line = LEGEND_ROW * size * ppp; - let sw = swatch_column(rows, (opts.scale, size)) * ppp; - // A line's or polygon's swatch, across the column of swatches. - let across = LEGEND_SWATCH * size * ppp; - let mut rows = rows.iter().peekable(); - while let Some(row) = rows.next() { - if let LegendRow::Picture(p) = row { - match &**p { - rustgis_tiles::cache::Payload::Image(pic) => match legend_picture(pm, r, y, pic, ppp * size) { - Some((h, true)) => y += h, - // Cut at the bottom, or no room for it. - _ => break, - }, - _ => continue, - } - continue; - } - // The rectangle's own bottom, which a sum of its top and height can miss by a rounding, - // and a thousandth of a row's slack: a legend sized to its rows keeps the last one. - let height = row.height(opts.scale, size) * ppp; - if y + height > r.bottom() + line * 1e-3 { - break; - } - // A WMS or WMTS layer's name only with room for some of its picture under it. - if let (LegendRow::Head(_), Some(LegendRow::Picture(p))) = (&row, rows.peek()) - && let rustgis_tiles::cache::Payload::Image(pic) = &**p - && y + line + picture_scale(r, pic, ppp * size) > r.bottom() + line * 1e-3 - { - break; - } - if let (true, LegendRow::Head(_), Some(next)) = (name_with_class, &row, rows.peek()) - && matches!(next, LegendRow::Class(..)) - && y + height + next.height(opts.scale, size) * ppp > r.bottom() + line * 1e-3 - { - break; - } - match row { - LegendRow::Plain(l, name) => { - let s = l.renderer.symbol_for(&l.dataset, 0); - let sym = (&s, l.line_strokes.as_slice(), l.fill_layers.as_slice()); - // Its room: left of the column, and the gap before its name. - let room = (lead, LEGEND_INDENT * size * ppp); - swatch(pm, (r.x(), y, sw, height), l, sym, map.layer_opacity(l), opts.scale, (ppp, across, room)); - let (x, pt) = (r.x() + sw + LEGEND_INDENT * size * ppp, LEGEND_NAME_PT * size * 1.33 * ppp); - text::text_at(pm, name, x, y + height / 2.0, pt, dark, false, text::Align::Left, false); - } - LegendRow::Head(name) => { - text::text_at(pm, name, r.x(), y + line / 2.0, LEGEND_NAME_PT * size * 1.33 * ppp, dark, true, text::Align::Left, false); - } - LegendRow::Class(l, en) => { - swatch( - pm, - (r.x() + LEGEND_INDENT * size * ppp, y, sw, height), - l, - (&en.symbol, row_strokes(l, en), row_fills(l, en)), - map.layer_opacity(l), - opts.scale, - // Its room: its indent and what lies left of the column, and the gap before its label. - (ppp, across, (lead + LEGEND_INDENT * size * ppp, (LEGEND_LABEL_INDENT - LEGEND_INDENT) * size * ppp)), - ); - text::text_at( - pm, - &en.label, - r.x() + sw + LEGEND_LABEL_INDENT * size * ppp, - y + height / 2.0, - LEGEND_LABEL_PT * size * 1.33 * ppp, - dark, - false, - text::Align::Left, - false, - ); - } - LegendRow::Picture(_) => {} - } - y += height; - } -} - -/// The pixels a legend picture's pixel takes in the legend `r`: a pixel a point, narrowed to fit -/// across after its indent. -fn picture_scale(r: Rect, pic: &Pixmap, ppp: f32) -> f32 { - ppp.min((r.right() - r.x() - 6.0 * ppp).max(0.0) / pic.width().max(1) as f32) -} - -/// Draws a WMS or WMTS layer's legend picture at `y` in the legend `r`, indented as a layer's -/// classes, a pixel a point, narrowed to fit across ([`picture_scale`]). One taller than the room -/// left is cut at the bottom. The height drawn and whether it all fitted; `None` when none of it -/// did. -fn legend_picture(pm: &mut Canvas, r: Rect, y: f32, pic: &Pixmap, ppp: f32) -> Option<(f32, bool)> { - let x = r.x() + 6.0 * ppp; - let k = picture_scale(r, pic, ppp); - let room = r.bottom() - y; - // The source rows that fit, a thousandth of a row's slack, as the rows have. - let rows = if k > 0.0 { ((room + LEGEND_ROW * ppp * 1e-3) / k).floor().min(pic.height() as f32) } else { 0.0 }; - if rows < 1.0 { - return None; - } - let shown; - let src = if (rows as u32) < pic.height() { - shown = tiny_skia::IntRect::from_xywh(0, 0, pic.width(), rows as u32).and_then(|c| pic.clone_rect(c))?; - &shown - } else { - pic - }; - pm.draw_pixmap( - 0, - 0, - src.as_ref(), - &PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..PixmapPaint::default() }, - Transform::from_row(k, 0.0, 0.0, k, x, y), - None, - ); - Some((rows * k, (rows as u32) == pic.height())) -} - -/// The size a legend with no title takes in one column, in two and so on, in mm (width, height): -/// its rows as [`legend`] draws them, the classes a frame shows at the renderer's scale denominator -/// `scale` (as the layout finds it for a frame, a complete source read through as [`render`] reads -/// it), or every class with `all_classes`. For sizing a legend to its content. `None` when a -/// complete source can't be read, as [`render`] then draws no page. A WMS or WMTS layer's legend -/// picture still on its way isn't waited for, nor counted ([`tile_legends_pending`] says whether -/// one is). Its layers' rows are measured by the `labels` it shows for them, else their names. -pub fn legend_sizes_mm( - map: &mut Map, - scale: f64, - all_classes: bool, - hide_other: bool, - (exclude, labels): (&[String], &BTreeMap), -) -> Option<[(f64, f64); MAX_LEGEND_COLUMNS]> { - let text_size = rustgis_map::layout::LEGEND_TEXT_PT; - legend_sizes_with_no_data_mm(map, scale, all_classes, hide_other, (false, text_size), (exclude, labels)) -} - -/// Sizes of an optional no-data legend whose text is `text_size` points (#2581), using the same -/// rows and filters as the drawing. -pub fn legend_sizes_with_no_data_mm( - map: &mut Map, - scale: f64, - all_classes: bool, - hide_other: bool, - (show_no_data, text_size): (bool, f64), - (exclude, labels): (&[String], &BTreeMap), -) -> Option<[(f64, f64); MAX_LEGEND_COLUMNS]> { - let drawn = if all_classes { None } else { Some(complete_shown_legends(map, scale, show_no_data, &mut None, &Env::default())?) }; - let size = legend_size(text_size); - let rows = legend_rows(map, drawn.as_deref(), &LegendOptions { show_no_data, hide_other, exclude, labels, scale, size }); - let mm = 25.4 / 96.0; - Some(std::array::from_fn(|i| { - let (starts, height) = balanced(&rows, i + 1, (scale, size)); - let gap = LEGEND_COLUMN_GAP * size * (starts.len() - 1) as f32; - let width: f32 = column_parts(&rows, &starts).map(|part| widest(part, (scale, size))).sum::() + gap; - (f64::from(width) * mm, f64::from(height) * mm) - })) -} - -/// The height in mm [`legend`] gives a title above its rows, which [`legend_sizes_mm`] leaves out, -/// in a legend whose text is `text_size` points (#2581). -pub fn legend_title_mm(text_size: f64) -> f64 { - f64::from(LEGEND_ROW * legend_size(text_size)) * f64::from(LEGEND_TITLE_ROWS) * 25.4 / 96.0 -} - -/// The renderer's scale denominator for a frame showing `map` at paper scale 1:`scale` (the one -/// [`legend_sizes_mm`] takes). -pub fn frame_render_scale(map: &Map, center: Coord, scale: f64) -> f64 { - let cam = frame_camera(map, center, scale, 0.0, 0.0); - map.ground_res_at(&cam) / rustgis_geom::PIXEL_M -} - -/// Whether a layer only outlines its polygons, with no fill and no labels: context around a map's -/// data, such as the neighbouring states' borders, which a surround can sit on. No Fill counts, -/// whatever the renderer; a transparent symbol under stacked fills such as a hatch (the layer's or a -/// class's), a fill by expression, diagrams or extrusion are more than an outline. -fn only_outlines(l: &rustgis_map::Layer) -> bool { - use rustgis_map::NoFill; - let hollow = l.no_fill == Some(NoFill::Override) - || (!l.has_fills() - && (l.no_fill == Some(NoFill::Symbols) || matches!(&l.renderer, rustgis_map::Renderer::Single(s) if s.fill.0[3] == 0))); - l.geometry_type() == GeometryType::Polygon - && !l.labels.enabled - && hollow - && l.symbol_by.fill.is_none() - && l.diagram.is_none() - && l.extrusion.is_none() -} - -/// Whether a layer fills its polygons in one colour, with no labels and nothing else: beside a layer -/// drawn by classes or a raster it is context too, such as the neighbouring states in grey. -fn plain_fill(l: &rustgis_map::Layer) -> bool { - l.geometry_type() == GeometryType::Polygon - && !l.labels.enabled - && !l.has_fills() - && matches!(&l.renderer, rustgis_map::Renderer::Single(_)) - && l.symbol_by.fill.is_none() - && l.diagram.is_none() - && l.extrusion.is_none() -} - -/// Where a frame showing `map` at 1:`scale` draws its layers: a grid of about `cells` cells across -/// the frame's longer side, row by row from the top, each `true` where a layer (or its labels) -/// drew. The basemap is left out, so the frame's background isn't counted, and so are layers that -/// only outline their polygons ([`only_outlines`]) unless nothing else is shown, and those that -/// fill them in one colour ([`plain_fill`]) beside a layer drawn by classes or a raster, when they -/// run on past the frame, as neighbouring states do: one inside it, such as a study area, is what -/// the map shows. For keeping a layout's surrounds off what its map shows. `None` when the frame -/// can't be drawn. -/// -/// The map itself is drawn, not a copy of it (every layer's features): its basemap, web tiles -/// (a background, like the basemap) and graticule are set aside for the drawing and put back, -/// however it ends, as is a label lock waiting to be filled, which the coarse drawing would -/// otherwise fill. -pub fn frame_coverage(map: &mut Map, center: Coord, scale: f64, w_mm: f64, h_mm: f64, cells: u32) -> Option<(u32, u32, Vec)> { - frame_coverage_judged_on(map, center, scale, (w_mm, h_mm), (w_mm, h_mm), cells) -} - -/// The visible layers a frame showing `map` at 1:`scale` around `center` takes as context around -/// its data, by id: those that only outline their polygons ([`only_outlines`]) unless nothing else -/// is shown, and those that fill them in one colour ([`plain_fill`]) beside a layer drawn by classes -/// or a raster, when they run on past a frame `judged` (mm) wide and tall, as neighbouring states -/// do. [`frame_coverage`] leaves them out of what the map draws; a publication's legend leaves them -/// out too (#1379). -pub fn context_layers(map: &Map, center: Coord, scale: f64, judged: (f64, f64)) -> Vec { - let at = frame_render_scale(map, center, scale); - if map.layers.iter().filter(|l| map.draws_at(l, at)).all(only_outlines) { - return Vec::new(); - } - let classes = - map.layers.iter().any(|l| map.draws_at(l, at) && (l.is_raster() || !matches!(&l.renderer, rustgis_map::Renderer::Single(_)))); - let judged_view = View { - width: judged.0 * PT_PER_MM, - height: judged.1 * PT_PER_MM, - pixels_per_point: 1.0, - camera: frame_camera(map, center, scale, 0.0, 0.0), - sky: false, - }; - let frame = crate::view_lonlat(map, &judged_view); - let past_the_frame = |l: &rustgis_map::Layer| { - let e = l.shown_extent(); - !e.is_empty() && (e.min_x < frame.min_x || e.max_x > frame.max_x || e.min_y < frame.min_y || e.max_y > frame.max_y) - }; - map.layers.iter().filter(|l| l.visible && (only_outlines(l) || (classes && plain_fill(l) && past_the_frame(l)))).map(|l| l.id).collect() -} - -/// [`frame_coverage`] of a frame `size` (mm), with what runs on past the frame judged on a frame -/// `judged` (mm) with the same centre: a drawing wider than the frame asked for, cut for frames -/// moved inside it, leaves out the same one-colour layers as that frame does. -pub fn frame_coverage_judged_on( - map: &mut Map, - center: Coord, - scale: f64, - (w_mm, h_mm): (f64, f64), - judged: (f64, f64), - cells: u32, -) -> Option<(u32, u32, Vec)> { - if !(w_mm > 0.0 && h_mm > 0.0 && judged.0 > 0.0 && judged.1 > 0.0) { - return None; - } - 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 }; - // Put back when this ends, a panic in the drawing included. - struct Aside<'a> { - basemap: rustgis_map::Basemap, - paper: Option, - tiles: Vec, - graticule: bool, - lock: Option>, - anchors: std::collections::HashMap, - outlines: Vec, - map: &'a mut Map, - } - impl Drop for Aside<'_> { - fn drop(&mut self) { - for l in self.map.layers.iter_mut().filter(|l| self.outlines.contains(&l.id)) { - l.visible = true; - } - self.map.basemap = self.basemap; - self.map.paper = self.paper; - self.map.tiles = std::mem::take(&mut self.tiles); - self.map.graticule = self.graticule; - self.map.label_lock = self.lock.take(); - self.map.label_lock_line_anchors = std::mem::take(&mut self.anchors); - } - } - // The space a globe is drawn on here: the blank basemap's, light. - let space = map.projection.is_globe().then(|| crate::globe_space(false)).map(|c| (c.r(), c.g(), c.b())); - let outlines = context_layers(map, center, scale, judged); - for l in map.layers.iter_mut().filter(|l| outlines.contains(&l.id)) { - l.visible = false; - } - let aside = Aside { - outlines, - basemap: std::mem::replace(&mut map.basemap, rustgis_map::Basemap::Blank), - // Judged on white paper: a blank basemap's paper colour (#2532) would count as drawn. - paper: map.paper.take(), - tiles: std::mem::take(&mut map.tiles), - graticule: std::mem::replace(&mut map.graticule, false), - lock: map.label_lock.take(), - anchors: std::mem::take(&mut map.label_lock_line_anchors), - map, - }; - let pm = crate::render(&mut *aside.map, &view)?.pixmap; - drop(aside); - let (gw, gh) = (pm.width(), pm.height()); - // Anything not the blank basemap's paper, pure opaque white (the graticule set aside too): a - // pale or translucent fill counts (only a fill of that very white, invisible on it, doesn't). - // On a globe, the space around it is paper too: counted, it took every cell and the surrounds - // landed on the globe (#2337). The atmosphere's glow at the rim is not, which keeps them off - // the globe's edge. - let paper = |r: u8, g: u8, b: u8| (r, g, b) == (255, 255, 255) || space == Some((r, g, b)); - let drawn = pm.pixels().iter().map(|p| p.alpha() > 0 && !(p.alpha() == 255 && paper(p.red(), p.green(), p.blue()))).collect(); - Some((gw, gh, drawn)) -} - -/// Whether a frame showing `map` at 1:`scale` around `center`, `size` (mm) wide and tall, shows -/// one light 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 }; - // A publication's legend has no ink (#2257): its text stays dark grey (INK), so dark water - // or land must keep its paper backing. - let background = [water, land] - .iter() - .any(|c| (c.0[0], c.0[1], c.0[2], 255) == first && u16::from(c.r()) + u16::from(c.g()) + u16::from(c.b()) > 3 * 160); - background && seen.all(|p| rgba(p) == first) -} - -/// A legend entry's symbol `s` of the layer `l` in the box (`x`, `y`, `w`, `h`), with its stacked -/// `strokes` and `fills` (#2490): a point as [`point_swatch`] draws it, or a line or a filled box a -/// swatch wide in the middle of the box (`across` pixels: [`LEGEND_SWATCH`] in the legend's size), -/// by the paths the map draws its features with, its widths at `ppp`. A line or polygon swatch's -/// ink ([`swatch_ink`]) is held to its row's top and bottom and, at its sides, to the `room` (left, -/// right, in pixels) its row leaves empty: left, its indent and what lies left of its column, none -/// at the legend's edge; right, the gap before its text. Stacked, see-through (`opacity`), grown -/// with the layer's reference scale at 1:`scale` or reaching past that, it is composited as one and -/// cut there. -fn swatch( - pm: &mut Canvas, - (x, y, w, h): (f32, f32, f32, f32), - l: &rustgis_map::Layer, - (s, strokes, fills): (&rustgis_map::Symbol, &[rustgis_map::LineStroke], &[rustgis_map::fills::FillLayer]), - opacity: f32, - scale: f64, - (ppp, across, (lead, gap)): (f32, f32, (f32, f32)), -) { - let gt = l.geometry_type(); - let k = l.size_factor(scale); - if gt == GeometryType::Point { - point_swatch(pm, (x, y, w, h), (s, strokes), opacity, ppp * k); - return; - } - // Every line or polygon swatch is cut to its row's top and bottom, so a line wider than its row, - // or shifted off it, doesn't paint over the rows beside it (#2518), and at its sides to the room - // its row leaves empty, so it doesn't paint over its label, the column before or past the - // legend's edge; within those it keeps its ink, as wide as the map draws it (#2581). - let plain = if gt == GeometryType::Polyline { strokes.is_empty() } else { fills.is_empty() }; - let ink = swatch_ink((x, y, w, h), gt, (s, strokes, fills), (across, ppp * k)); - let (lo, hi) = (x - lead, x + w + gap); - let within = ink.is_none_or(|b| b.top() >= y - 0.01 && b.bottom() <= y + h + 0.01 && b.left() >= lo - 0.01 && b.right() <= hi + 0.01); - if plain && opacity >= 0.999 && k == 1.0 && within { - // A layer with no stack, within its row: the swatch it always had. - flat_swatch(pm, (x, y, w, h), gt, s, (across, ppp)); - return; - } - let (left, right) = ink.map_or((x, x + w), |b| (x.min(b.left()).max(lo), (x + w).max(b.right()).min(hi))); - composited(pm, (left, y, right - left, h), opacity, |c, (cl, ct)| { - let cell = (x - cl, y - ct, w, h); - if plain { - flat_swatch(c, cell, gt, s, (across, ppp * k)); - } else { - stacked_swatch(c, cell, l, (s, strokes, fills), (ppp, across), k); - } - }); -} - -/// Where a line or polygon swatch drawn in `cell`, `across` pixels wide, its widths at `wppp`, -/// puts ink: a plain one's line stroked as [`flat_swatch`] strokes it (its joins too); a stacked -/// line's `strokes` the map draws, as it strokes them ([`crate::line_stroke`]), an offset one as -/// wide as its width and twice its offset, mitred, as its shifted line's corners are -/// (`offset_polyline`), a marked one as far as [`crate::line_markers::reach`]; a stacked polygon's -/// box and its outline. `None` for no shape. [`swatch`] keeps it within its row and the room its -/// row leaves empty. -fn swatch_ink( - cell: (f32, f32, f32, f32), - gt: GeometryType, - (s, strokes, fills): (&rustgis_map::Symbol, &[rustgis_map::LineStroke], &[rustgis_map::fills::FillLayer]), - (across, wppp): (f32, f32), -) -> Option { - let line = gt == GeometryType::Polyline; - if (line && strokes.is_empty()) || (!line && fills.is_empty()) { - let (p, stroke) = flat_swatch_outline(cell, gt, s, (across, wppp))?; - return p.stroke(&stroke, 1.0).map(|p| p.bounds()); - } - if !line { - let b = swatch_box(cell, across)?; - let o = if s.stroke.a() > 0 { s.stroke_width.max(0.0) * wppp / 2.0 } else { 0.0 }; - return Rect::from_ltrb(b.left() - o, b.top() - o, b.right() + o, b.bottom() + o); - } - let path = swatch_line_path(cell, across)?; - let b = path.bounds(); - strokes - .iter() - .filter_map(|st| { - let (c, w) = st.resolve(s); - let w = if w.is_finite() { w.max(0.0) } else { 0.0 }; - if st.markers.is_some() { - let r = crate::line_markers::reach(std::slice::from_ref(st), w) * wppp; - return Rect::from_ltrb(b.left() - r, b.top() - r, b.right() + r, b.bottom() + r); - } - // One the map skips (no width or no colour) puts no ink. - if w <= 0.0 || c.a() == 0 { - return None; - } - let mut stroke = crate::line_stroke(st, (w * wppp).max(0.5) + 2.0 * st.offset.abs() * wppp); - if st.offset != 0.0 { - stroke.line_join = tiny_skia::LineJoin::Miter; - } - path.stroke(&stroke, 1.0).map(|p| p.bounds()) - }) - .reduce(|a, c| { - Rect::from_ltrb(a.left().min(c.left()), a.top().min(c.top()), a.right().max(c.right()), a.bottom().max(c.bottom())).unwrap_or(a) - }) -} - -/// A line swatch's zigzag ([`swatch_line`]) as a path. -fn swatch_line_path(cell: (f32, f32, f32, f32), across: f32) -> Option { - let [a, b, c] = swatch_line(cell, across); - let mut pb = PathBuilder::new(); - pb.move_to(a.0, a.1); - pb.line_to(b.0, b.1); - pb.line_to(c.0, c.1); - pb.finish() -} - -/// A plain line or polygon swatch's line, `across` pixels wide in the box: a line's zigzag or a -/// polygon's box, and the stroke it is drawn with, its width at `wppp`. -fn flat_swatch_outline( - cell: (f32, f32, f32, f32), - gt: GeometryType, - s: &rustgis_map::Symbol, - (across, wppp): (f32, f32), -) -> Option<(tiny_skia::Path, Stroke)> { - if gt == GeometryType::Polyline { - Some((swatch_line_path(cell, across)?, Stroke { width: s.stroke_width.max(1.0) * wppp, ..Stroke::default() })) - } else { - Some((PathBuilder::from_rect(swatch_box(cell, across)?), Stroke { width: s.stroke_width.max(0.5) * wppp, ..Stroke::default() })) - } -} - -/// The part of the box (`x`, `w`) a line or polygon swatch `across` pixels wide takes, in its -/// middle. -fn swatch_across(x: f32, w: f32, across: f32) -> (f32, f32) { - (x + (w - across) / 2.0, across) -} - -/// The three points of a line swatch `across` pixels wide in the box, in pixels. -fn swatch_line((x, y, w, h): (f32, f32, f32, f32), across: f32) -> [(f32, f32); 3] { - let (x, w) = swatch_across(x, w, across); - let cy = y + h / 2.0; - [(x, cy + h * 0.2), (x + w * 0.4, cy - h * 0.2), (x + w, cy + h * 0.1)] -} - -/// A polygon swatch's box, `across` pixels wide, in the box, in pixels. -fn swatch_box((x, y, w, h): (f32, f32, f32, f32), across: f32) -> Option { - let (x, w) = swatch_across(x, w, across); - Rect::from_xywh(x, y + h * 0.2, w, h * 0.6) -} - -/// A line or polygon swatch of the symbol `s` alone, `across` pixels wide, its widths at `wppp`. -fn flat_swatch(pm: &mut Canvas, cell: (f32, f32, f32, f32), gt: GeometryType, s: &rustgis_map::Symbol, at: (f32, f32)) { - let Some((p, stroke)) = flat_swatch_outline(cell, gt, s, at) else { return }; - if gt != GeometryType::Polyline { - pm.fill_rect(p.bounds(), &paint(s.fill, 1.0), Transform::identity(), None); - } - pm.stroke_path(&p, &paint(s.stroke, 1.0), &stroke, Transform::identity(), None); -} - -/// A line or polygon swatch with its stacked `strokes` or `fills`, drawn by the map's own paths -/// for a feature of that shape: [`crate::stroke_paths::Paths`] and [`crate::Ctx::filled`], `across` -/// pixels wide, at `ppp` and the layer's reference scale `k`. The canvas stands for a view whose -/// map units are its points, y up, so the shape's pixels are its coordinates. -fn stacked_swatch( - pm: &mut Canvas, - cell: (f32, f32, f32, f32), - l: &rustgis_map::Layer, - (s, strokes, fills): (&rustgis_map::Symbol, &[rustgis_map::LineStroke], &[rustgis_map::fills::FillLayer]), - (ppp, across): (f32, f32), - k: f32, -) { - let (w, h) = (f64::from(pm.width()) / f64::from(ppp), f64::from(pm.height()) / f64::from(ppp)); - let camera = rustgis_map::Camera::new(Coord::new(w / 2.0, -h / 2.0), 1.0); - let view = View { width: w, height: h, pixels_per_point: f64::from(ppp), camera, sky: false }; - let ctx = crate::Ctx { - view: &view, - ppp: ppp * k, - wireframe: false, - // (The swatch's own view: the stroke and fill paths don't cull today, and one that does - // still keeps the swatch, where an empty extent would drop it.) - cull: crate::cull_extent(&view, crate::CULL_MARGIN), - globe: None, - sprites: Default::default(), - bursts: Default::default(), - }; - let at = |(x, y): (f32, f32)| Coord::new(f64::from(x / ppp), -f64::from(y / ppp)); - if l.geometry_type() == GeometryType::Polyline { - // Drawn level by level, as the map draws a feature's strokes with symbol levels on. - let mut ordered: Vec<(usize, rustgis_map::LineStroke)> = strokes.iter().copied().enumerate().collect(); - if l.stroke_levels { - ordered.sort_by_key(|(i, st)| st.level_at(*i)); - } - let ordered: Vec = ordered.into_iter().map(|(_, st)| st).collect(); - let part: Vec = swatch_line(cell, across).into_iter().map(at).collect(); - crate::stroke_paths::Paths::default().draw(&ctx, pm, &[part], s, &ordered); - } else if let Some(b) = swatch_box(cell, across) { - let ring: Vec = - [(b.left(), b.top()), (b.right(), b.top()), (b.right(), b.bottom()), (b.left(), b.bottom()), (b.left(), b.top())] - .into_iter() - .map(at) - .collect(); - ctx.filled(pm, &[vec![ring]], s, fills); - } -} - -/// A point's symbol at (`x`, `y`), unturned, by the path the map takes for it: its marker, or -/// `strokes`' stacked marks. -fn draw_point(pm: &mut Canvas, (x, y): (f32, f32), s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke], ppp: f32) { - if point_marks::plain(strokes, 0.0) { - crate::draw_marker(pm, x, y, s, 1.0, None, ppp); - } else { - point_marks::draw(pm, x, y, s, strokes, 0.0, None, ppp); - } -} - -/// A point layer's symbol in the middle of the box, as the map draws its points: `strokes`' stacked -/// marks or its marker, at `ppp` (with the layer's reference scale), unturned. See-through, the -/// marks are composited as one, as the map composites the layer, in a picture no larger than the -/// page. So are those too large for the box (past [`LegendRow::symbol_side`]'s limit), which the -/// picture cuts to it. -fn point_swatch( - pm: &mut Canvas, - (x, y, w, h): (f32, f32, f32, f32), - (s, strokes): (&rustgis_map::Symbol, &[rustgis_map::LineStroke]), - opacity: f32, - ppp: f32, -) { - let (cx, cy) = (x + w / 2.0, y + h / 2.0); - // A thousandth of slack: the box's size went through a rounding of its own. - let fits = 2.0 * point_marks::reach(s, strokes) * ppp <= w.min(h) * 1.001; - if opacity >= 0.999 && fits { - draw_point(pm, (cx, cy), s, strokes, ppp); - return; - } - composited(pm, (x, y, w, h), opacity, |c, (left, top)| draw_point(c, (cx - left, cy - top), s, strokes, ppp)); -} - -/// Draws by `draw` into a picture of the box (`x`, `y`, `w`, `h`), no larger than the page, and -/// composites it as one at `opacity`, cut to the box. `draw` gets the picture and where its corner -/// sits on the canvas, in pixels. -fn composited(pm: &mut Canvas, (x, y, w, h): (f32, f32, f32, f32), opacity: f32, draw: impl FnOnce(&mut Canvas, (f32, f32))) { - // Kept on the canvas: a picture as large as the canvas then covers all of it that shows. - let (left, top) = (x.floor().max(0.0), y.floor().max(0.0)); - let (cw, ch) = (((x + w).ceil() - left) as u32, ((y + h).ceil() - top) as u32); - let (cw, ch) = (cw.min(pm.width()), ch.min(pm.height())); - if let Some(mut picture) = pm.sub(cw, ch) { - draw(&mut picture, (left, top)); - let Some(r) = Rect::from_xywh(x, y, w, h) else { return }; - let clip = if picture.is_recording() { - // A recording keeps what lies past its picture's edge, so it is cut here, at the box. - Some(crate::vector::Clip { path: PathBuilder::from_rect(r), rule: FillRule::Winding, transform: Transform::identity() }) - } else { - // Pixels are cut in the picture, by a mask its size rather than the page's. - if let Some(mut m) = Mask::new(cw, ch) { - m.fill_path(&PathBuilder::from_rect(r), FillRule::Winding, true, Transform::from_translate(-left, -top)); - picture.pixels().apply_mask(&m); - } - None - }; - pm.place(picture, Transform::from_translate(left, top), opacity, rustgis_map::effects::Blend::Normal, clip); - } -} - -/// How a colorbar is laid out. -struct Bar<'a> { - title: &'a str, - orientation: Orientation, - ticks: usize, - side: TickSide, - reverse: bool, - /// Labels with a decimal comma ([`Layout::decimal_comma`]). - comma: bool, - /// Its title, outline, ticks and labels (#2257). - ink: Rgba, -} - -/// `n` values from `lo` to `hi`, the ends included, with the fewest decimals that keep each within -/// a twentieth of the step of its value. -fn tick_labels(lo: f64, hi: f64, n: usize) -> Vec<(f64, String)> { - if !(lo.is_finite() && hi.is_finite()) { - return Vec::new(); - } - let n = if hi > lo { n.clamp(2, rustgis_map::layout::MAX_COLORBAR_TICKS) } else { 1 }; - let step = if n > 1 { (hi - lo) / (n - 1) as f64 } else { 0.0 }; - let values: Vec = (0..n).map(|i| if i + 1 == n { hi } else { lo + step * i as f64 }).collect(); - if values.iter().any(|v| v.abs() >= 1e6) { - return values.into_iter().map(|v| (v, rustgis_map::symbology::fmt_num(v))).collect(); - } - let tol = if step > 0.0 { step * 0.05 } else { (lo.abs() * 1e-3).max(1e-9) }; - let decimals = (0..=6) - .find(|d| { - let k = 10f64.powi(*d); - values.iter().all(|v| ((v * k).round() / k - v).abs() <= tol) - }) - .unwrap_or(6) as usize; - // Rounded first, then + 0.0, so a value rounded to zero isn't printed "-0". - let k = 10f64.powi(decimals as i32); - values.into_iter().map(|v| (v, format!("{:.*}", decimals, (v * k).round() / k + 0.0))).collect() -} - -/// A colorbar laid out in its element ([`colorbar_plan`]): what [`colorbar`] draws, and what the -/// page's cut-off check ([`text_losses`]) says of it, from one layout. -struct ColorbarPlan { - /// The title's lines drawn, each with the middle of its line (pixels). - title: Vec<(String, f32)>, - /// The bar's blocks or samples, low to high, and its rectangle (x, y, width, height). - blocks: Vec, - rect: (f32, f32, f32, f32), - /// The bar runs down the page, and from high to low along it (its start is left or top). - vertical: bool, - flip: bool, - /// The labels drawn: each one's text, its tick's two ends, where it is drawn, and whether - /// centred on it (else from its left). - labels: Vec<(String, [(f32, f32); 2], (f32, f32), bool)>, - /// Labels left out because they would spill out of the element (#2638), not those thinned - /// for clearing the one before: a short or narrow element, or one with no room for a bar. - spilled: usize, -} - -/// A colorbar in `r` at `ppp` (#2638): its title's lines that fit over the bar's own room -/// ([`colorbar_title_drawn`]), the bar, leaving room for the labels on their side and for the end -/// labels to stand past its ends, and each label drawn only if it clears the one before and stays -/// inside the element. -fn colorbar_plan(r: Rect, scale: &ColorScale, bar: &Bar, ppp: f32) -> ColorbarPlan { - let px = 8.0 * 1.33 * ppp; - let width = |s: &str| text::measure(s, px / 1.33, false); - let (mut top, bottom) = (r.y(), r.y() + r.height()); - let mut title = Vec::new(); - if !bar.title.is_empty() { - let tpx = COLORBAR_TITLE_PT as f32 * 1.33 * ppp; - // Wrapped to the element's width (#2493). - let lines = colorbar_title_lines(bar.title, f64::from(r.width()) / (f64::from(ppp) * PT_PER_MM)); - let drawn = colorbar_title_drawn(lines.len(), top, bottom - colorbar_bar_room(ppp, bar.orientation), tpx); - title = lines.into_iter().take(drawn).enumerate().map(|(i, line)| (line, top + tpx * (0.6 + 1.25 * i as f32))).collect(); - // A title held back whole takes no room: the bar starts at the element's top. - if drawn > 0 { - top += tpx * (1.4 + 1.25 * (drawn - 1) as f32); - } - } - // Where each block or sample sits along the bar (0 low to 1 high), and the labels with theirs. - let (blocks, labels): (Vec, Vec<(f32, String)>) = match scale { - ColorScale::Ramp { lo, hi, colors } => { - let span = hi - lo; - let labels = tick_labels(*lo, *hi, bar.ticks) - .into_iter() - .map(|(v, s)| ((if span > 0.0 { (v - lo) / span } else { 0.5 }) as f32, s)) - .collect(); - (colors.clone(), labels) - } - ColorScale::Steps { edges, colors } => { - let n = colors.len().max(1) as f32; - let labels = edges.iter().enumerate().map(|(i, v)| (i as f32 / n, rustgis_map::symbology::fmt_num(*v))).collect(); - (colors.clone(), labels) - } - ColorScale::Values(v) => { - let n = v.len().max(1) as f32; - let labels = v.iter().enumerate().map(|(i, (val, _))| ((i as f32 + 0.5) / n, rustgis_map::symbology::fmt_num(*val))).collect(); - (v.iter().map(|(_, c)| *c).collect(), labels) - } - }; - let vertical = bar.orientation == Orientation::Vertical; - let flip = if vertical { !bar.reverse } else { bar.reverse }; - let mut plan = ColorbarPlan { title, blocks: Vec::new(), rect: (0.0, 0.0, 0.0, 0.0), vertical, flip, labels: Vec::new(), spilled: 0 }; - if blocks.is_empty() { - return plan; - } - // No room for a bar: none is drawn, nor its labels. - if r.width() < 2.0 || bottom - top < 2.0 { - plan.spilled = labels.len(); - return plan; - } - let labels: Vec<(f32, String)> = labels.into_iter().map(|(at, s)| (at, decimal(s, bar.comma))).collect(); - let tick = 2.5 * ppp; - let gap = 1.5 * ppp; - let (bx, by, bw, bh) = if vertical { - let label_w = labels.iter().map(|(_, s)| width(s)).fold(0.0f32, f32::max); - let bw = (r.width() - label_w - tick - gap).clamp(2.0 * ppp, (r.width() * 0.45).max(2.0 * ppp)).min(r.width()); - let inset = (px / 2.0).min((bottom - top) * 0.25); - let bx = if bar.side == TickSide::Start { r.x() + r.width() - bw } else { r.x() }; - (bx, top + inset, bw, (bottom - top - 2.0 * inset).max(1.0)) - } else { - let ends = labels.first().map(|(_, s)| width(s)).unwrap_or(0.0).max(labels.last().map(|(_, s)| width(s)).unwrap_or(0.0)); - let inset = (ends / 2.0).min(r.width() * 0.25); - // Too short for its labels (left out below, and said), the bar fills the element. - let bh = match bottom - top - px * 1.2 - tick - gap { - h if h >= 3.0 * ppp => h, - _ => bottom - top, - }; - let by = if bar.side == TickSide::Start { bottom - bh } else { top }; - (r.x() + inset, by, (r.width() - 2.0 * inset).max(1.0), bh) - }; - plan.blocks = blocks; - plan.rect = (bx, by, bw, bh); - let len = if vertical { bh } else { bw }; - let along = |t: f32| if flip { (1.0 - t) * len } else { t * len }; - // A label (and its tick) is left out where it would spill out of a short or narrow element. - let inside = - |x: f32, y: f32, w: f32, h: f32| x >= r.x() - 1.0 && y >= r.y() - 1.0 && x + w <= r.right() + 1.0 && y + h <= r.bottom() + 1.0; - // Labels in order along the bar, each drawn only if it clears the one before. - let mut last_end = f32::NEG_INFINITY; - let mut ordered: Vec<(f32, String)> = labels.into_iter().map(|(t, s)| (along(t.clamp(0.0, 1.0)), s)).collect(); - ordered.sort_by(|a, b| a.0.total_cmp(&b.0)); - for (d, label) in ordered { - let lw = width(&label); - let extent = if vertical { px } else { lw }; - if d - extent / 2.0 < last_end + gap { - continue; - } - let (tick_ends, at, centred, fits) = if vertical { - let (y, x0) = (by + d, if bar.side == TickSide::Start { bx } else { bx + bw }); - let x1 = if bar.side == TickSide::Start { x0 - tick } else { x0 + tick }; - let lx = if bar.side == TickSide::Start { x1 - gap - lw } else { x1 + gap }; - ([(x0, y), (x1, y)], (lx, y), false, inside(lx, y - px / 2.0, lw, px)) - } else { - let (x, y0) = (bx + d, if bar.side == TickSide::Start { by } else { by + bh }); - let y1 = if bar.side == TickSide::Start { y0 - tick } else { y0 + tick }; - let ly = if bar.side == TickSide::Start { y1 - gap - px * 0.5 } else { y1 + gap + px * 0.5 }; - ([(x, y0), (x, y1)], (x, ly), true, inside(x - lw / 2.0, ly - px / 2.0, lw, px)) - }; - // Only a label drawn takes room: one left out doesn't thin the next. - if fits { - last_end = d + extent / 2.0; - plan.labels.push((label, tick_ends, at, centred)); - } else { - plan.spilled += 1; - } - } - plan -} - -/// A colorbar: the bar, ticks and labels along it, and its title above, as [`colorbar_plan`] lays -/// them out. Title lines and labels left out are said with the page's cut-off texts -/// ([`text_losses`]). -fn colorbar(pm: &mut Canvas, r: Rect, scale: &ColorScale, bar: &Bar, ppp: f64) { - let ppp = ppp as f32; - let dark = bar.ink; - let px = 8.0 * 1.33 * ppp; - let plan = colorbar_plan(r, scale, bar, ppp); - let tpx = COLORBAR_TITLE_PT as f32 * 1.33 * ppp; - for (line, y) in &plan.title { - text::text_at(pm, line, r.x(), *y, tpx, dark, true, text::Align::Left, false); - } - if plan.blocks.is_empty() { - return; - } - let (bx, by, bw, bh) = plan.rect; - let len = if plan.vertical { bh } else { bw }; - let along = |t: f32| if plan.flip { (1.0 - t) * len } else { t * len }; - let n = plan.blocks.len(); - for (i, c) in plan.blocks.iter().enumerate() { - let (a, b) = (along(i as f32 / n as f32), along((i + 1) as f32 / n as f32)); - let (s0, s1) = (a.min(b), a.max(b)); - // A touch longer than its share, so neighbours leave no seam. - let rect = - if plan.vertical { Rect::from_xywh(bx, by + s0, bw, s1 - s0 + 0.6) } else { Rect::from_xywh(bx + s0, by, s1 - s0 + 0.6, bh) }; - if let Some(rect) = rect.and_then(|q| q.intersect(&Rect::from_xywh(bx, by, bw, bh)?)) { - pm.fill_rect(rect, &paint(*c, 1.0), Transform::identity(), None); - } - } - let line = Stroke { width: 0.6 * ppp, ..Stroke::default() }; - if let Some(b) = Rect::from_xywh(bx, by, bw, bh) { - pm.stroke_path(&PathBuilder::from_rect(b), &paint(dark, 1.0), &line, Transform::identity(), None); - } - for (label, [(x0, y0), (x1, y1)], (x, y), centred) in &plan.labels { - let align = if *centred { text::Align::Center } else { text::Align::Left }; - text::text_at(pm, label, *x, *y, px, dark, false, align, false); - let mut pb = PathBuilder::new(); - pb.move_to(*x0, *y0); - pb.line_to(*x1, *y1); - if let Some(p) = pb.finish() { - pm.stroke_path(&p, &paint(dark, 1.0), &line, Transform::identity(), None); - } - } -} - -/// How a text element's lines are drawn, beyond their size and colour. -#[derive(Clone, Copy)] -pub(crate) struct TextStyle { - /// Bold, italic and the family. - pub(crate) face: text::Face, - pub(crate) align: TextAlign, - /// Letter spacing in points. - pub(crate) spacing: f32, - /// Where its block of lines sits down its box ([`block_shift`]). - pub(crate) valign: TextVAlign, - /// The distance between its lines, a multiple of the usual (0.5 to 3). - pub(crate) line_spacing: f32, -} - -impl TextStyle { - /// This style with a text's block alignment and line spacing, brought into range here, so every - /// reader of `line_spacing` may trust it: an unknown alignment is the top, and the spacing is - /// as [`rustgis_map::layout::line_spacing_in_range`] reads it (not finite is the usual one, one - /// outside 0.5..=3 the nearer limit). The usual spacing is exactly 1, so a plain text is placed - /// as it always was. - pub(crate) fn with_block(self, valign: TextVAlign, line_spacing: f64) -> TextStyle { - TextStyle { valign: valign.kept(), line_spacing: rustgis_map::layout::line_spacing_in_range(line_spacing) as f32, ..self } - } -} - -/// A text element's style: its face in an installed family by name (#762), else its generic one. -/// The app doesn't wait for the font index while it is being built; a script or the command line -/// builds it now (`families::find_ready`). One for the page, its clipping check and the SVG, so -/// each measures and breaks a text alike. -pub(crate) fn text_style( - bold: bool, - italic: bool, - font: rustgis_map::layout::FontFamily, - font_name: Option<&str>, - align: TextAlign, - letter_spacing: f64, -) -> TextStyle { - let family = font_name.and_then(crate::families::find_ready); - let face = text::Face { bold, italic, serif: font == rustgis_map::layout::FontFamily::Serif, family }; - TextStyle { face, align, spacing: letter_spacing as f32, valign: TextVAlign::Top, line_spacing: USUAL_LINE_SPACING } -} - -/// Pixels per millimetre a wrapped text's lines are measured at (300 dpi), whatever the -/// resolution it is drawn at, so the layout view, each export and the SVG break the same lines. -const WRAP_PX_PER_MM: f64 = 300.0 / 25.4; - -/// A wrapped text (#2346) as the lines it is drawn in, joined by line breaks: each of its own -/// lines broken at spaces to fit `width` mm at `size` points, a word wider than that broken -/// across lines ([`crate::report::wrap_lines`]). A line is measured as [`text_block`] places it: -/// a left-aligned one from the box's edge to its ink's right, an aligned one by its ink. -pub(crate) fn wrapped(s: &str, width: f64, size: f64, style: TextStyle) -> String { - let ppp = (WRAP_PX_PER_MM / PT_PER_MM) as f32; - let px = (size as f32).clamp(2.0, 400.0) * 1.33 * ppp; - let spacing = style.spacing * 1.33 * ppp; - let measure = |t: &str| { - let (lo, hi) = text::styled_extent(t, px, style.face, spacing); - f64::from(if style.align == TextAlign::Left { hi } else { hi - lo }) - }; - // Lines past the 200 a text draws aren't broken: one more, with text, tells the cut-off check - // it goes on. - crate::report::wrap_lines(s, width * WRAP_PX_PER_MM, measure, 200).join("\n") -} - -/// A text element's lines as they are drawn, from its text with its tokens filled in ([`expand`]): -/// in its case, then, when it wraps, broken to its box `width_mm` wide ([`wrapped`]), so an upper -/// case text breaks at its own, wider, width. One for the page, its cut-off check and the SVG, so -/// they draw and count the same lines. Those that don't fit its box are left out from the bottom -/// whatever its block alignment: a block taller than its box starts at its top ([`block_shift`]). -pub(crate) fn drawn_text(expanded: String, case: TextCase, wrap: bool, width_mm: f64, size: f64, style: TextStyle) -> String { - let s = case.kept().apply(expanded); - if wrap { wrapped(&s, width_mm, size, style) } else { s } -} - -/// The most lines a text draws. -const MAX_TEXT_LINES: usize = 200; - -/// [`block_shift`] for the text `s` as it is drawn ([`drawn_text`]), by its lines. A text of more -/// lines than a text draws is cut at them, so it starts at the top like any block that doesn't fit -/// its box, though the lines kept would: one rule for the page, its cut-off check, a turned text's -/// picture and the SVG. -pub(crate) fn text_shift(valign: TextVAlign, box_h: f64, px: f64, s: &str, line_spacing: f64) -> f64 { - let lines = s.lines().take(MAX_TEXT_LINES + 1).count(); - if lines > MAX_TEXT_LINES { 0.0 } else { block_shift(valign, box_h, px, lines, line_spacing) } -} - -/// How far down its box of `box_h` pixels a text's block of `lines` lines at `px` pixels, spaced -/// `line_spacing` times the usual, starts: 0 at the top; half the room it leaves in the middle; -/// all of it at the bottom, its last line's pitch ending on the box's bottom edge. A block taller -/// than its box (or with no line) starts at its top whatever its alignment, so its first lines are -/// the ones kept and none is drawn above the box. -pub(crate) fn block_shift(valign: TextVAlign, box_h: f64, px: f64, lines: usize, line_spacing: f64) -> f64 { - if lines == 0 || valign.kept() == TextVAlign::Top { - return 0.0; - } - let block = px * 1.25 * (1.0 + (lines - 1) as f64 * line_spacing); - let free = box_h - block; - // A measure not a number, or past any page, is no room. - if !free.is_finite() || free <= 0.0 { - return 0.0; - } - match valign.kept() { - TextVAlign::Middle => free / 2.0, - TextVAlign::Bottom => free, - _ => 0.0, - } -} - -/// The lines a wrapped text element (#2346), upright and without letter spacing or a named family, -/// is drawn in: `s`, its text with the dynamic text filled in, in a box `width` mm wide. For a -/// caller that sizes the box around the text. -pub fn wrapped_lines(s: &str, width: f64, size: f64, bold: bool, font: rustgis_map::layout::FontFamily, align: TextAlign) -> Vec { - wrapped(s, width, size, text_style(bold, false, font, None, align, 0.0)).lines().map(str::to_string).collect() -} - -/// A colorbar's title's size in points; it is drawn bold. -pub const COLORBAR_TITLE_PT: f64 = 9.0; - -/// A colorbar's title's style, as [`colorbar_title_lines`] measures it: bold, from the left edge. -fn colorbar_title_style() -> TextStyle { - TextStyle { - face: text::Face { bold: true, ..Default::default() }, - align: TextAlign::Left, - spacing: 0.0, - valign: TextVAlign::Top, - line_spacing: USUAL_LINE_SPACING, - } -} - -/// A colorbar's title's width in mm, its widest line, measured as [`colorbar_title_lines`] breaks -/// it. -pub fn colorbar_title_width_mm(title: &str) -> f64 { - let px = (COLORBAR_TITLE_PT * 1.33 * WRAP_PX_PER_MM / PT_PER_MM) as f32; - let face = colorbar_title_style().face; - title.lines().map(|line| f64::from(text::styled_extent(line, px, face, 0.0).1)).fold(0.0, f64::max) / WRAP_PX_PER_MM -} - -/// The slack a colorbar's title gets on its width, in mm: a box made exactly as wide as the title -/// still takes it on one line once its width is rounded, or laid out in whole pixels. -const COLORBAR_TITLE_SLACK_MM: f64 = 0.01; - -/// A colorbar's title as the lines it is drawn in (#2493): broken at spaces to fit `width` mm, a -/// word wider than that across lines, as a wrapped text is ([`wrapped`]), at one resolution -/// whatever it is drawn at, so the page, each export and a publication's sizing break it alike. A -/// title of one line that fits is that line, as it is. Past 200 lines, one more line with text -/// says it goes on, as for a wrapped text. -pub fn colorbar_title_lines(title: &str, width: f64) -> Vec { - let width = width + COLORBAR_TITLE_SLACK_MM; - if !title.contains('\n') && colorbar_title_width_mm(title) <= width { - return vec![title.to_string()]; - } - wrapped(title, width, COLORBAR_TITLE_PT, colorbar_title_style()).lines().map(str::to_string).collect() -} - -/// How many of a colorbar's `lines` of title it draws in an element from `top` (pixels), its -/// title at `px` pixels (#2493): each line only when the room it takes ends by `limit`, the -/// element's bottom less the bar's own room ([`colorbar_bar_room`]), the first too, so the bar -/// always keeps its labels (#2638); at most 200. The page's cut-off check ([`text_losses`]) -/// counts the lines left out the same way, so a colorbar too short for its title says so. -fn colorbar_title_drawn(lines: usize, top: f32, limit: f32, px: f32) -> usize { - (0..lines.min(200)).take_while(|i| top + px * (1.4 + 1.25 * *i as f32) <= limit).count() -} - -/// The least room a colorbar's bar takes under its title, in pixels at `ppp` (#2638), as -/// [`colorbar`] lays it out: a horizontal bar 3 pixels thick (at 96 dpi) with its ticks and -/// 8-point labels under it; a vertical one, whose labels are at its side, two labels' height, so -/// its end labels, centred on the bar's ends, stay inside the element. A title stops short of it, -/// so its lines never leave the bar without its labels. -fn colorbar_bar_room(ppp: f32, orientation: Orientation) -> f32 { - match orientation { - Orientation::Horizontal => (8.0 * 1.33 * 1.2 + 2.5 + 1.5 + 3.0) * ppp, - Orientation::Vertical => 2.0 * 8.0 * 1.33 * ppp, - } -} - -/// The usual line spacing ([`rustgis_map::layout::LINE_SPACING`]) as the drawing holds it. -const USUAL_LINE_SPACING: f32 = rustgis_map::layout::LINE_SPACING as f32; - -/// The distance between two lines of text at `size` points, in mm, at the usual line spacing (1), -/// as [`text_block`] sets them there; a text's line spacing multiplies it. -pub fn line_pitch_mm(size: f64) -> f64 { - size.clamp(2.0, 400.0) * 1.33 * 1.25 * 25.4 / 96.0 -} - -/// The part of a text element's box (pixels, from its top-left corner) [`text_block`] inks, a line's -/// height more each way: across, its lines as each is aligned (past the box where one overruns -/// it); down, its lines from where its block starts ([`block_shift`]), or the box and the line -/// [`text_block`] still draws past it. `None` when it has no line. -fn text_area(r: Rect, s: &str, size: f32, style: TextStyle, ppp: f64) -> Option { - let px = size.clamp(2.0, 400.0) * 1.33 * ppp as f32; - let spacing = style.spacing * 1.33 * ppp as f32; - let w = r.width(); - let (mut x0, mut x1, mut lines) = (f32::INFINITY, f32::NEG_INFINITY, 0u16); - for line in s.lines().take(200) { - let (lo, hi) = text::styled_extent(line, px, style.face, spacing); - // Where `text_block` puts the ink: from the edge (left), or by the ink (centre, right). - let (a, b) = match style.align { - TextAlign::Left => (lo, hi), - TextAlign::Center => ((w - (hi - lo)) / 2.0, (w + (hi - lo)) / 2.0), - TextAlign::Right => (w - (hi - lo), w), - }; - (x0, x1, lines) = (x0.min(a), x1.max(b), lines + 1); - } - // Down to its last line, where its block alignment and line spacing put it. - let shift = text_shift(style.valign, f64::from(r.height()), f64::from(px), s, f64::from(style.line_spacing)) as f32; - let block = (1.0 + (f32::from(lines) - 1.0) * style.line_spacing) * px * 1.25; - let down = (r.height() + px).min(shift + block); - (lines > 0).then(|| Rect::from_ltrb(x0 - px, shift - px, x1 + px, down + px)).flatten() -} - -/// Draws with `draw` (given the box to draw in and how many of the page's pixels one of its own -/// is) turned `degrees` clockwise about the centre of `r`: kept turned on a recording canvas (a -/// vector PDF), else drawn upright in a picture of `area` (pixels from the box's top-left corner: -/// what it inks), which is placed turned. A picture past the page's budget is drawn at a lower -/// resolution and scaled up, as a frame that large is. Its size is at least a pixel and at most -/// the budget, and `r` and `area` have a size, so the picture is always made. -/// -/// A quarter turn at full resolution maps the picture's pixels one for one onto the page's: it is -/// placed on whole pixels and not filtered, the part of a pixel that moved it drawn into the -/// picture instead, so its text is sampled once, as upright text is, and keeps as sharp. Another -/// turn is sampled once more, by the turn. -fn draw_turned_box(pm: &mut Canvas, r: Rect, degrees: f32, area: Rect, draw: impl FnOnce(&mut Canvas, Rect, f64)) { - let (cx, cy) = (r.x() + r.width() / 2.0, r.y() + r.height() / 2.0); - if pm.is_recording() { - pm.with_transform(Transform::from_rotate_at(degrees, cx, cy), |c| draw(c, r, 1.0)); - return; - } - let (w, h) = (f64::from(area.width()), f64::from(area.height())); - let k = (MAX_PIXELS / (w * h)).sqrt().min(MAX_SIDE / w.max(h)).min(1.0) as f32; - let (pw, ph) = ((w as f32 * k).ceil().max(1.0), (h as f32 * k).ceil().max(1.0)); - let mut place = - Transform::from_scale(1.0 / k, 1.0 / k).post_translate(r.x() + area.x(), r.y() + area.y()).post_rotate_at(degrees, cx, cy); - let quarter = k == 1.0 && degrees.rem_euclid(90.0) == 0.0; - let (mut dx, mut dy) = (0.0, 0.0); - if quarter { - // Its turn exactly (0 or ±1 each way), and its corner on a whole pixel: the picture's - // content moves back by as much, turned back (the turn's inverse is its transpose). - let [sx, ky, kx, sy] = [place.sx, place.ky, place.kx, place.sy].map(f32::round); - let (ex, ey) = (place.tx.round() - place.tx, place.ty.round() - place.ty); - (dx, dy) = (-(sx * ex + ky * ey), -(kx * ex + sy * ey)); - place = Transform::from_row(sx, ky, kx, sy, place.tx.round(), place.ty.round()); - } - // The box in the picture: its corner `area`'s offset away from the picture's (and less than a - // pixel more, within the room `area` leaves round the ink). - let inner = Rect::from_xywh(-area.x() * k + dx, -area.y() * k + dy, r.width() * k, r.height() * k); - let (Some(mut pic), Some(inner)) = (Canvas::new(pw as u32, ph as u32), inner) else { return }; - draw(&mut pic, inner, f64::from(k)); - let quality = if quarter { tiny_skia::FilterQuality::Nearest } else { tiny_skia::FilterQuality::Bilinear }; - let paint = PixmapPaint { quality, ..PixmapPaint::default() }; - pm.draw_pixmap(0, 0, pic.pixmap().as_ref(), &paint, place, None); -} - -/// Text in an element: lines split at `\n`, the block of them at the top, middle or bottom of the -/// box ([`block_shift`]) and spaced by the style's line spacing, each placed by the style's -/// alignment. A block taller than its box starts at its top whatever its alignment, so its first -/// lines are drawn and the ones past the box left out ([`text_losses`] counts them). A centred or -/// right-aligned line wider than the element runs out past its left edge, as a left-aligned one -/// runs past its right. -fn text_block(pm: &mut Canvas, r: Rect, s: &str, size: f32, color: Rgba, style: TextStyle, ppp: f64) { - let px = size.clamp(2.0, 400.0) * 1.33 * ppp as f32; - // Letter spacing is in points, as the size is. - let spacing = style.spacing * 1.33 * ppp as f32; - let shift = text_shift(style.valign, f64::from(r.height()), f64::from(px), s, f64::from(style.line_spacing)) as f32; - let mut y = r.y() + shift + px * 0.6; - for line in s.lines().take(200) { - if y > r.y() + r.height() + px { - break; - } - // Centred and right-aligned lines are placed by the ink they draw (italic overhang and a - // negative spacing included), which an advance doesn't measure; left-aligned ones start - // at the edge as plain text always has. - let left = match style.align { - TextAlign::Left => r.x(), - aligned => { - let (ink_left, ink_right) = text::styled_extent(line, px, style.face, spacing); - let free = r.width() - (ink_right - ink_left); - r.x() + if aligned == TextAlign::Center { free / 2.0 } else { free } - ink_left - } - }; - text::styled_at(pm, line, left, y, px, color, style.face, spacing); - y += px * 1.25 * style.line_spacing; - } -} - -/// The first `rows` rows of a table, with as many columns as fit: on white cells in dark grey, or -/// with an `ink` (#2257) in it on no paper of its own, its header and stripes a tint of the ink, so -/// it reads on whatever is behind it (a dark page, or the element's background). -fn table(pm: &mut Canvas, r: Rect, ds: &rustgis_data::Dataset, rows: usize, ink: Option, ppp: f64) { - let ppp = ppp as f32; - let px = 8.0 * 1.33 * ppp; - let row_h = px * 1.6; - let col_w = (90.0 * ppp).min(r.width()); - let cols = ((r.width() / col_w).floor() as usize).clamp(1, ds.fields.len().max(1)); - let n = rows.min(ds.features.len()).min(((r.height() / row_h) as usize).saturating_sub(1)); - let dark = ink.unwrap_or(INK); - // Without an ink, the white paper, header and stripes it always had, so a table drawn before - // draws to the same pixels. With one, white cells could hide a light ink. - let ((header, header_alpha), (stripe, stripe_alpha)) = match ink { - None => ((Rgba::rgb(0xE4, 0xE8, 0xEE), 1.0), (Rgba::rgb(0xF5, 0xF6, 0xF8), 1.0)), - Some(c) => ((c, 0.18), (c, 0.08)), - }; - if ink.is_none() - && let Some(bg) = Rect::from_xywh(r.x(), r.y(), col_w * cols as f32, row_h * (n + 1) as f32) - { - pm.fill_rect(bg, &paint(Rgba::rgb(0xFF, 0xFF, 0xFF), 1.0), Transform::identity(), None); - } - if let Some(hdr) = Rect::from_xywh(r.x(), r.y(), col_w * cols as f32, row_h) { - pm.fill_rect(hdr, &paint(header, header_alpha), Transform::identity(), None); - } - let fit = |s: &str| -> String { - let mut t: String = s.chars().take(40).collect(); - while !t.is_empty() && text::measure(&t, 8.0, false) * ppp > col_w - 6.0 * ppp { - t.pop(); - } - t - }; - for (c, f) in ds.fields.iter().take(cols).enumerate() { - text::text_at( - pm, - &fit(f.display()), - r.x() + c as f32 * col_w + 3.0 * ppp, - r.y() + row_h / 2.0, - px, - dark, - true, - text::Align::Left, - false, - ); - } - for row in 0..n { - let y = r.y() + row_h * (row + 1) as f32; - if row % 2 == 1 - && let Some(b) = Rect::from_xywh(r.x(), y, col_w * cols as f32, row_h) - { - pm.fill_rect(b, &paint(stripe, stripe_alpha), Transform::identity(), None); - } - for c in 0..cols { - text::text_at( - pm, - &fit(&ds.value(row, c).to_string()), - r.x() + c as f32 * col_w + 3.0 * ppp, - y + row_h / 2.0, - px, - dark, - false, - text::Align::Left, - false, - ); - } - } -} - -/// A bar chart of `data`'s bars ([`ElementKind::chart_data`]) drawn as `look` says, its title, -/// labels and values in `dark`, its values with a decimal comma when `comma`. With a negative -/// value, bars run either way from a zero line (#2487). Stacked, each bar is drawn as its -/// stretches in the colours of the key under the title, those above zero from it on and those -/// below from it back, its value past the end of the side it ends on. -fn chart(pm: &mut Canvas, r: Rect, data: &rustgis_map::layout::ChartData, look: &ChartLook, dark: Rgba, ppp: f64, comma: bool) { - let ppp = ppp as f32; - let vals = &data.bars; - let (min, reach) = chart_span(data); - // A fixed maximum is the far end of the bars' room, whatever they reach (#2487 part 4). - let max = look.max.unwrap_or(reach); - if vals.is_empty() || (reach <= 0.0 && min >= 0.0) { - placeholder(pm, r, "Chart", ppp as f64); - return; - } - let px = 7.5 * 1.33 * ppp; - let Some((title_h, key_h)) = chart_head(r, data, look, px, ppp) else { - placeholder(pm, r, "Chart", ppp as f64); - return; - }; - if !data.title.is_empty() { - text::text_at(pm, &data.title, r.x(), r.y() + title_h / 2.0, px * 1.15, dark, true, text::Align::Left, false); - } - chart_key(Some(pm), r, r.y() + title_h, &data.key, px, ppp, dark); - // Each bar's value as written past its end, when it has them. - let values: Vec = if look.values { - vals.iter().map(|(v, _)| decimal(rustgis_map::layout::chart_value_text(*v, look.decimals), comma)).collect() - } else { - Vec::new() - }; - let bars = ChartBars { - r, - title_h: title_h + key_h, - vals, - values: &values, - colors: &data.colors, - stretches: &data.stretches, - key: &data.key, - min, - max, - px, - ppp, - dark, - look, - }; - let labelled = data.labelled && !look.hide_labels; - match look.orientation { - Orientation::Horizontal => bars.across(pm, labelled), - Orientation::Vertical => bars.columns(pm, labelled), - } -} - -/// The span a chart's bars run over: from the most a bar reaches below zero to the most above, -/// stacked its stretches below zero added up and those above. -pub fn chart_span(data: &rustgis_map::layout::ChartData) -> (f64, f64) { - data.bars - .iter() - .enumerate() - .map(|(i, (v, _))| data.stretches.get(i).filter(|s| !s.is_empty()).map_or_else(|| reach(&[*v]), |s| reach(s))) - .fold((0.0_f64, 0.0_f64), |(lo, hi), (l, h)| (lo.min(l), hi.max(h))) -} - -/// The heights of a chart's title and key over its bars in `r`, its text `px` high: no title -/// leaves its room to the bars. Stacked, a box too short to leave the bars a line under its title -/// and key has none (it draws its placeholder rather than a key past its bottom and bars with no -/// room); as columns, the bars' line is past the room their labels and values may take (written -/// at most `px` high, [`ChartBars::columns`]), so they always have it. Not stacked, it draws as -/// before. -fn chart_head(r: Rect, data: &rustgis_map::layout::ChartData, look: &ChartLook, px: f32, ppp: f32) -> Option<(f32, f32)> { - let title_h = if data.title.is_empty() { 0.0 } else { px * 1.6 }; - let key_h = chart_key(None, r, 0.0, &data.key, px, ppp, INK); - let line = px * 1.4; - let below = match look.orientation { - Orientation::Horizontal => 0.0, - Orientation::Vertical => { - let (min, max) = chart_span(data); - let values = |on: bool| if look.values && on { line } else { 0.0 }; - (if data.labelled && !look.hide_labels { line } else { 0.0 }) + values(max > 0.0) + values(min < 0.0) - } - }; - (data.key.is_empty() || title_h + key_h + line + below <= r.height()).then_some((title_h, key_h)) -} - -/// Whether a chart with bars to draw, `w` × `h` mm in its look, draws its placeholder instead as -/// its title and key leave the bars no room ([`chart_head`]): what the commands warn of, so the page and the commands -/// never tell it apart. -pub fn chart_crowded(data: &rustgis_map::layout::ChartData, look: &ChartLook, w: f64, h: f64) -> bool { - let Some(r) = Rect::from_xywh(0.0, 0.0, (w * PT_PER_MM).max(1.0) as f32, (h * PT_PER_MM).max(1.0) as f32) else { return false }; - !data.bars.is_empty() && chart_head(r, data, look, 7.5 * 1.33, 1.0).is_none() -} - -/// How far a bar's stretches reach below zero (its negative ones added up) and above it. -fn reach(stretches: &[f64]) -> (f64, f64) { - stretches.iter().fold((0.0, 0.0), |(lo, hi), v| if *v < 0.0 { (lo + v, hi) } else { (lo, hi + v) }) -} - -/// A stacked chart's key from `top`: a swatch in each value's colour and its name, in rows as -/// wide as the box, a name cut to fit one; the height it takes, 0 without a key, infinite in a -/// box narrower than a swatch. Without a canvas it only measures. -fn chart_key(mut pm: Option<&mut Canvas>, r: Rect, top: f32, key: &[(String, Rgba)], px: f32, ppp: f32, dark: Rgba) -> f32 { - if key.is_empty() { - return 0.0; - } - let size = px * 0.9; - let line_h = px * 1.4; - let (sw, gap) = (size * 0.8, 2.0 * ppp); - // A box narrower than a swatch has no room for the key at all. - if r.width() < sw + gap { - return f32::INFINITY; - } - let (mut x, mut y) = (r.x(), top); - for (name, colour) in key { - let t = fit_label(name, |t| sw + gap + text::measure(t, size / 1.33, false) > r.width()); - let w = sw + gap + text::measure(&t, size / 1.33, false); - // A name that doesn't fit after the others starts a row of its own. - if x > r.x() && x + w > r.right() { - (x, y) = (r.x(), y + line_h); - } - if let Some(pm) = pm.as_deref_mut() { - fill(pm, *colour, x, y + (line_h - sw) / 2.0, sw, sw); - text::text_at(pm, &t, x + sw + gap, y + line_h / 2.0, size, dark, false, text::Align::Left, false); - } - x += w + 3.0 * gap; - } - y + line_h - top -} - -/// `name`'s first 30 characters, cut from their end while `too_wide` says they don't fit. -fn fit_label(name: &str, too_wide: impl Fn(&str) -> bool) -> String { - let mut t: String = name.chars().take(30).collect(); - while !t.is_empty() && too_wide(&t) { - t.pop(); - } - t -} - -/// What [`chart`] draws its bars from: its box, the height of its title (and key) over the bars, -/// the bars and their values written out (none without), each bar's own colour (none: the look's -/// bar colour), stacked each bar's stretches and the key that colours them, the least a bar -/// reaches and the value at the far end of the bars' room (the greatest a bar reaches, or a fixed -/// maximum in its place; 0 among them), its text size and pixels per point. -struct ChartBars<'a> { - r: Rect, - title_h: f32, - vals: &'a [(f64, String)], - values: &'a [String], - colors: &'a [Option], - stretches: &'a [Vec], - key: &'a [(String, Rgba)], - min: f64, - max: f64, - px: f32, - ppp: f32, - dark: Rgba, - look: &'a ChartLook, -} - -impl ChartBars<'_> { - /// Bar `i` (of value `v`) as the stretches it is drawn in, each with the share of the span - /// ([`ChartBars::share`]) where it starts from zero, its own share (negative running back) and - /// its colour. A whole bar (none stacked, or no stretches) is one stretch, in its own colour or - /// the look's; a stacked one a stretch per value of the key, those above zero on from it and - /// those below back from it, one of 0 not drawn. - fn stretches(&self, i: usize, v: f64) -> Vec<(f32, f32, Rgba)> { - let Some(s) = self.stretches.get(i).filter(|s| !s.is_empty()) else { - return vec![(0.0, self.share(v.min(self.max)), self.colors.get(i).copied().flatten().unwrap_or(self.look.bar_color))]; - }; - let (mut lo, mut hi) = (0.0_f64, 0.0_f64); - // Past a fixed maximum a stretch above zero is cut at it, and one wholly past it isn't - // drawn; one running back from zero is drawn whole. - s.iter() - .zip(self.key) - .filter(|(v, _)| **v != 0.0) - .filter_map(|(v, (_, c))| { - let end = if *v < 0.0 { &mut lo } else { &mut hi }; - let from = *end; - *end += v; - if *v < 0.0 { - return Some((self.share(from), self.share(*v), *c)); - } - let len = (from + v).min(self.max) - from; - (len > 0.0).then(|| (self.share(from), self.share(len), *c)) - }) - .collect() - } - - /// What part `v` is of the span from the lowest value (or zero) to the highest (or zero). A span - /// past a number's range (the largest number and its opposite) is taken by halves. - fn share(&self, v: f64) -> f32 { - let span = self.max - self.min; - (if span.is_finite() { v / span } else { (v / 2.0) / (self.max / 2.0 - self.min / 2.0) }) as f32 - } - - /// The widest of the values written at `size` pixels past the bars running one way: - /// positive ones, or negative ones (`negative`); 0 without values. - fn widest(&self, size: f32, negative: bool) -> f32 { - self.vals - .iter() - .zip(self.values) - .filter(|((v, _), _)| (*v < 0.0) == negative) - .map(|(_, t)| text::measure(t, size / 1.33, false)) - .fold(0.0, f32::max) - } - - /// Bars running across, labels in a column at their left, each value past its bar's end with - /// room kept for it at the side its bar runs to. - fn across(&self, pm: &mut Canvas, labelled: bool) { - let (r, ppp, px) = (self.r, self.ppp, self.px); - let label_w = if labelled { r.width() * 0.32 } else { 0.0 }; - let bh = ((r.height() - self.title_h) / self.vals.len() as f32).min(18.0 * ppp); - let size = px.min(bh * 0.9); - let gap = 2.0 * ppp; - let room = |negative: bool, size: f32| { - let w = self.widest(size, negative); - if w > 0.0 { w + gap } else { 0.0 } - }; - // Values take at most half the width beside the labels, written smaller past that. - let beside = r.width() - label_w - 4.0; - let mut value_size = size; - let (mut room_lo, mut room_hi) = (room(true, size), room(false, size)); - if room_lo + room_hi > beside * 0.5 { - // Only the text grows smaller: the gaps beside it stay as they are. - let gaps = [room_lo, room_hi].iter().filter(|w| **w > 0.0).count() as f32 * gap; - let text = room_lo + room_hi - gaps; - value_size = (size * (beside * 0.5 - gaps) / text).max(0.0); - (room_lo, room_hi) = (room(true, value_size), room(false, value_size)); - } - let bar_area = beside - room_lo - room_hi; - // Where the bars start: the left of the bar area when none is negative. - let zero = r.x() + label_w + room_lo + bar_area * self.share(-self.min); - let right = self.look.label_align == TextAlign::Right; - // Laid out the usual way, then placed as its mirror image when mirrored: a box from `x`, - // `w` wide, and a text written from `x`, the text itself reading as ever. - let edges = r.x() + r.right(); - let place = |x: f32, w: f32| if self.look.mirror { edges - x - w } else { x }; - let write = |x: f32, align: text::Align| if self.look.mirror { (edges - x, mirrored(align)) } else { (x, align) }; - for (i, (v, name)) in self.vals.iter().enumerate() { - let y = r.y() + self.title_h + bh * i as f32; - // Each stretch at least a pixel wide, running back from its start below zero; where the - // bar ends at its left and at its right. - let (mut left, mut right_end) = (zero, zero); - let mut drawn = Vec::new(); - for (start, share, colour) in self.stretches(i, *v) { - let w = (bar_area * share.abs()).max(1.0); - let x = zero + bar_area * start - if share < 0.0 { w } else { 0.0 }; - drawn.push((place(x, w), w, colour)); - (left, right_end) = (left.min(x), right_end.max(x + w)); - } - self.bar(pm, &drawn, (y + bh * 0.15, bh * 0.7), true); - if labelled { - let t = fit_label(name, |t| text::measure(t, 7.5, false) * ppp > label_w - 4.0 * ppp); - // At the column's right, the label ends where the bars' side begins. - let (lx, align) = if right { (r.x() + label_w - 2.0 * ppp, text::Align::Right) } else { (r.x(), text::Align::Left) }; - let (lx, align) = write(lx, align); - text::text_at(pm, &t, lx, y + bh / 2.0, size, self.dark, false, align, false); - } - if let Some(t) = self.values.get(i) { - let (vx, align) = if *v < 0.0 { (left - gap, text::Align::Right) } else { (right_end + gap, text::Align::Left) }; - let (vx, align) = write(vx, align); - text::text_at(pm, t, vx, y + bh / 2.0, value_size, self.dark, false, align, false); - } - } - if self.min < 0.0 - && let Some(line) = - Rect::from_xywh(place(zero - 0.375 * ppp, 0.75 * ppp), r.y() + self.title_h, 0.75 * ppp, bh * self.vals.len() as f32) - { - pm.fill_rect(line, &paint(self.dark, 1.0), Transform::identity(), None); - } - } - - /// Columns standing on a zero line, each label centred under its column and cut to its width, - /// each value over a column (under one going down), made smaller to fit a narrow column. - fn columns(&self, pm: &mut Canvas, labelled: bool) { - let (r, ppp, px) = (self.r, self.ppp, self.px); - let slot = r.width() / self.vals.len() as f32; - let widest = self.widest(px, false).max(self.widest(px, true)); - let value_px = if widest > slot * 0.95 { px * slot * 0.95 / widest } else { px }; - let value_h = value_px * 1.4; - let room_hi = if self.max > 0.0 && !self.values.is_empty() { value_h } else { 0.0 }; - let room_lo = if self.min < 0.0 && !self.values.is_empty() { value_h } else { 0.0 }; - let label_h = if labelled { px * 1.4 } else { 0.0 }; - let top = r.y() + self.title_h + room_hi; - let plot_h = r.bottom() - label_h - room_lo - top; - if plot_h <= 0.0 { - placeholder(pm, r, "Chart", ppp as f64); - return; - } - // Where the columns stand: the bottom of the plot when none is negative. - let zero = top + plot_h * self.share(self.max); - // Laid out the usual way under its title, then placed upside down there when mirrored: a box - // from `y`, `h` high, and a text centred on `y`, the text itself reading as ever. - let edges = r.y() + self.title_h + r.bottom(); - let place = |y: f32, h: f32| if self.look.mirror { edges - y - h } else { y }; - let write = |y: f32| if self.look.mirror { edges - y } else { y }; - for (i, (v, name)) in self.vals.iter().enumerate() { - let cx = r.x() + slot * (i as f32 + 0.5); - // Each stretch at least a pixel high, standing up from its start above zero and hanging - // down below it; where the column ends at its top and at its bottom. - let (mut top_end, mut bottom) = (zero, zero); - let mut drawn = Vec::new(); - for (start, share, colour) in self.stretches(i, *v) { - let h = (plot_h * share.abs()).max(1.0); - let y = zero - plot_h * start - if share < 0.0 { 0.0 } else { h }; - drawn.push((place(y, h), h, colour)); - (top_end, bottom) = (top_end.min(y), bottom.max(y + h)); - } - self.bar(pm, &drawn, (cx - slot * 0.35, slot * 0.7), false); - if let Some(t) = self.values.get(i) { - let vy = if *v < 0.0 { bottom + value_h / 2.0 } else { top_end - value_h / 2.0 }; - text::text_at(pm, t, cx, write(vy), value_px, self.dark, false, text::Align::Center, false); - } - if labelled { - let t = fit_label(name, |t| text::measure(t, px / 1.33, false) > slot - 2.0 * ppp); - text::text_at(pm, &t, cx, write(r.bottom() - label_h / 2.0), px, self.dark, false, text::Align::Center, false); - } - } - if self.min < 0.0 - && let Some(line) = Rect::from_xywh(r.x(), place(zero - 0.375 * ppp, 0.75 * ppp), r.width(), 0.75 * ppp) - { - pm.fill_rect(line, &paint(self.dark, 1.0), Transform::identity(), None); - } - } -} - -/// A text's alignment in a chart's mirror image: from the right where it was from the left. -fn mirrored(align: text::Align) -> text::Align { - match align { - text::Align::Left => text::Align::Right, - text::Align::Right => text::Align::Left, - other => other, - } -} - -impl ChartBars<'_> { - /// A bar, filled stretch by stretch, with the look's outline round it (#2487 part 4b). Each - /// stretch is its start and length along the bar and its colour; `cross` is where the bar - /// starts across its run and how thick it is, and `across` says it runs across (else down). - /// The line runs just inside the bar's edge, so it takes no room the bars leave to their - /// values, labels and title, and is laid once between two stretches, centred where they meet, - /// so a see-through one reads the same everywhere. So that every stretch keeps its colour, the - /// edge's line narrows to a third of the bar's thickness, across each end to a third of the - /// stretch there too, and each line between two stretches to a third of either, kept within - /// the edge's line. - fn bar(&self, pm: &mut Canvas, stretches: &[(f32, f32, Rgba)], cross: (f32, f32), across: bool) { - // A box from where it starts and how long it is along the run, and across it. - let rect = |along: f32, run: f32, across_at: f32, thick: f32| { - if across { (along, across_at, run, thick) } else { (across_at, along, thick, run) } - }; - for (at, len, colour) in stretches { - let (x, y, w, h) = rect(*at, *len, cross.0, cross.1); - fill(pm, *colour, x, y, w, h); - } - let Some(o) = self.look.bar_outline else { return }; - let mut order: Vec<_> = stretches.iter().map(|(at, len, _)| (*at, *len)).collect(); - order.sort_by(|a, b| a.0.total_cmp(&b.0)); - let (Some(first), Some(last)) = (order.first(), order.last()) else { return }; - let (lo, hi) = (first.0, last.0 + last.1); - let line = (o.width as f32 * self.ppp).min(cross.1 / 3.0); - if line <= 0.0 { - return; - } - // Across the ends, narrowed only there by the stretch it would cover. - let (start, end) = (line.min(first.1 / 3.0), line.min(last.1 / 3.0)); - // The whole line, round the bar and between its stretches, is one shape filled once: boxes - // filled each on its own would cover a pixel they share in part twice over, leaving a - // lighter seam where they meet and a darker spot where they overlap. Boxes, not a stroke: - // a stroke thinner than a pixel is drawn a pixel wide, past the bar's end. - let mut shape = PathBuilder::new(); - let mut boxed = |(x, y, w, h): (f32, f32, f32, f32)| { - if let Some(b) = Rect::from_xywh(x, y, w, h) { - shape.push_rect(b); - } - }; - boxed(rect(lo, hi - lo, cross.0, line)); - boxed(rect(lo, hi - lo, cross.0 + cross.1 - line, line)); - boxed(rect(lo, start, cross.0 + line, cross.1 - 2.0 * line)); - boxed(rect(hi - end, end, cross.0 + line, cross.1 - 2.0 * line)); - // Between two stretches, inside the edge's line, and kept there along the bar too: a - // stretch drawn a pixel long though its share is shorter has the next start inside it, - // near the bar's end. - for pair in order.windows(2) { - let &[(_, a), (at, b)] = pair else { continue }; - let d = line.min(a / 3.0).min(b / 3.0); - let (from, to) = ((at - d / 2.0).max(lo + start), (at + d / 2.0).min(hi - end)); - boxed(rect(from, to - from, cross.0 + line, cross.1 - 2.0 * line)); - } - if let Some(shape) = shape.finish() { - pm.fill_path(&shape, &paint(o.color, 1.0), FillRule::Winding, Transform::identity(), None); - } - } -} - -/// A box filled with `colour`; none where it has no size. -fn fill(pm: &mut Canvas, colour: Rgba, x: f32, y: f32, w: f32, h: f32) { - if let Some(b) = Rect::from_xywh(x, y, w, h) { - pm.fill_rect(b, &paint(colour, 1.0), Transform::identity(), None); - } -} - -/// The first case-insensitive frame-map name match; a missing reference renders no map. -pub fn map_index(maps: &[rustgis_map::Map], name: &str) -> Option { - maps.iter().position(|map| map.name.eq_ignore_ascii_case(name)) -} - -/// Pages of one text each with none of the block settings, in the combinations main draws: each -/// alignment, wrapped or not, turned 0, 90, -90 or 33 degrees, spaced 0 or 3 points (bold, and -/// italic when turned 33), in a box that holds its lines and one that cuts them; and two texts -/// across the page's right and bottom edges. -#[cfg(all(test, not(target_arch = "wasm32")))] -pub(crate) fn plain_text_pages() -> Vec { - let text = "Population counts\nfrom the 2020 census; boundaries simplified for print\nPage {page} of {pages}"; - let page = |at: (f64, f64, f64, f64), f: &dyn Fn(&mut ElementKind)| { - let mut l = Layout::new("Plain", 120.0, 80.0); - let mut kind = ElementKind::text(text, 11.0, Rgba::rgb(0, 0, 0), false); - f(&mut kind); - l.add("Note", at, kind); - l - }; - let mut pages = Vec::new(); - for align in TextAlign::ALL { - for wrap in [false, true] { - for turn in [0.0, 90.0, -90.0, 33.0] { - for spacing in [0.0, 3.0] { - for h in [40.0, 9.0] { - pages.push(page((10.0, 10.0, 60.0, h), &|k| { - if let ElementKind::Text { align: a, wrap: w, rotation, letter_spacing, italic, bold, .. } = k { - (*a, *w, *rotation, *letter_spacing) = (align, wrap, turn, spacing); - (*italic, *bold) = (turn == 33.0, spacing > 0.0); - } - })); - } - } - } - } - } - pages.push(page((90.0, 10.0, 60.0, 30.0), &|_| {})); - pages.push(page((10.0, 74.0, 60.0, 30.0), &|_| {})); - pages -} - -#[expect(clippy::disallowed_methods, reason = "a thread the system refuses fails the test, as it should")] -#[cfg(test)] -mod tests { - use super::*; - - /// A chart element of layer "t" on frame 1, with `extra` keys (its field among them). - fn chart_kind(extra: serde_json::Value) -> ElementKind { - let mut chart = serde_json::json!({"frame": 1, "layer": "t"}); - if let (Some(c), Some(e)) = (chart.as_object_mut(), extra.as_object()) { - c.extend(e.clone()); - } - serde_json::from_value(serde_json::json!({ "Chart": chart })).unwrap() - } - - /// The chart as it was drawn before charts were grouped, ordered or cut by choice, kept to - /// show a chart saved then still draws to the same pixels. - fn chart_before(pm: &mut Canvas, r: Rect, ds: &rustgis_data::Dataset, field: &str, label: Option<&str>, dark: Rgba, ppp: f64) { - let ppp = ppp as f32; - let Some(fi) = ds.field_index(field) else { - placeholder(pm, r, "Chart", ppp as f64); - return; - }; - let li = label.and_then(|l| ds.field_index(l)); - let mut vals: Vec<(f64, String)> = (0..ds.features.len()) - .filter_map(|row| { - ds.value(row, fi) - .as_f64() - .filter(|v| v.is_finite()) - .map(|v| (v, li.map(|i| ds.value(row, i).to_string()).unwrap_or_default())) - }) - .collect(); - vals.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)); - vals.truncate(20); - let max = vals.iter().map(|v| v.0).fold(0.0_f64, f64::max); - if vals.is_empty() || max <= 0.0 { - placeholder(pm, r, "Chart", ppp as f64); - return; - } - let px = 7.5 * 1.33 * ppp; - let title_h = px * 1.6; - text::text_at(pm, field, r.x(), r.y() + title_h / 2.0, px * 1.15, dark, true, text::Align::Left, false); - let label_w = if li.is_some() { r.width() * 0.32 } else { 0.0 }; - let bar_area = r.width() - label_w - 4.0; - let bh = ((r.height() - title_h) / vals.len() as f32).min(18.0 * ppp); - for (i, (v, name)) in vals.iter().enumerate() { - let y = r.y() + title_h + bh * i as f32; - let w = (bar_area * (*v / max) as f32).max(1.0); - if let Some(b) = Rect::from_xywh(r.x() + label_w, y + bh * 0.15, w, bh * 0.7) { - pm.fill_rect(b, &paint(Rgba::rgb(0x3B, 0x82, 0xC4), 1.0), Transform::identity(), None); - } - if li.is_some() { - let mut t: String = name.chars().take(30).collect(); - while !t.is_empty() && text::measure(&t, 7.5, false) * ppp > label_w - 4.0 * ppp { - t.pop(); - } - text::text_at(pm, &t, r.x(), y + bh / 2.0, px.min(bh * 0.9), dark, false, text::Align::Left, false); - } - } - } - - /// A chart saved before grouping, order and limits draws to the same pixels: with labels or - /// without, past 20 features, with rows with no number, a missing label field, all zero. - #[test] - fn a_chart_saved_before_draws_to_the_same_pixels() { - use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; - let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new("name", FieldType::Text), Field::new("n", FieldType::Double)]); - for i in 0..27 { - let n = match i { - 3 => Value::Null, - 5 => Value::Float(f64::NAN), - _ => Value::Float(((i * 37) % 23) as f64 + 0.5), - }; - ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text(format!("Place {i}")), n]); - } - let mut zeros = Dataset::new("t", GeometryType::Point, vec![Field::new("n", FieldType::Double)]); - zeros.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Float(0.0)]); - let r = Rect::from_xywh(7.0, 5.0, 230.0, 170.0).unwrap(); - for (ds, label, ppp) in [(&ds, Some("name"), 1.0), (&ds, None, 2.0), (&ds, Some("gone"), 1.5), (&zeros, None, 1.0)] { - let draw = |f: &dyn Fn(&mut Canvas)| { - let mut c = Canvas::new(480, 360).unwrap(); - f(&mut c); - c - }; - let before = draw(&|c| chart_before(c, r, ds, "n", label, INK, ppp)); - let kind = chart_kind(serde_json::json!({"field": "n", "label": label})); - let now = draw(&|c| match kind.chart_data(ds) { - Some(data) => chart(c, r, &data, &ChartLook::default(), INK, ppp, false), - None => placeholder(c, r, "Chart", ppp), - }); - assert!(before.pixmap().data() == now.pixmap().data(), "{label:?} at {ppp}"); - } - } - - /// A negative value runs left of a zero line in the ink; a positive one right of it. - #[test] - fn a_chart_with_a_negative_value_draws_from_a_zero_line() { - use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; - let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new("n", FieldType::Double)]); - for n in [3.0, -1.0] { - ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Float(n)]); - } - let data = chart_kind(serde_json::json!({"field": "n"})).chart_data(&ds).unwrap(); - let mut c = Canvas::new(200, 120).unwrap(); - let r = Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(); - chart(&mut c, r, &data, &ChartLook::default(), INK, 1.0, false); - // Bar area 196 px over a span of 4: zero at 49 px. Rows of 18 px under a 16 px title, - // their bars from 18.7 to 30.6 px and from 36.7 to 48.6 px down. - assert!(bar_blue(&c, 150, 25) && !bar_blue(&c, 30, 25), "3 runs right of zero"); - assert!(bar_blue(&c, 30, 43) && !bar_blue(&c, 70, 43), "-1 runs left of zero"); - // Between the bars, the zero line (0.75 px wide, so partly covering its pixel). - let line = c.pixmap().pixel(49, 34).unwrap(); - assert!(line.alpha() > 60 && line.blue() < 60, "the zero line: {line:?}"); - } - - /// A chart of `vals` (value and name, labelled by the name) drawn with the keys `extra` on a - /// 200 × 120 canvas filling it. - fn chart_drawn(vals: &[(f64, &str)], extra: serde_json::Value) -> Canvas { - use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; - let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new("name", FieldType::Text), Field::new("n", FieldType::Double)]); - for (n, name) in vals { - ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text((*name).into()), Value::Float(*n)]); - } - let mut keys = serde_json::json!({"field": "n", "order": "layer"}); - if let (Some(k), Some(e)) = (keys.as_object_mut(), extra.as_object()) { - k.extend(e.clone()); - } - let kind = chart_kind(keys); - let data = kind.chart_data(&ds).unwrap(); - let mut c = Canvas::new(200, 120).unwrap(); - let r = Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(); - chart(&mut c, r, &data, &kind.chart_look().unwrap(), INK, 1.0, false); - c - } - - /// Each bar in its own colour (#2487 part 3), a bar without one in the look's: across and as - /// columns. - #[test] - fn chart_bars_take_their_own_colours() { - let red = Rgba::rgb(0xD0, 0x10, 0x10); - let data = rustgis_map::layout::ChartData { - bars: vec![(10.0, String::new()), (10.0, String::new())], - labelled: false, - left_out: 0, - out_of_range: 0, - no_number: 0, - title: String::new(), - colors: vec![Some(red), None], - ..Default::default() - }; - let is_red = |c: &Canvas, x: u32, y: u32| c.pixmap().pixel(x, y).is_some_and(|p| p.red() > 150 && p.blue() < 60); - for orientation in [Orientation::Horizontal, Orientation::Vertical] { - let look = ChartLook { orientation, ..ChartLook::default() }; - let mut c = Canvas::new(200, 120).unwrap(); - chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &data, &look, INK, 1.0, false); - // Across, two rows 18 px high from the top; as columns, two slots 100 px wide. - let ((x0, y0), (x1, y1)) = match orientation { - Orientation::Horizontal => ((20, 9), (20, 27)), - Orientation::Vertical => ((50, 100), (150, 100)), - }; - assert!(is_red(&c, x0, y0), "{orientation:?}: the first bar in its own colour"); - assert!(bar_blue(&c, x1, y1) && !is_red(&c, x1, y1), "{orientation:?}: the second in the look's"); - } - } - - /// Stacked (#2487 part 3b), a bar is drawn as its stretches in the key's colours, those above - /// zero from it on and those below from it back, with the key over the bars: across and as - /// columns. - #[test] - fn stacked_bars_draw_their_stretches_and_key() { - let (red, green) = (Rgba::rgb(0xD0, 0x10, 0x10), Rgba::rgb(0x10, 0xC0, 0x10)); - let is = |c: &Canvas, x: u32, y: u32, want: Rgba| { - c.pixmap().pixel(x, y).is_some_and(|p| { - p.red().abs_diff(want.0[0]) < 30 && p.green().abs_diff(want.0[1]) < 30 && p.blue().abs_diff(want.0[2]) < 30 - }) - }; - let stacked = |stretches: Vec| rustgis_map::layout::ChartData { - bars: vec![(stretches.iter().sum(), String::new())], - key: vec![("a".into(), red), ("b".into(), green)], - stretches: vec![stretches], - ..Default::default() - }; - let draw = |data: &rustgis_map::layout::ChartData, orientation: Orientation| { - let mut c = Canvas::new(200, 120).unwrap(); - let look = ChartLook { orientation, ..ChartLook::default() }; - chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), data, &look, INK, 1.0, false); - c - }; - // The key's row (14 px) over a bar 18 px high: 6 of 10 in red from the left, 4 in green. - let c = draw(&stacked(vec![6.0, 4.0]), Orientation::Horizontal); - assert!(is(&c, 3, 7, red), "the key's first swatch"); - assert!(is(&c, 50, 23, red) && is(&c, 150, 23, green), "the stretches along the bar"); - assert!(!is(&c, 50, 7, red), "the bar starts under the key"); - // As a column from the bottom up: red at its foot, green over it. - let c = draw(&stacked(vec![6.0, 4.0]), Orientation::Vertical); - assert!(is(&c, 100, 100, red) && is(&c, 100, 30, green), "the stretches up the column"); - // Mirrored (#2487 part 4), the stretches run from the right, the key staying where it is. - let mut c = Canvas::new(200, 120).unwrap(); - let look = ChartLook { mirror: true, ..ChartLook::default() }; - chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &stacked(vec![6.0, 4.0]), &look, INK, 1.0, false); - assert!(is(&c, 3, 7, red) && is(&c, 150, 23, red) && is(&c, 50, 23, green), "red from the right, green past it"); - // On a fixed maximum a stretch past it is cut at it, and one wholly past it isn't drawn. - for (max, far) in [(8.0, green), (5.0, red)] { - let mut c = Canvas::new(200, 120).unwrap(); - let look = ChartLook { max: Some(max), ..ChartLook::default() }; - chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &stacked(vec![6.0, 4.0]), &look, INK, 1.0, false); - assert!(is(&c, 190, 23, far) && !is(&c, 199, 23, far), "{max}: the bar ends at the maximum"); - } - // At 5 the green stretch, from 6 on, is wholly past it: none of it is drawn, anywhere. - let mut c = Canvas::new(200, 120).unwrap(); - let look = ChartLook { max: Some(5.0), ..ChartLook::default() }; - chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &stacked(vec![6.0, 4.0]), &look, INK, 1.0, false); - assert!((0..200).all(|x| !is(&c, x, 23, green)), "no green along the bar"); - // One running back from zero is drawn whole on a fixed maximum too: 2 of a span of 7 (from - // -2 to 5) left of zero, red cut at 5 on the right. - let mut c = Canvas::new(200, 120).unwrap(); - chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &stacked(vec![6.0, -2.0]), &look, INK, 1.0, false); - assert!(is(&c, 30, 23, green) && is(&c, 150, 23, red) && !is(&c, 199, 23, red), "back from zero, cut at the maximum"); - // Stretches all below zero run back from it, the first one too: red 6 of 10 from the - // right, green past it. - let c = draw(&stacked(vec![-6.0, -4.0]), Orientation::Horizontal); - assert!(is(&c, 150, 23, red) && is(&c, 50, 23, green), "both stretches back from zero"); - // A negative stretch runs back from zero: 2 of a span of 8 left of it, 6 right. - let c = draw(&stacked(vec![6.0, -2.0]), Orientation::Horizontal); - assert!(is(&c, 20, 23, green) && is(&c, 100, 23, red), "either way from zero"); - // A bar with no stretches (they add up past the largest number) is drawn whole. - let mut whole = stacked(vec![6.0, 4.0]); - whole.stretches = vec![Vec::new()]; - let c = draw(&whole, Orientation::Horizontal); - assert!(is(&c, 50, 23, ChartLook::default().bar_color) && is(&c, 150, 23, ChartLook::default().bar_color), "whole"); - // A key of a row a value, taller than a short box leaves the bars, draws neither: the - // placeholder instead, nothing past the box. - let mut long = stacked(vec![6.0, 4.0]); - long.key = (0..8).map(|k| (format!("{k} a value with a long name to fill a row"), red)).collect(); - long.stretches = vec![vec![1.0; 8]]; - for orientation in [Orientation::Horizontal, Orientation::Vertical] { - let mut c = Canvas::new(200, 120).unwrap(); - let look = ChartLook { orientation, ..ChartLook::default() }; - chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 60.0).unwrap(), &long, &look, INK, 1.0, false); - assert!(is(&c, 100, 50, Rgba::rgb(0xF0, 0xF1, 0xF3)) && !is(&c, 5, 50, red), "the placeholder"); - assert!(c.pixmap().pixel(5, 90).is_some_and(|p| p.alpha() == 0), "nothing under the box"); - } - // As columns, the head leaves the bars a line past their labels and values: 40 pt high, - // one key row, labelled and valued, is crowded so, not across; and the commands say so as - // the page draws it. - let mut short = stacked(vec![6.0, 4.0]); - short.key.truncate(1); - short.stretches = vec![vec![10.0]]; - short.labelled = true; - let (w, h) = (200.0 / PT_PER_MM, 40.0 / PT_PER_MM); - let valued = |orientation| ChartLook { orientation, values: true, ..ChartLook::default() }; - assert!(chart_crowded(&short, &valued(Orientation::Vertical), w, h)); - assert!(!chart_crowded(&short, &valued(Orientation::Horizontal), w, h)); - assert!(!chart_crowded(&stacked(vec![6.0, 4.0]), &ChartLook::default(), w, 120.0 / PT_PER_MM)); - // A box narrower than a swatch draws the placeholder too, nothing past its right. - // Sample above the centered "Chart" label so system font glyph shapes at y=60 don't mask the fill. - let mut c = Canvas::new(200, 120).unwrap(); - chart(&mut c, Rect::from_xywh(0.0, 0.0, 5.0, 120.0).unwrap(), &stacked(vec![6.0, 4.0]), &ChartLook::default(), INK, 1.0, false); - assert!(is(&c, 2, 10, Rgba::rgb(0xF0, 0xF1, 0xF3)) && (6..20).all(|x| c.pixmap().pixel(x, 7).is_some_and(|p| p.alpha() == 0))); - } - - fn bar_blue(c: &Canvas, x: u32, y: u32) -> bool { - c.pixmap().pixel(x, y).is_some_and(|p| p.blue() > 150 && p.red() < 100) - } - - /// Ink (dark, opaque enough) in the pixels `xs` × `ys`, read unpremultiplied: a bar's - /// half-covered edge is its own colour, not a dark one. - fn chart_inked(c: &Canvas, xs: std::ops::Range, ys: std::ops::Range) -> bool { - xs.flat_map(|x| ys.clone().map(move |y| (x, y))) - .any(|(x, y)| c.pixmap().pixel(x, y).map(|p| p.demultiply()).is_some_and(|p| p.alpha() > 80 && p.blue() < 90 && p.red() < 90)) - } - - /// Columns stand on the bottom, a slot each, 70 % of it wide; with no title they take its room. - #[test] - fn a_vertical_chart_draws_columns() { - let c = chart_drawn(&[(3.0, "a"), (1.0, "b")], serde_json::json!({"orientation": "Vertical", "title": ""})); - // Slots of 100 px, columns from 15 to 85 and 115 to 185; 3 fills the 120 px, 1 a third. - assert!(bar_blue(&c, 50, 10) && bar_blue(&c, 50, 110), "3 fills its slot's height"); - assert!(!bar_blue(&c, 150, 60) && bar_blue(&c, 150, 100), "1 stands a third as high"); - assert!(!bar_blue(&c, 100, 110) && !bar_blue(&c, 5, 110), "gaps between and beside the columns"); - // A negative one hangs from a zero line in the ink. - let c = chart_drawn(&[(3.0, "a"), (-1.0, "b")], serde_json::json!({"orientation": "Vertical", "title": ""})); - assert!(bar_blue(&c, 50, 60) && !bar_blue(&c, 50, 100), "3 stands above zero at 90 px"); - assert!(bar_blue(&c, 150, 105) && !bar_blue(&c, 150, 60), "-1 hangs below it"); - // Labelled, the labels sit under the columns, centred on them. - let c = chart_drawn(&[(3.0, "a"), (1.0, "b")], serde_json::json!({"orientation": "Vertical", "label": "name", "title": ""})); - assert!(chart_inked(&c, 40..60, 108..120) && chart_inked(&c, 140..160, 108..120) && !bar_blue(&c, 50, 112)); - } - - /// Values are written past each bar's end, the bars kept short enough to leave them room; - /// a negative one's past its left end. - #[test] - fn a_charts_values_are_written_past_its_bars() { - let plain = chart_drawn(&[(3.0, "a")], serde_json::json!({})); - let valued = chart_drawn(&[(3.0, "a")], serde_json::json!({"values": true})); - // One row of 18 px under a 16 px title: the bar from 18.7 to 30.6 px down. - assert!(bar_blue(&plain, 194, 25) && !chart_inked(&plain, 150..200, 18..32)); - assert!(!bar_blue(&valued, 194, 25) && bar_blue(&valued, 150, 25) && chart_inked(&valued, 185..200, 18..32), "3 at the bar's end"); - let negative = chart_drawn(&[(3.0, "a"), (-1.0, "b")], serde_json::json!({"values": true})); - assert!(chart_inked(&negative, 0..40, 36..50), "-1 left of its bar"); - } - - /// Values too wide for the chart are written smaller, leaving the bars half its width. - #[test] - fn a_charts_wide_values_leave_its_bars_room() { - let c = chart_drawn(&[(1e12, "a"), (-1e12, "b")], serde_json::json!({"values": true})); - // The bars of 1e12 and -1e12 take the bar area between them: at least half of the 196 px. - let blue = (0..200).filter(|x| bar_blue(&c, *x, 25) || bar_blue(&c, *x, 43)).count(); - assert!(blue >= 97, "{blue} px of bar"); - assert!(chart_inked(&c, 150..200, 18..32), "its value beside it"); - } - - /// The largest number and its opposite span past a number's range: each bar still takes its - /// half of the chart, across or as columns. - #[test] - fn a_charts_bars_past_a_numbers_range_take_their_half() { - let across = chart_drawn(&[(f64::MAX, "a"), (-f64::MAX, "b")], serde_json::json!({})); - let row = |y: u32| (0..200).filter(|x| bar_blue(&across, *x, y)).count(); - assert!(row(25) > 50 && row(43) > 50, "{} and {} px", row(25), row(43)); - let columns = chart_drawn(&[(f64::MAX, "a"), (-f64::MAX, "b")], serde_json::json!({"orientation": "Vertical"})); - let up = (0..120).filter(|y| bar_blue(&columns, 50, *y)).count(); - let down = (0..120).filter(|y| bar_blue(&columns, 150, *y)).count(); - assert!(up > 30 && down > 30, "{up} and {down} px"); - } - - /// No title gives its room to the bars; a bar colour is drawn as given. - #[test] - fn a_chart_without_a_title_and_with_a_bar_colour() { - let titled = chart_drawn(&[(3.0, "a")], serde_json::json!({})); - let untitled = chart_drawn(&[(3.0, "a")], serde_json::json!({"title": ""})); - assert!(!bar_blue(&titled, 150, 8) && bar_blue(&untitled, 150, 8)); - assert!(chart_inked(&titled, 0..20, 0..16) && !chart_inked(&untitled, 0..20, 0..16), "the title, or none"); - let rose = chart_drawn(&[(3.0, "a")], serde_json::json!({"bar_color": [194, 24, 91, 255]})); - let p = rose.pixmap().pixel(150, 25).unwrap(); - assert!(p.red() > 180 && p.green() < 40 && p.blue() > 80 && p.blue() < 100, "{p:?}"); - } - - /// Labels at the right of their column end against the bars; at its left, from its edge. - #[test] - fn a_charts_labels_sit_left_or_against_the_bars() { - let left = chart_drawn(&[(3.0, "Madrid")], serde_json::json!({"label": "name"})); - let right = chart_drawn(&[(3.0, "Madrid")], serde_json::json!({"label": "name", "label_align": "Right"})); - // The labels' column is 64 px wide. - assert!(chart_inked(&left, 0..6, 18..32) && !chart_inked(&left, 56..63, 18..32)); - assert!(!chart_inked(&right, 0..6, 18..32) && chart_inked(&right, 50..63, 18..32)); - } - - /// Mirrored (#2487 part 4), a chart is drawn as its mirror image, its text read as ever: bars - /// run from the right, their labels' column at the right, values past the bars' left ends, a - /// negative bar to the right of zero; columns hang from the top, their labels over them. - #[test] - fn a_mirrored_chart_runs_the_other_way() { - use serde_json::json; - let plain = chart_drawn(&[(3.0, "a"), (1.0, "b")], json!({})); - let mirrored = chart_drawn(&[(3.0, "a"), (1.0, "b")], json!({"mirror": true})); - // Rows of 18 px under a 16 px title. The bar area is 196 px, kept 4 px from the left when - // mirrored; 1 takes a third of it. - assert!(bar_blue(&plain, 20, 43) && !bar_blue(&plain, 180, 43), "1 runs right from the left"); - assert!(bar_blue(&mirrored, 180, 43) && !bar_blue(&mirrored, 20, 43), "1 runs left from the right"); - assert!(bar_blue(&mirrored, 10, 25) && !bar_blue(&mirrored, 1, 25), "3 fills the bar area"); - // Labelled, the 64 px column is at the right; the label at its outer edge, the right. - let labelled = chart_drawn(&[(3.0, "Madrid")], json!({"label": "name", "mirror": true})); - assert!(bar_blue(&labelled, 10, 25) && !bar_blue(&labelled, 140, 25), "the bars left of the labels"); - assert!(chart_inked(&labelled, 190..200, 18..32) && !chart_inked(&labelled, 0..40, 18..32), "the label at the right"); - // Values past the bar's left end. - let valued = chart_drawn(&[(3.0, "a")], json!({"values": true, "mirror": true})); - assert!(chart_inked(&valued, 0..15, 18..32) && !chart_inked(&valued, 185..200, 18..32)); - // Zero 49 px from the right: 3 runs left of it, -1 right. - let negative = chart_drawn(&[(3.0, "a"), (-1.0, "b")], json!({"mirror": true})); - assert!(bar_blue(&negative, 50, 25) && !bar_blue(&negative, 170, 25), "3 left of zero"); - assert!(bar_blue(&negative, 170, 43) && !bar_blue(&negative, 50, 43), "-1 right of zero"); - // Columns hang from the top: 1 a third of the 120 px down. - let columns = chart_drawn(&[(3.0, "a"), (1.0, "b")], json!({"orientation": "Vertical", "title": "", "mirror": true})); - assert!(bar_blue(&columns, 150, 10) && !bar_blue(&columns, 150, 100), "1 hangs from the top"); - assert!(bar_blue(&columns, 50, 110), "3 fills its slot"); - let labelled = - chart_drawn(&[(3.0, "a"), (1.0, "b")], json!({"orientation": "Vertical", "title": "", "label": "name", "mirror": true})); - assert!(chart_inked(&labelled, 40..60, 0..12) && !chart_inked(&labelled, 40..60, 108..120), "labels over the columns"); - } - - /// A fixed maximum is the far end of the bar area, so charts given the same one share a - /// scale; a bar past it runs to that end. A maximum not above zero isn't read. - #[test] - fn a_charts_maximum_sets_its_scale() { - use serde_json::json; - let own = chart_drawn(&[(50.0, "a")], json!({})); - let shared = chart_drawn(&[(50.0, "a")], json!({"max": 100.0})); - assert!(bar_blue(&own, 150, 25), "50 fills the 196 px on its own"); - assert!(bar_blue(&shared, 90, 25) && !bar_blue(&shared, 110, 25), "50 of 100 takes half of them"); - let past = chart_drawn(&[(150.0, "a"), (50.0, "b")], json!({"max": 100.0})); - assert!(bar_blue(&past, 194, 25) && !bar_blue(&past, 198, 25), "150 runs to the end, no further"); - assert!(bar_blue(&past, 90, 43) && !bar_blue(&past, 110, 43), "50 still half"); - // A column of one 140 px slot, 120 px high: 50 of 100 stands half as high. - let columns = chart_drawn(&[(50.0, "a")], json!({"orientation": "Vertical", "title": "", "max": 100.0})); - assert!(bar_blue(&columns, 100, 100) && !bar_blue(&columns, 100, 40)); - for bad in [json!(0.0), json!(-5.0)] { - assert!(bar_blue(&chart_drawn(&[(50.0, "a")], json!({"max": bad})), 150, 25), "{bad}"); - } - // Bars all at zero still draw the placeholder, as they do on their own scale. - let zeros = |extra| chart_drawn(&[(0.0, "a"), (0.0, "b")], extra).pixmap().data().to_vec(); - assert_eq!(zeros(json!({"max": 100.0})), zeros(json!({}))); - } - - /// A bar outline (#2487 part 4b) runs round each bar, across, mirrored and as columns, and - /// round each stretch of a stacked bar; none where it isn't given. - #[test] - fn a_charts_bar_outline_runs_round_each_bar() { - use serde_json::json; - let red = |c: &Canvas, x: u32, y: u32| c.pixmap().pixel(x, y).is_some_and(|p| p.red() > 150 && p.blue() < 100); - let outline = json!({"bar_outline": {"color": [208, 16, 16, 255], "width": 2.0}}); - let plain = chart_drawn(&[(50.0, "a")], json!({})); - assert!(!red(&plain, 100, 19) && bar_blue(&plain, 100, 25), "no outline unless given"); - let c = chart_drawn(&[(50.0, "a")], outline.clone()); - assert!(red(&c, 100, 19) && red(&c, 100, 30) && bar_blue(&c, 100, 25), "inside its top and bottom, filled within"); - let mut mirrored = outline.clone(); - mirrored["mirror"] = json!(true); - let c = chart_drawn(&[(50.0, "a"), (25.0, "b")], mirrored); - assert!(red(&c, 199, 25) && red(&c, 150, 37) && bar_blue(&c, 150, 43), "round the bars from the right"); - assert!(red(&c, 102, 43) && !bar_blue(&c, 50, 43), "the shorter bar's line where it ends, on the left"); - // Within each bar: a wide line paints nothing the bars leave blank, so it never runs into - // their values, labels or title, nor past the chart's room. - let blank = |c: &Canvas, x: u32, y: u32| c.pixmap().pixel(x, y).is_some_and(|p| p.alpha() < 16); - for look in [json!({"values": true}), json!({"mirror": true}), json!({"orientation": "Vertical", "values": true})] { - let vals = [(50.0, "a"), (25.0, "b"), (0.5, "c")]; - let plain = chart_drawn(&vals, look.clone()); - let mut wide = look.clone(); - wide["bar_outline"] = json!({"color": [208, 16, 16, 255], "width": 5.0}); - let c = chart_drawn(&vals, wide); - let spilt = - (0..200).flat_map(|x| (0..120).map(move |y| (x, y))).filter(|(x, y)| blank(&plain, *x, *y) && red(&c, *x, *y)).count(); - assert_eq!(spilt, 0, "{look}"); - } - let mut columns = outline.clone(); - (columns["orientation"], columns["title"]) = (json!("Vertical"), json!("")); - let c = chart_drawn(&[(50.0, "a")], columns); - assert!(red(&c, 100, 0) && red(&c, 30, 60) && red(&c, 169, 60) && bar_blue(&c, 100, 60), "round the column"); - // Round each stretch: a line between the two of a bar split 6 to 4. - let stacked = rustgis_map::layout::ChartData { - bars: vec![(10.0, String::new())], - key: vec![("a".into(), Rgba::rgb(0x10, 0x10, 0xD0)), ("b".into(), Rgba::rgb(0x10, 0x10, 0xD0))], - stretches: vec![vec![6.0, 4.0]], - ..Default::default() - }; - let look = ChartLook { - bar_outline: Some(rustgis_map::layout::ChartOutline { color: Rgba::rgb(0xD0, 0x10, 0x10), width: 2.0 }), - ..ChartLook::default() - }; - let mut c = Canvas::new(200, 120).unwrap(); - chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &stacked, &look, INK, 1.0, false); - // The divider's footprint: what isn't the bars' blue where the two stretches meet. One - // line of the outline's width, 2 px off the pixel grid touching 3, not one from each - // stretch (5). - let divider = (100..140).filter(|x| !bar_blue(&c, *x, 23)).count(); - assert_eq!(divider, 3, "one line of the outline's width between the stretches"); - // A see-through line is laid once everywhere: as red between the stretches as along the - // bar's edge, not twice over on one side of the divider. - let half_red = ChartLook { - bar_outline: Some(rustgis_map::layout::ChartOutline { color: Rgba([208, 16, 16, 128]), width: 3.0 }), - ..ChartLook::default() - }; - let mut c = Canvas::new(200, 120).unwrap(); - chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &stacked, &half_red, INK, 1.0, false); - let reddest = |xs: std::ops::Range, y: u32| xs.filter_map(|x| c.pixmap().pixel(x, y)).map(|p| p.red()).max().unwrap_or(0); - let (edge, between) = (reddest(0..8, 25), reddest(100..140, 25)); - assert!(edge > 60 && between.abs_diff(edge) <= 3, "edge {edge}, between {between}"); - // Bars thinner than the line, and a stretch thinner than it, keep their colour: the line - // narrows to a third of them rather than covering them. - let thin = json!({"bar_outline": {"color": [208, 16, 16, 255], "width": 5.0}}); - let c = chart_drawn(&[(50.0, "a"); 20], thin); - // Down the bars' middle, blue outweighs red at least once a bar (none when the line - // covered them). - let blue = (0..120).filter(|y| c.pixmap().pixel(100, *y).is_some_and(|p| p.alpha() > 0 && p.blue() > p.red())).count(); - assert!(blue >= 20, "every bar keeps its blue, {blue} px"); - let green = Rgba::rgb(0x10, 0xC0, 0x10); - let sliver = rustgis_map::layout::ChartData { - bars: vec![(10.0, String::new())], - key: vec![("a".into(), Rgba::rgb(0x10, 0x10, 0xD0)), ("b".into(), green)], - stretches: vec![vec![9.85, 0.15]], - ..Default::default() - }; - let look = ChartLook { - bar_outline: Some(rustgis_map::layout::ChartOutline { color: Rgba::rgb(0xD0, 0x10, 0x10), width: 5.0 }), - ..ChartLook::default() - }; - let mut c = Canvas::new(200, 120).unwrap(); - chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &sliver, &look, INK, 1.0, false); - // In the bar's rows, those it paints down its middle, which the key's green swatch is not in. - let rows: Vec = (0..120).filter(|y| c.pixmap().pixel(100, *y).is_some_and(|p| p.alpha() > 0)).collect(); - assert!(rows.len() > 5, "the bar's rows, {rows:?}"); - let greens = (0..200) - .flat_map(|x| rows.iter().map(move |y| (x, *y))) - .filter(|(x, y)| c.pixmap().pixel(*x, *y).is_some_and(|p| p.green() > 150 && p.red() < 100)) - .count(); - assert!(greens > 0, "the thin stretch keeps its green"); - // A first stretch drawn a pixel long though its share is far shorter: the next starts - // inside it, and the line, a third of a pixel, still stays inside the bar, between the - // stretches and round them (a stroke that thin is drawn a pixel wide), across and as - // columns. - let tiny = rustgis_map::layout::ChartData { stretches: vec![vec![0.001, 9.999]], ..sliver }; - for orientation in [rustgis_map::layout::Orientation::Horizontal, rustgis_map::layout::Orientation::Vertical] { - let mut plain = Canvas::new(200, 120).unwrap(); - let bare = ChartLook { bar_outline: None, orientation, ..look }; - chart(&mut plain, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &tiny, &bare, INK, 1.0, false); - let mut lined = Canvas::new(200, 120).unwrap(); - chart(&mut lined, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &tiny, &ChartLook { orientation, ..look }, INK, 1.0, false); - // Nothing where the bar itself paints nothing. - let spilt = (0..200) - .flat_map(|x| (0..120).map(move |y| (x, y))) - .filter(|(x, y)| plain.pixmap().pixel(*x, *y).is_some_and(|p| p.alpha() == 0)) - .filter(|(x, y)| lined.pixmap().pixel(*x, *y).is_some_and(|p| p.alpha() > 0 && p.red() > p.green())) - .count(); - assert_eq!(spilt, 0, "{orientation:?}: the lines round and between the stretches stay inside the bar"); - } - // Only the bar's end next to that stretch narrows: along the rest of the bar, the edge - // keeps its width. - let mut c = Canvas::new(200, 120).unwrap(); - chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &tiny, &look, INK, 1.0, false); - let lined = (0..120).filter(|y| c.pixmap().pixel(100, *y).is_some_and(|p| p.red() > 150 && p.blue() < 100)).count(); - assert!(lined >= 6, "both edges of the bar a few pixels wide, {lined} rows"); - // The edge is one shape: where its sides meet off the pixel grid, the shared pixel is - // covered once, not twice in part with the bar's blue showing through between them. - let one = rustgis_map::layout::ChartData { - bars: vec![(10.0, String::new())], - key: vec![("a".into(), Rgba::rgb(0x10, 0x10, 0xD0))], - stretches: vec![vec![10.0]], - ..Default::default() - }; - let mut c = Canvas::new(200, 120).unwrap(); - chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &one, &look, INK, 1.0, false); - // The bar's rows, below the key's swatch: those its end's line reaches. - let red = |y: &u32| c.pixmap().pixel(2, *y).is_some_and(|p| p.red() > 100); - let (Some(top), Some(bottom)) = ((0..120).find(red), (0..120).rev().find(red)) else { panic!("no line") }; - let seams = (top + 1..bottom).filter(|y| c.pixmap().pixel(2, *y).is_some_and(|p| p.blue() > 20)).count(); - assert!(bottom - top > 5 && seams == 0, "inside the bar's end, all line: {seams} rows show the bar"); - // Lines between twenty stretches too thin to part them overlap: a see-through colour - // covers the overlap once, never redder than along the edge. - let mut thin = vec![0.0005; 20]; - thin.insert(0, 5.0); - thin.push(4.99); - let crowded = rustgis_map::layout::ChartData { - key: (0..thin.len()).map(|i| (i.to_string(), if i % 2 == 0 { Rgba::rgb(0x10, 0x10, 0xD0) } else { green })).collect(), - stretches: vec![thin], - ..one - }; - let mut c = Canvas::new(200, 120).unwrap(); - chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &crowded, &half_red, INK, 1.0, false); - let reddest = |xs: std::ops::Range, y: u32| xs.filter_map(|x| c.pixmap().pixel(x, y)).map(|p| p.red()).max().unwrap_or(0); - // The middle of the bar, below the key. - let lined: Vec = (0..120).filter(|y| reddest(0..3, *y) > 60).collect(); - let row = lined.get(lined.len() / 2).copied().unwrap_or(0); - let (edge, between) = (reddest(0..8, row), reddest(8..190, row)); - assert!(edge > 60 && between <= edge + 3, "edge {edge}, between {between}"); - } - - /// Hidden labels leave their column, or their row under columns, to the bars. - #[test] - fn a_charts_hidden_labels_leave_their_room_to_the_bars() { - use serde_json::json; - let shown = chart_drawn(&[(3.0, "Madrid")], json!({"label": "name"})); - let hidden = chart_drawn(&[(3.0, "Madrid")], json!({"label": "name", "hide_labels": true})); - assert!(!bar_blue(&shown, 30, 25) && chart_inked(&shown, 0..6, 18..32)); - assert!(bar_blue(&hidden, 30, 25) && !chart_inked(&hidden, 0..60, 18..32)); - let columns = - chart_drawn(&[(3.0, "Madrid")], json!({"orientation": "Vertical", "title": "", "label": "name", "hide_labels": true})); - assert!(bar_blue(&columns, 100, 115), "the column down to the bottom"); - } - - /// Both map frames share the index feature, even though the locator draws a different map. - /// A page using expressions draws exactly like the same page with its values written inline. - #[test] - fn series_style_follows_the_index_feature_in_both_frames() { - use rustgis_data::{Dataset, Feature, Field, FieldType, Geometry, Value}; - use rustgis_map::layout::MapSeries; - - let mut ds = Dataset::new("Tracts", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); - for (x, id, name) in [(-0.18, 71, "West"), (0.04, 295, "East")] { - let ring = [(x, -0.06), (x + 0.14, -0.06), (x + 0.14, 0.06), (x, 0.06), (x, -0.06)]; - ds.features.push(Feature { - id, - geometry: Some(Geometry::Polygon(vec![vec![ring.map(|(x, y)| Coord::new(x, y)).to_vec()]])), - attrs: vec![Value::Text(name.into())], - }); - } - let mut main = Map::new("Main"); - let mut locator = Map::new("Locator"); - main.add_dataset(ds.clone()); - locator.add_dataset(ds); - let mut maps = [main, locator]; - let mut layout = Layout::new("Atlas", 140.0, 75.0); - let [frame, _] = std::array::from_fn(|i| { - let m = &maps[i]; - let frame = serde_json::from_value(serde_json::json!({"MapFrame": { - "map": m.name, "center": {"x": 0, "y": 0}, "scale": 1_000_000 - }})) - .unwrap(); - layout.add(&m.name, (5.0 + i as f64 * 70.0, 5.0, 60.0, 65.0), frame) - }); - let base = render(&layout, &mut maps, 72.0, &PageInfo::default()).unwrap(); - layout.series = Some(MapSeries { frame, layer: "Tracts".into(), name_field: "name".into(), margin: 0.1, page: 0 }); - let info = PageInfo::default(); - let unchanged = render(&layout, &mut maps, 72.0, &info).unwrap(); - assert_eq!(base.data(), unchanged.data()); - - let style = |maps: &mut [Map], id: &str, name: &str, number: &str| { - for (i, map) in maps.iter_mut().enumerate() { - let layer = map.layers.first_mut().unwrap(); - let page_feature = format!("$id = {id}"); - layer.definition_query = Some(format!("{number} > 0")); - layer.symbol_by.stroke_width = Some(format!("if({page_feature}, 3, 0.6)")); - if i == 0 { - layer.symbol_by.fill = Some(format!("if({page_feature}, '#8bbce8', '#e5e7eb')")); - } else { - // The locator keeps the two classes by a rule expression and filters by page. - let mut renderer = rustgis_map::Renderer::unique( - &layer.dataset, - &[], - "name", - rustgis_map::Ramp::Harbour, - rustgis_map::Symbol::default_for(GeometryType::Polygon, 0), - ) - .unwrap(); - let rustgis_map::Renderer::Unique { expression, .. } = &mut renderer else { panic!() }; - *expression = Some(format!("CASE WHEN {page_feature} THEN 'West' ELSE 'East' END")); - layer.renderer = renderer; - layer.display_filters = vec![rustgis_map::effects::DisplayFilter { - name: "Current tract".into(), - min_scale: None, - max_scale: None, - where_: page_feature.clone(), - }]; - } - layer.labels.enabled = true; - layer.labels.default.where_ = Some(page_feature); - layer.labels.default.by.text = Some(format!("{name} || ' ' || {number}")); - } - }; - let mut previous = base; - for (row, id, name) in [(0, "71", "'West'"), (1, "295", "'East'")] { - layout.series.as_mut().unwrap().page = row; - style(&mut maps, "@page_feature_id", "@page_name", "@page_number"); - let (page, _) = render_pending(&layout, &mut maps, 72.0, &info).unwrap(); - let svg = crate::svg::layout_svg(&layout, &mut maps, 72.0, &info).unwrap().0; - style(&mut maps, id, name, &(row + 1).to_string()); - let mut ordinary = layout.clone(); - ordinary.series = None; - let expected = render(&ordinary, &mut maps, 72.0, &info).unwrap(); - assert!(page.data() == expected.data(), "series page {} differs from the literal expressions", row + 1); - assert_ne!(page.data(), previous.data()); - assert_eq!(svg, crate::svg::layout_svg(&ordinary, &mut maps, 72.0, &info).unwrap().0); - previous = page; - } - } - - /// A legend's, colorbar's, table's or chart's ink colours its text and lines (#2257). Without - /// one, they draw in dark grey as before, a table on its white cells; with one, a table has no - /// white cells, only its header and stripes in a tint of the ink. - #[test] - fn an_ink_colours_legends_colorbars_tables_and_charts() { - use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; - let red = Rgba::rgb(0xE0, 0x10, 0x10); - let reddish = |c: &Canvas| c.pixmap().pixels().iter().any(|p| p.alpha() > 200 && p.red() > 150 && p.green() < 90 && p.blue() < 90); - let draw = |f: &dyn Fn(&mut Canvas)| { - let mut c = Canvas::new(200, 120).unwrap(); - f(&mut c); - c - }; - let r = Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(); - let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new("name", FieldType::Text), Field::new("n", FieldType::Double)]); - for (name, n) in [("a", 3.0), ("b", 1.0)] { - ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text(name.into()), Value::Float(n)]); - } - let map = Map::new("m"); - let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - let grey = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(0, 0, 0), Rgba::rgb(255, 255, 255)] }; - let bar = |ink| Bar { - title: "Height", - orientation: Orientation::Horizontal, - ticks: 3, - side: TickSide::End, - reverse: false, - comma: false, - ink, - }; - for (ink, expected) in [(INK, false), (red, true)] { - let legend = draw(&|c| { - legend_missing(c, r, &map, ("Key", 1), None, opts, ink, 1.0); - }); - assert_eq!(reddish(&legend), expected, "legend {ink:?}"); - assert_eq!(reddish(&draw(&|c| colorbar(c, r, &grey, &bar(ink), 1.0))), expected, "colorbar {ink:?}"); - // Its bars keep their blue. - let data = chart_kind(serde_json::json!({"field": "n", "label": "name"})).chart_data(&ds).unwrap(); - assert_eq!(reddish(&draw(&|c| chart(c, r, &data, &ChartLook::default(), ink, 1.0, false))), expected, "chart {ink:?}"); - } - // Two columns 90 px wide, a header and two rows 17 px high: (175, 25) is in the first - // row's empty right end, (175, 8) in the header's. - let plain = draw(&|c| table(c, r, &ds, 5, None, 1.0)); - let inked = draw(&|c| table(c, r, &ds, 5, Some(red), 1.0)); - assert!(!reddish(&plain) && reddish(&inked)); - let at = |c: &Canvas, x, y| c.pixmap().pixel(x, y).unwrap(); - assert_eq!((at(&plain, 175, 25).red(), at(&plain, 175, 25).alpha()), (255, 255), "white cells without an ink"); - assert_eq!(at(&inked, 175, 25).alpha(), 0, "none with one"); - let header = at(&inked, 175, 8); - assert!(header.alpha() > 0 && header.alpha() < 100 && header.green() < header.red(), "a tint of the ink: {header:?}"); - } - - /// No-data rows reuse the map's fallback symbol, respect filters, and never appear by - /// default. All-classes mode can key the symbol even when the current frame doesn't use it. - #[test] - fn layout_no_data_legend_follows_the_frame() { - use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; - let mut map = Map::new("m"); - let mut ds = Dataset::new("tracts", GeometryType::Point, vec![Field::new("percent", FieldType::Double)]); - for v in [Value::Float(10.0), Value::Float(50.0), Value::Null] { - ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![v]); - } - let id = map.add_dataset(ds); - let l = map.layer_mut(id).unwrap(); - l.renderer = rustgis_map::Renderer::graduated( - &l.dataset, - &[], - "percent", - 2, - rustgis_map::ClassMethod::EqualInterval, - rustgis_map::Ramp::Ember, - rustgis_map::Symbol::default_for(GeometryType::Point, 0), - ) - .unwrap(); - let fallback = l.renderer.symbol_for(&l.dataset, 2); - let listed = |map: &mut Map, all: bool, show: bool| { - let drawn = (!all).then(|| complete_shown_legends(map, 1e6, show, &mut None, &Env::default()).unwrap()); - let opts = LegendOptions { show_no_data: show, hide_other: true, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - legend_rows(map, drawn.as_deref(), &opts) - .into_iter() - .filter_map(|r| match r { - LegendRow::Class(_, e) if e.label == "No data" => Some(e.symbol), - _ => None, - }) - .collect::>() - }; - assert!(listed(&mut map, false, false).is_empty()); - assert_eq!(listed(&mut map, false, true), vec![fallback]); - map.layer_mut(id).unwrap().definition_query = Some("percent IS NOT NULL".into()); - assert!(listed(&mut map, false, true).is_empty()); - assert_eq!(listed(&mut map, true, true), vec![fallback]); - let sizes = |map: &mut Map, show| { - legend_sizes_with_no_data_mm(map, 1e6, true, true, (show, rustgis_map::layout::LEGEND_TEXT_PT), (&[], &NO_LABELS)).unwrap()[0] - }; - assert!(sizes(&mut map, true).1 > sizes(&mut map, false).1); - } - - /// Page clipping is tested after alignment and rotation; box width alone is not clipping. - /// A legend's long title is text too, and invisible elements must not generate notices. - #[test] - fn layout_text_clipping_uses_ink_and_visibility() { - let mut l = Layout::new("Page", 120.0, 90.0); - let id = l.add("Title", (10.0, 10.0, 5.0, 12.0), ElementKind::text("Long line", 14.0, Rgba::rgb(0, 0, 0), false)); - let info = PageInfo::default(); - assert!(clipped_text(&l, &[], 96.0, &info).is_empty(), "outside the box but on the page"); - l.element_mut(id).unwrap().x = 117.0; - assert_eq!(clipped_text(&l, &[], 96.0, &info), vec![(id, "Title".into())]); - l.element_mut(id).unwrap().visible = false; - assert!(clipped_text(&l, &[], 96.0, &info).is_empty()); - let e = l.element_mut(id).unwrap(); - e.visible = true; - (e.x, e.y, e.w) = (0.0, 40.0, 60.0); - if let ElementKind::Text { align, rotation, letter_spacing, .. } = &mut e.kind { - *align = TextAlign::Right; - *letter_spacing = 2.0; - *rotation = 90.0; - } - assert!(clipped_text(&l, &[], 96.0, &info).is_empty(), "turned ink fits"); - l.element_mut(id).unwrap().y = 85.0; - assert_eq!(clipped_text(&l, &[], 96.0, &info).len(), 1, "turned ink is off-page"); - l.element_mut(id).unwrap().visible = false; - let frame = l.add( - "Frame", - (10.0, 10.0, 60.0, 70.0), - serde_json::from_value(serde_json::json!({"MapFrame":{"map":"m", "center":{"x":0,"y":0}, "scale":1000000}})).unwrap(), - ); - let legend = l.add( - "Legend", - (115.0, 10.0, 5.0, 40.0), - ElementKind::Legend { - frame, - title: "Long legend title".into(), - all_classes: false, - hide_other: false, - show_no_data: false, - exclude: vec![], - columns: 1, - labels: BTreeMap::new(), - color: None, - text_size: rustgis_map::layout::LEGEND_TEXT_PT, - }, - ); - assert_eq!(clipped_text(&l, &[Map::new("m")], 96.0, &info), vec![(legend, "Legend".into())]); - // Its title is measured at the size it is drawn at (#2581): one that fits on the page at - // 9 points runs past its edge at 36. - l.element_mut(legend).unwrap().x = 60.0; - assert!(clipped_text(&l, &[Map::new("m")], 96.0, &info).is_empty(), "fits at 9 points"); - if let ElementKind::Legend { text_size, .. } = &mut l.element_mut(legend).unwrap().kind { - *text_size = 36.0; - } - assert_eq!(clipped_text(&l, &[Map::new("m")], 96.0, &info), vec![(legend, "Legend".into())]); - } - - /// Shortens the legend wait on this thread until dropped, then puts back what was there (a test - /// run on one thread, `--test-threads=1`, shares it with the tests after). - struct ShortLegendWait(Option); - - fn short_legend_wait(wait: web_time::Duration) -> ShortLegendWait { - ShortLegendWait(TEST_LEGEND_WAIT.replace(Some(wait))) - } - - impl Drop for ShortLegendWait { - fn drop(&mut self) { - TEST_LEGEND_WAIT.set(self.0); - } - } - - /// No layer labelled: every layer under its name. - static NO_LABELS: BTreeMap = BTreeMap::new(); - - fn legend_page(url: &str) -> (Layout, Vec) { - let (mut page, mut maps) = vector_page(); - // Only the legend is painted; its hidden frame still provides the map and scale. - page.elements[0].visible = false; - page.add( - "Legend", - (10.0, 20.0, 100.0, 60.0), - ElementKind::Legend { - frame: page.elements[0].id, - title: String::new(), - all_classes: true, - hide_other: false, - show_no_data: false, - exclude: Vec::new(), - columns: 1, - labels: BTreeMap::new(), - color: None, - text_size: rustgis_map::layout::LEGEND_TEXT_PT, - }, - ); - let mut tile = rustgis_map::TileLayer::new("Walls", rustgis_map::TileKind::Raster, "https://tiles.test/red/{z}/{x}/{y}.png"); - tile.legends = vec![rustgis_data::ogc::Legend { url: url.into(), ..Default::default() }]; - maps[0].tiles.push(tile); - (page, maps) - } - - fn red_picture() -> Vec { - let mut image = Pixmap::new(24, 24).unwrap(); - image.fill(tiny_skia::Color::from_rgba8(220, 20, 20, 255)); - image.encode_png().unwrap() - } - - #[test] - fn an_interactive_page_does_not_wait_for_legend_pictures() { - use std::sync::mpsc; - let url = "https://tiles.test/waits/interactive-legend.png"; - let fetch = crate::tiles::tests::hold_fetch(url); - let (page, mut maps) = legend_page(url); - let (tx, rx) = mpsc::channel(); - let worker = std::thread::spawn(move || { - let result = render_pending(&page, &mut maps, 72.0, &PageInfo::default()); - tx.send((page, maps, result)).unwrap(); - }); - let done = fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); - // test-wait: an interactive render must finish while the legend fetch is deliberately held. - let result = rx.recv_timeout(std::time::Duration::from_secs(2)); - // Always release the fetch, even if the responsiveness assertion below fails. - done(Ok(red_picture())); - let (page, mut maps, short) = result.expect("the UI must not wait for the legend fetch"); - assert!(short.unwrap().1.legends, "the incomplete page stays pending"); - worker.join().unwrap(); - wait_for_tile_legends(&maps[0], 1e6, &[], web_time::Instant::now() + LEGEND_WAIT).unwrap(); - let (whole, pending) = render_pending(&page, &mut maps, 72.0, &PageInfo::default()).unwrap(); - assert_eq!(pending, PagePending::default(), "ready content does not keep the page pending"); - assert!(whole.pixels().iter().any(|p| p.red() > 200 && p.green() < 60), "the completed picture is painted"); - let exported = render(&page, &mut maps, 72.0, &PageInfo::default()).unwrap(); - assert_eq!(whole.data(), exported.data(), "ready interactive and complete rendering agree"); - } - - #[test] - fn a_page_waits_for_its_legends_only_until_its_deadline() { - let url = "https://tiles.test/waits/deadline-legend.png"; - let fetch = crate::tiles::tests::hold_fetch(url); - let (_, maps) = legend_page(url); - // A deadline already passed ends the wait at once, with the picture still on its way. - assert_eq!(wait_for_tile_legends(&maps[0], 1e6, &[], web_time::Instant::now()), Some(())); - assert!(tile_legends_pending(&maps[0], 1e6, &[])); - fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap()(Ok(red_picture())); - } - - #[test] - fn an_export_shares_one_legend_deadline_across_its_calls() { - assert!(LEGEND_BUDGET.get().is_none()); - { - let _export = legend_budget(); - let first = legend_deadline(); - { - let _inner = legend_budget(); - assert_eq!(legend_deadline(), first, "a call inside the export keeps its deadline"); - } - assert_eq!(legend_deadline(), first, "the inner call didn't end the export's budget"); - } - assert!(LEGEND_BUDGET.get().is_none(), "the budget ends with the export"); - let _next = legend_budget(); - assert!(LEGEND_BUDGET.get() == Some(None), "the next export starts afresh"); - } - - #[test] - fn a_legend_whose_picture_is_ready_does_not_start_the_exports_legend_clock() { - let url = "https://tiles.test/waits/ready-legend.png"; - let fetch = crate::tiles::tests::hold_fetch(url); - let (page, mut maps) = legend_page(url); - assert!(tile_legends_pending(&maps[0], 1e6, &[]), "the picture is asked for"); - fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap()(Ok(red_picture())); - wait_for_tile_legends(&maps[0], 1e6, &[], web_time::Instant::now() + LEGEND_WAIT).unwrap(); - assert!(!tile_legends_pending(&maps[0], 1e6, &[]), "the picture has landed"); - let _export = legend_budget(); - render_drawing_inner(&page, &mut maps, 72.0, &PageInfo::default(), &mut None).unwrap(); - assert!(LEGEND_BUDGET.get() == Some(None), "a legend with nothing to wait for leaves the clock unstarted"); - assert!(finish_legends().is_ok()); - // A later legend whose picture is first asked for now still gets the whole wait. - let before = web_time::Instant::now(); - assert!(legend_deadline() >= before + LEGEND_WAIT); - } - - #[test] - fn an_svg_export_gives_up_on_held_legends_at_one_deadline() { - let url = "https://tiles.test/waits/svg-deadline-legend.png"; - let fetch = crate::tiles::tests::hold_fetch(url); - let (mut page, mut maps) = legend_page(url); - let frame = page.elements[0].id; - page.add( - "Second legend", - (10.0, 5.0, 100.0, 10.0), - ElementKind::Legend { - frame, - title: String::new(), - all_classes: true, - hide_other: false, - show_no_data: false, - exclude: Vec::new(), - columns: 1, - labels: BTreeMap::new(), - color: None, - text_size: rustgis_map::layout::LEGEND_TEXT_PT, - }, - ); - // The thread-local budget and the shortened wait belong to this worker alone. - let worker = std::thread::spawn(move || { - TEST_LEGEND_WAIT.set(Some(web_time::Duration::from_millis(50))); - crate::svg::layout_svg(&page, &mut maps, 72.0, &PageInfo::default()).map(|_| ()) - }); - let done = fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); - let result = worker.join().unwrap(); - done(Err("test fetch released".into())); - assert!(result.unwrap_err().contains("still on their way"), "no successful SVG without its legend"); - } - - #[test] - fn an_export_drawn_without_a_legend_picture_stays_refused_when_the_picture_lands_later() { - let url = "https://tiles.test/waits/late-legend.png"; - let fetch = crate::tiles::tests::hold_fetch(url); - let (page, mut maps) = legend_page(url); - // A wait that has ended before it begins: the legend is drawn with its picture missing. - let _short = short_legend_wait(web_time::Duration::ZERO); - let _export = legend_budget(); - render_drawing_inner(&page, &mut maps, 72.0, &PageInfo::default(), &mut None).unwrap(); - fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap()(Ok(red_picture())); - wait_for_tile_legends(&maps[0], 1e6, &[], web_time::Instant::now() + LEGEND_WAIT).unwrap(); - assert!(!tile_legends_pending(&maps[0], 1e6, &[]), "the picture has landed"); - // What was drawn still lacks it: landing later doesn't make the export complete. - assert!(finish_legends().unwrap_err().contains("still on their way")); - } - - #[test] - fn an_off_page_legend_does_not_hold_any_export_up() { - let url = "https://tiles.test/waits/off-page-legend.png"; - let _held = crate::tiles::tests::hold_fetch(url); - let (mut page, mut maps) = legend_page(url); - let legend = page.elements.last().map(|e| e.id).unwrap(); - page.element_mut(legend).unwrap().x = 1000.0; - // No wait at all: were the legend's picture waited for or counted missing, each fails. - let _short = short_legend_wait(web_time::Duration::ZERO); - let info = PageInfo::default(); - // Drawn nowhere, its picture is neither waited for nor missing from the file. - render(&page, &mut maps, 72.0, &info).unwrap(); - render_drawing(&page, &mut maps, 72.0, &info).unwrap(); - crate::svg::layout_svg(&page, &mut maps, 72.0, &info).unwrap(); - } - - #[test] - fn a_legend_says_from_the_lookup_that_draws_it_whether_a_picture_is_missing() { - let url = "https://tiles.test/waits/lookup-legend.png"; - let fetch = crate::tiles::tests::hold_fetch(url); - let (_, maps) = legend_page(url); - let opts = || LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - let mut canvas = Canvas::new(200, 200).unwrap(); - let draw = |canvas: &mut Canvas| { - legend_missing(canvas, Rect::from_xywh(0.0, 0.0, 200.0, 200.0).unwrap(), &maps[0], ("", 1), None, opts(), INK, 1.0) - }; - assert!(draw(&mut canvas), "drawn while its picture is on its way"); - fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap()(Ok(red_picture())); - wait_for_tile_legends(&maps[0], 1e6, &[], web_time::Instant::now() + LEGEND_WAIT).unwrap(); - assert!(!draw(&mut canvas), "drawn with it"); - } - - #[test] - fn only_an_on_page_legend_is_waited_for_by_the_redraw() { - let url = "https://tiles.test/waits/redraw-legend.png"; - let fetch = crate::tiles::tests::hold_fetch(url); - let (mut page, maps) = legend_page(url); - let legend = page.elements.last().map(|e| e.id).unwrap(); - page.element_mut(legend).unwrap().x = 1000.0; - assert!(!legends_pending(&page, &maps), "off the page: not waited for"); - assert!(fetch.try_recv().is_err(), "nor is its picture asked for"); - page.element_mut(legend).unwrap().x = 10.0; - assert!(legends_pending(&page, &maps), "on the page, its picture is on its way"); - fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap()(Ok(red_picture())); - } - - #[test] - fn the_drawing_and_the_redraw_gate_agree_on_a_legend_at_the_pages_edge() { - // The page is 120 mm wide: 0.01 mm of the legend on it counts; none does not, at whatever - // resolution the page is drawn (a sub-pixel sliver must not make them disagree). - for (x, on_page) in [(119.99, true), (120.0, false)] { - let url = format!("https://tiles.test/waits/edge-legend-{x}.png"); - let fetch = crate::tiles::tests::hold_fetch(&url); - let (mut page, mut maps) = legend_page(&url); - let legend = page.elements.last().map(|e| e.id).unwrap(); - page.element_mut(legend).unwrap().x = x; - assert_eq!(legends_pending(&page, &maps), on_page, "the redraw gate at x = {x}"); - let _short = short_legend_wait(web_time::Duration::ZERO); - let _export = legend_budget(); - render_drawing_inner(&page, &mut maps, 72.0, &PageInfo::default(), &mut None).unwrap(); - assert_eq!(finish_legends().is_err(), on_page, "the page's drawing at x = {x}"); - if on_page { - fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap()(Ok(red_picture())); - } - } - } - - #[test] - fn an_export_includes_a_legend_that_arrives_while_it_waits() { - let url = "https://tiles.test/waits/export-legend.png"; - let fetch = crate::tiles::tests::hold_fetch(url); - let (page, mut maps) = legend_page(url); - let worker = std::thread::spawn(move || render(&page, &mut maps, 72.0, &PageInfo::default())); - let done = fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); - assert!(!worker.is_finished(), "a complete export waits for the held picture"); - done(Ok(red_picture())); - let image = worker.join().unwrap().unwrap(); - assert!(image.pixels().iter().any(|p| p.red() > 200 && p.green() < 60), "not a successful page without its picture"); - } - - #[test] - fn cancelled_legend_waits_return_no_export() { - use std::sync::{ - Arc, - atomic::{AtomicBool, Ordering}, - mpsc, - }; - struct Probe { - flag: Arc, - waiting: mpsc::SyncSender<()>, - } - impl rustgis_data::progress::Probe for Probe { - fn cancelled(&self) -> bool { - let _ = self.waiting.try_send(()); - self.flag.load(Ordering::Relaxed) - } - fn begin(&self, _: u64) {} - fn advance(&self, _: u64) {} - } - for kind in 0..4 { - let url = format!("https://tiles.test/waits/cancelled-legend-{kind}.png"); - let fetch = crate::tiles::tests::hold_fetch(&url); - let (page, mut maps) = legend_page(&url); - let flag = Arc::new(AtomicBool::new(false)); - let cancel = flag.clone(); - let (waiting, observed) = mpsc::sync_channel(1); - let (tx, rx) = mpsc::channel(); - let worker = std::thread::spawn(move || { - let probe_flag = if kind == 3 { Arc::new(AtomicBool::new(false)) } else { flag.clone() }; - let _probe = rustgis_data::progress::install(Some(Arc::new(Probe { flag: probe_flag, waiting }))); - let _frame = (kind == 3).then(|| crate::cancel::install(flag)); - let info = PageInfo::default(); - let result = match kind { - 0 | 3 => render(&page, &mut maps, 72.0, &info).map(|_| ()), - 1 => render_drawing(&page, &mut maps, 72.0, &info).map(|_| ()), - _ => crate::svg::layout_svg(&page, &mut maps, 72.0, &info).map(|_| ()), - }; - tx.send(result).unwrap(); - }); - let done = fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); - observed.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); - cancel.store(true, Ordering::Relaxed); - // test-wait: cancellation must finish before the deliberately pending fetch is released. - let result = rx.recv_timeout(std::time::Duration::from_secs(2)); - done(Err("test fetch released".into())); - assert_eq!(result.unwrap(), Err(rustgis_data::DataError::Cancelled.to_string()), "format {kind}"); - worker.join().unwrap(); - } - } - - /// A frame drawn over another takes its rectangle out of the other's: the bands above and below - /// it and the strips beside it are left, a strip too narrow to point into is dropped, and one - /// that covers it all leaves nothing (#1191). - #[test] - fn a_frame_drawn_over_another_leaves_the_rest_of_it() { - let r = [0.0, 0.0, 100.0, 50.0]; - assert_eq!(uncovered(r, [200.0, 0.0, 10.0, 10.0]), [r], "apart"); - assert_eq!( - uncovered(r, [10.0, 10.0, 20.0, 20.0]), - [[0.0, 0.0, 100.0, 10.0], [0.0, 30.0, 100.0, 20.0], [0.0, 10.0, 10.0, 20.0], [30.0, 10.0, 70.0, 20.0]] - ); - // Over its top-left corner, and past it. - assert_eq!(uncovered(r, [-5.0, -5.0, 15.0, 15.0]), [[0.0, 10.0, 100.0, 40.0], [10.0, 0.0, 90.0, 10.0]]); - assert_eq!(uncovered(r, [0.0, 0.0, 100.0, 49.995]), Vec::<[f64; 4]>::new(), "a 0.005 mm strip is dropped"); - assert!(uncovered(r, [-1.0, -1.0, 102.0, 52.0]).is_empty()); - } - - /// Each element is a layer of the page's recording, named after it and identified by its id - /// (#1815): two elements named alike are told apart by id, not by which comes first, so an - /// element that draws nothing on one page of a series doesn't hand its layer to the other. - #[test] - fn each_element_is_a_layer_with_its_id() { - use crate::vector::Item; - let mut layout = Layout::new("Layers", 120.0, 90.0); - let text = |t: &str| ElementKind::text(t, 12.0, Rgba::rgb(0, 0, 0), false); - let (a, b) = - (layout.add("Texto", (10.0, 10.0, 60.0, 10.0), text("Um")), layout.add("Texto", (10.0, 30.0, 60.0, 10.0), text("Dois"))); - let layers = |layout: &Layout| { - let (drawing, _) = render_drawing(layout, &mut [], 96.0, &PageInfo::default()).unwrap(); - let (_, _, items) = drawing.finish(); - items.into_iter().filter_map(|i| if let Item::Group(g) = i { Some((g.layer?, g.layer_id?)) } else { None }).collect::>() - }; - assert_eq!(layers(&layout), [("Texto".to_string(), u64::from(a)), ("Texto".to_string(), u64::from(b))]); - // The first draws nothing: the second keeps its own layer. - if let Some(ElementKind::Text { text, .. }) = layout.elements.iter_mut().find(|e| e.id == a).map(|e| &mut e.kind) { - text.clear(); - } - assert_eq!(layers(&layout), [("Texto".to_string(), u64::from(b))]); - } - - /// The page's colour (#2855) is the first thing the PDF's drawing fills, over the whole page; - /// a white page is filled white as before. - #[test] - fn a_pages_colour_is_filled_first_in_the_pdfs_drawing() { - use crate::vector::{Brush, Item}; - let mut layout = Layout::new("Paper", 120.0, 90.0); - let first = |layout: &Layout| { - let (drawing, _) = render_drawing(layout, &mut [], 72.0, &PageInfo::default()).unwrap(); - let (w, h, items) = drawing.finish(); - match items.into_iter().next() { - Some(Item::Fill { path, brush: Brush::Solid(c), .. }) => { - let b = path.bounds(); - assert!(b.left() <= 0.0 && b.top() <= 0.0 && b.right() >= w - 0.5 && b.bottom() >= h - 0.5, "{b:?}"); - c.to_color_u8() - } - _ => panic!("the page is not filled first"), - } - }; - let c = first(&layout); - assert_eq!((c.red(), c.green(), c.blue(), c.alpha()), (255, 255, 255, 255)); - layout.paper = Some(Rgba::rgb(0x0B, 0x1B, 0x2B)); - let c = first(&layout); - assert_eq!((c.red(), c.green(), c.blue(), c.alpha()), (0x0B, 0x1B, 0x2B, 255)); - } - - /// A page with a frame of the built-in world and a title. - fn vector_page() -> (Layout, Vec) { - let mut layout = Layout::new("Vectors", 120.0, 90.0); - let kind = serde_json::from_value(serde_json::json!({"MapFrame": { - "map": "Map", "center": {"x": 0, "y": 0}, "scale": 150000000 - }})) - .unwrap(); - layout.add("World", (10.0, 20.0, 100.0, 60.0), kind); - let title = ElementKind::text("Shelby County", 18.0, Rgba::rgb(20, 20, 20), true); - layout.add("Title", (10.0, 4.0, 100.0, 12.0), title); - (layout, vec![Map::new("Map")]) - } - - #[test] - fn a_recorded_page_keeps_its_text_and_frame_as_vectors() { - use crate::vector::Item; - let (layout, mut maps) = vector_page(); - let (drawing, pictured) = render_drawing(&layout, &mut maps, 150.0, &PageInfo::default()).unwrap(); - assert!(pictured.is_empty() && !drawing.overflowed()); - let (_, _, items) = drawing.finish(); - let items = crate::vector::without_layers(items); - let text: String = items - .iter() - .filter_map(|i| if let Item::Glyphs(r) = i { Some(r) } else { None }) - .flat_map(|r| r.glyphs.iter().map(|g| g.ch)) - .collect(); - assert_eq!(text, "Shelby County", "the title, its space kept for copying"); - // The frame: a group cut to its box, its land as paths, not a picture of it. - let frame = items.iter().find_map(|i| if let Item::Group(g) = i { Some(g) } else { None }).expect("the frame's group"); - assert!(frame.clip.is_some()); - assert!(frame.items.iter().filter(|i| matches!(i, Item::Fill { .. })).count() > 50); - assert!(!frame.items.iter().any(|i| matches!(i, Item::Image(_)))); - } - - #[test] - fn a_recorded_page_draws_what_the_picture_of_it_shows() { - let (layout, mut maps) = vector_page(); - let info = PageInfo::default(); - let png = render(&layout, &mut maps, 96.0, &info).unwrap(); - let (drawing, _) = render_drawing(&layout, &mut maps, 96.0, &info).unwrap(); - let (_, _, items) = drawing.finish(); - let mut replayed = Pixmap::new(png.width(), png.height()).unwrap(); - crate::vector::replay(&items, &mut replayed, Transform::identity()); - // The same paths through the same rasteriser: only glyph edges (coverage against filled - // outlines) may differ. - let differ = png.pixels().iter().zip(replayed.pixels()).filter(|(a, b)| { - let (a, b) = (a.demultiply(), b.demultiply()); - a.red().abs_diff(b.red()).max(a.green().abs_diff(b.green())).max(a.blue().abs_diff(b.blue())) > 48 - }); - let share = differ.count() as f64 / png.pixels().len() as f64; - assert!(share < 0.005, "{:.3}% of pixels differ", share * 100.0); - } - - #[test] - fn a_huge_page_records_within_its_bounds() { - let mut layout = Layout::new("Huge", 5000.0, 5000.0); - layout.add("Title", (10.0, 10.0, 4000.0, 400.0), ElementKind::text("Shelby County", 300.0, Rgba::rgb(0, 0, 0), true)); - let (drawing, _) = render_drawing(&layout, &mut [], 600.0, &PageInfo::default()).unwrap(); - // Held to the page budget's size, as the picture of it is. - assert!(drawing.width as f64 <= MAX_SIDE && drawing.height as f64 <= MAX_SIDE); - assert!(!drawing.overflowed()); - } - - #[test] - fn a_turned_frame_stays_vectors() { - use crate::vector::Item; - let (mut layout, mut maps) = vector_page(); - if let Some(ElementKind::MapFrame { bearing, .. }) = layout.elements.first_mut().map(|e| &mut e.kind) { - *bearing = 30.0; - } - let (drawing, _) = render_drawing(&layout, &mut maps, 96.0, &PageInfo::default()).unwrap(); - let (_, _, items) = drawing.finish(); - let items = crate::vector::without_layers(items); - let frame = items.iter().find_map(|i| if let Item::Group(g) = i { Some(g) } else { None }).expect("the frame's group"); - // The turned view holds the north-up frame, turned. - let Some(Item::Group(north)) = frame.items.first() else { panic!("the north-up frame inside") }; - assert!(north.transform.ky.abs() > 0.3, "turned: {:?}", north.transform); - assert!(north.items.iter().filter(|i| matches!(i, Item::Fill { .. })).count() > 50); - } - - #[test] - fn a_frame_too_large_for_vectors_is_drawn_as_a_picture_and_named() { - use crate::vector::{Item, TEST_MAX_COST}; - let (layout, mut maps) = vector_page(); - TEST_MAX_COST.with(|l| l.set(Some(20_000))); - let result = render_drawing(&layout, &mut maps, 72.0, &PageInfo::default()); - TEST_MAX_COST.with(|l| l.set(None)); - let (drawing, pictured) = result.unwrap(); - assert_eq!(pictured.iter().map(|p| p.1.as_str()).collect::>(), ["World"]); - let (_, _, items) = drawing.finish(); - let items = crate::vector::without_layers(items); - assert!(items.iter().any(|i| matches!(i, Item::Image(_))), "the frame as a picture"); - } - - /// Every token the Format pane offers a layout's text is one the page expands (#516). - #[test] - fn the_tokens_offered_are_the_ones_expanded() { - let layout = Layout::new("Atlas", 100.0, 100.0); - let info = PageInfo { page: 2, pages: 5, page_name: "North".into() }; - let tokens = rustgis_map::layout::PAGE_TOKENS.iter().chain(rustgis_map::graphics::TOKENS); - for (token, _) in tokens { - assert!(!expand(token, &layout, &info, None).contains('{'), "{token}"); - } - assert_eq!(expand("{page} of {pages}, {pageName} · {layout}", &layout, &info, None), "2 of 5, North · Atlas"); - } - - /// A WMS or WMTS layer's legend is its service's picture under its name, as the Layers pane - /// shows it, narrowed to fit across and sized for; left out by name, hidden, or with none at - /// the frame's scale, it isn't listed. - #[test] - fn a_web_layers_legend_is_its_services_picture() { - crate::tiles::tests::serve(); - let mut map = Map::new("m"); - let mut t = rustgis_map::TileLayer::new("Walls", rustgis_map::TileKind::Raster, "https://tiles.test/red/{z}/{x}/{y}.png"); - t.legends = vec![rustgis_data::ogc::Legend { url: "https://tiles.test/red/legend.png".into(), ..Default::default() }]; - map.tiles.push(t); - // The red drawn (the picture is red; the name is dark) and how far right, in pixels. - let red = |map: &Map, width: f32, exclude: &[String], scale: f64| { - let mut pm = Pixmap::new(300, 400).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let opts = LegendOptions { show_no_data: false, hide_other: false, exclude, labels: &NO_LABELS, scale, size: 1.0 }; - crate::canvas::with_canvas(&mut pm, |c| { - legend(c, Rect::from_xywh(0.0, 0.0, width, 400.0).unwrap(), map, ("", 1), None, opts, 1.0) - }); - let hits: Vec = (0..pm.height()) - .flat_map(|y| (0..pm.width()).map(move |x| (x, y))) - .filter(|&(x, y)| pm.pixel(x, y).is_some_and(|p| p.red() > 200 && p.green() < 60)) - .map(|(x, _)| x) - .collect(); - (hits.len(), hits.iter().max().copied().unwrap_or(0)) - }; - wait_for_tile_legends(&map, 1e6, &[], web_time::Instant::now() + LEGEND_WAIT).unwrap(); - let (ink, right) = red(&map, 300.0, &[], 1e6); - assert!(ink > 200 * 200, "the picture is drawn: {ink} px"); - assert!(right < 6 + 256, "a pixel a point: {right}"); - // Its name's row and the picture, 256 points down and 6 + 256 across. - let (w, h) = legend_sizes_mm(&mut map, 1e6, false, false, (&[], &NO_LABELS)).unwrap()[0]; - let mm = 25.4 / 96.0; - assert!((w - 262.0 * mm).abs() < 1e-6 && (h - (f64::from(LEGEND_ROW) + 256.0) * mm).abs() < 1e-6, "{w} × {h} mm"); - let (_, right) = red(&map, 100.0, &[], 1e6); - assert!(right < 100, "narrowed to fit: {right}"); - assert_eq!(red(&map, 300.0, &["WALLS".into()], 1e6).0, 0, "left out by name"); - map.tiles[0].legends[0].max_scale = Some(1e5); - assert_eq!(red(&map, 300.0, &[], 1e6).0, 0, "none at this scale"); - map.tiles[0].legends[0].max_scale = None; - // Narrowed, a picture takes only the height it's drawn at: a second layer's fits under it - // (a 70-point legend: 64 points across, so 64 down), and the drawing order is the map's. - let mut second = map.tiles[0].clone(); - second.name = "Floors".into(); - map.tiles.push(second); - let mut pm = Pixmap::new(70, 200).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 70.0, 200.0).unwrap(), &map, ("", 1), None, opts, 1.0)); - let red_rows = - (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| pm.pixel(x, y).is_some_and(|p| p.red() > 200 && p.green() < 60))).count(); - assert!(red_rows >= 2 * 63, "both pictures, {red_rows} rows"); - let names: Vec<&str> = legend_rows(&map, None, &opts) - .iter() - .filter_map(|r| match r { - LegendRow::Head(n) => Some(*n), - _ => None, - }) - .collect(); - assert_eq!(names, ["Walls", "Floors"]); - // Among the map's layers where the map draws them: a web layer placed over a feature - // layer is listed just above it, under the feature layers above. - let lower = map.add_dataset(rustgis_data::Dataset::new("Lower", GeometryType::Point, vec![])); - map.add_dataset(rustgis_data::Dataset::new("Upper", GeometryType::Point, vec![])); - map.tiles[1].over = Some(lower); - let listed: Vec<&str> = legend_rows(&map, None, &opts) - .iter() - .filter_map(|r| match r { - LegendRow::Head(n) => Some(*n), - LegendRow::Plain(_, name) => Some(*name), - _ => None, - }) - .collect(); - let feature_order: Vec<&str> = map.layers.iter().map(|l| l.name.as_str()).collect(); - let expected: Vec<&str> = - feature_order.iter().flat_map(|n| if *n == "Lower" { vec!["Floors", "Lower"] } else { vec![*n] }).chain(["Walls"]).collect(); - assert_eq!(listed, expected, "layers top first: {feature_order:?}"); - // A heading with no room for any of its picture under it isn't drawn: a legend one row - // tall stays blank (the map's layers set aside, whose rows would fit). - map.layers.clear(); - let mut pm = Pixmap::new(300, 15).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - crate::canvas::with_canvas(&mut pm, |c| { - legend(c, Rect::from_xywh(0.0, 0.0, 300.0, LEGEND_ROW).unwrap(), &map, ("", 1), None, opts, 1.0) - }); - assert!(pm.pixels().iter().all(|p| p.red() > 200 && p.green() > 200), "no heading alone"); - map.tiles.truncate(1); - map.tiles[0].visible = false; - 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"); - // A paper colour (#2532) is the background too, and coverage still finds only the data. - let white = frame_coverage(&mut map, Coord::new(0.0, 0.0), 1_000_000.0, 100.0, 100.0, 64); - map.paper = Some(Rgba::rgb(0xF1, 0xEA, 0xDF)); - assert!(plain(&mut map, (2.0, 70.0, 25.0, 25.0)), "a corner is the coloured paper"); - assert_eq!(frame_coverage(&mut map, Coord::new(0.0, 0.0), 1_000_000.0, 100.0, 100.0, 64), white); - assert_eq!(map.paper, Some(Rgba::rgb(0xF1, 0xEA, 0xDF)), "put back after coverage"); - map.paper = None; - 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"); - } - - #[test] - fn plain_dark_basemaps_keep_the_legend_paper_while_light_ones_clear_it() { - for body in ["earth", "mars"] { - for basemap in [rustgis_map::Basemap::Midnight, rustgis_map::Basemap::Paper, rustgis_map::Basemap::Ocean] { - let mut map = Map::new("plain"); - (map.body, map.basemap, map.graticule) = (body.into(), basemap, false); - // The Earth frame is open Gulf of Guinea water; on Mars it is the palette's grey. - let plain = frame_plain_under(&mut map, Coord::new(0.0, 0.0), 1_000_000.0, (100.0, 100.0), (40.0, 40.0, 20.0, 20.0), 128); - assert_eq!(plain, basemap != rustgis_map::Basemap::Midnight, "{body}: {basemap:?}"); - } - } - } - - /// 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] - fn frame_coverage_leaves_out_layers_that_only_outline() { - use rustgis_data::{Dataset, Geometry}; - let count = |map: &mut Map| { - let (.., cells) = frame_coverage(map, Coord::new(0.0, 0.0), 1_000_000.0, 100.0, 100.0, 64).unwrap(); - cells.iter().filter(|c| **c).count() - }; - let point = || { - let mut d = Dataset::new("far", GeometryType::Point, Vec::new()); - d.push(Some(Geometry::Point(Coord::new(-0.3, -0.3))), Vec::new()); - d - }; - let mut map = Map::new("m"); - let mut square = Dataset::new("border", GeometryType::Polygon, Vec::new()); - square.push( - Some(Geometry::Polygon(vec![vec![ - [(-0.2, -0.2), (0.2, -0.2), (0.2, 0.2), (-0.2, 0.2), (-0.2, -0.2)].map(|(x, y)| Coord::new(x, y)).to_vec(), - ]])), - Vec::new(), - ); - let border = map.add_dataset(square); - 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!(count(&mut map) > 0, "alone, it is what the map shows"); - map.add_dataset(point()); - let beside = count(&mut map); - assert!(map.layer(border).is_some_and(|l| l.visible), "shown again"); - let mut alone = Map::new("m"); - alone.add_dataset(point()); - assert_eq!(beside, count(&mut alone), "only the point counts"); - let l = map.layers.iter_mut().find(|l| l.id == border).unwrap(); - assert!(only_outlines(l)); - l.labels.enabled = true; - assert!(!only_outlines(l), "labels make it more than an outline"); - l.labels.enabled = false; - l.fill_layers = vec![rustgis_map::fills::FillLayer::default()]; - assert!(!only_outlines(l), "a stacked fill draws inside it"); - l.no_fill = Some(rustgis_map::NoFill::Symbols); - assert!(!only_outlines(l), "No Fill's symbols leave a stacked fill drawn"); - l.no_fill = Some(rustgis_map::NoFill::Override); - assert!(only_outlines(l), "No Fill's override is the fill that hides the rest"); - l.no_fill = None; - l.fill_layers.clear(); - l.symbol_by.fill = Some("'#ff0000'".into()); - assert!(!only_outlines(l), "a fill by expression draws inside it"); - l.symbol_by.fill = None; - l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol::default_for(GeometryType::Polygon, 0)); - assert!(!only_outlines(l), "a filled symbol"); - l.no_fill = Some(rustgis_map::NoFill::Symbols); - assert!(only_outlines(l), "No Fill counts as no fill"); - let symbol = rustgis_map::Symbol::default_for(GeometryType::Polygon, 0); - l.renderer = rustgis_map::Renderer::Unique { - field: "g".into(), - classes: vec![("a".into(), symbol)], - other: symbol, - ramp: rustgis_map::Ramp::Ember, - class_labels: Default::default(), - other_label: None, - class_strokes: Default::default(), - other_strokes: Vec::new(), - class_fills: [("a".to_string(), vec![rustgis_map::fills::FillLayer::default()])].into(), - other_fills: Vec::new(), - expression: None, - }; - assert!(!only_outlines(l), "No Fill's symbols leave a class's stacked fill drawn"); - l.no_fill = Some(rustgis_map::NoFill::Override); - assert!(only_outlines(l), "the override hides that too"); - l.no_fill = None; - l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { - fill: Rgba::new(0, 0, 0, 0), - ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) - }); - - // A layer out of scale at the frame's scale draws nothing there: the outline is all it shows. - let drawn_alone = { - let far = map.layers.iter().find(|l| l.id != border).map(|l| l.id).unwrap(); - map.layers.iter_mut().find(|l| l.id == far).unwrap().min_scale = Some(1.0); - let shown = count(&mut map); - map.layers.iter_mut().find(|l| l.id == far).unwrap().min_scale = None; - shown - }; - assert!(drawn_alone > beside, "{drawn_alone} of {beside}"); - let l = map.layers.iter_mut().find(|l| l.id == border).unwrap(); - l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol::default_for(GeometryType::Polygon, 0)); - assert!(plain_fill(l), "one colour"); - l.labels.enabled = true; - assert!(!plain_fill(l), "labels make it more than context"); - } - - /// A polygon layer in one colour running on past the frame is context beside a layer drawn by - /// classes; one inside the frame, such as a study area, is what the map shows. - #[test] - fn frame_coverage_leaves_out_one_colour_fills_beside_classes() { - use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; - let count = |map: &mut Map| { - let (.., cells) = frame_coverage(map, Coord::new(0.0, 0.0), 1_000_000.0, 100.0, 100.0, 64).unwrap(); - cells.iter().filter(|c| **c).count() - }; - let mut map = Map::new("m"); - let square = |name: &str, r: f64| { - let mut d = Dataset::new(name, GeometryType::Polygon, Vec::new()); - d.push( - Some(Geometry::Polygon(vec![vec![[(-r, -r), (r, -r), (r, r), (-r, r), (-r, -r)].map(|(x, y)| Coord::new(x, y)).to_vec()]])), - Vec::new(), - ); - d - }; - // About 0.9° across the frame: the states run on past it. - let states = map.add_dataset(square("states", 2.0)); - let mut d = Dataset::new("far", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); - d.push(Some(Geometry::Point(Coord::new(-0.3, -0.3))), vec![Value::Text("c".into())]); - let far = map.add_dataset(d); - let with_states = count(&mut map); - let s = |c| rustgis_map::Symbol::default_for(GeometryType::Point, c); - if let Some(l) = map.layers.iter_mut().find(|l| l.id == far) { - l.renderer = rustgis_map::Renderer::Unique { - field: "g".into(), - classes: vec![("c".to_string(), s(0))], - other: s(1), - ramp: rustgis_map::Ramp::Ember, - class_labels: Default::default(), - other_label: None, - class_strokes: Default::default(), - other_strokes: Vec::new(), - class_fills: Default::default(), - other_fills: Vec::new(), - expression: None, - }; - } - let beside_classes = count(&mut map); - assert!(beside_classes > 0 && beside_classes < with_states, "{beside_classes} of {with_states}"); - assert!(map.layer(states).is_some_and(|l| l.visible), "shown again"); - map.add_dataset(square("study area", 0.1)); - let with_study_area = count(&mut map); - assert!(with_study_area > beside_classes, "a one-colour layer inside the frame counts: {with_study_area} of {beside_classes}"); - - // A drawing three times the frame's width, judged on the frame: a layer running past the - // frame but not past the drawing is context in both, and one inside the frame is counted. - let mut map = Map::new("m"); - let neighbour = map.add_dataset(square("neighbour", 0.6)); - let far = { - let mut d = Dataset::new("far", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); - d.push(Some(Geometry::Point(Coord::new(-0.3, -0.3))), vec![Value::Text("c".into())]); - map.add_dataset(d) - }; - if let Some(l) = map.layers.iter_mut().find(|l| l.id == far) { - l.renderer = rustgis_map::Renderer::Unique { - field: "g".into(), - classes: vec![("c".to_string(), s(0))], - other: s(1), - ramp: rustgis_map::Ramp::Ember, - class_labels: Default::default(), - other_label: None, - class_strokes: Default::default(), - other_strokes: Vec::new(), - class_fills: Default::default(), - other_fills: Vec::new(), - expression: None, - }; - } - let drawn = |map: &mut Map, judged: (f64, f64)| { - let (.., cells) = frame_coverage_judged_on(map, Coord::new(0.0, 0.0), 1_000_000.0, (300.0, 300.0), judged, 192).unwrap(); - cells.iter().filter(|c| **c).count() - }; - let on_the_drawing = drawn(&mut map, (300.0, 300.0)); - let on_the_frame = drawn(&mut map, (100.0, 100.0)); - assert!(on_the_frame < on_the_drawing / 4, "the neighbour is context on the frame: {on_the_frame} of {on_the_drawing}"); - assert!(map.layer(neighbour).is_some_and(|l| l.visible), "shown again"); - } - - /// A legend's rows go into columns: as even as they go, a layer's name with the row under it, - /// and in a box too short each filled in turn; one column draws as it always has. - #[test] - fn a_legends_rows_go_into_columns() { - use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; - let mut map = Map::new("m"); - let mut d = Dataset::new("pts", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); - d.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text("c0".into())]); - let pts = map.add_dataset(d); - let s = |c| rustgis_map::Symbol::default_for(GeometryType::Point, c); - if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) { - // The layer's name, 30 classes and the other values: 32 rows. - let classes = (0u32..30).map(|i| (format!("c{i}"), s(i))).collect(); - l.renderer = rustgis_map::Renderer::Unique { - field: "g".into(), - classes, - other: s(31), - ramp: rustgis_map::Ramp::Ember, - class_labels: Default::default(), - other_label: None, - class_strokes: Default::default(), - other_strokes: Vec::new(), - class_fills: Default::default(), - other_fills: Vec::new(), - expression: None, - }; - } - let opts = || LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - let rows = legend_rows(&map, None, &opts()); - assert_eq!(rows.len(), 32); - assert_eq!(balanced(&rows, 1, (1e6, 1.0)), (vec![0], 32.0 * LEGEND_ROW)); - assert_eq!(balanced(&rows, 2, (1e6, 1.0)), (vec![0, 16], 16.0 * LEGEND_ROW)); - assert_eq!(balanced(&rows, 3, (1e6, 1.0)).1, 11.0 * LEGEND_ROW); - assert_eq!(balanced(&[], 3, (1e6, 1.0)), (vec![0], 0.0)); - // Too short for them all: each filled in turn, and the last holds what fits of the rest. - let (starts, fits) = flow(&rows, 3, 5.0 * LEGEND_ROW, (1e6, 1.0)); - assert_eq!((starts, fits), (vec![0, 5, 10], false)); - // A layer's name isn't left at the foot of a column; the last, with none under it, can be. - let heads = [LegendRow::Head("a"), LegendRow::Head("b"), LegendRow::Head("c"), LegendRow::Head("d"), LegendRow::Head("e")]; - assert_eq!(flow(&heads, 3, 3.0 * LEGEND_ROW, (1e6, 1.0)), (vec![0, 2], true)); - - let sizes = legend_sizes_mm(&mut map, 1e6, true, false, (&[], &NO_LABELS)).unwrap(); - let row = f64::from(LEGEND_ROW) * 25.4 / 96.0; - for (size, rows) in sizes.iter().zip([32.0, 16.0, 11.0]) { - assert!((size.1 - rows * row).abs() < 1e-6, "{size:?} for {rows} rows"); - } - assert!(sizes[0].0 < sizes[1].0 && sizes[1].0 < sizes[2].0, "{sizes:?}"); - - // How far right and down the legend draws in a box, and how many pixels. - let ink = |columns: usize, w: f32, h: f32| { - let mut pm = Pixmap::new(500, 500).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - crate::canvas::with_canvas(&mut pm, |c| { - legend(c, Rect::from_xywh(0.0, 0.0, w, h).unwrap(), &map, ("", columns), None, opts(), 1.0); - }); - let dark = |x, y| pm.pixel(x, y).is_some_and(|p| p.red() < 200 || p.green() < 200 || p.blue() < 200); - let right = (0..500).filter(|&x| (0..500).any(|y| dark(x, y))).max().unwrap_or(0); - let down = (0..500).filter(|&y| (0..500).any(|x| dark(x, y))).max().unwrap_or(0); - (right, down) - }; - let mm_pt = 96.0 / 25.4; - let (right1, down1) = ink(1, 500.0, 500.0); - let (right2, down2) = ink(2, 500.0, 500.0); - let (right3, down3) = ink(3, 500.0, 500.0); - assert!(f64::from(down1) > 31.0 * sizes[0].1 / 32.0 * mm_pt, "{down1}"); - assert!(f64::from(down2) <= sizes[1].1 * mm_pt && down2 > down3, "{down2} then {down3}"); - assert!(right1 < right2 && right2 < right3, "{right1}, {right2}, {right3}"); - assert!(f64::from(right3) <= sizes[2].0 * mm_pt + 1.0, "{right3} across {:?}", sizes[2]); - // A value out of range, from a file edited by hand, draws what the nearest would. - assert_eq!(ink(0, 500.0, 500.0), (right1, down1)); - assert_eq!(ink(9, 500.0, 500.0), (right3, down3)); - // A box too narrow for the columns closes them up: the last still starts inside it, past - // where the first two end in a box of their own. - let narrow = f64::from(right3) as f32 * 0.8; - let (right_narrow, down_narrow) = ink(3, narrow, 500.0); - assert!(f64::from(right_narrow) < f64::from(right3) && right_narrow > right1, "{right_narrow} of {right3}"); - // Moved sideways, the letters' lowest edge can land a pixel higher; a lost row would be 15. - assert!(down_narrow.abs_diff(down3) < LEGEND_ROW as u32 / 2, "no row left out: {down_narrow} of {down3}"); - } - - /// The widest class label of `rows`, in points. - fn widest_label(rows: &[LegendRow]) -> f32 { - rows.iter().map(|row| row.width(0.0, 1.0) - 12.0).fold(0.0, f32::max) - } - - /// A point layer in Unique Values, for a legend's rows. - fn classed_point_map(classes: Vec<(String, rustgis_map::Symbol)>, small: rustgis_map::Symbol) -> Map { - point_legend_map(|l| { - l.renderer = rustgis_map::Renderer::Unique { - field: "g".into(), - classes, - other: small, - ramp: rustgis_map::Ramp::Ember, - class_labels: Default::default(), - other_label: None, - class_strokes: Default::default(), - other_strokes: Vec::new(), - class_fills: Default::default(), - other_fills: Vec::new(), - expression: None, - }; - }) - } - - /// A box one row tall: in one column a layer's name is drawn alone, as it always was; in more, - /// it waits for room for the class under it, and the first column stays blank. - #[test] - fn a_layers_name_stays_with_its_class_only_in_columns() { - let small = rustgis_map::Symbol::default_for(GeometryType::Point, 0); - let classes = (0u32..4).map(|i| (format!("c{i}"), small)).collect(); - let map = classed_point_map(classes, small); - let opts = || LegendOptions { show_no_data: false, hide_other: true, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - let rows = legend_rows(&map, None, &opts()); - let (starts, _) = flow(&rows, 2, LEGEND_ROW, (1e6, 1.0)); - assert_eq!(starts, vec![0, 2]); - let first = widest(column_parts(&rows, &starts).next().unwrap(), (1e6, 1.0)); - let drawn_in_first = |columns: usize| { - let mut pm = Pixmap::new(300, 15).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - crate::canvas::with_canvas(&mut pm, |c| { - legend(c, Rect::from_xywh(0.0, 0.0, 300.0, LEGEND_ROW).unwrap(), &map, ("", columns), None, opts(), 1.0); - }); - (0..first as u32).any(|x| (0..15).any(|y| pm.pixel(x, y).is_some_and(|p| p.red() < 200))) - }; - assert!(drawn_in_first(1), "one column draws the name alone"); - assert!(!drawn_in_first(2), "two columns keep it with its class"); - } - - /// A large point symbol makes its row taller and widens its column's symbols only: the columns - /// balance what the rows take, and the other column stays as narrow as its labels let it. - #[test] - fn a_legends_columns_hold_large_point_symbols() { - let small = rustgis_map::Symbol { size: 4.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; - let classes = - (0u32..10).map(|i| (format!("c{i}"), rustgis_map::Symbol { size: if i < 2 { 40.0 } else { 4.0 }, ..small })).collect(); - let map = classed_point_map(classes, small); - let opts = LegendOptions { show_no_data: false, hide_other: true, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - let rows = legend_rows(&map, None, &opts); - let tall = rows[1].height(1e6, 1.0); - assert!(tall > 2.0 * LEGEND_ROW, "{tall}"); - // The name and the two large symbols, then the eight small ones: counted row by row, these - // would be split at the middle. - let (starts, height) = balanced(&rows, 2, (1e6, 1.0)); - assert_eq!(starts, vec![0, 3], "{height}"); - assert_eq!(height, 8.0 * LEGEND_ROW); - let parts: Vec<_> = column_parts(&rows, &starts).collect(); - assert!( - widest(parts[1], (1e6, 1.0)) < widest(parts[0], (1e6, 1.0)) - 20.0, - "{} and {}", - widest(parts[0], (1e6, 1.0)), - widest(parts[1], (1e6, 1.0)) - ); - // In one column, the small rows' labels line up with the large symbols' as before. - assert_eq!( - widest(&rows, (1e6, 1.0)), - widest(parts[0], (1e6, 1.0)).max(swatch_column(&rows, (1e6, 1.0)) + 12.0 + widest_label(parts[1])) - ); - } - - /// A legend shows a layer under the label it gives it, by the layer's name in any case (#1654): - /// a plain layer's row and a classed layer's heading; it measures and draws the label, so its - /// size follows it. A layer it gives no label, or a blank one, shows its name. - #[test] - fn a_legend_shows_a_layers_label() { - use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; - let mut map = Map::new("m"); - let long = "BrasilData: Setores censitários 2022 (MG)"; - map.add_dataset(Dataset::new(long, GeometryType::Point, vec![])); - let mut d = Dataset::new("pts", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); - d.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text("a".into())]); - let pts = map.add_dataset(d); - if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) { - l.renderer = rustgis_map::Renderer::Unique { - field: "g".into(), - classes: vec![("a".into(), rustgis_map::Symbol::default_for(GeometryType::Point, 0))], - other: rustgis_map::Symbol::default_for(GeometryType::Point, 1), - ramp: rustgis_map::Ramp::Ember, - class_labels: Default::default(), - other_label: None, - class_strokes: Default::default(), - other_strokes: Vec::new(), - class_fills: Default::default(), - other_fills: Vec::new(), - expression: None, - }; - } - let labels = - |pairs: &[(&str, &str)]| -> BTreeMap { pairs.iter().map(|(n, l)| (n.to_string(), l.to_string())).collect() }; - let names = |labels: &BTreeMap| -> Vec { - let opts = LegendOptions { show_no_data: false, hide_other: true, exclude: &[], labels, scale: 1e6, size: 1.0 }; - legend_rows(&map, None, &opts) - .iter() - .filter_map(|r| match r { - LegendRow::Head(n) | LegendRow::Plain(_, n) => Some(n.to_string()), - _ => None, - }) - .collect() - }; - // Top first: pts over the long-named layer. - assert_eq!(names(&NO_LABELS), ["pts", long]); - let short = labels(&[("brasildata: Setores censitários 2022 (mg)", "Setores"), ("PTS", "Pontos")]); - assert_eq!(names(&short), ["Pontos", "Setores"], "by name, any case"); - assert_eq!(names(&labels(&[("pts", " ")])), ["pts", long], "a blank label shows the name"); - assert_eq!(names(&labels(&[("Atlantis", "x")])), ["pts", long], "a label for no layer of the map changes nothing"); - // Its size: narrower with the short label, wider with a long one; as tall either way. - let size = |labels: &BTreeMap| legend_sizes_mm(&mut map.clone(), 1e6, true, true, (&[], labels)).unwrap()[0]; - let (named, labelled) = (size(&NO_LABELS), size(&short)); - let wide = size(&labels(&[(long, "Setores censitários do Censo Demográfico de 2022 em Minas Gerais")])); - assert!(labelled.0 < named.0 - 20.0 && wide.0 > named.0 + 20.0, "{labelled:?} {named:?} {wide:?}"); - assert!((labelled.1 - named.1).abs() < 1e-9 && (wide.1 - named.1).abs() < 1e-9); - // Drawn: the label, which ends within the width measured for it. - let reach = |labels: &BTreeMap| { - let mut pm = Pixmap::new(400, 200).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let opts = LegendOptions { show_no_data: false, hide_other: true, exclude: &[], labels, scale: 1e6, size: 1.0 }; - crate::canvas::with_canvas(&mut pm, |c| { - legend(c, Rect::from_xywh(0.0, 0.0, 400.0, 200.0).unwrap(), &map, ("", 1), None, opts, 1.0) - }); - let right = (0..pm.width()).filter(|&x| (0..pm.height()).any(|y| pm.pixel(x, y).is_some_and(|p| p.red() < 200))).max(); - f64::from(right.unwrap_or(0)) * 25.4 / 96.0 - }; - for (labels, (w, _)) in [(&NO_LABELS, named), (&short, labelled)] { - let right = reach(labels); - assert!(right <= w + 0.3 && right > w - 1.5, "{right} mm drawn across {w} mm"); - } - } - - #[test] - fn legends_leave_out_what_the_frame_does_not_draw() { - use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; - // A layer with one feature, of class "a", classed a, b and c; and an empty layer. - let mut map = Map::new("m"); - let mut d = Dataset::new("pts", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); - d.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text("a".into())]); - let pts = map.add_dataset(d); - map.add_dataset(Dataset::new("empty", GeometryType::Point, vec![])); - let s = |c| rustgis_map::Symbol::default_for(GeometryType::Point, c); - if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) { - let classes = ["a", "b", "c"].iter().zip(0u32..).map(|(k, i)| (k.to_string(), s(i))).collect(); - l.renderer = rustgis_map::Renderer::Unique { - field: "g".into(), - classes, - other: s(3), - ramp: rustgis_map::Ramp::Ember, - class_labels: Default::default(), - other_label: None, - class_strokes: Default::default(), - other_strokes: Vec::new(), - class_fills: Default::default(), - other_fills: Vec::new(), - expression: None, - }; - } - // How far down the legend draws, in pixels. - let depth_without = |map: &Map, drawn: Option<&[(u32, Vec)]>, hide_other: bool, exclude: &[String]| { - let mut pm = Pixmap::new(300, 400).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let opts = LegendOptions { show_no_data: false, hide_other, exclude, labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - crate::canvas::with_canvas(&mut pm, |c| { - legend(c, Rect::from_xywh(0.0, 0.0, 300.0, 400.0).unwrap(), map, ("", 1), drawn, opts, 1.0) - }); - (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| pm.pixel(x, y).is_some_and(|p| p.red() < 200))).max().unwrap_or(0) - }; - let depth = |map: &Map, drawn: Option<&[(u32, Vec)]>, hide_other: bool| depth_without(map, drawn, hide_other, &[]); - let drawn = shown_legends(&map, 1e6, false, &Env::default()); - assert_eq!(drawn.len(), 1, "the empty layer draws nothing: {drawn:?}"); - let (shown, all) = (depth(&map, Some(&drawn), false), depth(&map, None, false)); - // The drawn legend is two rows (the layer's heading and "a"); every class makes it six - // (b, c, and the empty layer's row too). Compared with each other, so - // the font and antialiasing don't matter. - assert!(shown > 0, "the drawn class is listed"); - assert!(all >= 2 * shown, "{shown} px of {all}"); - // The size a legend takes holds what it draws, to within a row: two rows drawn, six with - // every class. - let row = f64::from(LEGEND_ROW) * 25.4 / 96.0; - // How far right the legend draws, in pixels (points at this scale), as `depth` goes down. - let reach = |map: &Map, drawn: Option<&[(u32, Vec)]>| { - let mut pm = Pixmap::new(300, 400).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - crate::canvas::with_canvas(&mut pm, |c| { - legend( - c, - Rect::from_xywh(0.0, 0.0, 300.0, 400.0).unwrap(), - map, - ("", 1), - drawn, - LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }, - 1.0, - ) - }); - (0..pm.width()).filter(|&x| (0..pm.height()).any(|y| pm.pixel(x, y).is_some_and(|p| p.red() < 200))).max().unwrap_or(0) - }; - for (all_classes, ink, right) in [(false, shown, reach(&map, Some(&drawn))), (true, all, reach(&map, None))] { - let (w, h) = legend_sizes_mm(&mut map, 1e6, all_classes, false, (&[], &NO_LABELS)).unwrap()[0]; - let (ink, right) = (f64::from(ink) * 25.4 / 96.0, f64::from(right) * 25.4 / 96.0); - assert!(w > 0.0 && ink <= h && h - ink < row, "{ink} mm drawn in {h} mm"); - // The widths in the same units as the drawing: the ink ends within the width measured, - // short of it by no more than a glyph's side bearing. - assert!(right <= w + 0.3 && right > w - 1.5, "{right} mm drawn across {w} mm"); - } - assert!((legend_sizes_mm(&mut map, 1e6, false, false, (&[], &NO_LABELS)).unwrap()[0].1 - 2.0 * row).abs() < 1e-9); - // A layer the legend leaves out (by name, any case) isn't listed, drawn or not. - let name = map.layer(pts).unwrap().name.to_uppercase(); - assert_eq!(depth_without(&map, Some(&drawn), false, std::slice::from_ref(&name)), 0, "its only drawn layer left out"); - let rest = depth_without(&map, None, false, &[name]); - assert!(rest > 0 && rest < all, "the other layer is still listed: {rest} px of {all}"); - // Hiding takes one row off the full legend, and nothing off the drawn - // one, which has none. - assert!(depth(&map, None, true) < all); - assert_eq!(depth(&map, Some(&drawn), true), shown); - // A layer whose drawn features all fall in , hidden, is left out rather - // than drawn as a plain swatch. - if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) - && let rustgis_map::Renderer::Unique { classes, .. } = &mut l.renderer - { - classes.retain(|(k, _)| k != "a"); - } - let drawn = shown_legends(&map, 1e6, false, &Env::default()); - assert!(depth(&map, Some(&drawn), false) > 0, " alone is listed"); - assert_eq!(depth(&map, Some(&drawn), true), 0, "and hidden, the layer is left out"); - // So is one whose drawn features all fall in a fully transparent , - // rather than drawn as a plain swatch of its first feature. - let set_other_alpha = |map: &mut Map, a: u8| { - if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) - && let rustgis_map::Renderer::Unique { other, .. } = &mut l.renderer - { - other.fill = other.fill.with_alpha(a); - other.stroke = other.stroke.with_alpha(a); - } - }; - set_other_alpha(&mut map, 0); - let drawn = shown_legends(&map, 1e6, false, &Env::default()); - assert_eq!(depth(&map, Some(&drawn), false), 0, "the invisible fallback stands for nothing"); - set_other_alpha(&mut map, 255); - // A class that bears the fallback's name is a class: hiding the fallback keeps it. - if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) - && let rustgis_map::Renderer::Unique { classes, .. } = &mut l.renderer - { - classes.push(("a".into(), s(0))); - classes.iter_mut().for_each(|(k, _)| { - if k == "a" { - *k = rustgis_map::symbology::OTHER_VALUES.into(); - } - }); - } - if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) { - l.dataset.features.iter_mut().for_each(|f| f.attrs = vec![Value::Text(rustgis_map::symbology::OTHER_VALUES.into())]); - } - let drawn = shown_legends(&map, 1e6, false, &Env::default()); - assert!(depth(&map, Some(&drawn), true) > 0, "the class named like the fallback is still listed"); - // A Graduated layer with no classes still shows its plain swatch, as before #207. - if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) { - l.renderer = rustgis_map::Renderer::Graduated { - field: "g".into(), - breaks: Vec::new(), - symbols: Vec::new(), - ramp: rustgis_map::Ramp::Ember, - method: rustgis_map::ClassMethod::NaturalBreaks, - min: 0.0, - classes: 0, - class_labels: Default::default(), - class_strokes: Default::default(), - class_fills: Default::default(), - }; - } - map.layers.retain(|l| l.id == pts); - assert!(depth(&map, None, false) > 0, "the empty Graduated layer is listed"); - } - - /// A layout with one map frame on `map` and a colorbar of its first raster, by name (one drawn by - /// classes isn't a colorbar's by default, #1679), at 10–90 × 10–30 mm (a vertical one at 10–30 × - /// 10–90 mm), drawn at 96 dpi. - fn colorbar_page(map: &Map, orientation: Orientation, reverse: bool, title: &str) -> Pixmap { - let mut l = Layout::new("Layout", 100.0, 100.0); - let frame = l.add( - "Map", - (95.0, 95.0, 4.0, 4.0), - ElementKind::MapFrame { - map: map.name.clone(), - center: Coord::new(0.0, 0.0), - scale: 1e8, - shape: FrameShape::Rectangle, - grid: None, - extent_of: None, - extent_color: rustgis_map::layout::INDICATOR_COLOR, - extent_width: rustgis_map::layout::INDICATOR_WIDTH, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }, - ); - let rect = if orientation == Orientation::Vertical { (10.0, 10.0, 20.0, 80.0) } else { (10.0, 10.0, 80.0, 20.0) }; - let layer = map.layers.iter().find(|l| l.is_raster()).map(|l| l.name.clone()); - let kind = ElementKind::Colorbar { - frame, - layer, - title: title.into(), - orientation, - ticks: 5, - tick_side: TickSide::End, - reverse, - color: None, - }; - l.add("Colorbar", rect, kind); - render(&l, &mut [map.clone()], 96.0, &PageInfo::default()).unwrap() - } - - /// A page whose frame draws a layer without its cast shadows says why, named by the layer; one - /// with them, or without any asked for, says nothing. - #[test] - fn a_page_says_why_a_frame_drew_no_cast_shadows() { - let relief = |shadow| rustgis_map::raster::RasterRenderer::ShadedRelief { - band: 0, - ramp: None, - azimuth: 315.0, - altitude: 30.0, - z_factor: 1.0, - shadow, - sky: 0.0, - fill: 0.0, - rock: None, - ambient: None, - balanced: false, - }; - for shadow in [0.0, 1.0] { - let map = ramp_map(relief(shadow), rustgis_map::raster::Stretch::MinMax); - let (_, said) = crate::shadows_said(|| colorbar_page(&map, Orientation::Horizontal, false, "")); - assert!(said.notices.is_empty() && !said.to_come, "shadow {shadow}: {said:?}"); - } - // Read in place with only its overview held: no whole grid to trace. - let mut map = ramp_map(relief(1.0), rustgis_map::raster::Stretch::MinMax); - let rl = map.layers.iter_mut().find_map(|l| l.raster.as_mut()).unwrap(); - rl.in_place = true; - let mut r = (**rl.data.as_ref().unwrap()).clone(); - r.overview = Some((1000, 10)); - rl.data = Some(std::sync::Arc::new(r)); - let (_, said) = crate::shadows_said(|| colorbar_page(&map, Orientation::Horizontal, false, "")); - let said = said.notices; - assert_eq!(said.len(), 1, "{said:?}"); - assert!(said[0].starts_with("dem: ") && said[0].contains("read in place"), "{said:?}"); - // What the map view's frame said is not a page's: a clean page drawn after it says nothing. - let camera = - rustgis_map::Camera { center: rustgis_geom::lonlat_to_merc(Coord::new(0.5, 0.5)), res: 2000.0, bearing: 0.0, pitch: 0.0 }; - crate::render(&mut map, &crate::View { width: 64.0, height: 64.0, pixels_per_point: 1.0, camera, sky: false }); - let clean = ramp_map(relief(0.0), rustgis_map::raster::Stretch::MinMax); - let (_, said) = crate::shadows_said(|| colorbar_page(&clean, Orientation::Horizontal, false, "")); - assert!(said.notices.is_empty(), "{said:?}"); - } - - /// A page with maps showing copies of one relief (each layer the first of its map, so with the - /// same id), each under its own sun, drawn again until it has no shadows to come, as the - /// Layout view draws it while they land. Panics if it never settles. - fn page_settles_with_suns(suns: &[f64]) { - use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; - let n = 300usize; - let heights: Vec = (0..n * n).map(|i| (((i % n) as f32 / 9.0).sin() + ((i / n) as f32 / 7.0).cos()) * 400.0).collect(); - let gt = GeoTransform { origin_x: -1.0, origin_y: 1.0, pixel_width: 2.0 / n as f64, pixel_height: -2.0 / n as f64 }; - let dem = Raster::new("dem", n as u32, n as u32, vec![heights], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); - let rl = rustgis_map::raster::RasterLayer::from_path(dem, "dem.tif"); - let mut maps = Vec::new(); - let mut l = Layout::new("Layout", 100.0, 100.0); - for (i, azimuth) in suns.iter().enumerate() { - let name = format!("m{i}"); - let mut copy = rl.clone(); - copy.style.renderer = rustgis_map::raster::RasterRenderer::ShadedRelief { - band: 0, - ramp: None, - azimuth: *azimuth, - altitude: 10.0, - z_factor: 1.0, - shadow: 1.0, - sky: 0.0, - fill: 0.0, - rock: None, - ambient: None, - balanced: false, - }; - let mut m = Map::new(name.clone()); - assert_eq!(m.add_raster("dem", copy), 1); - maps.push(m); - let frame = ElementKind::MapFrame { - map: name.clone(), - center: Coord::new(0.0, 0.0), - scale: 1e7, - shape: FrameShape::Rectangle, - grid: None, - extent_of: None, - extent_color: rustgis_map::layout::INDICATOR_COLOR, - extent_width: rustgis_map::layout::INDICATOR_WIDTH, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }; - l.add(&name, (5.0 + 20.0 * i as f64, 5.0, 18.0, 18.0), frame); - } - let start = std::time::Instant::now(); - loop { - let (drawn, said) = crate::shadows_said(|| render_pending(&l, &mut maps, 48.0, &PageInfo::default())); - drawn.unwrap(); - assert!(said.notices.is_empty(), "{said:?}"); - if !said.to_come { - break; - } - assert!(start.elapsed() < std::time::Duration::from_secs(60), "the page never got its shadows"); - std::thread::yield_now(); - } - } - - /// Two maps lit otherwise on a page: neither map's grid stops the other's. - #[test] - fn two_maps_lit_otherwise_on_a_page_keep_their_own_shadows() { - page_settles_with_suns(&[315.0, 135.0]); - } - - /// More maps lit otherwise than the grids kept for going back: none is let go while it is drawn. - #[test] - fn many_maps_lit_otherwise_on_a_page_all_get_their_shadows() { - page_settles_with_suns(&[315.0, 135.0, 45.0, 225.0, 0.0]); - } - - /// A map with one 100 × 1 raster valued 0–99 by column, styled by `renderer`. - fn ramp_map(renderer: rustgis_map::raster::RasterRenderer, stretch: rustgis_map::raster::Stretch) -> Map { - use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; - let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 0.01, pixel_height: -0.01 }; - let data: Vec = (0..100).map(|i| i as f32).collect(); - let r = Raster::new("dem", 100, 1, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); - let mut rl = rustgis_map::raster::RasterLayer::from_path(r, "dem.tif"); - rl.style.renderer = renderer; - rl.style.stretch = stretch; - let mut map = Map::new("m"); - map.add_raster("dem", rl); - map - } - - /// A map with a land cover raster of `n` classes (values 1 to `n`, one cell each) drawn by its - /// colour table, the first named "Forest". - fn classes_map(n: u8) -> Map { - use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; - let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 0.01, pixel_height: -0.01 }; - let mut palette = vec![[0, 0, 0, 0]; 256]; - for v in 1..=n { - palette[usize::from(v)] = [v, 255 - v, 128, 255]; - } - let data: Vec = (1..=n).map(f32::from).collect(); - let mut r = Raster::new("lc", u32::from(n), 1, vec![data], gt, Crs::LonLat, None, ColorHint::Palette(palette), "UInt8").unwrap(); - r.bands[0].classes = vec![String::new(), "Forest".into()]; - let mut rl = rustgis_map::raster::RasterLayer::from_path(r, "lc.tif"); - rl.style.renderer = rustgis_map::raster::RasterRenderer::Colormap; - let mut map = Map::new("m"); - map.add_raster("Land cover", rl); - map - } - - /// A classified raster's legend: its name over its classes, as the Layers pane lists them, by - /// what the frame shows and with every class alike (a colour table lists the values it holds); - /// left out by name; a raster on a ramp isn't listed (#1679). - #[test] - fn a_legend_lists_a_classified_rasters_classes() { - let mut map = classes_map(5); - let opts = LegendOptions { show_no_data: false, hide_other: true, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - let labels = |rows: &[LegendRow]| -> Vec { - rows.iter() - .map(|r| match r { - LegendRow::Head(name) => format!("[{name}]"), - LegendRow::Class(_, en) => en.label.clone(), - LegendRow::Plain(_, name) => format!("plain {name}"), - LegendRow::Picture(_) => "picture".into(), - }) - .collect() - }; - let want = ["[Land cover]", "Forest", "2", "3", "4", "5"]; - assert_eq!(labels(&legend_rows(&map, None, &opts)), want); - let drawn = shown_legends(&map, 1e6, false, &Env::default()); - assert_eq!(labels(&legend_rows(&map, Some(&drawn), &opts)), want); - // Its swatches are the pane's colours. - let pane: Vec = map.layers[0] - .raster - .as_ref() - .unwrap() - .legend() - .into_iter() - .filter_map(|e| match e { - rustgis_map::raster::RasterLegend::Class { color, .. } => Some(color), - _ => None, - }) - .collect(); - let swatches: Vec = legend_rows(&map, None, &opts) - .iter() - .filter_map(|r| if let LegendRow::Class(_, en) = r { Some(en.symbol.fill) } else { None }) - .collect(); - assert_eq!(swatches, pane); - // Sized by its rows: its name and five classes. - let mm = 25.4 / 96.0; - let [(_, h), ..] = legend_sizes_mm(&mut map, 1e6, false, false, (&[], &NO_LABELS)).unwrap(); - assert!((h - 6.0 * f64::from(LEGEND_ROW) * mm).abs() < 1e-6, "{h} mm"); - let labelled = BTreeMap::from([("Land cover".to_string(), "Classes do MapBiomas".to_string())]); - let opts_labelled = LegendOptions { labels: &labelled, ..opts }; - assert_eq!(labels(&legend_rows(&map, None, &opts_labelled))[0], "[Classes do MapBiomas]"); - // Left out by name, or when hidden. - let exclude = ["land cover".to_string()]; - assert!(legend_rows(&map, None, &LegendOptions { exclude: &exclude, ..opts }).is_empty()); - map.layers[0].visible = false; - assert!(shown_legends(&map, 1e6, false, &Env::default()).is_empty()); - assert!(legend_rows(&map, None, &opts).is_empty()); - // A raster on a ramp: a colorbar keys it, the legend doesn't list it. - let ramp = ramp_map( - rustgis_map::raster::RasterRenderer::Stretch { band: 0, ramp: rustgis_map::Ramp::Harbour, invert: false }, - rustgis_map::raster::Stretch::MinMax, - ); - assert!(legend_rows(&ramp, None, &opts).is_empty() && shown_legends(&ramp, 1e6, false, &Env::default()).is_empty()); - } - - /// A drawn legend fills each class's swatch with its colour, under the raster's name. - #[test] - fn a_drawn_legend_fills_a_raster_class_with_its_colour() { - let map = classes_map(5); - let pm = point_legend(&map); - for v in 1..=5u8 { - let c = (v, 255 - v, 128); - let found = pm.pixels().iter().any(|p| (p.red(), p.green(), p.blue()) == c); - assert!(found, "class {v}'s colour {c:?}"); - } - } - - /// A page with a main frame and an inset (5–55 mm) that outlines it in `color` at `width`. - fn indicator_page(color: Rgba, width: f64) -> Pixmap { - let map = Map::new("m"); - let frame = |center, scale, extent_of| ElementKind::MapFrame { - map: "m".into(), - center, - scale, - shape: FrameShape::Rectangle, - grid: None, - extent_of, - extent_color: color, - extent_width: width, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }; - let mut l = Layout::new("Layout", 100.0, 100.0); - let main = l.add("Main", (60.0, 60.0, 30.0, 30.0), frame(Coord::new(20.0, 10.0), 5e7, None)); - l.add("Inset", (5.0, 5.0, 50.0, 50.0), frame(Coord::new(0.0, 0.0), 2e8, Some(main))); - render(&l, &mut [map], 96.0, &PageInfo::default()).unwrap() - } - - /// Pixels inside the inset (5–55 mm) close to `c`. - fn inset_pixels(pm: &Pixmap, c: Rgba) -> usize { - let k = PT_PER_MM; - let near = |p: (u8, u8, u8)| p.0.abs_diff(c.r()) < 40 && p.1.abs_diff(c.g()) < 40 && p.2.abs_diff(c.b()) < 40; - ((5.0 * k) as u32..(55.0 * k) as u32) - .flat_map(|y| ((5.0 * k) as u32..(55.0 * k) as u32).map(move |x| (x, y))) - .filter(|&(x, y)| near(rgb(pm, x, y))) - .count() - } - - /// One line of black text drawn in a white 400 × 60 px box with `style`. - fn styled_line(style: TextStyle) -> Pixmap { - let mut pm = Pixmap::new(400, 60).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let r = Rect::from_xywh(0.0, 0.0, 400.0, 60.0).unwrap(); - crate::canvas::with_canvas(&mut pm, |c| text_block(c, r, "Oceano Atlântico", 20.0, Rgba::rgb(0, 0, 0), style, 1.0)); - pm - } - - /// The leftmost and rightmost inked columns, and the inked column nearest the left at the - /// top and at the bottom of the letters. - fn text_ink(pm: &Pixmap) -> (u32, u32, u32, u32) { - let dark = |x: u32, y: u32| rgb(pm, x, y).0 < 128; - let rows: Vec = (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| dark(x, y))).collect(); - let (top, bottom) = (rows[0], rows[rows.len() - 1]); - let cols: Vec = (0..pm.width()).filter(|&x| (0..pm.height()).any(|y| dark(x, y))).collect(); - let first = |y: u32| (0..pm.width()).find(|&x| dark(x, y)).unwrap_or(0); - (cols[0], cols[cols.len() - 1], first(top + 1), first(bottom - 1)) - } - - /// The height of the inked rows. - fn text_height(pm: &Pixmap) -> u32 { - let rows: Vec = (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| rgb(pm, x, y).0 < 128)).collect(); - rows[rows.len() - 1] - rows[0] - } - - /// A page with `kind` in (10, 10, 80, 30) mm on white. - fn shape_page(kind: ElementKind) -> Layout { - let mut l = Layout::new("L", 100.0, 50.0); - l.add("Shape", (10.0, 10.0, 80.0, 30.0), kind); - l - } - - /// The runs of inked and blank pixels along a row (or a column) from `from` to `to`: how many - /// times it goes from ink to blank. - fn gaps(pm: &Pixmap, along: impl Iterator) -> usize { - let ink: Vec = along.map(|(x, y)| rgb(pm, x, y).0 < 128).collect(); - ink.windows(2).filter(|w| w[0] && !w[1]).count() - } - - /// A dashed line has gaps where its pattern says, its arrowhead solid; a dashed rectangle's - /// outline has gaps on all four sides; solid, both draw as before (#1763). - #[test] - fn dashed_lines_and_outlines_have_gaps() { - use rustgis_map::layout::LineDir; - let black = Rgba::rgb(0, 0, 0); - let dash = rustgis_map::symbology::Dash::new(&[6.0, 6.0]); - let png = |kind: ElementKind| render(&shape_page(kind), &mut [], 96.0, &PageInfo::default()).unwrap(); - // 96 dpi: 1 mm is 3.78 px. The line runs along y = 25 mm from x = 10 to 90 mm. - let px = |mm: f64| (mm * 96.0 / 25.4).round() as u32; - let line = |dash, head| ElementKind::Line { color: black, width: 2.0, dir: LineDir::Horizontal, head, dash }; - let along = |pm: &Pixmap| gaps(pm, (px(11.0)..px(80.0)).map(|x| (x, px(25.0)))); - assert_eq!(along(&png(line(None, LineHead::None))), 0, "solid"); - // 69 mm is about 261 points (PT_PER_MM): a 12-point round each, so some 22 gaps. - let dashed = png(line(dash, LineHead::End)); - assert!((20..=24).contains(&along(&dashed)), "{} gaps", along(&dashed)); - // The head (the last 6 + 2.5 × 2 = 11 points, 2.9 mm) is filled: no gap across it. - assert_eq!(gaps(&dashed, (px(87.5)..px(89.8)).map(|x| (x, px(25.0)))), 0, "the arrowhead stays solid"); - let rect = |dash| ElementKind::Rectangle { fill: Rgba::new(0, 0, 0, 0), outline: black, width: 2.0, radius: 0.0, dash }; - let sides = |pm: &Pixmap| { - let (x0, x1, y0, y1) = (px(10.0), px(90.0), px(10.0), px(40.0)); - [ - gaps(pm, (x0 + 4..x1 - 4).map(|x| (x, y0))), - gaps(pm, (x0 + 4..x1 - 4).map(|x| (x, y1))), - gaps(pm, (y0 + 4..y1 - 4).map(|y| (x0, y))), - gaps(pm, (y0 + 4..y1 - 4).map(|y| (x1, y))), - ] - }; - assert_eq!(sides(&png(rect(None))), [0; 4], "solid"); - let dashed = sides(&png(rect(dash))); - assert!(dashed.iter().all(|g| *g >= 3), "gaps on every side: {dashed:?}"); - let oval = |dash| ElementKind::Ellipse { fill: Rgba::new(0, 0, 0, 0), outline: black, width: 2.0, dash }; - // Round its outline: the ellipse fills (10, 10, 80, 30) mm. - let round = |pm: &Pixmap| { - let px = |mm: f64| mm * 96.0 / 25.4; - // Inked where any pixel within one of the curve's point is: the 2-point stroke is about - // 2 pixels wide. - let near = |(x, y): (f64, f64)| { - (-1..=1).any(|dx| (-1..=1).any(|dy| rgb(pm, (x.round() as i32 + dx) as u32, (y.round() as i32 + dy) as u32).0 < 128)) - }; - let ink: Vec = (0..2000) - .map(|i| f64::from(i) / 2000.0 * std::f64::consts::TAU) - .map(|t| near((px(50.0 + 40.0 * t.cos()), px(25.0 + 15.0 * t.sin())))) - .collect(); - ink.windows(2).filter(|w| w[0] && !w[1]).count() - }; - assert_eq!(round(&png(oval(None))), 0, "solid"); - assert!(round(&png(oval(dash))) >= 20, "{}", round(&png(oval(dash)))); - } - - /// A dashed box round a turned text, on one page (#1763): the picture has the box's gaps and - /// the text running down the page inside it; the recorded page (the PDF's) keeps the dashes as - /// pieces and the text as glyphs; the SVG writes the dash array and the turn. - #[test] - fn a_dashed_box_and_a_turned_text_share_a_page() { - use crate::vector::Item; - // The text's box (10, 45, 80, 10) mm turned 90° about (50, 50): 45..55 across, 10..90 down. - let mut layout = turned_text_page(90.0); - let dash = rustgis_map::symbology::Dash::new(&[6.0, 6.0]); - let outline = Rgba::rgb(0, 0, 0); - layout.add( - "Box", - (5.0, 5.0, 90.0, 90.0), - ElementKind::Rectangle { fill: Rgba::new(0, 0, 0, 0), outline, width: 2.0, radius: 0.0, dash }, - ); - let info = PageInfo::default(); - let png = render(&layout, &mut [], 96.0, &info).unwrap(); - let px = |mm: f64| (mm * 96.0 / 25.4).round() as u32; - assert!(gaps(&png, (px(10.0)..px(90.0)).map(|x| (x, px(5.0)))) >= 3, "the box's top is dashed"); - // Inside the box: the text, tall and narrow about x = 50 mm. - let inside: Vec<(u32, u32)> = - (px(8.0)..px(92.0)).flat_map(|y| (px(8.0)..px(92.0)).map(move |x| (x, y))).filter(|&(x, y)| rgb(&png, x, y).0 < 128).collect(); - let (l, r) = (inside.iter().map(|p| p.0).min().unwrap(), inside.iter().map(|p| p.0).max().unwrap()); - let (t, b) = (inside.iter().map(|p| p.1).min().unwrap(), inside.iter().map(|p| p.1).max().unwrap()); - assert!(b - t > 4 * (r - l) && l > px(44.0) && r < px(56.0), "the text runs down the page: {l},{t} to {r},{b}"); - let (drawing, _) = render_drawing(&layout, &mut [], 96.0, &info).unwrap(); - let (_, _, items) = drawing.finish(); - let items = crate::vector::without_layers(items); - let pieces: usize = items - .iter() - .filter_map(|i| if let Item::Stroke { path, .. } = i { Some(path) } else { None }) - .map(|p| p.segments().filter(|s| matches!(s, tiny_skia::PathSegment::MoveTo(_))).count()) - .sum(); - let text: String = items - .iter() - .filter_map(|i| if let Item::Glyphs(r) = i { Some(r) } else { None }) - .flat_map(|r| r.glyphs.iter().map(|g| g.ch)) - .collect(); - assert!(pieces > 20 && text == "Fonte: IBGE, 2022", "{pieces} dashes, text {text:?}"); - let svg = crate::svg::layout_svg(&layout, &mut [], 96.0, &info).unwrap().0; - assert!(svg.contains("stroke-dasharray") && svg.contains(r#"transform="rotate(90 50 50)""#), "{svg}"); - } - - /// A dashed outline is kept as vectors, its dashes as the pieces of the path (as a dashed line - /// layer's are), which draw what its picture shows (#1763). - #[test] - fn a_dashed_outline_is_kept_as_its_dashes() { - use crate::vector::Item; - let dash = rustgis_map::symbology::Dash::new(&[6.0, 6.0]); - let kind = ElementKind::Rectangle { fill: Rgba::new(0, 0, 0, 0), outline: Rgba::rgb(0, 0, 0), width: 2.0, radius: 0.0, dash }; - let layout = shape_page(kind); - let info = PageInfo::default(); - let png = render(&layout, &mut [], 96.0, &info).unwrap(); - let (drawing, _) = render_drawing(&layout, &mut [], 96.0, &info).unwrap(); - let (_, _, items) = drawing.finish(); - let items = crate::vector::without_layers(items); - let pieces: usize = items - .iter() - .filter_map(|i| if let Item::Stroke { path, .. } = i { Some(path) } else { None }) - .map(|p| p.segments().filter(|s| matches!(s, tiny_skia::PathSegment::MoveTo(_))).count()) - .sum(); - assert!(pieces > 20, "{pieces} dashes kept"); - let mut replayed = Pixmap::new(png.width(), png.height()).unwrap(); - replayed.fill(tiny_skia::Color::WHITE); - crate::vector::replay(&items, &mut replayed, Transform::identity()); - let differ = png.pixels().iter().zip(replayed.pixels()).filter(|(a, b)| a.red().abs_diff(b.red()) > 48).count(); - assert!(differ < 50, "{differ} pixels differ"); - } - - /// A page with one text element in (10, 45, 80, 10) mm, turned `turn` degrees. - fn turned_text_page(turn: f64) -> Layout { - let mut l = Layout::new("L", 100.0, 100.0); - let mut kind = ElementKind::text("Fonte: IBGE, 2022", 14.0, Rgba::rgb(0, 0, 0), false); - if let ElementKind::Text { rotation, .. } = &mut kind { - *rotation = turn; - } - l.add("Source", (10.0, 45.0, 80.0, 10.0), kind); - l - } - - /// The dark pixels' bounds: left, top, right, bottom. - fn ink_bounds(pm: &Pixmap) -> (u32, u32, u32, u32) { - let dark: Vec<(u32, u32)> = - (0..pm.height()).flat_map(|y| (0..pm.width()).map(move |x| (x, y))).filter(|&(x, y)| rgb(pm, x, y).0 < 128).collect(); - let xs = dark.iter().map(|p| p.0); - let ys = dark.iter().map(|p| p.1); - (xs.clone().min().unwrap(), ys.clone().min().unwrap(), xs.max().unwrap(), ys.max().unwrap()) - } - - /// A page with `text` at 12 pt in (10, 10, 40, 60) mm, wrapped to its box or not (#2346), - /// aligned `align` and turned `turn` degrees. - fn note_page(text: &str, wrap: bool, align: TextAlign, turn: f64) -> Layout { - let mut l = Layout::new("L", 100.0, 100.0); - let mut kind = ElementKind::text(text, 12.0, Rgba::rgb(0, 0, 0), false); - if let ElementKind::Text { wrap: w, align: a, rotation, .. } = &mut kind { - (*w, *a, *rotation) = (wrap, align, turn); - } - l.add("Note", (10.0, 10.0, 40.0, 60.0), kind); - l - } - - const NOTE: &str = "Population counts from the 2020 census; boundaries simplified for print"; - - /// A wrapped text breaks at spaces into lines that stay within its box's width, whichever - /// its alignment; unwrapped, the same sentence runs past the box as it always has (#2346). - #[test] - fn a_wrapped_text_breaks_into_lines_that_fit_its_box() { - let mm = 96.0 / 25.4; - let (left, right) = (10.0 * mm, 50.0 * mm); - let ink = |l: &Layout| ink_bounds(&render(l, &mut [], 96.0, &PageInfo::default()).unwrap()); - let (_, t, r, b) = ink(¬e_page(NOTE, false, TextAlign::Left, 0.0)); - assert!(f64::from(r) > right + 40.0, "unwrapped, it runs past the box: {r}"); - let line = b - t; - for align in TextAlign::ALL { - let (l, t, r, b) = ink(¬e_page(NOTE, true, align, 0.0)); - assert!(f64::from(l) >= left - 2.0 && f64::from(r) <= right + 2.0, "{align:?}: inked {l}..{r} in {left}..{right}"); - assert!(b - t > 3 * line, "{align:?}: in several lines, {t}..{b}"); - } - // A word wider than the box (an address) is broken across lines, kept within it. - let url = "https://example.org/data/population/census-2020/boundaries-simplified.zip"; - let (l, t, r, b) = ink(¬e_page(url, true, TextAlign::Left, 0.0)); - assert!(f64::from(l) >= left - 2.0 && f64::from(r) <= right + 2.0 && b - t > 2 * line, "{l},{t} to {r},{b}"); - // Its own line breaks are kept: a blank line between two short ones stays. - let (_, t, _, b) = ink(¬e_page("Source\n\nIBGE", true, TextAlign::Left, 0.0)); - let (_, t2, _, b2) = ink(¬e_page("Source\nIBGE", true, TextAlign::Left, 0.0)); - assert!(b - t > b2 - t2 + line / 2, "{t}..{b} against {t2}..{b2}"); - } - - /// A turned wrapped text wraps to its unturned box's width: turned 90°, its lines run down the - /// page within the box's 40 mm about its centre (#2346). - #[test] - fn a_turned_wrapped_text_wraps_to_its_unturned_width() { - let mm = 96.0 / 25.4; - let (l, t, r, b) = ink_bounds(&render(¬e_page(NOTE, true, TextAlign::Left, 90.0), &mut [], 96.0, &PageInfo::default()).unwrap()); - // The box's centre is at (30, 40) mm: 40 mm wide, turned, it spans 20 to 60 mm down the page. - assert!(f64::from(t) >= 20.0 * mm - 2.0 && f64::from(b) <= 60.0 * mm + 2.0, "{t}..{b}"); - assert!(r - l > 40, "its lines side by side: {l}..{r}"); - } - - /// A wrapped text whose lines reach past its box's bottom is reported as cut, as a text with - /// too many line breaks is; one whose lines fit isn't (#2346). - #[test] - fn a_wrapped_text_past_its_box_is_reported_cut() { - let info = PageInfo::default(); - let mut l = note_page(NOTE, true, TextAlign::Left, 0.0); - assert!(clipped_text(&l, &[], 96.0, &info).is_empty()); - let id = l.elements[0].id; - l.element_mut(id).unwrap().h = 4.0; - assert_eq!(clipped_text(&l, &[], 96.0, &info), vec![(id, "Note".into())]); - } - - /// A wrapped text past the 200 lines a text draws is reported cut, even when its 201st line is - /// blank and the text goes on after it (#2346); one followed only by blank lines loses nothing - /// and isn't. - #[test] - fn a_wrapped_text_past_its_last_drawn_line_is_reported_cut() { - let info = PageInfo::default(); - let page = |tail: &str| { - let mut l = Layout::new("L", 100.0, 1500.0); - let mut kind = ElementKind::text(format!("{}{tail}", vec!["a"; 200].join("\n")), 12.0, Rgba::rgb(0, 0, 0), false); - if let ElementKind::Text { wrap, .. } = &mut kind { - *wrap = true; - } - let id = l.add("Note", (10.0, 10.0, 40.0, 1400.0), kind); - (l, id) - }; - let (l, id) = page("\n\u{a0}\nZ"); - assert_eq!(clipped_text(&l, &[], 96.0, &info), vec![(id, "Note".into())]); - let (l, _) = page("\n\n\n"); - assert!(clipped_text(&l, &[], 96.0, &info).is_empty(), "only blank lines past it"); - // Counted as more than the one line seen: the wrapped text was broken no further. - let (l, id) = page("\nZ"); - let loss = text_losses(&l, &[], 96.0, &info); - assert_eq!( - loss, - vec![TextLoss { - id, - name: "Note".into(), - left_out: 1, - at_least: true, - below_box: false, - past_limit: true, - off_page: false, - unit_label: None - }] - ); - let said = lines_left_out_notice(&loss[0]).unwrap(); - assert!(said.starts_with("1 or more lines of the text \"Note\""), "{said}"); - assert!(said.ends_with("aren't drawn: a text draws at most 200 lines; split it into more than one text"), "{said}"); - } - - /// The lines of a text left out below its box are counted, blank ones not, and said in the - /// singular or the plural; a text whose lines all fit says nothing (#2346). - #[test] - fn a_text_counts_the_lines_left_out_of_its_box() { - let info = PageInfo::default(); - let mut l = note_page("one\ntwo\n\nfour\nfive", false, TextAlign::Left, 0.0); - let id = l.elements[0].id; - let losses = |l: &Layout| text_losses(l, &[], 96.0, &info); - assert!(losses(&l).is_empty(), "all fit"); - l.element_mut(id).unwrap().h = 2.0; - let loss = losses(&l); - assert_eq!( - loss, - vec![TextLoss { - id, - name: "Note".into(), - left_out: 3, - at_least: false, - below_box: true, - past_limit: false, - off_page: false, - unit_label: None - }] - ); - // The element alone is measured the same, and another id finds nothing. - assert_eq!(text_loss(&l, &[], 96.0, &info, id).as_ref(), loss.first()); - assert_eq!(text_loss(&l, &[], 96.0, &info, id + 1), None); - let said = lines_left_out_notice(&loss[0]).unwrap(); - assert!(said.starts_with(&format!("3 lines of the text \"Note\" ({id}) don't fit its box and aren't drawn")), "{said}"); - if let ElementKind::Text { text, .. } = &mut l.element_mut(id).unwrap().kind { - *text = "one\ntwo".into(); - } - let said = lines_left_out_notice(&losses(&l)[0]).unwrap(); - assert!(said.starts_with(&format!("1 line of the text \"Note\" ({id}) doesn't fit its box and isn't drawn")), "{said}"); - // Off the page but all drawn: cut, with no line left out to count. - let e = l.element_mut(id).unwrap(); - (e.h, e.x) = (60.0, 99.0); - let loss = losses(&l); - assert_eq!(loss.len(), 1); - assert_eq!(lines_left_out_notice(&loss[0]), None); - } - - /// A text whose ink crosses the page's edge is told apart from its lines left out, with the - /// advice that fixes an edge: moved past each side it is, back inside or turned within the - /// page it isn't, and one cut below its box and past the edge has both (#2703). - #[test] - fn a_text_past_the_pages_edge_is_told_with_its_advice() { - let info = PageInfo::default(); - let mut l = note_page("Note", false, TextAlign::Left, 0.0); - let id = l.elements[0].id; - let put = |l: &mut Layout, (x, y): (f64, f64)| { - if let Some(e) = l.element_mut(id) { - (e.x, e.y) = (x, y); - } - }; - let turn = |l: &mut Layout, degrees: f64| { - if let Some(ElementKind::Text { rotation, .. }) = l.element_mut(id).map(|e| &mut e.kind) { - *rotation = degrees; - } - }; - let told = |l: &Layout| text_loss(l, &[], 96.0, &info, id).and_then(|loss| off_page_notice(&loss)); - let said = format!( - "The text \"Note\" ({id}) runs off the page, so part of it isn't drawn; move it inside the page, resize it or reduce its size" - ); - assert_eq!(told(&l), None, "inside the page"); - // Past each edge. - for at in [(98.0, 10.0), (10.0, 99.0), (-30.0, 10.0), (10.0, -5.0)] { - put(&mut l, at); - let loss = text_loss(&l, &[], 96.0, &info, id).unwrap_or_else(|| panic!("{at:?} is past an edge")); - assert!(loss.off_page && loss.left_out == 0 && !loss.below_box, "{at:?} {loss:?}"); - assert_eq!(off_page_notice(&loss), Some(said.clone()), "{at:?}"); - assert_eq!(lines_left_out_notice(&loss), None, "{at:?}: no line is left out"); - put(&mut l, (10.0, 10.0)); - assert_eq!(told(&l), None, "{at:?} moved back inside"); - } - // A text that doesn't cross says nothing, whatever else is lost. - let inside = TextLoss { - id, - name: "Note".into(), - left_out: 1, - at_least: false, - below_box: true, - past_limit: false, - off_page: false, - unit_label: None, - }; - assert_eq!(off_page_notice(&inside), None); - // Turned within the page: nothing. Turned about its box's centre past the edge: told. - put(&mut l, (30.0, 10.0)); - turn(&mut l, 90.0); - assert_eq!(told(&l), None, "turned within the page"); - turn(&mut l, 180.0); - assert_eq!(told(&l), None, "turned within the page"); - put(&mut l, (80.0, 10.0)); - turn(&mut l, 0.0); - assert_eq!(told(&l), None, "unturned, it is inside"); - turn(&mut l, 180.0); - assert_eq!(told(&l), Some(said.clone()), "turned about its box's centre, past the edge"); - // Cut below its box and past the edge: each is told, apart. - let mut l = note_page("one\ntwo\nthree", false, TextAlign::Left, 0.0); - let id = l.elements[0].id; - if let Some(e) = l.element_mut(id) { - (e.x, e.h) = (98.0, 2.0); - } - let loss = text_loss(&l, &[], 96.0, &info, id).unwrap_or_else(|| panic!("cut")); - assert!(loss.below_box && loss.off_page && loss.left_out == 2, "{loss:?}"); - let (lines, edge) = (lines_left_out_notice(&loss).unwrap_or_default(), off_page_notice(&loss).unwrap_or_default()); - assert!(lines.contains("don't fit its box") && !lines.contains("page"), "{lines}"); - assert!(edge.contains("runs off the page") && !edge.contains("lines"), "{edge}"); - // No ink, nothing to cut: an empty or blank text, past the edge. - for blank in ["", " \n "] { - let mut l = note_page(blank, false, TextAlign::Left, 0.0); - let id = l.elements[0].id; - if let Some(e) = l.element_mut(id) { - e.x = 98.0; - } - assert_eq!(text_loss(&l, &[], 96.0, &info, id), None, "{blank:?} has no ink"); - } - // A file can hold any place and size: measured without a panic, and told at most once. - for (x, y, size) in - [(1e300, -1e300, 12.0), (f64::NAN, f64::INFINITY, 12.0), (10.0, 10.0, f64::NAN), (10.0, 10.0, 1e300), (98.0, 10.0, 1e300)] - { - let mut l = note_page("Note", false, TextAlign::Left, 0.0); - let id = l.elements[0].id; - if let Some(e) = l.element_mut(id) { - (e.x, e.y) = (x, y); - if let ElementKind::Text { size: s, .. } = &mut e.kind { - *s = size; - } - } - let losses = text_losses(&l, &[], 96.0, &info); - assert!(losses.len() <= 1 && losses.iter().all(|loss| off_page_notice(loss).iter().count() <= 1), "{x} {y} {size}"); - } - } - - /// A long text counts every line left out below its box, each only looked at for a letter - /// past the box: none is shaped there (#2346). - #[test] - fn a_long_text_counts_every_line_left_out() { - let info = PageInfo::default(); - let mut l = note_page(&vec!["x"; 3000].join("\n"), false, TextAlign::Left, 0.0); - let id = l.elements[0].id; - l.element_mut(id).unwrap().h = 2.0; - let loss = text_losses(&l, &[], 96.0, &info); - assert_eq!( - loss, - vec![TextLoss { - id, - name: "Note".into(), - left_out: 2999, - at_least: false, - below_box: true, - past_limit: true, - off_page: false, - unit_label: None - }] - ); - let said = lines_left_out_notice(&loss[0]).unwrap(); - assert!(said.ends_with("make the box taller or the text smaller, and split it, as a text draws at most 200 lines"), "{said}"); - // A box tall enough for 200 lines: the rest are past the limit, which no box draws (#2346). - let mut tall = note_page(&vec!["x"; 250].join("\n"), false, TextAlign::Left, 0.0); - tall.height = 2000.0; - tall.element_mut(id).unwrap().h = 1900.0; - let loss = text_losses(&tall, &[], 96.0, &info); - assert_eq!( - loss, - vec![TextLoss { - id, - name: "Note".into(), - left_out: 50, - at_least: false, - below_box: false, - past_limit: true, - off_page: false, - unit_label: None - }] - ); - let said = lines_left_out_notice(&loss[0]).unwrap(); - assert_eq!( - said, - format!("50 lines of the text \"Note\" ({id}) aren't drawn: a text draws at most 200 lines; split it into more than one text") - ); - // Blank lines below the box and then one letter: that one line is left out. - let mut l = note_page(&format!("x{}\nZ", "\n".repeat(2000)), false, TextAlign::Left, 0.0); - l.element_mut(id).unwrap().h = 2.0; - assert_eq!( - text_losses(&l, &[], 96.0, &info), - vec![TextLoss { - id, - name: "Note".into(), - left_out: 1, - at_least: false, - below_box: false, - past_limit: true, - off_page: false, - unit_label: None - }] - ); - } - - /// The cut-off notice suggests breaking lines or wrapping them for a text not wrapped, and - /// only the box or the size when every text it names is wrapped already (#2346). - #[test] - fn the_cut_off_notice_suggests_wrapping_a_text_not_wrapped() { - let info = PageInfo::default(); - for wrap in [false, true] { - let mut l = note_page(NOTE, wrap, TextAlign::Left, 0.0); - let id = l.elements[0].id; - l.element_mut(id).unwrap().h = 2.0; - let note = clipped_text_notice(&l, &clipped_text(&l, &[], 96.0, &info)).unwrap(); - assert!(note.starts_with(&format!("Text is cut off in 1 layout element(s): Note ({id}); ")), "{note}"); - assert_eq!(note.contains("Wrap to the box"), !wrap, "{note}"); - assert_eq!(note.contains("add line breaks"), !wrap, "{note}"); - assert!(note.contains("reduce its size"), "{note}"); - } - // A legend's title, or an element gone since, has no wrap to turn on: line breaks, as before. - let l = note_page(NOTE, true, TextAlign::Left, 0.0); - let note = clipped_text_notice(&l, &[(999, "Gone".into())]).unwrap(); - assert!(note.ends_with("resize or move the text, reduce its size, or add line breaks"), "{note}"); - let both = clipped_text_notice(&l, &[(l.elements[0].id, "Note".into()), (999, "Gone".into())]).unwrap(); - assert!(!both.contains("Wrap to the box") && both.contains("add line breaks"), "{both}"); - assert_eq!(clipped_text_notice(&Layout::new("L", 10.0, 10.0), &[]), None); - } - - /// The same lines at every resolution: they are measured at one (#2346), so the layout view, - /// an image export and a print break a text alike. - #[test] - fn a_wrapped_text_breaks_alike_at_every_resolution() { - let style = - TextStyle { face: text::Face::default(), align: TextAlign::Left, spacing: 0.0, valign: TextVAlign::Top, line_spacing: 1.0 }; - let lines = wrapped(NOTE, 40.0, 12.0, style); - assert!(lines.lines().count() > 3, "{lines}"); - assert!(lines.lines().all(|l| !l.starts_with(' ') && !l.ends_with(' ')), "{lines:?}"); - assert_eq!(lines.replace('\n', " "), NOTE, "broken only at its spaces"); - let tall = |dpi: f64| { - let pm = render(¬e_page(NOTE, true, TextAlign::Left, 0.0), &mut [], dpi, &PageInfo::default()).unwrap(); - let (_, t, _, b) = ink_bounds(&pm); - f64::from(b - t) / dpi - }; - assert!((tall(96.0) - tall(300.0)).abs() < 0.03, "{} against {} inches", tall(96.0), tall(300.0)); - } - - /// A text turned 90° runs down the page from the top of its turned box, -90° up it from the - /// bottom, about the centre of its box (#1763); upright, it runs across as before. - #[test] - fn a_turned_text_runs_down_or_up_the_page() { - // 100 mm at 96 dpi; the box's centre at 50 mm. - let centre = 50.0 * 96.0 / 25.4; - let ink = |turn: f64| ink_bounds(&render(&turned_text_page(turn), &mut [], 96.0, &PageInfo::default()).unwrap()); - let (l, t, r, b) = ink(0.0); - assert!(r - l > 4 * (b - t), "upright runs across: {l},{t} to {r},{b}"); - for turn in [90.0, -90.0] { - let (l, t, r, b) = ink(turn); - assert!(b - t > 4 * (r - l), "{turn}° runs along the page: {l},{t} to {r},{b}"); - // Across: within the turned box, 10 mm wide about the centre. - assert!((f64::from(l + r) / 2.0 - centre).abs() < 10.0 * 96.0 / 25.4 / 2.0, "{turn}°: {l}..{r}"); - // Along: a left-aligned line starts at the box's left edge, which a turn of 90° takes to - // the top and one of -90° to the bottom. - let middle = f64::from(t + b) / 2.0; - assert!(if turn > 0.0 { middle < centre } else { middle > centre }, "{turn}°: {t}..{b} about {centre}"); - } - } - - /// A quarter-turned text keeps as sharp as an upright one: its picture is put on whole pixels, - /// not filtered between them, so its edges have no more part-covered pixels (#1763). At 300 dpi - /// the box's corner falls between pixels (10 mm is 118.1 of them). - #[test] - fn a_quarter_turned_text_is_as_sharp_as_upright() { - // Solid pixels (darker than 80 %) and part-covered ones (20 to 80 %). - let edges = |turn: f64| { - let pm = render(&turned_text_page(turn), &mut [], 300.0, &PageInfo::default()).unwrap(); - let dark = (0..pm.height()).flat_map(|y| (0..pm.width()).map(move |x| (x, y))).map(|(x, y)| 255 - u32::from(rgb(&pm, x, y).0)); - dark.fold((0u32, 0u32), |(solid, part), d| (solid + u32::from(d > 204), part + u32::from(d > 51 && d <= 204))) - }; - let (solid, part) = edges(0.0); - let upright = f64::from(part) / f64::from(solid); - for turn in [90.0, -90.0, 180.0] { - let (s, p) = edges(turn); - let turned = f64::from(p) / f64::from(s); - assert!(turned < upright * 1.2, "{turn}°: {p} part-covered to {s} solid, upright {part} to {solid}"); - assert!(s.abs_diff(solid) * 10 < solid, "{turn}°: as much ink, {s} solid to {solid}"); - } - } - - /// A turned text's picture covers the lines it draws, not its whole box: a short line in a - /// large box takes a small picture, where its alignment puts the line (#1763). - #[test] - fn a_turned_texts_picture_covers_its_lines() { - let r = Rect::from_xywh(0.0, 0.0, 2000.0, 1000.0).unwrap(); - let plain = - TextStyle { face: text::Face::default(), align: TextAlign::Left, spacing: 0.0, valign: TextVAlign::Top, line_spacing: 1.0 }; - let px = 14.0 * 1.33; - let area = |align| text_area(r, "Fonte: IBGE", 14.0, TextStyle { align, ..plain }, 1.0).unwrap(); - let left = area(TextAlign::Left); - assert!(left.width() < 200.0 && left.height() < 4.0 * px, "{left:?}"); - assert!(left.left() < 0.0 && left.top() < 0.0, "a line's height of room: {left:?}"); - let right = area(TextAlign::Right); - assert!((right.right() - (2000.0 + px)).abs() < 1.0 && (right.width() - left.width()).abs() < 1.0, "{right:?}"); - let centre = area(TextAlign::Center); - assert!(((centre.left() + centre.right()) / 2.0 - 1000.0).abs() < 1.0, "{centre:?}"); - // Two lines, twice the pitch; nothing when there is no line. - let two = text_area( - r, - "Fonte: IBGE -Elaboração: RustGIS", - 14.0, - plain, - 1.0, - ) - .unwrap(); - assert!((two.height() - left.height() - px * 1.25).abs() < 0.01); - assert!(text_area(r, "", 14.0, plain, 1.0).is_none()); - } - - /// A turned box past the page's budget is still drawn turned, at a lower resolution, not - /// left out or left upright (#1763). - #[test] - fn a_huge_turned_box_is_drawn_at_a_lower_resolution() { - let mut pm = Canvas::new(200, 200).unwrap(); - // 20,000 px long (past MAX_SIDE), 20 high, about the canvas's centre. - let r = Rect::from_xywh(-9_900.0, 90.0, 20_000.0, 20.0).unwrap(); - let mut scale = 0.0; - let area = Rect::from_xywh(0.0, 0.0, r.width(), r.height()).unwrap(); - draw_turned_box(&mut pm, r, 90.0, area, |c, inner, k| { - scale = k; - c.fill_rect(inner, &paint(Rgba::rgb(0, 0, 0), 1.0), Transform::identity(), None); - }); - assert!(scale < 1.0 && scale > 0.0, "{scale}"); - // Turned upright: a bar down the middle, top to bottom; nothing beside it. - let dark = |x: u32, y: u32| pm.pixmap().pixel(x, y).is_some_and(|p| p.alpha() > 128); - assert!(dark(100, 2) && dark(100, 197) && dark(95, 100), "the bar runs down the page"); - assert!(!dark(70, 100) && !dark(130, 100)); - } - - /// A turned text is kept as turned glyphs, which draw what its picture shows (#1763). - #[test] - fn a_turned_text_is_kept_turned_as_vectors() { - use crate::vector::Item; - let layout = turned_text_page(90.0); - let info = PageInfo::default(); - let png = render(&layout, &mut [], 96.0, &info).unwrap(); - let (drawing, _) = render_drawing(&layout, &mut [], 96.0, &info).unwrap(); - let (_, _, items) = drawing.finish(); - let items = crate::vector::without_layers(items); - let text: String = items - .iter() - .filter_map(|i| if let Item::Glyphs(r) = i { Some(r) } else { None }) - .flat_map(|r| r.glyphs.iter().map(|g| g.ch)) - .collect(); - assert_eq!(text, "Fonte: IBGE, 2022", "kept as text, not a picture"); - let mut replayed = Pixmap::new(png.width(), png.height()).unwrap(); - replayed.fill(tiny_skia::Color::WHITE); - crate::vector::replay(&items, &mut replayed, Transform::identity()); - let (pl, pt, pr, pb) = ink_bounds(&png); - let (vl, vt, vr, vb) = ink_bounds(&replayed); - assert!( - pl.abs_diff(vl) <= 2 && pt.abs_diff(vt) <= 2 && pr.abs_diff(vr) <= 2 && pb.abs_diff(vb) <= 2, - "{pl},{pt},{pr},{pb} vs {vl},{vt},{vr},{vb}" - ); - } - - /// Text elements take italic, alignment and letter spacing (#213, point c); plain, they draw - /// as before. - #[test] - fn text_takes_italic_alignment_and_letter_spacing() { - let plain = - TextStyle { face: text::Face::default(), align: TextAlign::Left, spacing: 0.0, valign: TextVAlign::Top, line_spacing: 1.0 }; - let base = styled_line(plain); - let (l, r, ..) = text_ink(&base); - assert!(l < 4, "left-aligned starts at the left: {l}"); - // Plain is what the old upright, left-aligned drawing gave. - let mut old = Pixmap::new(400, 60).unwrap(); - old.fill(tiny_skia::Color::WHITE); - let px = 20.0 * 1.33; - crate::canvas::with_canvas(&mut old, |c| { - text::text_at(c, "Oceano Atlântico", 0.0, px * 0.6, px, Rgba::rgb(0, 0, 0), false, text::Align::Left, false) - }); - assert_eq!(text_ink(&old).0.abs_diff(l), 0); - assert_eq!(text_ink(&old).1.abs_diff(r), 0); - // Right and centre: the same width, moved. - let (rl, rr, ..) = text_ink(&styled_line(TextStyle { align: TextAlign::Right, ..plain })); - assert!((397..=399).contains(&rr) && (rr - rl).abs_diff(r - l) <= 1, "right-aligned ends at the right: {rl}..{rr}"); - let (cl, cr, ..) = text_ink(&styled_line(TextStyle { align: TextAlign::Center, ..plain })); - assert!(cl.abs_diff(400 - cr) <= 2, "centred: {cl}..{cr}"); - // Spacing: 15 gaps of 3 pt widen the line by about 15 × 3 × 1.33 px. - let (sl, sr, ..) = text_ink(&styled_line(TextStyle { spacing: 3.0, ..plain })); - let grown = (sr - sl) as f32 - (r - l) as f32; - assert!((grown - 15.0 * 3.0 * 1.33).abs() < 3.0, "{grown}"); - // Italic: a straight stem (an `l`) leans right, its top about tan 12° of its height - // right of its foot; upright, it stands straight. - let stem = |italic: bool| { - let mut pm = Pixmap::new(120, 120).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let r = Rect::from_xywh(40.0, 0.0, 80.0, 120.0).unwrap(); - crate::canvas::with_canvas(&mut pm, |c| { - text_block(c, r, "l", 60.0, Rgba::rgb(0, 0, 0), TextStyle { face: text::Face { italic, ..plain.face }, ..plain }, 1.0) - }); - let (.., top, bottom) = text_ink(&pm); - (top as i32 - bottom as i32, text_height(&pm)) - }; - let ((upright, _), (lean, height)) = (stem(false), stem(true)); - assert!(upright.abs() <= 1, "upright stem: {upright}"); - assert!((lean as f32 - 0.2126 * height as f32).abs() <= 3.0, "lean {lean} over {height} px"); - // Right-aligned, slanted or tightened past the letters' width, the ink stays in the box. - for style in [ - TextStyle { align: TextAlign::Right, face: text::Face { italic: true, ..plain.face }, ..plain }, - TextStyle { align: TextAlign::Right, spacing: -5.0, ..plain }, - ] { - let mut pm = Pixmap::new(400, 60).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let r = Rect::from_xywh(0.0, 0.0, 300.0, 60.0).unwrap(); - crate::canvas::with_canvas(&mut pm, |c| text_block(c, r, "Oceano Atlântico", 20.0, Rgba::rgb(0, 0, 0), style, 1.0)); - let (l, r, ..) = text_ink(&pm); - assert!((296..=300).contains(&r) && l < r, "inked {l}..{r} in a 300 px box"); - } - // 2 pt letters at -5 pt run backwards: still drawn, inside the box. - let mut pm = Pixmap::new(400, 60).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let r = Rect::from_xywh(0.0, 0.0, 300.0, 60.0).unwrap(); - crate::canvas::with_canvas(&mut pm, |c| { - text_block(c, r, "MMMM", 2.0, Rgba::rgb(0, 0, 0), TextStyle { align: TextAlign::Right, spacing: -5.0, ..plain }, 4.0) - }); - let (l, r, ..) = text_ink(&pm); - assert!(r <= 300 && l < r, "inked {l}..{r}"); - } - - /// A 100 × 100 mm page with `text` at 12 pt in black in (10, 10, 40, `h`) mm, its kind changed - /// by `f`. - fn block_page(text: &str, h: f64, f: &dyn Fn(&mut ElementKind)) -> Layout { - let mut l = Layout::new("L", 100.0, 100.0); - let mut kind = ElementKind::text(text, 12.0, Rgba::rgb(0, 0, 0), false); - f(&mut kind); - l.add("Block", (10.0, 10.0, 40.0, h), kind); - l - } - - /// Sets a text's block alignment, line spacing and case. - fn set_block(k: &mut ElementKind, v: TextVAlign, ls: f64, c: TextCase) { - if let ElementKind::Text { valign, line_spacing, case, .. } = k { - (*valign, *line_spacing, *case) = (v, ls, c); - } - } - - /// The rows with a dark pixel, from the top. - fn ink_rows(pm: &Pixmap) -> Vec { - (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| rgb(pm, x, y).0 < 128)).collect() - } - - /// How many separate runs of columns with a dark pixel there are, from the left. - fn ink_column_runs(pm: &Pixmap) -> usize { - let inked: Vec = (0..pm.width()).map(|x| (0..pm.height()).any(|y| rgb(pm, x, y).0 < 128)).collect(); - inked.windows(2).filter(|w| !w[0] && w[1]).count() + usize::from(inked.first() == Some(&true)) - } - - /// A text's block sits at the top of its box, as texts always have, in its middle, or with its - /// last line on its bottom edge; the block itself is the same, moved. - #[test] - fn a_text_block_sits_at_the_top_middle_or_bottom_of_its_box() { - let draw = |v: TextVAlign| { - render(&block_page("one\ntwo\nthree", 60.0, &|k| set_block(k, v, 1.0, TextCase::None)), &mut [], 96.0, &PageInfo::default()) - .unwrap() - }; - let (top, mid, bottom) = - (ink_rows(&draw(TextVAlign::Top)), ink_rows(&draw(TextVAlign::Middle)), ink_rows(&draw(TextVAlign::Bottom))); - let plain = ink_rows(&render(&block_page("one\ntwo\nthree", 60.0, &|_| {}), &mut [], 96.0, &PageInfo::default()).unwrap()); - assert_eq!(top, plain, "top is today's drawing"); - let span = |r: &[u32]| r[r.len() - 1] - r[0]; - // Moved by part of a pixel, its edge rows may shade past the threshold one row more or less. - for moved in [&mid, &bottom] { - assert!(span(moved).abs_diff(span(&top)) <= 1, "the same block, moved: {} and {}", span(moved), span(&top)); - } - let (box_top, box_bottom) = ((10.0 * 96.0 / 25.4) as u32, (70.0 * 96.0 / 25.4) as u32); - assert!(box_bottom - bottom[bottom.len() - 1] <= 12, "bottom: last ink row {} of the box's {box_bottom}", bottom[bottom.len() - 1]); - let (above, below) = (mid[0] - box_top, box_bottom - mid[mid.len() - 1]); - assert!(above.abs_diff(below) <= 8, "middle: {above} above, {below} below"); - } - - /// Line spacing multiplies the distance between lines: twice as far apart at 2, half at 0.5. - #[test] - fn line_spacing_spreads_the_lines_by_its_multiple() { - let span = |ls: f64| { - let pm = render( - &block_page("one\ntwo\nthree", 60.0, &|k| set_block(k, TextVAlign::Top, ls, TextCase::None)), - &mut [], - 96.0, - &PageInfo::default(), - ) - .unwrap(); - let r = ink_rows(&pm); - (r[r.len() - 1] - r[0]) as f64 - }; - // The usual pitch in pixels at 96 dpi, a layout point a pixel there. - let pitch = 12.0 * 1.33 * 1.25; - assert!(((span(2.0) - span(1.0)) - 2.0 * pitch).abs() <= 2.0, "{} {}", span(2.0), span(1.0)); - assert!(((span(1.0) - span(0.5)) - pitch).abs() <= 2.0, "{} {}", span(1.0), span(0.5)); - } - - /// A block taller than its box is drawn from the top whatever its alignment: its first lines - /// are kept, the same lines left out and said, and none is drawn above the box. - #[test] - fn a_block_taller_than_its_box_keeps_its_first_lines_whatever_its_valign() { - let info = PageInfo::default(); - let page = |v| block_page("one\ntwo\nthree\nfour\nfive", 7.0, &|k| set_block(k, v, 1.0, TextCase::None)); - let top = page(TextVAlign::Top); - let loss = text_losses(&top, &[], 96.0, &info); - assert_eq!(loss.iter().map(|l| l.left_out).collect::>(), [3]); - for v in [TextVAlign::Middle, TextVAlign::Bottom] { - let l = page(v); - assert_eq!(render(&l, &mut [], 96.0, &info).unwrap().data(), render(&top, &mut [], 96.0, &info).unwrap().data(), "{v:?}"); - assert_eq!(text_losses(&l, &[], 96.0, &info), loss, "{v:?}"); - assert_eq!(lines_left_out_notice(&text_losses(&l, &[], 96.0, &info)[0]), lines_left_out_notice(&loss[0])); - } - } - - /// A text of more lines than a text draws is cut at them, so it is drawn from the top whatever - /// its alignment, though the lines kept would fit its box; one of exactly that many, all - /// drawn, is still aligned. - #[test] - fn a_text_cut_at_the_most_lines_it_draws_starts_at_the_top() { - let info = PageInfo::default(); - // 2 pt lines are 0.88 mm apart: 200 of them fill 176 mm of a 200 mm box. - let page = |lines: usize, v| { - let text = (0..lines).map(|i| format!("line {i}")).collect::>().join( - " -", - ); - let mut l = Layout::new("L", 100.0, 300.0); - let mut kind = ElementKind::text(&text, 2.0, Rgba::rgb(0, 0, 0), false); - set_block(&mut kind, v, 1.0, TextCase::None); - l.add("Block", (10.0, 10.0, 40.0, 200.0), kind); - l - }; - let drawn = |l: &Layout| render(l, &mut [], 96.0, &info).unwrap(); - let top = page(300, TextVAlign::Top); - for v in [TextVAlign::Middle, TextVAlign::Bottom] { - let l = page(300, v); - assert_eq!(drawn(&l).data(), drawn(&top).data(), "{v:?}"); - assert_eq!(text_losses(&l, &[], 96.0, &info), text_losses(&top, &[], 96.0, &info), "{v:?}"); - let svg = |l: &Layout| crate::svg::layout_svg(l, &mut [], 96.0, &info).unwrap().0; - assert_eq!(svg(&l), svg(&top), "{v:?}"); - assert_ne!(drawn(&page(200, v)).data(), drawn(&page(200, TextVAlign::Top)).data(), "{v:?}: all drawn, aligned"); - } - let text = |n: usize| { - vec!["x"; n].join( - " -", - ) - }; - assert_eq!(text_shift(TextVAlign::Bottom, 5000.0, 10.0, &text(201), 1.0), 0.0); - assert_eq!(text_shift(TextVAlign::Bottom, 5000.0, 10.0, &text(200), 1.0), block_shift(TextVAlign::Bottom, 5000.0, 10.0, 200, 1.0)); - assert!(text_shift(TextVAlign::Bottom, 5000.0, 10.0, &text(200), 1.0) > 0.0); - } - - /// The cut-off check steps by the spaced pitch, as the page draws: a wider spacing leaves lines - /// out of a box that held them, a tighter one draws lines a box cut. - #[test] - fn line_spacing_changes_the_lines_left_out() { - let info = PageInfo::default(); - let left_out = |h: f64, ls: f64| { - let l = block_page("one\ntwo\nthree\nfour\nfive", h, &|k| set_block(k, TextVAlign::Top, ls, TextCase::None)); - text_losses(&l, &[], 96.0, &info).first().map_or(0, |l| l.left_out) - }; - assert_eq!((left_out(25.0, 1.0), left_out(25.0, 2.0)), (0, 2)); - assert_eq!((left_out(12.0, 1.0), left_out(12.0, 0.5)), (2, 0)); - } - - /// Case applies once the tokens are filled in, and before the wrap, which breaks the wider - /// words. - #[test] - fn case_applies_after_the_tokens_and_before_the_wrap() { - let info = PageInfo { page: 2, pages: 3, page_name: String::new() }; - let draw = |t: &str, c| render(&block_page(t, 20.0, &|k| set_block(k, TextVAlign::Top, 1.0, c)), &mut [], 96.0, &info).unwrap(); - assert_eq!(draw("Page {page} of {pages}", TextCase::Upper).data(), draw("PAGE 2 OF 3", TextCase::None).data()); - assert_eq!(draw("PAGE {page} OF {pages}", TextCase::Lower).data(), draw("page 2 of 3", TextCase::None).data()); - let style = text_style(false, false, rustgis_map::layout::FontFamily::Sans, None, TextAlign::Left, 0.0); - let s = "boundaries simplified for print from the census".to_string(); - let lines = |c| drawn_text(s.clone(), c, true, 40.0, 12.0, style).lines().count(); - assert!(lines(TextCase::Upper) > lines(TextCase::Lower), "{} {}", lines(TextCase::Upper), lines(TextCase::Lower)); - assert_eq!(drawn_text(s.clone(), TextCase::None, false, 40.0, 12.0, style), s, "unwrapped and as typed: unchanged"); - } - - /// A turned text's picture covers its lines where its block alignment and spacing put them. - #[test] - fn a_turned_bottom_aligned_text_is_drawn_whole() { - let info = PageInfo::default(); - let ink = |v, ls| { - let pm = render( - &block_page("one\ntwo\nthree", 60.0, &|k| { - set_block(k, v, ls, TextCase::None); - if let ElementKind::Text { rotation, .. } = k { - *rotation = 90.0; - } - }), - &mut [], - 96.0, - &info, - ) - .unwrap(); - (ink_bounds(&pm), ink_column_runs(&pm)) - }; - // Spaced alike, so only the alignment differs. Turned a quarter clockwise, the box's - // down runs leftwards across the page: its lines are runs of inked columns. - let ((tl, tt, tr, tb), top_runs) = ink(TextVAlign::Top, 1.5); - let ((bl, bt, br, bb), bottom_runs) = ink(TextVAlign::Bottom, 1.5); - assert_eq!((top_runs, bottom_runs), (3, 3), "a run of columns a line, all three drawn"); - assert!((tr - tl).abs_diff(br - bl) <= 2, "the same block across: {tl}..{tr} and {bl}..{br}"); - assert!((tb - tt).abs_diff(bb - bt) <= 2, "the same lines along: {tt}..{tb} and {bt}..{bb}"); - // Moved left by the room the block leaves: the box's 60 mm less three lines at 1.5, - // 12 pt × 1.33 × 1.25 × (1 + 2 × 1.5) = 79.8 px, of 226.8 px: 147.0 px. - let free = 60.0 * 96.0 / 25.4 - 12.0 * 1.33 * 1.25 * (1.0 + 2.0 * 1.5); - for (t, b) in [(tl, bl), (tr, br)] { - assert!((f64::from(t) - f64::from(b) - free).abs() <= 2.0, "moved {} px of {free:.1}", f64::from(t) - f64::from(b)); - } - } - - /// Where a text's block and case put its ink decides whether it runs off the page: a box - /// hanging past the page's bottom, its one line at the box's top, middle or bottom; and a line - /// near the page's right edge in upper case, its letters wider. - #[test] - fn a_text_block_and_case_are_said_off_the_page_where_they_put_the_ink() { - let info = PageInfo::default(); - // The 100 mm page is 378.0 px tall at 96 dpi; the box (10, 80, 40, 30) mm runs from 302.4 - // to 415.7 px. Its one line of 12 pt (15.96 px a line, a pitch of 19.95) has its middle - // 9.6 px under where the block starts, the block 19.95 px tall in a box of 113.4: at the - // top at 312.0 px, in the middle 46.7 px lower at 358.7, at the bottom 93.4 px lower at - // 405.4, below the page's 378.0 whatever the font's letters (some 8 px each way). - let hanging = |v| { - let mut l = Layout::new("L", 100.0, 100.0); - let mut kind = ElementKind::text("one", 12.0, Rgba::rgb(0, 0, 0), false); - set_block(&mut kind, v, 1.0, TextCase::None); - l.add("Hanging", (10.0, 80.0, 40.0, 30.0), kind); - text_losses(&l, &[], 96.0, &info) - }; - assert_eq!(hanging(TextVAlign::Top), [], "at the top, on the page"); - assert_eq!(hanging(TextVAlign::Middle), [], "in the middle, still on the page"); - let bottom = hanging(TextVAlign::Bottom); - assert!(bottom.len() == 1 && bottom[0].off_page && bottom[0].left_out == 0, "{bottom:?}"); - assert!(off_page_notice(&bottom[0]).is_some()); - // The page is 378.0 px wide; the box starts at 83 mm, 313.7 px, 64.3 px from its edge. - // Ten letters `lflflflflf` of 12 pt (an em of 15.96 px) take some 0.25 em each as typed, - // about 40 px, and some 0.58 em in upper case (`LFLFLFLFLF`), about 93 px: on the page as - // typed with room for 1.6 times as wide letters, past its edge in upper case at 0.69 times - // as wide ones. - let near_edge = |c| { - let mut l = Layout::new("L", 100.0, 100.0); - let mut kind = ElementKind::text("lflflflflf", 12.0, Rgba::rgb(0, 0, 0), false); - set_block(&mut kind, TextVAlign::Top, 1.0, c); - l.add("Edge", (83.0, 50.0, 10.0, 10.0), kind); - text_losses(&l, &[], 96.0, &info) - }; - assert_eq!(near_edge(TextCase::None), [], "as typed, on the page"); - let upper = near_edge(TextCase::Upper); - assert!(upper.len() == 1 && upper[0].off_page && upper[0].left_out == 0, "{upper:?}"); - assert!(off_page_notice(&upper[0]).is_some()); - } - - /// A block alignment or line spacing that reaches the page unrepaired is clamped where it is - /// used: an unknown alignment draws at the top, a spacing not a finite number (an infinity too) - /// at the usual one, one out of range at the nearer limit; none moves a line to a place not a - /// number. - #[test] - fn hostile_text_block_settings_draw_clamped() { - let style = text_style(false, false, rustgis_map::layout::FontFamily::Sans, None, TextAlign::Left, 0.0); - let kept = |v, ls: f64| { - let s = style.with_block(v, ls); - (s.valign, s.line_spacing) - }; - assert_eq!(kept(TextVAlign::Invalid, f64::NAN), (TextVAlign::Top, 1.0)); - assert_eq!(kept(TextVAlign::Bottom, 9.0), (TextVAlign::Bottom, 3.0)); - assert_eq!(kept(TextVAlign::Middle, f64::INFINITY), (TextVAlign::Middle, 1.0)); - assert_eq!(kept(TextVAlign::Middle, f64::NEG_INFINITY), (TextVAlign::Middle, 1.0)); - assert_eq!(kept(TextVAlign::Top, 0.1), (TextVAlign::Top, 0.5)); - for (v, box_h, px, ls) in [ - (TextVAlign::Bottom, f64::NAN, 10.0, 1.0), - (TextVAlign::Middle, 100.0, f64::NAN, 1.0), - (TextVAlign::Bottom, 100.0, 10.0, f64::NAN), - (TextVAlign::Bottom, f64::INFINITY, 10.0, 1.0), - (TextVAlign::Invalid, 100.0, 10.0, 1.0), - ] { - assert_eq!(block_shift(v, box_h, px, 3, ls), 0.0, "{v:?} {box_h} {px} {ls}"); - } - assert_eq!(block_shift(TextVAlign::Bottom, 100.0, 10.0, 0, 1.0), 0.0, "no line"); - let info = PageInfo::default(); - let draw = - |v, ls| render(&block_page("one\ntwo", 60.0, &|k| set_block(k, v, ls, TextCase::Invalid)), &mut [], 96.0, &info).unwrap(); - assert_eq!(draw(TextVAlign::Invalid, f64::NAN).data(), draw(TextVAlign::Top, 1.0).data()); - assert_eq!(draw(TextVAlign::Bottom, 1e300).data(), draw(TextVAlign::Bottom, 3.0).data()); - let l = block_page("one\ntwo", 60.0, &|k| set_block(k, TextVAlign::Bottom, f64::NAN, TextCase::Invalid)); - assert!(text_losses(&l, &[], 96.0, &info).is_empty()); - } - - /// The extent indicator is drawn in its own colour and width (#213): red and 2 pt until set. - #[test] - fn extent_indicators_take_their_colour_and_width() { - use rustgis_map::layout::{INDICATOR_COLOR, INDICATOR_WIDTH}; - let blue = Rgba::rgb(0x1F, 0x4E, 0x9A); - let default = indicator_page(INDICATOR_COLOR, INDICATOR_WIDTH); - assert!(inset_pixels(&default, INDICATOR_COLOR) > 0, "red by default"); - let thin = indicator_page(blue, 1.0); - let thick = indicator_page(blue, 6.0); - assert_eq!(inset_pixels(&thin, INDICATOR_COLOR), 0, "no red once restyled"); - let (t, w) = (inset_pixels(&thin, blue), inset_pixels(&thick, blue)); - assert!(t > 0 && w > 3 * t, "a wider outline covers more: {t} at 1 pt, {w} at 6 pt"); - } - - /// A map frame's border (#2557): dark grey and 0.8 pt by default, in its own colour and width - /// once set, none at a width of 0, and along the frame's shape, a round frame's leaving the - /// corners of its box clear. - #[test] - fn a_map_frame_border_takes_its_colour_and_width_or_none() { - use rustgis_map::layout::{FRAME_BORDER_COLOR, FRAME_BORDER_WIDTH, INDICATOR_COLOR, INDICATOR_WIDTH}; - let page = |shape: FrameShape, border_color: Rgba, border_width: f64| { - let mut map = Map::new("m"); - (map.basemap, map.graticule) = (rustgis_map::Basemap::Blank, false); - let mut l = Layout::new("Layout", 100.0, 100.0); - l.add( - "Frame", - (20.0, 20.0, 60.0, 60.0), - ElementKind::MapFrame { - map: "m".into(), - center: Coord::new(0.0, 0.0), - scale: 1e7, - shape, - grid: None, - extent_of: None, - extent_color: INDICATOR_COLOR, - extent_width: INDICATOR_WIDTH, - border_color, - border_width, - bearing: 0.0, - pitch: 0.0, - }, - ); - render(&l, &mut [map], 96.0, &PageInfo::default()).unwrap() - }; - // Pixels of a tone (a line this thin is blended with the white page), over the whole page - // or in the frame box's top-left corner. - let count = |pm: &Pixmap, tone: fn(u8, u8, u8) -> bool, corner: bool| { - let edge = (20.0 * PT_PER_MM + 6.0) as u32; - let (w, h) = if corner { (edge, edge) } else { (pm.width(), pm.height()) }; - (0..h) - .flat_map(|y| (0..w).map(move |x| (x, y))) - .filter(|&(x, y)| { - let (r, g, b) = rgb(pm, x, y); - tone(r, g, b) - }) - .count() - }; - let grey: fn(u8, u8, u8) -> bool = |r, g, b| r.max(g).max(b) - r.min(g).min(b) < 12 && r < 240; - let bluish: fn(u8, u8, u8) -> bool = |r, _, b| i32::from(b) - i32::from(r) > 30; - let inked: fn(u8, u8, u8) -> bool = |r, g, b| r.min(g).min(b) < 240; - let blue = Rgba::rgb(0x1F, 0x4E, 0x9A); - let default = page(FrameShape::Rectangle, FRAME_BORDER_COLOR, FRAME_BORDER_WIDTH); - assert!(count(&default, grey, false) > 0, "dark grey by default"); - assert_eq!(count(&default, bluish, false), 0); - let thin = page(FrameShape::Rectangle, blue, 1.0); - let thick = page(FrameShape::Rectangle, blue, 6.0); - assert_eq!(count(&thin, grey, false), 0, "no grey once recoloured"); - let (t, w) = (count(&thin, bluish, false), count(&thick, bluish, false)); - assert!(t > 0 && w > 3 * t, "a wider border covers more: {t} at 1 pt, {w} at 6 pt"); - let none = page(FrameShape::Rectangle, blue, 0.0); - assert_eq!(count(&none, inked, false), 0, "no border at 0"); - let clear = page(FrameShape::Rectangle, Rgba::new(0x1F, 0x4E, 0x9A, 0), 3.0); - assert_eq!(count(&clear, inked, false), 0, "none in a clear colour"); - let round = page(FrameShape::Circle, blue, 3.0); - assert!(count(&round, bluish, false) > 0, "a round frame has its border too"); - assert_eq!(count(&round, bluish, true), 0, "along the circle, not the box's corner"); - assert!(count(&thick, bluish, true) > 0, "a rectangle's border reaches its corner"); - } - - /// On a globe, the extent indicator is drawn where the globe shows the area, also away from - /// the disc's centre (#2348): through the flat camera, Svalbard 18° north of the centre came out - /// half as far again up, nearly 5 mm off on a 50 mm locator. - #[test] - fn an_extent_indicator_on_a_globe_lands_on_the_area() { - use rustgis_map::layout::{INDICATOR_COLOR, INDICATOR_WIDTH, frame_camera}; - let (area, at, scale) = (Coord::new(20.0, 78.0), Coord::new(20.0, 60.0), 2e8); - let mut globe = Map::new("g"); - globe.set_projection(rustgis_map::Projection::Globe); - let maps = || [Map::new("m"), globe.clone()]; - let frame = |map: &str, center, scale, extent_of| ElementKind::MapFrame { - map: map.into(), - center, - scale, - shape: FrameShape::Rectangle, - grid: None, - extent_of, - extent_color: INDICATOR_COLOR, - extent_width: INDICATOR_WIDTH, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }; - let mut l = Layout::new("Layout", 100.0, 100.0); - let main = l.add("Main", (60.0, 60.0, 30.0, 30.0), frame("m", area, 2e7, None)); - l.add("Locator", (5.0, 5.0, 50.0, 50.0), frame("g", at, scale, Some(main))); - let pm = render(&l, &mut maps(), 96.0, &PageInfo::default()).unwrap(); - // Where the globe draws the area, in pixels on the page. - let side = 50.0 * PT_PER_MM; - let g = rustgis_map::globe::Globe::new(&frame_camera(&globe, at, scale, 0.0, 0.0), side, side); - let (x, y) = g.forward(area).unwrap(); - // At 96 dpi a layout point is a pixel. - let expected = (5.0 * PT_PER_MM + x, 5.0 * PT_PER_MM + y); - // The red pixels' middle, inside the locator. - let px_mm = PT_PER_MM; - let red: Vec<(f64, f64)> = ((5.0 * px_mm) as u32..(55.0 * px_mm) as u32) - .flat_map(|y| ((5.0 * px_mm) as u32..(55.0 * px_mm) as u32).map(move |x| (x, y))) - .filter(|&(x, y)| { - let (r, g, b) = rgb(&pm, x, y); - r > 180 && g < 90 && b < 90 - }) - .map(|(x, y)| (f64::from(x), f64::from(y))) - .collect(); - assert!(!red.is_empty(), "no extent indicator on the globe"); - let n = red.len() as f64; - let mid = (red.iter().map(|p| p.0).sum::() / n, red.iter().map(|p| p.1).sum::() / n); - let off = ((mid.0 - expected.0).powi(2) + (mid.1 - expected.1).powi(2)).sqrt() / px_mm; - assert!(off < 1.5, "the indicator's middle {mid:?} is {off:.1} mm from the area at {expected:?}"); - } - - /// A frame on the globe is outlined by what it shows of the globe (#2348): zoomed in on Iceland, - /// around Iceland on a globe locator; seen whole, with no edge on the disc, not at all (through - /// the flat camera its edges were read as a flat world, a line drawn across the locator). - #[test] - fn a_frame_on_the_globe_is_outlined_by_what_it_shows() { - use rustgis_map::layout::{INDICATOR_COLOR, INDICATOR_WIDTH, frame_camera}; - let mut globe = Map::new("g"); - globe.set_projection(rustgis_map::Projection::Globe); - let frame = |center, scale, extent_of| ElementKind::MapFrame { - map: "g".into(), - center, - scale, - shape: FrameShape::Rectangle, - grid: None, - extent_of, - extent_color: INDICATOR_COLOR, - extent_width: INDICATOR_WIDTH, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }; - let (at, scale) = (Coord::new(-20.0, 55.0), 2e8); - // The red pixels inside the locator (5–55 mm), with the source frame on `center` at 1:`main`. - let red = |center: Coord, main: f64| { - let mut l = Layout::new("Layout", 100.0, 100.0); - // 40 mm across: near the equator, wider than the smallest globe the camera draws there. - let source = l.add("Main", (58.0, 58.0, 40.0, 40.0), frame(center, main, None)); - l.add("Locator", (5.0, 5.0, 50.0, 50.0), frame(at, scale, Some(source))); - let pm = render(&l, &mut [globe.clone()], 96.0, &PageInfo::default()).unwrap(); - let k = PT_PER_MM; - ((5.0 * k) as u32..(55.0 * k) as u32) - .flat_map(|y| ((5.0 * k) as u32..(55.0 * k) as u32).map(move |x| (x, y))) - .filter(|&(x, y)| { - let (r, g, b) = rgb(&pm, x, y); - r > 180 && g < 90 && b < 90 - }) - .map(|(x, y)| (f64::from(x), f64::from(y))) - .collect::>() - }; - let iceland = red(Coord::new(-19.0, 65.0), 2e7); - assert!(!iceland.is_empty(), "no outline of the zoomed-in frame"); - let n = iceland.len() as f64; - let mid = (iceland.iter().map(|p| p.0).sum::() / n, iceland.iter().map(|p| p.1).sum::() / n); - let side = 50.0 * PT_PER_MM; - let g = rustgis_map::globe::Globe::new(&frame_camera(&globe, at, scale, 0.0, 0.0), side, side); - let (x, y) = g.forward(Coord::new(-19.0, 65.0)).unwrap(); - let expected = (5.0 * PT_PER_MM + x, 5.0 * PT_PER_MM + y); - let off = ((mid.0 - expected.0).powi(2) + (mid.1 - expected.1).powi(2)).sqrt() / PT_PER_MM; - assert!(off < 1.5, "the outline's middle {mid:?} is {off:.1} mm from Iceland at {expected:?}"); - let whole = red(Coord::new(-20.0, 10.0), 4e8); - assert!(whole.is_empty(), "the globe seen whole outlined by {} red pixels", whole.len()); - } - - /// A frame on the globe whose sides run off the disc is outlined by its top and bottom edges - /// only, broken where they leave the disc, not joined by a line across the globe (#2348), and - /// running up to the disc's rim (#2369). - #[test] - fn a_frame_partly_off_the_globe_is_outlined_without_a_chord() { - use rustgis_map::layout::{INDICATOR_COLOR, INDICATOR_WIDTH, frame_camera}; - let mut globe = Map::new("g"); - globe.set_projection(rustgis_map::Projection::Globe); - let frame = |center, scale, extent_of| ElementKind::MapFrame { - map: "g".into(), - center, - scale, - shape: FrameShape::Rectangle, - grid: None, - extent_of, - extent_color: INDICATOR_COLOR, - extent_width: INDICATOR_WIDTH, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }; - let center = Coord::new(-20.0, 0.0); - // The source frame, 40 × 20 mm: a scale whose disc is taller than the frame, its sides in - // the sky beside the disc, and its corners too. - let (sw, sh) = (40.0, 20.0); - let disc = |scale: f64| { - let cam = frame_camera(&globe, center, scale, 0.0, 0.0); - rustgis_map::globe::Globe::new(&cam, sw * PT_PER_MM, sh * PT_PER_MM).disc_radius() / PT_PER_MM - }; - let source_scale = (1..400).map(|i| f64::from(i) * 1e6).find(|&s| disc(s) < 0.5 * sw - 3.0).unwrap(); - assert!(disc(source_scale) > 0.5 * sh + 2.0, "a disc {:.1} mm across", 2.0 * disc(source_scale)); - let (at, scale) = (center, 2.0 * source_scale); - let mut l = Layout::new("Layout", 100.0, 100.0); - let source = l.add("Main", (55.0, 70.0, sw, sh), frame(center, source_scale, None)); - l.add("Locator", (5.0, 5.0, 50.0, 50.0), frame(at, scale, Some(source))); - let pm = render(&l, &mut [globe.clone()], 96.0, &PageInfo::default()).unwrap(); - let red = |x: u32, y: u32| { - let (r, g, b) = rgb(&pm, x, y); - r > 180 && g < 90 && b < 90 - }; - let k = PT_PER_MM; - let (x0, x1) = ((5.0 * k) as u32, (55.0 * k) as u32); - let inked = (x0..x1).flat_map(|y| (x0..x1).map(move |x| (x, y))).filter(|&(x, y)| red(x, y)).count(); - assert!(inked > 0, "no outline of the frame"); - // The row through the source frame's centre, between its top and bottom edges: crossed only - // by a chord. - let side = 50.0 * k; - let g = rustgis_map::globe::Globe::new(&frame_camera(&globe, at, scale, 0.0, 0.0), side, side); - let (_, cy) = g.forward(center).unwrap(); - let row = (5.0 * k + cy).round() as u32; - let crossed: Vec = (row - 2..=row + 2).flat_map(|y| (x0..x1).filter(move |&x| red(x, y))).collect(); - assert!(crossed.is_empty(), "the outline crosses the middle of the globe at {crossed:?}"); - // The top and bottom edges are outlined up to the rim, where they leave the disc, not up - // to the last of their samples on it (#2369). - let s = rustgis_map::globe::Globe::new(&frame_camera(&globe, center, source_scale, 0.0, 0.0), sw * k, sh * k); - let (r, (sx0, sy0)) = (s.disc_radius(), s.forward(center).unwrap()); - let half = (r * r - sy0 * sy0).sqrt() - 1e-3; - for (sx, sy) in [(sx0 - half, 0.0), (sx0 + half, 0.0), (sx0 - half, sh * k), (sx0 + half, sh * k)] { - let on_rim = s.inverse(sx, sy).expect("a point just inside the rim is on the globe"); - let (x, y) = g.forward(on_rim).expect("the rim seen on the locator"); - let (x, y) = (5.0 * k + x, 5.0 * k + y); - let gap = (x0..x1) - .flat_map(|py| (x0..x1).map(move |px| (px, py))) - .filter(|&(px, py)| red(px, py)) - .map(|(px, py)| (f64::from(px) - x).hypot(f64::from(py) - y)) - .fold(f64::INFINITY, f64::min) - / k; - assert!(gap < 0.3, "the outline ends {gap:.2} mm short of the rim at ({sx:.0}, {sy:.0}) on the frame"); - } - } - - /// A frame on the globe across the antimeridian, outlined on a flat frame, stays one small box - /// near the flat frame's centre (#2348): its edge's longitudes kept continuous, not jumping from - /// 179.5° to -179.5° and drawing a line across the flat map, and brought to the flat frame's side - /// of ±180° when they start on the other. - #[test] - fn a_globe_frame_across_the_antimeridian_is_outlined_in_one_piece() { - use rustgis_map::layout::{INDICATOR_COLOR, INDICATOR_WIDTH}; - let mut globe = Map::new("g"); - globe.set_projection(rustgis_map::Projection::Globe); - let frame = |map: &str, center, scale, extent_of| ElementKind::MapFrame { - map: map.into(), - center, - scale, - shape: FrameShape::Rectangle, - grid: None, - extent_of, - extent_color: INDICATOR_COLOR, - extent_width: INDICATOR_WIDTH, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }; - // The globe frame's centre and the flat locator's: on 180°, and a frame on -179° whose - // first point (its top-left corner) is on the +180° side, on a locator on -175°. - for (source_at, locator_at) in [(180.0, 180.0), (-179.0, -175.0)] { - let mut l = Layout::new("Layout", 100.0, 100.0); - // 40 mm at 1:20M, about 800 km across: 4 mm on the locator at 1:200M. - let source = l.add("Main", (58.0, 58.0, 40.0, 40.0), frame("g", Coord::new(source_at, 0.0), 2e7, None)); - l.add("Locator", (5.0, 5.0, 50.0, 50.0), frame("m", Coord::new(locator_at, 0.0), 2e8, Some(source))); - let pm = render(&l, &mut [globe.clone(), Map::new("m")], 96.0, &PageInfo::default()).unwrap(); - let k = PT_PER_MM; - let (x0, x1) = ((5.0 * k) as u32, (55.0 * k) as u32); - let red: Vec<(u32, u32)> = (x0..x1) - .flat_map(|y| (x0..x1).map(move |x| (x, y))) - .filter(|&(x, y)| { - let (r, g, b) = rgb(&pm, x, y); - r > 180 && g < 90 && b < 90 - }) - .collect(); - assert!(!red.is_empty(), "{source_at}° on {locator_at}°: no outline of the frame"); - let middle = 30.0 * k; - let far = - red.iter().filter(|&&(x, y)| (f64::from(x) - middle).abs() > 6.0 * k || (f64::from(y) - middle).abs() > 6.0 * k).count(); - assert_eq!(far, 0, "{source_at}° on {locator_at}°: {far} of {} red pixels more than 6 mm from the middle", red.len()); - } - } - - /// A frame of the map `map`, named "s", at `source` (centre, scale, width and height in mm) - /// outlined on a locator 90 × 80 mm of the map `locator`, named "m", at `view` (centre and - /// scale), on a page 200 × 120 mm: the outline's red pixels, in millimetres from the locator's - /// centre (x east, y south). - fn outline_on(map: Map, source: (Coord, f64, f64, f64), locator: Map, view: (Coord, f64)) -> Vec<(f64, f64)> { - use rustgis_map::layout::{INDICATOR_COLOR, INDICATOR_WIDTH}; - let frame = |map: &str, center, scale, extent_of| ElementKind::MapFrame { - map: map.into(), - center, - scale, - shape: FrameShape::Rectangle, - grid: None, - extent_of, - extent_color: INDICATOR_COLOR, - extent_width: INDICATOR_WIDTH, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }; - let (at, scale, w, h) = source; - let mut l = Layout::new("Layout", 200.0, 120.0); - let main = l.add("Main", (5.0, 5.0, w, h), frame("s", at, scale, None)); - l.add("Locator", (100.0, 5.0, 90.0, 80.0), frame("m", view.0, view.1, Some(main))); - let pm = render(&l, &mut [map, locator], 96.0, &PageInfo::default()).unwrap(); - let k = PT_PER_MM; - let (x0, x1, y0, y1) = ((100.0 * k) as u32, (190.0 * k) as u32, (5.0 * k) as u32, (85.0 * k) as u32); - (y0..y1) - .flat_map(|y| (x0..x1).map(move |x| (x, y))) - .filter(|&(x, y)| { - let (r, g, b) = rgb(&pm, x, y); - r > 180 && g < 90 && b < 90 - }) - .map(|(x, y)| (f64::from(x) / k - 145.0, f64::from(y) / k - 45.0)) - .collect() - } - - /// [`outline_on`] a flat world map at 1:600M centred on (0°, 0°). - fn outline_on_flat_world(map: Map, source: (Coord, f64, f64, f64)) -> Vec<(f64, f64)> { - outline_on(map, source, Map::new("m"), (Coord::new(0.0, 0.0), 6e8)) - } - - /// A flat frame wider than what its locator's projection can show (UTM zone 31, 30° either - /// side of 3°E) is outlined there in pieces, broken where its edges leave what the locator - /// shows, not joined by a line across the locator (#2369). - #[test] - fn a_frame_wider_than_its_locators_projection_is_outlined_without_a_chord() { - let mut utm = Map::new("m"); - utm.set_projection(rustgis_map::Projection::Custom("EPSG:32631".into())); - // 80 × 20 mm at 1:175M on the equator, centred on 3°E: about 60°W to 66°E and 16°S to 16°N, - // its sides outside the zone, its top and bottom edges crossing it. - let red = outline_on(Map::new("s"), (Coord::new(3.0, 0.0), 1.75e8, 80.0, 20.0), utm, (Coord::new(3.0, 0.0), 1.5e8)); - assert!(!red.is_empty(), "no outline of the frame"); - // The equator's row is crossed only by a line joining the top edge to the bottom one. - let across: Vec<_> = red.iter().filter(|p| p.1.abs() < 1.0).collect(); - assert!(across.is_empty(), "the outline crosses the equator at {across:?}"); - } - - #[test] - fn an_extent_indicator_reaches_its_locators_projection_boundary() { - let source = Map::new("s"); - let mut locator = Map::new("m"); - locator.set_projection(rustgis_map::Projection::Custom("EPSG:32631".into())); - let center = Coord::new(3.0, 0.0); - let camera = rustgis_map::layout::frame_camera(&source, center, 1.75e8, 0.0, 0.0); - let top = source.to_lonlat(camera.to_map(40.0 * PT_PER_MM, 0.0, 80.0 * PT_PER_MM, 20.0 * PT_PER_MM)).unwrap().y; - let red = outline_on(source, (center, 1.75e8, 80.0, 20.0), locator.clone(), (center, 1.5e8)); - // UTM's forward transform accepts 30 degrees on either side of its central meridian. - // All four ends reach that boundary, whether entering or leaving the visible area. - for lon in [-27.0 + 1e-7, 33.0 - 1e-7] { - for lat in [-top, top] { - let edge = locator.to_map(Coord::new(lon, lat)).unwrap(); - let middle = locator.to_map(center).unwrap(); - let expected = ((edge.x - middle.x) / 150_000.0, (middle.y - edge.y) / 150_000.0); - let distance = red.iter().map(|p| (p.0 - expected.0).hypot(p.1 - expected.1)).fold(f64::INFINITY, f64::min); - assert!(distance < 0.6, "the outline stops {distance:.2} mm short of ({lon}, {lat})"); - } - } - } - - /// A boundary search on either side of the date line follows the short arc, in either - /// direction, rather than drawing a chord across the UTM overview (#2433). - #[test] - fn an_overviews_boundary_search_crosses_the_date_line_on_the_short_arc() { - for (code, center, inside, outside, edge) in - [("EPSG:32655", 147.0, 176.0, -179.0, 177.0 - 1e-7), ("EPSG:32606", -147.0, -176.0, 179.0, -177.0 + 1e-7)] - { - let mut map = Map::new("overview"); - map.set_projection(rustgis_map::Projection::Custom(code.into())); - let camera = rustgis_map::layout::frame_camera(&map, Coord::new(center, 0.0), 1e8, 0.0, 0.0); - let view = View { width: 600.0, height: 400.0, pixels_per_point: 1.0, camera, sky: false }; - let screen = |lon| { - let p = map.to_map(Coord::new(lon, 10.0)).unwrap(); - camera.try_to_screen(p, view.width, view.height).unwrap() - }; - let start = screen(inside); - let end = screen(edge); - for reverse in [false, true] { - let mut ring = [Some(Coord::new(inside, 10.0)), Some(Coord::new(outside, 10.0))]; - if reverse { - ring.reverse(); - } - let mut canvas = Canvas::new(600, 400).unwrap(); - outline_lonlat(&mut canvas, &map, &view, &ring, false, Rgba::rgb(255, 0, 0), 2.0); - let pm = canvas.into_pixmap(); - let red: Vec<_> = (0..400) - .flat_map(|y| (0..600).map(move |x| (x, y))) - .filter(|&(x, y)| { - let (r, g, b) = rgb(&pm, x, y); - r > 180 && g < 90 && b < 90 - }) - .map(|(x, y)| (f64::from(x), f64::from(y))) - .collect(); - assert!(!red.is_empty(), "{code}, reverse {reverse}: no outline"); - assert!( - red.iter().all(|p| p.0 >= start.0.min(end.0) - 2.0 && p.0 <= start.0.max(end.0) + 2.0), - "{code}, reverse {reverse}: a chord across the overview" - ); - assert!( - red.iter().any(|p| (p.0 - end.0).hypot(p.1 - end.1) < 2.0), - "{code}, reverse {reverse}: the outline does not reach the boundary" - ); - } - } - } - - /// A flat frame on a custom projection whose edges run off its world (Mollweide, zoomed out - /// past its ellipse) is outlined by its top and bottom edges, broken where they leave the - /// world and reaching it there, not joined by lines across the map (#2369). - #[test] - fn a_flat_frame_off_its_projections_world_is_outlined_without_a_chord() { - let mut moll = Map::new("s"); - moll.set_projection(rustgis_map::Projection::from_code("mollweide").unwrap()); - // 80 × 20 mm at 1:600M: Mollweide's world is 60 × 30 mm, so the frame's sides are off it - // and its top and bottom edges leave it about 22 mm either side of the centre. - let red = outline_on_flat_world(moll, (Coord::new(0.0, 0.0), 6e8, 80.0, 20.0)); - assert!(!red.is_empty(), "no outline of the frame"); - // The equator's row is crossed only by a line joining the top edge to the bottom one. - let across: Vec<_> = red.iter().filter(|p| p.1.abs() < 1.0).collect(); - assert!(across.is_empty(), "the outline crosses the equator at {across:?}"); - // The edges run to the world's sides, ±180° (33.4 mm from the centre at 1:600M), and no - // further: without bisecting, they stopped at the last sample on the world, at about 160°. - let reach = red.iter().fold(0.0_f64, |m, p| m.max(p.0.abs())); - assert!((reach - 33.4).abs() < 0.6, "the outline reaches {reach:.1} mm from the centre, not ±180°"); - for side in [-1.0, 1.0] { - assert!(red.iter().any(|p| (p.0 * side - 33.4).abs() < 0.6), "no outline at the world's {side} side"); - } - } - - /// A frame on the globe around the North Pole, outlined on a flat world map, is split at ±180° - /// and drawn across the whole world, not as one piece a stretch of which is off the world, past - /// ±180° (#2369). - #[test] - fn a_globe_frame_around_a_pole_is_outlined_across_a_flat_world() { - let mut globe = Map::new("s"); - globe.set_projection(rustgis_map::Projection::Globe); - // 40 mm at 1:40M, about 1600 km across, centred 5° (550 km) from the pole: the pole inside - // it. (A frame's centre is kept in Web Mercator, up to 85.05°.) - let (at, scale) = (Coord::new(30.0, 85.0), 4e7); - let cam = rustgis_map::layout::frame_camera(&globe, at, scale, 0.0, 0.0); - let side = 40.0 * PT_PER_MM; - let (px, py) = rustgis_map::globe::Globe::new(&cam, side, side).forward(Coord::new(0.0, 90.0)).expect("the pole on the disc"); - assert!((0.0..side).contains(&px) && (0.0..side).contains(&py), "the pole at ({px:.0}, {py:.0}), off the frame"); - let red = outline_on_flat_world(globe, (at, scale, 40.0, 40.0)); - assert!(!red.is_empty(), "no outline of the frame"); - // On both of the world's sides, ±180° (33.4 mm from the centre), and not past them. - for dir in [-1.0, 1.0] { - assert!(red.iter().any(|p| (p.0 * dir - 33.4).abs() < 1.0), "no outline at the world's {dir} side"); - } - let past: Vec<_> = red.iter().filter(|p| p.0.abs() > 34.2).collect(); - assert!(past.is_empty(), "{} red pixels past ±180°, as far as {:?}", past.len(), past.iter().map(|p| p.0).fold(0.0_f64, f64::max)); - } - - /// A ring placed on Robinson centred on 150°E, whose edge is at -30°, is cut there, each piece - /// on its side of the map, not joined across it (#2369): a flat frame's ring across the edge, - /// and a globe frame's around a pole, a whole turn of longitude. - #[test] - fn a_ring_is_cut_at_its_maps_own_edge() { - let mut robinson = Map::new("m"); - robinson.set_projection(rustgis_map::Projection::Custom("robinson +lon_0=150".into())); - let mid = Some(Coord::new(150.0, 0.0)); - let flat = [(-40.0, 10.0), (-20.0, 10.0), (-20.0, 20.0), (-40.0, 20.0), (-40.0, 10.0)].map(|(x, y)| Some(Coord::new(x, y))); - // From 20°E all the way round, 85°N, as a pole's ring runs, its longitudes continuous. - let pole: Vec> = (0..=36).map(|i| Some(Coord::new(20.0 + 10.0 * f64::from(i), 85.0))).collect(); - for (name, ring, from_globe) in [("flat", &flat[..], false), ("pole", &pole[..], true)] { - let placed = ring_on_flat(&robinson, mid, ring, from_globe); - let points: Vec = placed.iter().flatten().copied().collect(); - assert!(!points.is_empty(), "{name}: nothing placed"); - // Every point in the map's world, -30° to 330°, so it projects onto its own side. - let out: Vec<_> = points.iter().filter(|c| !(-30.0..=330.0).contains(&c.x)).collect(); - assert!(out.is_empty(), "{name}: points outside the map's world: {out:?}"); - // On both sides of the edge, the pieces broken apart. - assert!(points.iter().any(|c| c.x < -29.0) && points.iter().any(|c| c.x > 329.0), "{name}: not on both sides: {points:?}"); - let jumps: Vec<_> = placed.windows(2).filter_map(|w| Some((w[0]?, w[1]?))).filter(|(a, b)| (a.x - b.x).abs() > 180.0).collect(); - assert!(jumps.is_empty(), "{name}: joined across the edge: {jumps:?}"); - } - // On Web Mercator, which doesn't wrap, a flat frame's ring is placed where it is. - assert_eq!(ring_on_flat(&Map::new("m"), Some(Coord::new(0.0, 0.0)), &flat, false), flat.to_vec()); - } - - /// A flat frame wider than the world, outlined on another flat frame, is drawn where it is - /// (#2348): its first point past -180° doesn't move it a turn east, so both its sides show. - #[test] - fn a_flat_frame_wider_than_the_world_is_outlined_where_it_is() { - use rustgis_map::layout::{INDICATOR_COLOR, INDICATOR_WIDTH}; - let frame = |center, scale, extent_of| ElementKind::MapFrame { - map: "m".into(), - center, - scale, - shape: FrameShape::Rectangle, - grid: None, - extent_of, - extent_color: INDICATOR_COLOR, - extent_width: INDICATOR_WIDTH, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }; - let at = Coord::new(0.0, 0.0); - let mut l = Layout::new("Layout", 200.0, 120.0); - // 80 mm at 1:529M on the equator: about 380° of longitude, -190° to 190°. - let source = l.add("Main", (5.0, 5.0, 80.0, 20.0), frame(at, 5.29e8, None)); - // 90 mm at 1:593M: about 480°, so both of the source's sides are in it. - l.add("Locator", (100.0, 5.0, 90.0, 60.0), frame(at, 5.93e8, Some(source))); - let pm = render(&l, &mut [Map::new("m")], 96.0, &PageInfo::default()).unwrap(); - let k = PT_PER_MM; - let red = |x: u32, y: u32| { - let (r, g, b) = rgb(&pm, x, y); - r > 180 && g < 90 && b < 90 - }; - let (top, bottom) = ((5.0 * k) as u32, (65.0 * k) as u32); - let middle = 145.0 * k; - let side = |xs: std::ops::Range| xs.flat_map(|x| (top..bottom).map(move |y| (x, y))).filter(|&(x, y)| red(x, y)).count(); - let (west, east) = (side((100.0 * k) as u32..(middle - 10.0 * k) as u32), side((middle + 10.0 * k) as u32..(190.0 * k) as u32)); - assert!(west > 0 && east > 0, "the outline's sides: {west} red pixels west of the middle, {east} east"); - } - - fn rgb(pm: &Pixmap, x: u32, y: u32) -> (u8, u8, u8) { - pm.pixel(x, y).map(|p| (p.red(), p.green(), p.blue())).unwrap_or((255, 255, 255)) - } - - /// A colorbar's title longer than the element is wide wraps inside it (#2493), every word kept; - /// the bar goes under its lines. - #[test] - fn a_colorbars_long_title_wraps_inside_it() { - let scale = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(200, 200, 200), Rgba::rgb(230, 230, 230)] }; - let title = "Precipitação média mensal JAXA GSMaP (mm/mês), jan–mar 2025"; - let bar = - Bar { title, orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; - // A canvas wider than the element, so ink past its right edge shows. - let mut c = Canvas::new(600, 200).unwrap(); - let r = Rect::from_xywh(10.0, 10.0, 200.0, 150.0).unwrap(); - colorbar(&mut c, r, &scale, &bar, 1.0); - let dark = |x: u32, y: u32| c.pixmap().pixel(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120); - let past = (r.right().ceil() as u32 + 1..600).find(|x| (0..200).any(|y| dark(*x, y))); - assert_eq!(past, None, "the title's ink past the element's right edge"); - let lines = colorbar_title_lines(title, 200.0 / PT_PER_MM); - assert!(lines.len() >= 2, "{lines:?}"); - assert_eq!(lines.concat().replace(' ', ""), title.replace(' ', ""), "every word is kept"); - // The second line is inked, under the first. - let pitch = (COLORBAR_TITLE_PT * 1.33 * 1.25) as u32; - let line = |y0: u32| (y0..y0 + 8).any(|y| (10..210).any(|x| dark(x, y))); - assert!(line(10 + pitch + 3), "a second line of title"); - } - - /// A colorbar's title stops short of the bar's own room, so a long title never leaves the bar - /// without its tick labels: the bar ends above them, its labels under it (#2638). Before, the - /// title's second line took the room, and the bar filled the element's bottom with no labels. - #[test] - fn a_colorbars_long_title_leaves_its_bar_room_for_labels() { - // A red-to-blue bar, so its pixels are told apart from the grey text. - let scale = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(220, 30, 30), Rgba::rgb(30, 30, 220)] }; - let title = "Precipitação média mensal JAXA GSMaP (mm/mês), jan–mar 2025"; - let bar = - Bar { title, orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; - // 100 × 40 px: room for two lines of title, but then only 8 px of bar, with no labels. - let mut c = Canvas::new(300, 200).unwrap(); - colorbar(&mut c, Rect::from_xywh(10.0, 10.0, 100.0, 40.0).unwrap(), &scale, &bar, 1.0); - let px = |x: u32, y: u32| c.pixmap().pixel(x, y); - let coloured = - |y: u32| (10..110).any(|x| px(x, y).is_some_and(|p| p.alpha() > 200 && p.green() < 90 && p.red().abs_diff(p.blue()) > 60)); - let dark = |y: u32| (10..110).any(|x| px(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120 && p.blue() < 120)); - assert!((26..36).any(coloured), "the bar under the title"); - assert!(!(44..50).any(coloured), "the bar ends above its labels, not at the element's bottom"); - assert!((40..50).any(dark), "its labels under it"); - } - - /// A vertical colorbar's end labels are centred on its bar's ends, so its title leaves the bar - /// two labels' height (#2638): a vertical colorbar 25 px high (6.6 mm at 96 dpi) holds its - /// one-line title back and says so, its bar keeping both end labels, and one 12 mm high draws - /// the title and says nothing. A vertical colorbar too short for its end labels, or too narrow - /// for its labels beside the bar, says so even with no title, and a horizontal one too short - /// for its labels under its bar, too. - #[test] - fn a_colorbars_labels_left_out_are_said() { - let map = ramp_map( - rustgis_map::raster::RasterRenderer::Stretch { band: 0, ramp: rustgis_map::Ramp::Thermal, invert: false }, - rustgis_map::raster::Stretch::MinMax, - ); - let info = PageInfo::default(); - let mm = 25.4 / 96.0; - // (orientation, title, width and height in mm, a loss said, title lines left out) - for (orientation, title, w, h, said, left_out) in [ - (Orientation::Vertical, "Elevation (m)", 25.0, 25.0 * mm, true, 1), - (Orientation::Vertical, "Elevation (m)", 25.0, 12.0, false, 0), - (Orientation::Vertical, "", 25.0, 12.0 * mm, true, 0), - (Orientation::Vertical, "", 25.0, 25.0 * mm, false, 0), - // Too narrow for its labels beside the bar: they're left out, and said. - (Orientation::Vertical, "", 2.0, 25.0, true, 0), - (Orientation::Horizontal, "", 25.0, 15.0 * mm, true, 0), - (Orientation::Horizontal, "", 25.0, 25.0 * mm, false, 0), - ] { - let mut l = Layout::new("Page", 120.0, 90.0); - let frame = l.add( - "Frame", - (60.0, 60.0, 50.0, 25.0), - serde_json::from_value(serde_json::json!({"MapFrame":{"map":"m", "center":{"x":0,"y":0}, "scale":1000000}})).unwrap(), - ); - let kind = ElementKind::Colorbar { - frame, - layer: None, - title: title.into(), - orientation, - ticks: 5, - tick_side: TickSide::End, - reverse: false, - color: None, - }; - l.add("Colorbar", (5.0, 5.0, w, h), kind); - let losses = text_losses(&l, std::slice::from_ref(&map), 96.0, &info); - let case = format!("{orientation:?} {title:?} {w:.1} × {h:.1} mm: {losses:?}"); - assert_eq!(losses.len() == 1, said, "{case}"); - if let Some(loss) = losses.first() { - assert!(loss.below_box && loss.left_out == left_out, "{case}"); - // Its own advice, not a text's line breaks. - let note = clipped_text_notice(&l, &[(loss.id, loss.name.clone())]).unwrap_or_default(); - assert!(note.contains("make the colorbar larger"), "{case}: {note}"); - } - } - // As drawn: 25 px high, the title held back, both end labels inside the element. - let scale = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(220, 30, 30), Rgba::rgb(30, 30, 220)] }; - let bar = Bar { - title: "Elevation (m)", - orientation: Orientation::Vertical, - ticks: 2, - side: TickSide::End, - reverse: false, - comma: false, - ink: INK, - }; - let mut c = Canvas::new(200, 100).unwrap(); - colorbar(&mut c, Rect::from_xywh(10.0, 10.0, 100.0, 25.0).unwrap(), &scale, &bar, 1.0); - let dark = |x: u32, y: u32| c.pixmap().pixel(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120 && p.blue() < 120); - // The labels stand to the bar's right, past its ticks: ink near its top end and its bottom. - let label_ink = |ys: std::ops::Range| ys.into_iter().any(|y| (60..110).any(|x| dark(x, y))); - assert!(label_ink(10..20), "the top end's label"); - assert!(label_ink(26..36), "the bottom end's label"); - } - - /// A label left out for spilling out of a colorbar takes no room, so it doesn't thin the next - /// one away unsaid (#2638): on a bar 40 px wide, the end label 1000 spills past its left - /// side and is counted, and the middle label 1500, inside, is still drawn. - #[test] - fn a_colorbars_spilled_label_doesnt_thin_the_next() { - let scale = ColorScale::Ramp { lo: 1000.0, hi: 2000.0, colors: vec![Rgba::rgb(220, 30, 30), Rgba::rgb(30, 30, 220)] }; - let bar = - Bar { title: "", orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; - let plan = colorbar_plan(Rect::from_xywh(0.0, 0.0, 40.0, 40.0).unwrap(), &scale, &bar, 1.0); - let drawn: Vec<&str> = plan.labels.iter().map(|l| l.0.as_str()).collect(); - assert!(plan.spilled >= 1, "the end label spills: {drawn:?}"); - assert!(drawn.contains(&"1500"), "the middle label is drawn: {drawn:?}"); - } - - /// A colorbar too short for a line of title over its bar holds the title back, and the bar - /// then starts at the element's top, keeping its labels: a title not drawn takes no room - /// (#2638). Before, the bar was pushed down by the room of a line never drawn, and lost them. - #[test] - fn a_colorbar_whose_title_is_held_back_keeps_its_labels() { - let scale = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(220, 30, 30), Rgba::rgb(30, 30, 220)] }; - let title = "Precipitação média mensal JAXA GSMaP (mm/mês), jan–mar 2025"; - let bar = - Bar { title, orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; - // 100 × 30 px, from y = 10 to 40: a line of title (16.8 px) and the bar's own room - // (19.8) don't both fit, so no line is drawn. - assert_eq!( - colorbar_title_drawn(4, 10.0, 40.0 - colorbar_bar_room(1.0, Orientation::Horizontal), COLORBAR_TITLE_PT as f32 * 1.33), - 0 - ); - let mut c = Canvas::new(300, 200).unwrap(); - colorbar(&mut c, Rect::from_xywh(10.0, 10.0, 100.0, 30.0).unwrap(), &scale, &bar, 1.0); - let px = |x: u32, y: u32| c.pixmap().pixel(x, y); - let coloured = - |y: u32| (10..110).any(|x| px(x, y).is_some_and(|p| p.alpha() > 200 && p.green() < 90 && p.red().abs_diff(p.blue()) > 60)); - let dark = |y: u32| (10..110).any(|x| px(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120 && p.blue() < 120)); - assert!((11..15).any(coloured), "the bar at the element's top"); - assert!(!(35..40).any(coloured), "the bar ends above its labels"); - assert!((30..40).any(dark), "its labels under it"); - } - - /// A colorbar's title lines are drawn only where the bar keeps its own room under them, the - /// first too, with no slack: the bar never loses its labels to them (#2638). At 12 px a line, - /// the first needs 16.8 px and each further one 15 more, over the bar's 19.8. - #[test] - fn a_colorbars_title_lines_leave_the_bar_its_room() { - let (px, room) = (COLORBAR_TITLE_PT as f32 * 1.33, colorbar_bar_room(1.0, Orientation::Horizontal)); - for (height, lines) in [(20.0, 0), (36.0, 0), (37.0, 1), (51.2, 1), (52.0, 2), (200.0, 5)] { - assert_eq!(colorbar_title_drawn(5, 0.0, height - room, px), lines, "{height} px"); - } - // Whatever the height, the lines drawn leave the bar its room. - for h in 0..300 { - let h = h as f32 * 0.5; - let n = colorbar_title_drawn(5, 0.0, h - room, px); - assert!(n == 0 || px * (1.4 + 1.25 * (n - 1) as f32) + room <= h, "{h} px: {n} lines"); - } - } - - /// A colorbar too short for its title's lines draws those that fit inside it, not lines past - /// its bottom, and the page's cut-off check says the rest are left out; one tall enough says - /// nothing (#2493). - #[test] - fn a_colorbars_title_lines_past_its_bottom_are_left_out_and_said() { - let scale = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(200, 200, 200), Rgba::rgb(230, 230, 230)] }; - let title = "Precipitação média mensal JAXA GSMaP (mm/mês), jan–mar 2025"; - let bar = - Bar { title, orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; - // 100 px wide, four lines or more; 20 px high, no line: the first's room would end at - // 10 + 12 × 1.4 = 26.8, leaving the bar less than its own 19.8 (a second would be centred - // at 32, within a line of the bottom at 30, as a text element's line may be). - assert!(colorbar_title_lines(title, 100.0 / PT_PER_MM).len() >= 4); - let mut c = Canvas::new(300, 200).unwrap(); - colorbar(&mut c, Rect::from_xywh(10.0, 10.0, 100.0, 20.0).unwrap(), &scale, &bar, 1.0); - let dark = |x: u32, y: u32| c.pixmap().pixel(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120); - let lowest = (0..200).rev().find(|y| (0..300).any(|x| dark(x, *y))); - assert!(lowest.is_some_and(|y| y <= 30), "ink down to {lowest:?}, past the colorbar's bottom at 30"); - // On a page, in a frame whose map has a raster on a ramp. - let map = ramp_map( - rustgis_map::raster::RasterRenderer::Stretch { band: 0, ramp: rustgis_map::Ramp::Thermal, invert: false }, - rustgis_map::raster::Stretch::MinMax, - ); - let mut l = Layout::new("Page", 120.0, 90.0); - let frame = l.add( - "Frame", - (60.0, 60.0, 50.0, 25.0), - serde_json::from_value(serde_json::json!({"MapFrame":{"map":"m", "center":{"x":0,"y":0}, "scale":1000000}})).unwrap(), - ); - let kind = ElementKind::Colorbar { - frame, - layer: None, - title: title.into(), - orientation: Orientation::Horizontal, - ticks: 5, - tick_side: TickSide::End, - reverse: false, - color: None, - }; - let id = l.add("Colorbar", (5.0, 5.0, 25.0, 6.0), kind); - let info = PageInfo::default(); - let losses = text_losses(&l, std::slice::from_ref(&map), 96.0, &info); - assert_eq!(losses.len(), 1, "the short colorbar's title is cut"); - // 6 mm high: no room for a line of title over the bar's own: every line said. - let lines = colorbar_title_lines(title, 25.0).len(); - assert!(lines >= 3 && losses[0].id == id && losses[0].below_box, "{lines} lines"); - assert_eq!(losses[0].left_out, lines); - l.element_mut(id).unwrap().h = 40.0; - assert!(text_losses(&l, std::slice::from_ref(&map), 96.0, &info).is_empty(), "tall enough for every line"); - } - - #[test] - fn colorbars_draw_the_raster_colour_scale() { - use rustgis_map::raster::{RasterRenderer, Stretch}; - let ramp = rustgis_map::Ramp::Thermal; - let map = ramp_map(RasterRenderer::Stretch { band: 0, ramp: ramp.clone(), invert: false }, Stretch::MinMax); - let k = PT_PER_MM; - // A row through the bar, near its top edge (the labels are below it). - let y = (12.0 * k) as u32; - let pm = colorbar_page(&map, Orientation::Horizontal, false, ""); - let (left, right) = (rgb(&pm, (16.0 * k) as u32, y), rgb(&pm, (84.0 * k) as u32, y)); - let close = |a: (u8, u8, u8), b: Rgba| a.0.abs_diff(b.r()) < 40 && a.1.abs_diff(b.g()) < 40 && a.2.abs_diff(b.b()) < 40; - assert!(close(left, ramp.at(0.0)), "the low end is the ramp's start: {left:?} vs {:?}", ramp.at(0.0)); - assert!(close(right, ramp.at(1.0)), "the high end is the ramp's end: {right:?} vs {:?}", ramp.at(1.0)); - // Labelled below the bar: dark text under it, between the bar and the element's bottom. - let inked = |pm: &Pixmap, y0: f64, y1: f64| { - ((y0 * k) as u32..(y1 * k) as u32).any(|y| (0..pm.width()).any(|x| rgb(pm, x, y).0 < 80 && rgb(pm, x, y).2 < 80)) - }; - assert!(inked(&pm, 26.0, 30.0), "tick labels below the bar"); - // Reversed, the ends swap. - let rev = colorbar_page(&map, Orientation::Horizontal, true, ""); - assert!(close(rgb(&rev, (16.0 * k) as u32, y), ramp.at(1.0))); - assert!(close(rgb(&rev, (84.0 * k) as u32, y), ramp.at(0.0))); - // Vertical, low values sit at the bottom. - let v = colorbar_page(&map, Orientation::Vertical, false, ""); - let x = (11.0 * k) as u32; - assert!(close(rgb(&v, x, (85.0 * k) as u32), ramp.at(0.0)), "{:?}", rgb(&v, x, (85.0 * k) as u32)); - assert!(close(rgb(&v, x, (15.0 * k) as u32), ramp.at(1.0)), "{:?}", rgb(&v, x, (15.0 * k) as u32)); - // A title pushes the bar down under it. - let t = colorbar_page(&map, Orientation::Horizontal, false, "Elevation (m)"); - assert!(inked(&t, 10.0, 13.0), "the title is drawn at the top"); - - // Classes draw as steps, one colour each. - let breaks = vec![24.0, 49.0, 74.0, 99.0]; - let classify = - RasterRenderer::Classify { band: 0, method: rustgis_map::ClassMethod::EqualInterval, ramp: ramp.clone(), breaks, classes: 4 }; - let classes = ramp_map(classify, Stretch::MinMax); - // Named: a colorbar with no layer leaves a raster drawn by classes to the legend (#1679). - assert!(rustgis_map::layout::colorbar_layer(&classes, None).is_none()); - assert!(rustgis_map::layout::colorbar_layer(&map, None).is_some(), "a stretch is the default's"); - // A stretched raster in a hidden group isn't the default's: the one the map shows is. - let mut hidden = map.clone(); - let top = hidden.layers[0].clone(); - let id = hidden.add_raster("hidden", top.raster.clone().unwrap()); - let mut group = rustgis_map::LayerGroup::new("off"); - group.visible = false; - group.children.push(id); - hidden.add_group(group); - assert_eq!(rustgis_map::layout::colorbar_layer(&hidden, None).map(|l| l.name.as_str()), Some("dem")); - let pm = colorbar_page(&classes, Orientation::Horizontal, false, ""); - let mut colours: Vec<(u8, u8, u8)> = ((16.0 * k) as u32..(84.0 * k) as u32).map(|x| rgb(&pm, x, y)).collect(); - colours.dedup(); - assert!((4..=7).contains(&colours.len()), "four steps (and their seams): {colours:?}"); - - // In an element too short for its labels, they are left out rather than drawn under it. - let mut l = Layout::new("Layout", 100.0, 100.0); - let frame = l.add( - "Map", - (95.0, 95.0, 4.0, 4.0), - ElementKind::MapFrame { - map: "m".into(), - center: Coord::new(0.0, 0.0), - scale: 1e8, - shape: FrameShape::Rectangle, - grid: None, - extent_of: None, - extent_color: rustgis_map::layout::INDICATOR_COLOR, - extent_width: rustgis_map::layout::INDICATOR_WIDTH, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }, - ); - let kind = ElementKind::Colorbar { - frame, - layer: None, - title: String::new(), - orientation: Orientation::Horizontal, - ticks: 5, - tick_side: TickSide::End, - reverse: false, - color: None, - }; - l.add("Colorbar", (10.0, 10.0, 80.0, 3.0), kind); - let short = render(&l, &mut [map.clone()], 96.0, &PageInfo::default()).unwrap(); - assert!(!inked(&short, 13.5, 20.0), "nothing spills below the element"); - assert!(close(rgb(&short, (16.0 * k) as u32, (11.0 * k) as u32), ramp.at(0.0)), "the bar is still drawn"); - - // RGB has no colour scale: a placeholder, not a bar. - let pm = colorbar_page( - &ramp_map(RasterRenderer::Rgb { red: 0, green: 0, blue: 0 }, Stretch::MinMax), - Orientation::Horizontal, - false, - "", - ); - assert_eq!(rgb(&pm, (16.0 * k) as u32, y), (0xF0, 0xF1, 0xF3)); - } - - #[test] - fn colorbar_tick_labels_are_even_and_tidy() { - let labels = |lo, hi, n| tick_labels(lo, hi, n).into_iter().map(|(_, s)| s).collect::>(); - assert_eq!(labels(0.0, 100.0, 5), ["0", "25", "50", "75", "100"]); - assert_eq!(labels(0.0, 1.0, 5), ["0.00", "0.25", "0.50", "0.75", "1.00"]); - assert_eq!(labels(0.0, 1.0, 3), ["0.0", "0.5", "1.0"]); - assert_eq!(labels(-1.0, 1.0, 2), ["-1", "1"]); - // Odd bounds keep only the decimals the step needs. - assert_eq!(labels(12.345, 87.9, 2), ["12", "88"]); - assert_eq!(labels(-0.004, 1.0, 2), ["0", "1"], "no -0"); - // One value: one label. Out of range counts are clamped. - assert_eq!(labels(5.0, 5.0, 5), ["5"]); - assert_eq!(tick_labels(0.0, 1.0, 0).len(), 2); - assert_eq!(tick_labels(0.0, 1.0, 1000).len(), rustgis_map::layout::MAX_COLORBAR_TICKS); - assert!(tick_labels(f64::NAN, 1.0, 5).is_empty()); - assert_eq!(labels(0.0, 4e6, 2), ["0", "4.0M"]); - } - - #[test] - fn hairline_rectangles_draw_thin() { - // A filled 0.15 mm rule at 300 dpi is under two pixels tall, not a 1 mm bar (#211). - let mut l = Layout::new("Layout", 50.0, 20.0); - l.add( - "Rule", - (5.0, 10.0, 40.0, 0.15), - ElementKind::Rectangle { fill: Rgba::rgb(0, 0, 0), outline: Rgba::rgb(0, 0, 0), width: 0.0, radius: 0.0, dash: None }, - ); - let pm = render(&l, &mut [], 300.0, &PageInfo::default()).unwrap(); - let x = pm.width() / 2; - let inked = (0..pm.height()).filter(|&y| pm.pixel(x, y).is_some_and(|p| p.red() < 250)).count(); - assert!((1..=3).contains(&inked), "{inked} rows inked"); - } - - #[test] - fn arrowheads_are_drawn_at_the_ends_they_point_to() { - use rustgis_map::layout::LineDir; - // 100 × 20 mm at 254 dpi (ten pixels a millimetre); a level arrow from 10 to 90 mm. - let mut l = Layout::new("Layout", 100.0, 20.0); - let blue = Rgba::rgb(0, 0, 255); - l.add( - "Arrow", - (10.0, 7.0, 80.0, 6.0), - ElementKind::Line { color: blue, width: 1.0, dir: LineDir::Horizontal, head: LineHead::End, dash: None }, - ); - let pm = render(&l, &mut [], 254.0, &PageInfo::default()).unwrap(); - let inked = |x: u32, y: u32| pm.pixel(x, y).is_some_and(|p| p.red() < 128 && p.blue() > 128); - // At 254 dpi (2.65 pixels a point) the shaft is about 2.6 px wide and the head about 22 px - // long and 10 px either side of the line: 5 px off the line, 15 px back from the tip, is - // inside the head, but clear of the shaft at the tail. - assert!(inked(500, 100), "the shaft"); - assert!(inked(885, 105) && inked(885, 95), "the head, either side of the line"); - assert!(!inked(115, 105) && !inked(115, 95), "no head at the tail"); - assert!(!inked(905, 100), "nothing past the tip"); - } - - #[test] - fn ellipses_and_lines_draw_inside_their_boxes() { - use rustgis_map::layout::LineDir; - // 100 × 50 mm at 254 dpi: ten pixels a millimetre. - let mut l = Layout::new("Layout", 100.0, 50.0); - let red = Rgba::rgb(255, 0, 0); - l.add("Circle", (10.0, 10.0, 30.0, 30.0), ElementKind::Ellipse { fill: red, outline: red, width: 0.0, dash: None }); - l.add( - "Line", - (50.0, 10.0, 40.0, 30.0), - ElementKind::Line { color: Rgba::rgb(0, 0, 255), width: 2.0, dir: LineDir::Rising, head: LineHead::None, dash: None }, - ); - let pm = render(&l, &mut [], 254.0, &PageInfo::default()).unwrap(); - let is = |x: u32, y: u32, want: (u8, u8, u8)| pm.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == want); - let (white, red, blue) = ((255, 255, 255), (255, 0, 0), (0, 0, 255)); - // The circle's middle is filled; its box's corner, outside the circle, isn't. - assert!(is(250, 250, red), "circle centre"); - assert!(is(110, 110, white), "outside the circle, in its box's corner"); - // The rising line runs from the box's bottom-left to its top-right, through the middle. - assert!(is(700, 250, blue), "the line's middle"); - assert!(is(550, 150, white) && is(850, 350, white), "the other diagonal stays blank"); - } - - /// A 100 × 100 mm page with one map frame filling 10–90 mm, showing the world at 1:200M with - /// `grid` over it, drawn at 96 dpi. - fn grid_page(grid: rustgis_map::layout::Grid) -> Pixmap { - let mut maps = vec![Map::new("m")]; - let mut l = Layout::new("Layout", 100.0, 100.0); - l.add( - "Map", - (10.0, 10.0, 80.0, 80.0), - ElementKind::MapFrame { - map: "m".into(), - center: Coord::new(0.0, 0.0), - scale: 2e8, - shape: FrameShape::Rectangle, - grid: Some(grid), - extent_of: None, - extent_color: rustgis_map::layout::INDICATOR_COLOR, - extent_width: rustgis_map::layout::INDICATOR_WIDTH, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }, - ); - render(&l, &mut maps, 96.0, &PageInfo::default()).unwrap() - } - - /// Pixels in the box (page millimetres) that `hit` picks. - fn count(pm: &Pixmap, (x0, y0, x1, y1): (f64, f64, f64, f64), hit: impl Fn(tiny_skia::PremultipliedColorU8) -> bool) -> usize { - let px = |mm: f64| (mm * PT_PER_MM) as u32; - (px(y0)..px(y1)).flat_map(|y| (px(x0)..px(x1)).map(move |x| (x, y))).filter(|&(x, y)| pm.pixel(x, y).is_some_and(&hit)).count() - } - - fn red(p: tiny_skia::PremultipliedColorU8) -> bool { - p.red() > 180 && p.green() < 90 && p.blue() < 90 - } - - fn ink(p: tiny_skia::PremultipliedColorU8) -> bool { - p.red() < 90 && p.green() < 90 && p.blue() < 90 - } - - /// A page whose 80 mm frame shows Winterthur at 1:25,000 (2 km across) on a map in `projection`. - fn winterthur_page(grid: rustgis_map::layout::Grid, projection: rustgis_map::Projection) -> Pixmap { - let mut m = Map::new("m"); - m.projection = projection; - let mut maps = vec![m]; - let mut l = Layout::new("Layout", 100.0, 100.0); - l.add( - "Map", - (10.0, 10.0, 80.0, 80.0), - ElementKind::MapFrame { - map: "m".into(), - center: Coord::new(8.73, 47.5), - scale: 25_000.0, - shape: FrameShape::Rectangle, - grid: Some(grid), - extent_of: None, - extent_color: rustgis_map::layout::INDICATOR_COLOR, - extent_width: rustgis_map::layout::INDICATOR_WIDTH, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }, - ); - render(&l, &mut maps, 96.0, &PageInfo::default()).unwrap() - } - - /// Where red runs cross a row of the page (page millimetres): the middle of each run. - fn red_runs(pm: &Pixmap, y_mm: f64) -> Vec { - let y = (y_mm * PT_PER_MM) as u32; - let mut out = Vec::new(); - let mut start = None; - for x in 0..pm.width() { - match (pm.pixel(x, y).is_some_and(red), start) { - (true, None) => start = Some(x), - (false, Some(s)) => { - out.push(f64::from(s + x - 1) / 2.0 / PT_PER_MM); - start = None; - } - _ => {} - } - } - out - } - - /// A measured grid: eastings and northings its step apart in its coordinate system (1 km is - /// 40 mm at 1:25,000), bent onto the map's projection, straight on a map in that system; the - /// map's own system, else the frame's UTM zone, when it names none; nothing for a system it - /// can't draw. - #[test] - fn measured_grids_draw_eastings_and_northings() { - use rustgis_map::layout::{Grid, GridKind}; - let utm = Grid { - kind: GridKind::Measured, - crs: Some("EPSG:25832".into()), - step: 1000.0, - color: Rgba::rgb(0xFF, 0, 0), - labels: false, - width: 1.5, - ..Grid::default() - }; - let gaps = |xs: &[f64]| xs.windows(2).map(|w| w[1] - w[0]).collect::>(); - // On Web Mercator: 1 km is 40 mm on paper, give or take Mercator's scale at 47.5°N. - let pm = winterthur_page(utm.clone(), rustgis_map::Projection::WebMercator); - let xs = red_runs(&pm, 50.0); - assert!(xs.len() >= 2, "{xs:?}"); - assert!(gaps(&xs).iter().all(|g| (g - 40.0).abs() < 1.5), "{xs:?}"); - // On a map in EPSG:25832 itself: exactly 40 mm, and straight (the same at the top and bottom). - let own = rustgis_map::Projection::Custom("EPSG:25832".into()); - let pm = winterthur_page(utm.clone(), own.clone()); - let (top, bottom) = (red_runs(&pm, 20.0), red_runs(&pm, 80.0)); - assert!(gaps(&top).iter().all(|g| (g - 40.0).abs() < 0.3), "{top:?}"); - assert_eq!(top.len(), bottom.len()); - assert!(top.iter().zip(&bottom).all(|(a, b)| (a - b).abs() < 0.3), "{top:?} {bottom:?}"); - // Naming none: the map's own system draws the same grid; on Web Mercator, UTM 32N's - // (EPSG:32632, the same eastings as 25832 to a metre) does. - let unnamed = Grid { crs: None, ..utm.clone() }; - assert!(red_runs(&winterthur_page(unnamed.clone(), own), 20.0).iter().zip(&top).all(|(a, b)| (a - b).abs() < 0.3)); - let mercator = red_runs(&winterthur_page(utm.clone(), rustgis_map::Projection::WebMercator), 20.0); - let zone = red_runs(&winterthur_page(unnamed, rustgis_map::Projection::WebMercator), 20.0); - assert_eq!(mercator.len(), zone.len()); - assert!(mercator.iter().zip(&zone).all(|(a, b)| (a - b).abs() < 0.3), "{mercator:?} {zone:?}"); - // A map in an ESRI system (or a preset): its own, by its PROJ definition, straight on it. - let esri = rustgis_map::Projection::Custom("ESRI:102031".into()); - let pm = winterthur_page(Grid { crs: None, ..utm.clone() }, esri); - let (top, bottom) = (red_runs(&pm, 20.0), red_runs(&pm, 80.0)); - assert!(top.len() >= 2 && top.len() == bottom.len(), "{top:?} {bottom:?}"); - assert!(top.iter().zip(&bottom).all(|(a, b)| (a - b).abs() < 0.3), "the map's own system: straight {top:?} {bottom:?}"); - // A system it can't draw (geographic, unknown): nothing. - for crs in ["EPSG:4326", "EPSG:1", "not a system"] { - let pm = winterthur_page(Grid { crs: Some(crs.into()), ..utm.clone() }, rustgis_map::Projection::WebMercator); - assert_eq!(count(&pm, (10.0, 10.0, 90.0, 90.0), red), 0, "{crs}"); - } - // A step too fine for the frame is widened rather than drawn as a blur. - let fine = winterthur_page(Grid { step: 1.0, ..utm.clone() }, rustgis_map::Projection::WebMercator); - // (About 2 km across: 50 m apart, some 40 lines across the frame.) - let across = red_runs(&fine, 50.0).len(); - assert!((20..=55).contains(&across), "{across} lines across: not a red blur"); - // Its labels: eastings and northings, whole or short, a step apart. - let tr = rustgis_data::raster::Crs::parse("EPSG:25832").unwrap().transformer().unwrap(); - let frame: Vec = - [(8.71, 47.49), (8.75, 47.49), (8.75, 47.51), (8.71, 47.51)].iter().map(|&(x, y)| Coord::new(x, y)).collect(); - let mut lines = Vec::new(); - measured_lines(&utm, &tr, &frame, false, &mut lines); - let eastings: Vec<&str> = lines.iter().filter(|l| l.2).map(|l| l.1.as_str()).collect(); - assert!(eastings.contains(&"479000") && eastings.contains(&"480000"), "{eastings:?}"); - assert!(lines.iter().filter(|l| !l.2).any(|l| l.1 == "5261000"), "{lines:?}"); - let mut short = Vec::new(); - measured_lines(&Grid { short: true, ..utm.clone() }, &tr, &frame, false, &mut short); - assert!(short.iter().any(|l| l.2 && l.1 == "79") && short.iter().any(|l| !l.2 && l.1 == "61")); - // MGRS labels: an interval picked for the frame is at most 100 km, a square's side. - let country: Vec = [(3.0, 43.0), (15.0, 43.0), (15.0, 52.0), (3.0, 52.0)].iter().map(|&(x, y)| Coord::new(x, y)).collect(); - let tr32 = rustgis_data::raster::Crs::from_epsg(32632).unwrap().transformer().unwrap(); - let step_of = |g: &Grid| { - let mut l = Vec::new(); - measured_lines(g, &tr32, &country, false, &mut l); - let mut xs: Vec = l.iter().filter(|l| l.2).filter_map(|l| l.1.parse::().ok()).collect(); - xs.sort_by(f64::total_cmp); - xs.windows(2).map(|w| w[1] - w[0]).fold(f64::INFINITY, f64::min) - }; - let plain = Grid { step: 0.0, ..utm.clone() }; - assert_eq!(step_of(&plain), 200_000.0); - assert_eq!(step_of(&Grid { mgrs: true, ..plain }), 100_000.0); - // A frame of no extent draws none. - let mut none = Vec::new(); - measured_lines(&utm, &tr, &[], false, &mut none); - assert!(none.is_empty()); - assert_eq!((nice_step(2000.0, 1.0), nice_step(7000.0, 1.0), nice_step(1.0, 1.0)), (500.0, 1000.0, 1.0)); - } - - /// A measured grid labelled as MGRS names each 100 km square that shows, by its grid zone - /// designation and letters, where the label fits in it: one square over Winterthur at - /// 1:25,000, several at 1:2,000,000, each label in the square it names; in zone 32 only on a - /// frame across its edge with zone 33; both bands across the Equator; none on a frame too small - /// for a label. The grid is in UTM 32N for MGRS on a map in it, and in the frame's MGRS zone - /// (Norway's and Svalbard's exceptions kept) over LV95 or Web Mercator. - #[test] - fn mgrs_labels_name_the_100_km_squares() { - use rustgis_map::layout::{Grid, GridKind}; - let map = Map::new("m"); - let tr = rustgis_data::raster::Crs::from_epsg(32632).unwrap().transformer().unwrap(); - // (A label's size fixed, not measured: the fonts installed differ between machines.) - let size = |_: &str| (40.0_f32, 16.0_f32); - let view = |center: Coord, scale: f64, mm: f64| View { - width: mm * PT_PER_MM, - height: mm * PT_PER_MM, - pixels_per_point: 1.0, - camera: frame_camera(&map, center, scale, 0.0, 0.0), - sky: false, - }; - let at = |v: &View, x: f32, y: f32| map.to_lonlat(v.camera.to_map(f64::from(x), f64::from(y), v.width, v.height)).unwrap(); - let near = view(Coord::new(8.73, 47.5), 25_000.0, 80.0); - let one = mgrs_squares(&map, &near, None, 32, &tr, size); - assert_eq!(one.len(), 1, "{one:?}"); - assert_eq!(one[0].0, "32T MT"); - assert!((f64::from(one[0].1) - near.width / 2.0).abs() < 2.0 && (f64::from(one[0].2) - near.height / 2.0).abs() < 2.0); - let wide = view(Coord::new(8.73, 47.5), 2_000_000.0, 80.0); - let many = mgrs_squares(&map, &wide, None, 32, &tr, size); - assert!(many.len() >= 2, "{many:?}"); - for (text, x, y) in &many { - let named = rustgis_geom::to_mgrs(at(&wide, *x, *y), 0).unwrap().to_string(); - assert_eq!(&named, text); - } - // Across the edge with zone 33 at 12° E: only zone 32's squares, west of it. - let edge = view(Coord::new(11.0, 47.5), 2_000_000.0, 80.0); - let west = mgrs_squares(&map, &edge, None, 32, &tr, size); - assert!(!west.is_empty() && west.iter().all(|(t, x, y)| t.starts_with("32") && at(&edge, *x, *y).x < 12.0), "{west:?}"); - assert!(mgrs_squares(&map, &view(Coord::new(8.73, 47.5), 25_000.0, 15.0), None, 32, &tr, size).is_empty()); - // Across the Equator, a northern zone's grid names the southern squares too, as MGRS does. - let equator = view(Coord::new(9.0, 0.0), 2_000_000.0, 80.0); - let both = mgrs_squares(&map, &equator, None, 32, &tr, size); - for band in ["32N ", "32M "] { - assert!(both.iter().any(|(t, ..)| t.starts_with(band)), "{band}: {both:?}"); - } - for (text, x, y) in &both { - assert_eq!(&rustgis_geom::to_mgrs(at(&equator, *x, *y), 0).unwrap().to_string(), text); - } - // Its system: UTM 32N on a map in it or over LV95 (the frame's zone), the one named. - let g = Grid { kind: GridKind::Measured, mgrs: true, ..Grid::default() }; - let c = Coord::new(8.73, 47.5); - let on = |code: &str| { - let mut m = Map::new("m"); - m.projection = rustgis_map::Projection::Custom(code.into()); - m - }; - assert_eq!(measured_crs(&g, &on("EPSG:32632"), Coord::new(14.0, 47.5)).map(|c| c.epsg()), Some(32632)); - assert_eq!(measured_crs(&g, &on("EPSG:2056"), c).map(|c| c.epsg()), Some(32632)); - assert_eq!(measured_crs(&g, &map, c).map(|c| c.epsg()), Some(32632)); - // MGRS's zone at the centre: Bergen's 32V, Svalbard's 33X; a plain measured grid's 6° one. - assert_eq!(measured_crs(&g, &map, Coord::new(5.3, 60.4)).map(|c| c.epsg()), Some(32632)); - assert_eq!(measured_crs(&g, &map, Coord::new(10.0, 78.0)).map(|c| c.epsg()), Some(32633)); - assert_eq!(measured_crs(&g, &map, Coord::new(9.0, -1.0)).map(|c| c.epsg()), Some(32732)); - let plain = Grid { mgrs: false, ..g.clone() }; - assert_eq!(measured_crs(&plain, &map, Coord::new(5.3, 60.4)).map(|c| c.epsg()), Some(32631)); - let named = Grid { crs: Some("EPSG:32733".into()), ..g.clone() }; - assert_eq!(measured_crs(&named, &map, c).map(|c| c.epsg()), Some(32733)); - assert_eq!(measured_crs(&Grid { crs: Some("EPSG:2056".into()), ..g }, &map, c), None); - } - - #[test] - fn mgrs_labels_on_the_globe_name_the_squares_it_draws() { - // #2337: on a globe, a label names the square the globe draws under it, not the one the - // flat map would show at that place in the frame. - let mut map = Map::new("m"); - map.set_projection(rustgis_map::Projection::Globe); - let tr = rustgis_data::raster::Crs::from_epsg(32632).unwrap().transformer().unwrap(); - // Small labels at 1:20,000,000, where the globe's curve parts it from the flat map: the - // two agree at the middle of the frame and drift apart away from it. - let size = |_: &str| (6.0_f32, 4.0_f32); - let view = View { - width: 120.0 * PT_PER_MM, - height: 120.0 * PT_PER_MM, - pixels_per_point: 1.0, - camera: frame_camera(&map, Coord::new(9.0, 47.5), 20_000_000.0, 0.0, 0.0), - sky: false, - }; - let globe = rustgis_map::globe::Globe::new(&view.camera, view.width, view.height); - // The square the globe draws at a label's place, if any. - let under = - |x: f32, y: f32| globe.inverse(f64::from(x), f64::from(y)).and_then(|c| rustgis_geom::to_mgrs(c, 0)).map(|m| m.to_string()); - let squares = mgrs_squares(&map, &view, Some(&globe), 32, &tr, size); - assert!(squares.len() >= 2, "{squares:?}"); - for (text, x, y) in &squares { - assert_eq!(under(*x, *y).as_ref(), Some(text)); - } - // Through the flat camera, as before, some labels sit on another square of the globe. - let flat = mgrs_squares(&map, &view, None, 32, &tr, size); - assert!(flat.iter().any(|(text, x, y)| under(*x, *y).as_ref() != Some(text)), "{flat:?}"); - } - - #[test] - fn the_space_around_a_globe_is_free_in_its_coverage() { - // #2337: the light space a globe is drawn on leaves room for a layout's surrounds, as the - // blank basemap's white paper does (its ocean too, as open sea on a flat map); the - // atmosphere's glow at the globe's rim doesn't. Before, every cell was taken. - let mut map = Map::new("m"); - map.set_projection(rustgis_map::Projection::Globe); - // A globe about 64 mm across in a frame 100 mm square. - let (gw, gh, cells) = frame_coverage(&mut map, Coord::new(0.0, 0.0), 2e8, 100.0, 100.0, 50).unwrap(); - let cell = |x: u32, y: u32| cells[(y * gw + x) as usize]; - assert!(cells.iter().any(|c| *c), "the glow at the rim is drawn"); - for (x, y) in [(1, 1), (gw - 2, 1), (1, gh - 2), (gw - 2, gh - 2)] { - assert!(!cell(x, y), "the space at the corner ({x}, {y}) is free"); - } - } - - #[test] - fn a_measured_grid_on_the_globe_seen_whole_is_drawn() { - // #2337: with the whole globe inside the frame, no edge of it lands on the globe; the - // measured grid takes its bounds from the globe in the frame instead of drawing nothing. - use rustgis_map::layout::{Grid, GridKind}; - let mut m = Map::new("m"); - m.set_projection(rustgis_map::Projection::Globe); - let mut maps = vec![m]; - let mut l = Layout::new("Layout", 100.0, 100.0); - let grid = Grid { - kind: GridKind::Measured, - crs: Some("EPSG:32632".into()), - step: 0.0, - color: Rgba::rgb(0xFF, 0, 0), - labels: false, - width: 1.0, - ..Grid::default() - }; - l.add( - "Map", - (10.0, 10.0, 80.0, 80.0), - ElementKind::MapFrame { - map: "m".into(), - center: Coord::new(9.0, 45.0), - scale: 2e8, - shape: FrameShape::Rectangle, - grid: Some(grid), - extent_of: None, - extent_color: rustgis_map::layout::INDICATOR_COLOR, - extent_width: rustgis_map::layout::INDICATOR_WIDTH, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }, - ); - let pm = render(&l, &mut maps, 96.0, &PageInfo::default()).unwrap(); - assert!(count(&pm, (30.0, 30.0, 70.0, 70.0), red) > 20, "the measured grid's lines on the globe"); - assert_eq!(count(&pm, (11.0, 11.0, 20.0, 20.0), red), 0, "none past the rim"); - } - - #[test] - fn a_grid_on_the_globe_is_drawn_on_it() { - // #2337: a frame of a map on the globe draws its graticule through the globe, not as a - // flat world around it: none of it beyond the globe's rim, in the frame's corners. - use rustgis_map::layout::Grid; - let mut m = Map::new("m"); - m.set_projection(rustgis_map::Projection::Globe); - let mut maps = vec![m]; - let mut l = Layout::new("Layout", 100.0, 100.0); - let grid = Grid { step: 30.0, color: Rgba::rgb(0xFF, 0, 0), labels: true, width: 1.0, ..Grid::default() }; - l.add( - "Map", - (10.0, 10.0, 80.0, 80.0), - ElementKind::MapFrame { - map: "m".into(), - center: Coord::new(0.0, 0.0), - // A globe about 64 mm across, in the middle of the 80 mm frame. - scale: 2e8, - shape: FrameShape::Rectangle, - grid: Some(grid), - extent_of: None, - extent_color: rustgis_map::layout::INDICATOR_COLOR, - extent_width: rustgis_map::layout::INDICATOR_WIDTH, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }, - ); - let pm = render(&l, &mut maps, 96.0, &PageInfo::default()).unwrap(); - assert!(count(&pm, (40.0, 40.0, 60.0, 60.0), red) > 50, "lines on the globe"); - // Neither lines nor labels (dark) past the rim: in the corners and along the edges. - let ink = |p: tiny_skia::PremultipliedColorU8| red(p) || (p.alpha() > 0 && p.red() < 120 && p.green() < 120 && p.blue() < 120); - let corners = [(11.0, 11.0, 20.0, 20.0), (80.0, 11.0, 89.0, 20.0), (11.0, 80.0, 20.0, 89.0), (80.0, 80.0, 89.0, 89.0)]; - let edges = [(25.0, 11.0, 75.0, 15.0), (25.0, 85.0, 75.0, 89.0), (11.0, 25.0, 15.0, 75.0), (85.0, 25.0, 89.0, 75.0)]; - for r in corners.into_iter().chain(edges) { - assert_eq!(count(&pm, r, ink), 0, "nothing past the rim at {r:?}"); - } - } - - #[test] - fn grids_draw_lines_ticks_or_both() { - use rustgis_map::layout::{Grid, GridStyle}; - let g = |style| Grid { - step: 30.0, - color: Rgba::rgb(0xFF, 0, 0), - labels: false, - style, - tick_length: 4.0, - width: 1.0, - ..Grid::default() - }; - let inner = (25.0, 25.0, 75.0, 75.0); - let rim = (10.0, 10.0, 90.0, 13.0); - let lines = grid_page(g(GridStyle::Lines)); - let ticks = grid_page(g(GridStyle::Ticks)); - let both = grid_page(g(GridStyle::LinesAndTicks)); - // Ticks only: nothing across the middle of the frame, but marks along its edge. - assert!(count(&lines, inner, red) > 100, "lines cross the frame"); - assert_eq!(count(&ticks, inner, red), 0, "ticks stay at the edges"); - assert!(count(&ticks, rim, red) > 10, "ticks along the top edge"); - // Lines and ticks: the lines, with the ticks' extra width along the edge. - assert!(count(&both, inner, red) > 100); - assert!(count(&both, rim, red) > count(&lines, rim, red), "ticks thicken the lines at the edge"); - // The line width is the grid's. - let thick = grid_page(Grid { width: 3.0, ..g(GridStyle::Lines) }); - assert!(count(&thick, inner, red) > 2 * count(&lines, inner, red)); - } - - #[test] - fn grid_labels_go_on_the_edges_picked() { - use rustgis_map::layout::{Grid, GridEdges}; - let g = |edges, label_orientation| Grid { step: 30.0, color: Rgba::new(0, 0, 0, 0), edges, label_orientation, ..Grid::default() }; - let (top, bottom) = ((20.0, 10.0, 80.0, 16.0), (20.0, 84.0, 80.0, 90.0)); - let (left, right) = ((10.0, 20.0, 18.0, 80.0), (82.0, 20.0, 90.0, 80.0)); - let default = grid_page(g(GridEdges::default(), Orientation::Horizontal)); - assert!(count(&default, bottom, ink) > 0 && count(&default, left, ink) > 0, "bottom and left by default"); - assert_eq!(count(&default, top, ink) + count(&default, right, ink), 0); - let flipped = grid_page(g(GridEdges { top: true, bottom: false, left: false, right: true }, Orientation::Horizontal)); - assert!(count(&flipped, top, ink) > 0 && count(&flipped, right, ink) > 0, "top and right when picked"); - assert_eq!(count(&flipped, bottom, ink) + count(&flipped, left, ink), 0); - // Vertical side labels run along the edge: narrower across it than horizontal ones. - // Columns with any text in them, inside the frame's left edge; antialiased text counts - // too, as a thin system font (Windows) may leave no pixel of a stem fully dark. - let across = |pm: &Pixmap| { - let px = |mm: f64| (mm * PT_PER_MM) as u32; - let shaded = |p: tiny_skia::PremultipliedColorU8| p.red() < 200 && p.green() < 200 && p.blue() < 200; - (px(11.0)..px(30.0)).filter(|&x| (px(20.0)..px(80.0)).any(|y| pm.pixel(x, y).is_some_and(shaded))).count() - }; - let horizontal = grid_page(g(GridEdges { top: false, bottom: false, left: true, right: false }, Orientation::Horizontal)); - let vertical = grid_page(g(GridEdges { top: false, bottom: false, left: true, right: false }, Orientation::Vertical)); - assert!(count(&vertical, left, ink) > 0); - assert!(across(&vertical) < across(&horizontal), "{} columns, against {}", across(&vertical), across(&horizontal)); - } - - /// A grid's labels at its label size (#2581): at 16 points each is twice as tall as at the - /// default 8 and sits twice as far in from the edge past the ticks; at 8 they are where they - /// always were; out of range they are drawn in range. - #[test] - fn a_grids_labels_take_its_label_size() { - use rustgis_map::layout::Grid; - let (fw, fh, ppp) = (80.0 * PT_PER_MM, 80.0 * PT_PER_MM, 2.0); - let map = Map::new("m"); - let view = View { - width: fw, - height: fh, - pixels_per_point: ppp, - camera: frame_camera(&map, Coord::new(0.0, 0.0), 2e8, 0.0, 0.0), - sky: false, - }; - let labels = |label_size: f64| { - let mut pm = Canvas::from_pixmap(Pixmap::new((fw * ppp) as u32, (fh * ppp) as u32).unwrap()); - let g = Grid { step: 30.0, tick_length: 0.0, label_size, ..Grid::default() }; - draw_grid(&mut pm, &map, &view, &g, false) - }; - let (small, big) = (labels(GRID_LABEL_PT), labels(16.0)); - let bottom = |drawn: &[(Edge, [f32; 4])]| drawn.iter().find(|(e, _)| *e == Edge::Bottom).map(|(_, r)| *r).unwrap(); - let (s, b) = (bottom(&small), bottom(&big)); - assert!(((b[3] - b[1]) - 2.0 * (s[3] - s[1])).abs() < 1e-3, "{b:?} against {s:?}"); - let gap = |r: [f32; 4]| fh as f32 - r[3]; - assert!(gap(b) > gap(s), "farther in from the edge: {} against {}", gap(b), gap(s)); - // The default: 8 points, 1.33 pixels a point, 3 points past the ticks, its halo 1.2 lines. - assert!(((s[3] - s[1]) - 8.0 * 1.33 * 1.2).abs() < 1e-3, "{s:?}"); - assert_eq!(labels(1e9), labels(100.0)); - assert_eq!(labels(f64::NAN), small); - } - - /// A tile layer's credit on a frame with a labelled grid (#1767): in the bottom-right corner, - /// where it was drawn, it runs over the bottom labels; the frame moves it clear of every label, - /// whichever edges carry them and however the side ones run, and leaves the labels as the grid - /// drew them. - #[test] - fn a_frames_attribution_keeps_clear_of_its_grid_labels() { - use rustgis_map::layout::{Grid, GridEdges}; - let (fw, fh, ppp) = (80.0 * PT_PER_MM, 80.0 * PT_PER_MM, 2.0); - let map = Map::new("m"); - let view = View { - width: fw, - height: fh, - pixels_per_point: ppp, - camera: frame_camera(&map, Coord::new(0.0, 0.0), 2e8, 0.0, 0.0), - sky: false, - }; - let credit = vec!["© OpenStreetMap contributors".to_string()]; - let white = || { - let mut pm = Pixmap::new((fw * ppp) as u32, (fh * ppp) as u32).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - pm - }; - // Whether each pixel is darkened by text, antialiased edges included. - let shaded = |pm: &Pixmap| pm.pixels().iter().map(|p| p.red() < 200 && p.green() < 200 && p.blue() < 200).collect::>(); - let grid = - |edges, label_orientation| Grid { step: 30.0, color: Rgba::new(0, 0, 0, 0), edges, label_orientation, ..Grid::default() }; - // The grid's labels and the credit, each on its own frame (the credit `inset` from the - // corner, else where the frame puts it); the pixels both darken. - let overlap = |g: &Grid, credit: &[String], inset: Option<(f32, f32)>| { - let mut labels_pm = Canvas::from_pixmap(white()); - let labels = draw_grid(&mut labels_pm, &map, &view, g, false); - assert!(!labels.is_empty()); - let (w, h) = (fw as f32, fh as f32); - let tw = crate::attribution_text(credit).unwrap().1; - let inset = inset.unwrap_or_else(|| attribution_inset((w, h), tw, &labels)); - let mut credit_pm = Canvas::from_pixmap(white()); - crate::draw_attribution(&mut credit_pm, credit, ppp as f32, inset); - shaded(labels_pm.pixmap()).iter().zip(shaded(credit_pm.pixmap())).filter(|(a, b)| **a && *b).count() - }; - let default = grid(GridEdges::default(), Orientation::Horizontal); - assert!(overlap(&default, &credit, Some((0.0, 0.0))) > 20, "in the corner, the credit runs over the bottom labels"); - for (bottom, right) in [(true, false), (true, true), (false, true)] { - for orientation in [Orientation::Horizontal, Orientation::Vertical] { - let g = grid(GridEdges { top: true, bottom, left: true, right }, orientation); - assert_eq!(overlap(&g, &credit, None), 0, "bottom {bottom}, right {right}, {orientation:?}"); - } - } - // A credit wider than the frame (several layers' credits, a narrow frame) runs past both - // edges; it keeps clear of the bottom and right labels all the same. - let long = vec![ - "© OpenStreetMap contributors".to_string(), - "MapBiomas, sistemas de irrigação (CC BY 4.0)".to_string(), - "Instituto Brasileiro de Geografia e Estatística".to_string(), - ]; - assert!(crate::attribution_text(&long).unwrap().1 > fw as f32); - for (bottom, right) in [(true, true), (false, true)] { - for orientation in [Orientation::Horizontal, Orientation::Vertical] { - let g = grid(GridEdges { top: false, bottom, left: false, right }, orientation); - assert_eq!(overlap(&g, &long, None), 0, "long credit: bottom {bottom}, right {right}, {orientation:?}"); - } - } - // Drawn with the frame's map: the labels' pixels are the grid's alone. - let mut labels_pm = Canvas::from_pixmap(white()); - let all = grid(GridEdges { top: false, bottom: true, left: false, right: true }, Orientation::Horizontal); - let labels = draw_grid(&mut labels_pm, &map, &view, &all, false); - let img = crate::Rendered { - pixmap: white(), - labels: Vec::new(), - unplaced: Vec::new(), - attribution: credit.clone(), - tiles_pending: false, - data_pending: false, - tile_errors: Vec::new(), - partial: Vec::new(), - pending_in_place: Vec::new(), - recorded: None, - label_layers: Vec::new(), - }; - let framed = finish_frame(img, ppp, Some((&map, &view, &all, false))); - let (a, b) = (labels_pm.pixmap(), framed.pixmap()); - assert_ne!(a.data(), b.data(), "the credit is drawn"); - for (_, [x0, y0, x1, y1]) in &labels { - let px = |v: f32| (v * ppp as f32) as u32; - for (x, y) in (px(*y0)..px(*y1)).flat_map(|y| (px(*x0)..px(*x1)).map(move |x| (x, y))) { - assert_eq!(a.pixel(x, y), b.pixel(x, y), "({x}, {y})"); - } - } - } - - /// The credit stays in the corner with nothing under it, goes up above a bottom label and left - /// of a right one (above it, when going left would take it out of the frame), and pays no heed - /// to the top and left labels. - #[test] - fn attribution_inset_steps_round_the_labels_in_its_way() { - let (size, tw) = ((200.0, 100.0), 60.0); - assert_eq!(attribution_inset(size, tw, &[]), (0.0, 0.0)); - // A bottom label under the credit, another left of it. - let under = [(Edge::Bottom, [150.0, 88.0, 170.0, 98.0]), (Edge::Bottom, [40.0, 88.0, 60.0, 98.0])]; - let (bottom, right) = attribution_inset(size, tw, &under); - assert_eq!(right, 0.0); - // The credit's foot (its centre plus half its height) sits 2 points over the label's top. - assert!((100.0 - bottom - crate::ATTRIBUTION_SIZE * 0.9 + crate::ATTRIBUTION_SIZE * 0.8 - 86.0).abs() < 1e-3, "{bottom}"); - // A right label beside it once it is up: it moves left of it too. - let both = [under[0], (Edge::Right, [180.0, 70.0, 197.0, 82.0])]; - let (b2, r2) = attribution_inset(size, tw, &both); - assert_eq!(b2, bottom); - assert!((200.0 - r2 - 4.0 - 178.0).abs() < 1e-3, "{r2}"); - // Labels on the other edges are not in its way. - let others = [(Edge::Left, [130.0, 88.0, 196.0, 98.0]), (Edge::Top, [130.0, 88.0, 196.0, 98.0])]; - assert_eq!(attribution_inset(size, tw, &others), (0.0, 0.0)); - // Left of a right label it would leave the frame (180 points from x = 16, a label at - // x = 163, it would start at x = -19): it goes above the label instead, still in the - // corner's column. - let side = [(Edge::Right, [163.0, 85.0, 197.0, 97.0])]; - let (b3, r3) = attribution_inset(size, 180.0, &side); - assert_eq!(r3, 0.0); - assert!((100.0 - b3 - crate::ATTRIBUTION_SIZE * 0.9 + crate::ATTRIBUTION_SIZE * 0.8 - 83.0).abs() < 1e-3, "{b3}"); - // No room above it either (a frame 20 points tall): as far left as the frame holds it, - // starting at its left edge. - let low = [(Edge::Right, [163.0, 3.0, 197.0, 15.0])]; - let (b4, r4) = attribution_inset((200.0, 20.0), 180.0, &low); - assert_eq!(b4, 0.0); - assert!((crate::attribution_center(200.0, 180.0, r4) - 90.0).abs() < 1e-3, "{r4}"); - // Wider than the frame: never left (it can't fit), above the label when there is room. - let (b5, r5) = attribution_inset(size, 300.0, &side); - assert_eq!((b5, r5), (b3, 0.0)); - let (b6, r6) = attribution_inset((200.0, 20.0), 300.0, &low); - assert_eq!((b6, r6), (0.0, 0.0), "it stays where it was drawn"); - } - - #[test] - fn north_arrow_styles_differ_and_take_their_colours() { - let draw = |style, fill| { - let mut pm = Pixmap::new(80, 120).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - crate::canvas::with_canvas(&mut pm, |c| { - north_arrow(c, Rect::from_xywh(0.0, 0.0, 80.0, 120.0).unwrap(), style, fill, Rgba::rgb(0x22, 0x22, 0x22), 1.0, 0.0) - }); - pm - }; - let red_fill = Rgba::rgb(0xFF, 0, 0); - let all: Vec = ArrowStyle::ALL.iter().map(|&s| draw(s, red_fill)).collect(); - for (i, a) in all.iter().enumerate() { - let filled = (0..120).flat_map(|y| (0..80).map(move |x| (x, y))).filter(|&(x, y)| a.pixel(x, y).is_some_and(red)).count(); - assert!(filled > 50, "{:?} uses the fill colour", ArrowStyle::ALL[i]); - for b in &all[i + 1..] { - assert_ne!(a.data(), b.data(), "each style draws differently"); - } - } - } - - #[test] - fn a_north_arrow_turns_with_its_frame() { - // The mean position of the red arrowhead (its N and outline are dark), as an offset from - // the middle of an 80 × 120 arrow. - let lean = |bearing| { - let mut pm = Pixmap::new(80, 120).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let r = Rect::from_xywh(0.0, 0.0, 80.0, 120.0).unwrap(); - crate::canvas::with_canvas(&mut pm, |c| { - north_arrow(c, r, ArrowStyle::Triangle, Rgba::rgb(0xFF, 0, 0), Rgba::rgb(0x22, 0x22, 0x22), 1.0, bearing) - }); - let pts: Vec<(f64, f64)> = (0..120) - .flat_map(|y| (0..80).map(move |x| (x, y))) - .filter(|&(x, y)| pm.pixel(x, y).is_some_and(red)) - .map(|(x, y)| (f64::from(x), f64::from(y))) - .collect(); - let n = pts.len().max(1) as f64; - (pts.iter().map(|p| p.0).sum::() / n - 40.0, pts.iter().map(|p| p.1).sum::() / n - 60.0) - }; - // North up: the arrowhead's bulk (its base) lies below the middle, its tip above. - let (x, y) = lean(0.0); - assert!(x.abs() < 1.0 && y > 3.0, "{x}, {y}"); - // East up (the map turned 90°): north points left, so the base lies right of the middle. - let (x, y) = lean(90.0); - assert!(x > 3.0 && y.abs() < 1.0, "{x}, {y}"); - let (x, _) = lean(-90.0); - assert!(x < -3.0, "{x}"); - } - - /// A scale bar's default colour and fill. - const DEFAULT_COLORS: (Rgba, Rgba) = (Rgba::rgb(0x22, 0x22, 0x22), Rgba::rgb(0xFF, 0xFF, 0xFF)); - - /// A white `width` x 60 pixmap with `bar` drawn on it at 100 m of ground a point, a pixel a - /// point, with a decimal point, in the default colours. - fn draw_bar(bar: &BarOptions<'_>, width: u32) -> Pixmap { - let mut pm = Pixmap::new(width, 60).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let r = Rect::from_xywh(0.0, 0.0, width as f32, 60.0).unwrap(); - crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, bar, DEFAULT_COLORS, 1.0, false)); - pm - } - - /// Dark runs along row `y`. - fn dark_runs(pm: &Pixmap, y: u32) -> usize { - let dark: Vec = (0..pm.width()).map(|x| pm.pixel(x, y).is_some_and(ink)).collect(); - dark.windows(2).filter(|w| !w[0] && w[1]).count() + usize::from(dark.first() == Some(&true)) - } - - /// The first and last columns with anything but white on row `y`. - fn marked_span(pm: &Pixmap, y: u32) -> Option<(u32, u32)> { - let marked = |x: &u32| pm.pixel(*x, y).is_some_and(|p| p.red() < 200 || p.green() < 200 || p.blue() < 200); - let first = (0..pm.width()).find(marked)?; - let last = (0..pm.width()).rev().find(marked)?; - Some((first, last)) - } - - /// The rows holding ink. - fn bar_ink_rows(pm: &Pixmap) -> Vec { - (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| pm.pixel(x, y).is_some_and(ink))).collect() - } - - /// How much darker than white the pixels in rows `from..=to` are, summed. - fn darkness(pm: &Pixmap, from: u32, to: u32) -> u32 { - (from..=to) - .flat_map(|y| (0..pm.width()).map(move |x| (x, y))) - .filter_map(|(x, y)| pm.pixel(x, y)) - .map(|p| 255 - u32::from(p.red())) - .sum() - } - - /// 64-bit FNV-1a over the pixmaps' bytes. - #[cfg(not(target_arch = "wasm32"))] - fn fnv(pms: &[Pixmap]) -> u64 { - pms.iter().flat_map(|p| p.data().iter()).fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) - } - - /// 64-bit FNV-1a over one byte slice. - #[cfg(not(target_arch = "wasm32"))] - fn fnv_bytes(b: &[u8]) -> u64 { - b.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) - } - - /// A plain scale bar on a white `w` x 60 pixmap, in the default colours. - #[cfg(not(target_arch = "wasm32"))] - fn draw_default(style: ScaleBarStyle, units: ScaleUnits, divisions: usize, ground: f64, w: u32, ppp: f64, comma: bool) -> Pixmap { - let mut pm = Pixmap::new(w, 60).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let r = Rect::from_xywh(0.0, 0.0, w as f32, 60.0).unwrap(); - let bar = BarOptions { units, divisions, style, ..BarOptions::default() }; - crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, ground, &bar, DEFAULT_COLORS, ppp, comma)); - pm - } - - /// How [`plain_texts_draw_as_before`]'s pages drew, and what their cut-off check found, before - /// texts had a block alignment, line spacing or case; in the built-in face. - #[cfg(not(target_arch = "wasm32"))] - const PINNED_TEXT_PIXELS: u64 = 0x0556_a0ef_54c0_2e87; - #[cfg(not(target_arch = "wasm32"))] - const PINNED_TEXT_LOSSES: u64 = 0x26af_01ce_67e5_7cfd; - - /// A text with none of the block settings draws, and is measured for lines that don't fit and ink - /// off the page, exactly as main did: every page at 96 dpi, and the first eight (left-aligned, - /// unwrapped, upright and turned a quarter) at 300 dpi too, which is enough to hold the scaling - /// of the line pitch. In a process of its own, told to use the built-in face before any text. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn plain_texts_draw_as_before() { - if std::env::var_os("RUSTGIS_TEXT_PIN_CHILD").is_none() { - let output = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "layout::tests::plain_texts_draw_as_before", "--nocapture"]) - .env("RUSTGIS_TEXT_PIN_CHILD", "1") - .env("RUSTGIS_BUILTIN_FONTS", "1") - .output() - .unwrap(); - assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); - assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"), "the test didn't run in the child process"); - return; - } - let info = PageInfo { page: 2, pages: 3, page_name: String::new() }; - let (mut drawn, mut measured) = (Vec::new(), String::new()); - for (i, l) in crate::layout::plain_text_pages().iter().enumerate() { - for dpi in if i < 8 { &[96.0, 300.0][..] } else { &[96.0][..] } { - drawn.push(render(l, &mut [], *dpi, &info).unwrap()); - measured.push_str(&format!("{:?}\n", text_losses(l, &[], *dpi, &info))); - } - } - // The pages exercise both checks. - assert!(measured.contains("below_box: true") && measured.contains("off_page: true"), "{measured}"); - let losses = fnv_bytes(measured.as_bytes()); - assert_eq!((fnv(&drawn), losses), (PINNED_TEXT_PIXELS, PINNED_TEXT_LOSSES), "{:#x} {:#x}", fnv(&drawn), losses); - } - - /// How [`scale_bars_without_details_draw_as_before`]'s bars drew before scale bars had details, - /// their labels in the built-in face. - #[cfg(not(target_arch = "wasm32"))] - const PINNED: u64 = 0x3975_8d68_da45_882b; - - /// A bar with none of the details draws exactly as main drew it: every style, unit, division - /// count, ground resolution, density and decimal mark. Its labels are drawn in the built-in - /// face, whatever fonts the machine has: in a process of its own, told so before any text. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn scale_bars_without_details_draw_as_before() { - if std::env::var_os("RUSTGIS_SCALE_BAR_PIN_CHILD").is_none() { - let output = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "layout::tests::scale_bars_without_details_draw_as_before", "--nocapture"]) - .env("RUSTGIS_SCALE_BAR_PIN_CHILD", "1") - .env("RUSTGIS_BUILTIN_FONTS", "1") - .output() - .unwrap(); - assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); - assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"), "the test didn't run in the child process"); - return; - } - let mut drawn = Vec::new(); - for style in ScaleBarStyle::ALL { - for units in [ScaleUnits::Auto, ScaleUnits::Miles, ScaleUnits::Feet, ScaleUnits::Meters] { - for divisions in [1, 4, 10] { - for ground in [0.37, 100.0, 7.84] { - for (w, ppp) in [(93u32, 1.0), (300, 1.0), (300, 300.0 / 72.0)] { - for comma in [false, true] { - drawn.push(draw_default(style, units, divisions, ground, w, ppp, comma)); - } - } - } - } - } - } - assert_eq!(fnv(&drawn), PINNED, "{:#x}", fnv(&drawn)); - } - - #[test] - fn scale_bars_count_in_their_units_and_divisions() { - // 100 m of ground per point: about 25 km across the bar. - let draw = |(units, divisions, style)| draw_bar(&BarOptions { units, divisions, style, ..BarOptions::default() }, 300); - // Dark runs along the bar's middle row: one per dark division of an alternating bar. - let runs = |pm: &Pixmap| { - let y = (60.0 * 0.62) as u32; - let dark: Vec = (0..pm.width()).map(|x| pm.pixel(x, y).is_some_and(ink)).collect(); - dark.windows(2).filter(|w| !w[0] && w[1]).count() + usize::from(dark.first() == Some(&true)) - }; - let four = draw((ScaleUnits::Auto, 4, ScaleBarStyle::Alternating)); - let five = draw((ScaleUnits::Auto, 5, ScaleBarStyle::Alternating)); - assert_eq!(runs(&four), 2, "two dark divisions"); - assert_eq!(runs(&five), 3, "three dark divisions, the last at the end"); - // Miles and kilometres give bars of different lengths and labels. - assert_ne!(draw((ScaleUnits::Miles, 4, ScaleBarStyle::Alternating)).data(), four.data()); - // A line or a stepped line fills no division. - for style in [ScaleBarStyle::Line, ScaleBarStyle::Stepped] { - let pm = draw((ScaleUnits::Auto, 4, style)); - let dark = (0..300).filter(|&x| pm.pixel(x, 37).is_some_and(ink)).count(); - assert!(dark < 20, "{style:?}: {dark} dark pixels across the bar"); - assert_ne!(pm.data(), four.data()); - } - let with = |f: &dyn Fn(&mut BarOptions<'static>)| { - let mut b = BarOptions::default(); - f(&mut b); - draw_bar(&b, 300) - }; - let runs = |pm: &Pixmap| dark_runs(pm, 37); - assert_eq!(runs(&with(&|_| {})), 2); - // The first division cut in four alternating parts from zero, the first dark, and the - // divisions after going on from them: parts 0 and 2, then divisions 1 and 3. - assert_eq!(runs(&with(&|b| b.subdivisions = 4)), 4); - assert_eq!(with(&|b| b.subdivisions = 1).data(), with(&|_| {}).data(), "one part is the division whole"); - // A stepped bar's upper steps are the alternating bar's dark divisions, after the cut one too: - // its thin line, drawn soft, marks the bar's top row. - let cut4 = |style| { - let bar = BarOptions { style, subdivisions: 4, ..BarOptions::default() }; - let placed = bar_layout(Rect::from_xywh(0.0, 0.0, 300.0, 60.0).unwrap(), 100.0, &bar, 1.0, false).unwrap(); - (draw_bar(&bar, 300), placed) - }; - let (alternating, placed) = cut4(ScaleBarStyle::Alternating); - let (stepped, _) = cut4(ScaleBarStyle::Stepped); - let seg = placed.len / placed.divs as f32; - let top = placed.y0.round() as u32; - let mid = |j: usize| (placed.x0 + seg * (j as f32 + 0.5)) as u32; - let dark: Vec = (placed.before + 1..placed.divs).map(|j| alternating.pixel(mid(j), 37).is_some_and(ink)).collect(); - let upper: Vec = (placed.before + 1..placed.divs) - .map(|j| (top - 1..=top + 1).any(|y| stepped.pixel(mid(j), y).is_some_and(|p| p.red() < 200))) - .collect(); - assert_eq!(dark, [true, false, true], "divisions 1 and 3 dark"); - assert_eq!(upper, dark, "the stepped bar's upper steps"); - // Two whole divisions before zero: six divisions, three dark. - assert_eq!(runs(&with(&|b| b.divisions_before_zero = 2)), 3); - assert_eq!(bar_ink_rows(&with(&|b| b.divisions_before_zero = 2)), bar_ink_rows(&with(&|_| {})), "the same rows, bar and labels"); - // Across zero the light division before it meets a dark part: the bar's first ink is at - // zero, as on the same bar uncut, with the light division left of it. - let first_ink = |pm: &Pixmap| (0..pm.width()).find(|&x| pm.pixel(x, 37).is_some_and(ink)); - let uncut = with(&|b| b.divisions_before_zero = 1); - let cut = with(&|b| { - b.divisions_before_zero = 1; - b.subdivisions = 4; - }); - let zero = first_ink(&uncut).unwrap(); - assert!(zero > 20, "a division before zero: {zero}"); - assert_eq!(first_ink(&cut), Some(zero), "dark right of zero"); - assert!(cut.pixel(zero + 1, 37).is_some_and(ink) && !cut.pixel(zero - 2, 37).is_some_and(ink), "dark right of zero, light left"); - // A single or stepped line gets short ticks inside its first division. - for style in [ScaleBarStyle::Line, ScaleBarStyle::Stepped] { - let plain = with(&|b| b.style = style); - let cut = with(&|b| { - b.style = style; - b.subdivisions = 3; - }); - assert!(darkness(&cut, 35, 39) > darkness(&plain, 35, 39) + 100, "{style:?}"); - } - } - - /// A bar whose first negative label leaves it no room still draws: the label takes at most - /// half the bar's room, reaching left of the box past that. - #[test] - fn a_scale_bar_before_zero_draws_where_its_first_label_leaves_no_room() { - let bar = BarOptions { text_size: 24.0, divisions_before_zero: 2, divisions: 10, ..BarOptions::default() }; - let mut pm = Pixmap::new(40, 60).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let r = Rect::from_xywh(0.0, 0.0, 40.0, 60.0).unwrap(); - // Filled in its colour throughout, so along its middle the bar is one solid run. - let solid = (DEFAULT_COLORS.0, DEFAULT_COLORS.0); - crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, &bar, solid, 1.0, false)); - // Moved down so its big labels reach no higher than the box's top, the bar is drawn under - // them: along its middle row, one solid run, half the bar's room at least (34 px, the 1 km - // that fits in 17), not a sliver. - let placed = bar_layout(r, 100.0, &bar, 1.0, false).unwrap(); - let middle = (placed.y0 + placed.bar_h / 2.0) as u32; - assert!(placed.y0 > 30.0, "moved down: {}", placed.y0); - assert!(dark_runs(&pm, middle) > 0, "the bar is drawn"); - let (a, b) = marked_span(&pm, middle).unwrap(); - assert!(b - a >= 8, "the bar keeps half its room: {a}..{b}"); - } - - #[test] - fn scale_bars_fit_their_box_by_the_strategy() { - // 79 px to use at 100 m a point: 7.9 km of ground, in kilometres. - let width = |fit| { - let bar = BarOptions { units: ScaleUnits::Kilometers, fit, ..BarOptions::default() }; - let (a, b) = marked_span(&draw_bar(&bar, 93), 37).unwrap(); - b - a - }; - assert!((width(ScaleBarFit::AdjustDivisionValue) as i32 - 50).abs() <= 2, "a round 5 km in four 1.25 km divisions"); - assert!((width(ScaleBarFit::AdjustDivision) as i32 - 70).abs() <= 2, "seven round 1 km divisions"); - assert!((width(ScaleBarFit::AdjustWidth) as i32 - 40).abs() <= 2, "four 1 km divisions, narrower than the box"); - // Ten asked: fifteen 0.5 km divisions would fit, so the division steps up to 1 km, seven. - let bar = BarOptions { units: ScaleUnits::Kilometers, fit: ScaleBarFit::AdjustDivision, divisions: 10, ..BarOptions::default() }; - let (a, b) = marked_span(&draw_bar(&bar, 93), 37).unwrap(); - assert!(((b - a) as i32 - 70).abs() <= 2, "seven 1 km divisions, not ten of 0.5 km: {}", b - a); - // Extreme grounds, every fit, divisions before zero: never past the box, never empty. - for ground in [1e-4, 0.37, 100.0, 1e5, 1e7] { - for fit in ScaleBarFit::ALL { - for before in [0, 2] { - let bar = BarOptions { fit, divisions_before_zero: before, divisions: 10, ..BarOptions::default() }; - let mut pm = Pixmap::new(120, 60).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let r = Rect::from_xywh(10.0, 0.0, 100.0, 60.0).unwrap(); - crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, ground, &bar, DEFAULT_COLORS, 1.0, false)); - let (a, b) = marked_span(&pm, 37).unwrap_or((0, 0)); - assert!(b > a && b < 110, "{ground} {fit:?} {before}: {a}..{b}"); - } - } - } - // Two divisions before zero count toward the ten: in a wide room, ten in all, never twelve. - let bar = BarOptions { - units: ScaleUnits::Kilometers, - fit: ScaleBarFit::AdjustDivision, - divisions_before_zero: 2, - ..BarOptions::default() - }; - let mut most = 0; - for w in (300..1400).step_by(23) { - let b = bar_layout(Rect::from_xywh(0.0, 0.0, w as f32, 60.0).unwrap(), 100.0, &bar, 1.0, false).unwrap(); - assert!(b.divs <= rustgis_map::layout::MAX_SCALE_DIVISIONS && b.before == 2, "{w} px: {} divisions", b.divs); - let pm = draw_bar(&bar, w); - let middle = (b.y0 + b.bar_h / 2.0) as u32; - // An alternating bar's dark divisions: half of them, the first before zero dark. - assert_eq!(dark_runs(&pm, middle), b.divs.div_ceil(2), "{w} px"); - let (a, z) = marked_span(&pm, middle).unwrap(); - assert!(((z - a) as f32 - b.len).abs() <= 2.0, "{w} px: {a}..{z} for {}", b.len); - most = most.max(b.divs); - } - assert_eq!(most, rustgis_map::layout::MAX_SCALE_DIVISIONS, "a wide room reaches ten"); - // Ten asked and two before zero: ten in all under every fit, not twelve. - for fit in ScaleBarFit::ALL { - let bar = BarOptions { fit, divisions: 10, divisions_before_zero: 2, ..BarOptions::default() }; - let b = bar_layout(Rect::from_xywh(0.0, 0.0, 300.0, 60.0).unwrap(), 100.0, &bar, 1.0, false).unwrap(); - assert!(b.divs <= rustgis_map::layout::MAX_SCALE_DIVISIONS, "{fit:?}: {} divisions", b.divs); - let middle = (b.y0 + b.bar_h / 2.0) as u32; - assert!(dark_runs(&draw_bar(&bar, 300), middle) <= 5, "{fit:?}: at most five dark of ten"); - } - } - - /// The narrowest element keeps its bar where an export rebuilds it from an f32 rectangle: near - /// an A2 sheet's right edge, at 300 and 600 dpi (#1379). - #[test] - fn a_scale_bar_keeps_its_bar_near_the_right_edge_at_print_density() { - // As an export places an element: page mm at `k` pixels a mm, `ppp` pixels a point. - let pt_per_mm = rustgis_map::layout::PT_PER_MM; - for i in 0..400 { - let ground = 10f64.powf(-1.0 + 4.0 * f64::from(i) / 400.0); - for widest_mm in [25.0, 63.0, 126.0] { - let w_pt = scale_bar_width_pt(ground, widest_mm * pt_per_mm, (ScaleUnits::Auto, 4, SCALE_BAR_TEXT_PT), false, 4.0).unwrap(); - let plan = bar_plan(ground, w_pt, ScaleUnits::Auto); - for (x_mm, dpi) in [(380.0, 300.0), (560.0, 300.0), (380.0, 600.0), (560.0, 600.0)] { - let k = dpi / 25.4; - let ppp = k / pt_per_mm; - let r = Rect::from_xywh((x_mm * k) as f32, 0.0, (w_pt / pt_per_mm * k) as f32, 10.0).unwrap(); - let drawn = bar_plan(ground, f64::from(r.width()) / ppp, ScaleUnits::Auto); - assert_eq!(drawn, plan, "{ground} m a point, {widest_mm} mm at most, x {x_mm} mm, {dpi} dpi"); - } - } - } - } - - /// The narrowest element for a scale bar draws the very bar a wider one does, labels and all, - /// within itself (#1379). - #[test] - fn a_scale_bar_draws_the_same_in_its_narrowest_element() { - let draw = |ground: f64, width: f32| { - let mut pm = Pixmap::new(320, 60).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let r = Rect::from_xywh(0.0, 0.0, width, 60.0).unwrap(); - crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, ground, &BarOptions::default(), DEFAULT_COLORS, 1.0, true)); - pm - }; - // 20 km on a bar of 300 points takes two thirds of it; 10 km at 37.2 m a point, a third. - for (ground, narrower_than) in [(100.0, 260.0), (37.2, 190.0), (78.4, 300.0)] { - let w = scale_bar_width_pt(ground, 300.0, (ScaleUnits::Auto, 4, SCALE_BAR_TEXT_PT), true, 4.0).unwrap(); - assert!(w < narrower_than, "{ground} m a point: {w} points"); - let (wide, narrow) = (draw(ground, 300.0), draw(ground, w as f32)); - assert_eq!(wide.data(), narrow.data(), "{ground} m a point: the same bar in {w} points"); - let past = - (w.ceil() as u32..320).flat_map(|x| (0..60).map(move |y| (x, y))).filter(|&(x, y)| narrow.pixel(x, y).is_some_and(ink)); - assert_eq!(past.count(), 0, "{ground} m a point: nothing drawn past {w} points"); - } - assert_eq!(scale_bar_width_pt(0.0, 300.0, (ScaleUnits::Auto, 4, SCALE_BAR_TEXT_PT), false, 4.0), None); - // Miles count in other lengths: the box still draws the same bar. - let w = scale_bar_width_pt(100.0, 300.0, (ScaleUnits::Miles, 4, SCALE_BAR_TEXT_PT), false, 4.0).unwrap(); - assert!(w <= 300.0 && bar_plan(100.0, w, ScaleUnits::Miles) == bar_plan(100.0, 300.0, ScaleUnits::Miles)); - } - - #[test] - fn scale_bars_draw_in_their_colours() { - let mut pm = Pixmap::new(300, 60).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - type Px = tiny_skia::PremultipliedColorU8; - // A red colour and a blue fill. - let colors = (Rgba::rgb(0xD0, 0x10, 0x10), Rgba::rgb(0x10, 0x10, 0xD0)); - let r = Rect::from_xywh(0.0, 0.0, 300.0, 60.0).unwrap(); - crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, &BarOptions::default(), colors, 1.0, false)); - let count = |hit: fn(Px) -> bool, y: u32| (0..300).filter(|&x| pm.pixel(x, y).is_some_and(hit)).count(); - let y = (60.0 * 0.62) as u32; - // Along the bar: the dark divisions in the colour, the light ones in the fill, nothing in - // the old ink. - assert!(count(red, y) > 40, "red divisions"); - assert!(count(|p| p.blue() > 180 && p.red() < 90 && p.green() < 90, y) > 40, "blue divisions"); - assert_eq!(count(ink, y), 0, "no default ink left"); - // The labels above the bar are in the colour too. - let labels = (0..y.saturating_sub(8)).map(|row| count(|p| p.red() > 120 && p.green() < 90 && p.blue() < 90, row)).sum::(); - assert!(labels > 0, "red labels"); - assert_eq!((0..y.saturating_sub(8)).map(|row| count(ink, row)).sum::(), 0, "no ink labels"); - } - - /// A detailed scale bar's box (#1379) is the narrowest that draws the same bar with all it - /// has: its unit after the bar written in full, its label before zero, and nothing past the - /// box's side but its padding. A plain bar's is the one it always had. - #[test] - fn a_detailed_scale_bars_box_holds_all_it_draws() { - let mut bar = ElementKind::scale_bar(0); - if let ElementKind::ScaleBar { unit_label, unit_label_position, divisions_before_zero, .. } = &mut bar { - (*unit_label, *unit_label_position, *divisions_before_zero) = (Some("Kilometres".into()), UnitLabelPosition::AfterBar, 1); - } - let options = BarOptions::of(&bar).unwrap(); - let w = scale_bar_box_width_pt(100.0, 300.0, &bar, false, 4.0).unwrap(); - assert!(w < 300.0, "{w}"); - let at = |w: f64| bar_layout(Rect::from_xywh(0.0, 0.0, w as f32, 60.0).unwrap(), 100.0, &options, 1.0, false).unwrap(); - let (wide, narrow) = (at(300.0), at(w)); - assert_eq!((narrow.total, narrow.divs, narrow.len), (wide.total, wide.divs, wide.len), "the same bar"); - assert_eq!(narrow.unit.as_ref().map(|u| u.text.as_str()), Some("Kilometres"), "its unit in full"); - assert!(f64::from(narrow.right) + 4.0 <= w + 1e-6, "{} in {w}", narrow.right); - // A little narrower, it would draw another bar or cut what it writes. - let less = at(w * 0.98); - let cut = less.total != wide.total || less.unit.as_ref().map(|u| u.text.as_str()) != Some("Kilometres"); - assert!(cut || f64::from(less.right) + 4.0 > w * 0.98, "the narrowest"); - let plain = ElementKind::scale_bar(0); - assert_eq!( - scale_bar_box_width_pt(100.0, 300.0, &plain, false, 4.0), - scale_bar_width_pt(100.0, 300.0, (ScaleUnits::Auto, 4, SCALE_BAR_TEXT_PT), false, 4.0) - ); - assert_eq!(scale_bar_box_width_pt(0.0, 300.0, &bar, false, 4.0), None); - } - - /// A scale bar's labels at their text size (#2581): at 16 points their room over the bar and - /// between them is twice the default's and the bar keeps its length and height; 8 points draws - /// as the bar always did; the width a box needs counts its last label at that size. - #[test] - fn a_scale_bars_labels_take_its_text_size() { - let plain = |divisions: usize, text_size: f64| BarOptions { divisions, text_size, ..BarOptions::default() }; - let r = Rect::from_xywh(0.0, 0.0, 400.0, 80.0).unwrap(); - let at = |pt: f64| bar_layout(r, 100.0, &plain(4, pt), 1.0, false).unwrap(); - let (small, big) = (at(SCALE_BAR_TEXT_PT), at(16.0)); - assert_eq!((small.len, small.bar_h, small.y0), (big.len, big.bar_h, big.y0), "the bar keeps its size"); - assert!((big.px - 2.0 * small.px).abs() < 1e-3, "{} against {}", big.px, small.px); - // Its inset follows, and more: its first label reaches no further left than at 8 points, - // where its "0" pokes a little past the box's side. - let reach = |b: &BarLayout| b.x0 - text::measure(&b.labels[0].1, b.px / 1.33, false) / 2.0; - assert!(reach(&small) < 0.0, "{}", reach(&small)); - assert!(big.x0 >= 2.0 * BAR_INSET - 1e-3 && (reach(&big) - reach(&small)).abs() < 1e-3, "{} {}", big.x0, reach(&big)); - let over = |b: &BarLayout| b.y0 - b.label_y; - assert!((over(&big) - 2.0 * over(&small)).abs() < 1e-3, "its room over the bar follows"); - // The default draws the bar as before: an 8-point label 1.33 pixels a point, 2 pixels in. - assert_eq!((small.px, small.x0), (8.0 * 1.33, BAR_INSET)); - // Out of range or non-finite, as a program may hand it, it is drawn in range. - assert_eq!(at(1e9).px, at(100.0).px); - assert_eq!(at(f64::NAN).px, small.px); - // Labels that would touch at the larger size are left out, never the ends. - let crowded = bar_layout(Rect::from_xywh(0.0, 0.0, 120.0, 80.0).unwrap(), 100.0, &plain(10, 40.0), 1.0, false).unwrap(); - assert!(crowded.labels.len() < 11, "{} labels", crowded.labels.len()); - assert_eq!(crowded.labels.first().map(|l| l.1.as_str()), Some("0")); - // In a box 34 pixels tall (9 mm at a point a pixel), the default leaves room over its - // labels; at 14 points the bar moves down so they reach no higher than the box's top, and - // at 40 the box is too short for them and the bar, which is drawn below it. - let in_box = |h: f32, pt: f64| bar_layout(Rect::from_xywh(0.0, 0.0, 400.0, h).unwrap(), 100.0, &plain(4, pt), 1.0, false).unwrap(); - let rise = |b: &BarLayout| b.label_y - b.px * BAR_LABEL_RISE; - let (eight, fourteen, forty) = (in_box(34.0, 8.0), in_box(34.0, 14.0), in_box(34.0, 40.0)); - assert!((eight.y0 - (34.0 * 0.62 - eight.bar_h / 2.0)).abs() < 1e-4 && rise(&eight) > 0.0, "the default where it was"); - assert!(fourteen.y0 > eight.y0 && rise(&fourteen).abs() < 1e-3 && !fourteen.cramped, "moved down: {}", fourteen.y0); - assert!(forty.cramped && rise(&forty).abs() < 1e-3, "too short: the bar at {}", forty.y0); - assert!(!eight.cramped && !fourteen.cramped); - // Sideways, its last label at 40 points past a narrow box's right side, its bar the same - // length: too narrow, its box tall enough. At 8 points the same box holds it. - let narrow = |pt: f64| bar_layout(Rect::from_xywh(0.0, 0.0, 90.0, 400.0).unwrap(), 100.0, &plain(4, pt), 1.0, false).unwrap(); - let (n8, n40) = (narrow(8.0), narrow(40.0)); - assert!(!n8.cramped && n40.cramped && n40.y0 + n40.bar_h < 400.0 && n40.len == n8.len, "{} {}", n40.y0, n40.len); - // Its end label, always drawn as its first is, running into the first above the default - // size reaches past the box's side too: the box is too small, and said. - for pt in [9.0, 12.0, 20.0, 40.0, 100.0] { - for w in (20..400).step_by(7) { - let Some(b) = bar_layout(Rect::from_xywh(0.0, 0.0, w as f32, 400.0).unwrap(), 100.0, &plain(4, pt), 1.0, false) else { - continue; - }; - let half = |s: &str| text::measure(s, b.px / 1.33, false) / 2.0; - let ((fx, fs), (ex, es)) = (&b.labels[0], &b.labels[b.labels.len() - 1]); - let clash = b.labels.len() > 1 && ex - half(es) < fx + half(fs); - assert!(!clash || b.cramped, "{pt} pt in {w} px: its end label over its first, not said"); - } - } - // A publication's short box (17 pixels): the default reaches over it, as it always did, - // and a larger size reaches no higher. - let (short8, short12) = (in_box(17.0, 8.0), in_box(17.0, 12.0)); - assert!((short8.y0 - (17.0 * 0.62 - short8.bar_h / 2.0)).abs() < 1e-4 && rise(&short8) < 0.0); - assert!((rise(&short12) - rise(&short8)).abs() < 1e-3, "{} against {}", rise(&short12), rise(&short8)); - let width = |pt| scale_bar_width_pt(100.0, 300.0, (ScaleUnits::Auto, 4, pt), false, 4.0).unwrap(); - assert!(width(40.0) > width(SCALE_BAR_TEXT_PT), "{} against {}", width(40.0), width(SCALE_BAR_TEXT_PT)); - } - - /// A scale bar's labels that don't fit are reported as a text is, measured where they are - /// drawn (#2581): at 40 points a box too short for them and its bar, and a label past the - /// page's right edge. - #[test] - fn a_scale_bars_labels_off_the_page_are_reported() { - let maps = vec![Map::new("m")]; - let mut l = Layout::new("Page", 120.0, 90.0); - let frame = l.add( - "Frame", - (10.0, 30.0, 100.0, 50.0), - serde_json::from_value(serde_json::json!({"MapFrame":{"map":"m", "center":{"x":0,"y":0}, "scale":1000000}})).unwrap(), - ); - let bar = l.add("Scale Bar", (10.0, 0.0, 100.0, 12.0), ElementKind::scale_bar(frame)); - let info = PageInfo::default(); - assert!(clipped_text(&l, &maps, 96.0, &info).is_empty(), "8 points fit"); - if let Some(ElementKind::ScaleBar { text_size, .. }) = l.element_mut(bar).map(|e| &mut e.kind) { - *text_size = 40.0; - } - assert_eq!(clipped_text(&l, &maps, 96.0, &info), vec![(bar, "Scale Bar".into())]); - let note = clipped_text_notice(&l, &clipped_text(&l, &maps, 96.0, &info)).unwrap(); - assert!(note.ends_with("move it inside the page or make its box larger, or reduce its text size"), "{note}"); - let loss = text_loss(&l, &maps, 96.0, &info, bar).unwrap(); - assert!(loss.below_box && scale_bar_fit_notices(std::slice::from_ref(&loss))[0].contains("its box is too small"), "{loss:?}"); - // A tall box holds them at 20 points; off the page's right edge, its last label is cut. - l.element_mut(bar).unwrap().h = 60.0; - if let Some(ElementKind::ScaleBar { text_size, .. }) = l.element_mut(bar).map(|e| &mut e.kind) { - *text_size = 20.0; - } - assert!(clipped_text(&l, &maps, 96.0, &info).is_empty(), "a tall box holds them"); - l.element_mut(bar).unwrap().x = 60.0; - let loss = text_loss(&l, &maps, 96.0, &info, bar).unwrap(); - assert!( - !loss.below_box && loss.off_page && scale_bar_fit_notices(std::slice::from_ref(&loss))[0].contains("runs off the page"), - "{loss:?}" - ); - // Too small and off the page both: each said. - l.element_mut(bar).unwrap().h = 12.0; - if let Some(ElementKind::ScaleBar { text_size, .. }) = l.element_mut(bar).map(|e| &mut e.kind) { - *text_size = 40.0; - } - let both = text_loss(&l, &maps, 96.0, &info, bar).unwrap(); - let said = scale_bar_fit_notices(std::slice::from_ref(&both)); - assert!(both.below_box && both.off_page && said.len() == 2 && said[1].contains("runs off the page"), "{both:?} {said:?}"); - // Several bars are told in one notice a kind, their count and names. - let small = TextLoss { below_box: true, off_page: false, ..loss.clone() }; - let two = scale_bar_fit_notices(&[small.clone(), TextLoss { name: "B".into(), ..small.clone() }]); - assert!(two.len() == 1 && two[0].starts_with("2 scale bars (\"Scale Bar\", \"B\"): their boxes are too small"), "{two:?}"); - assert_eq!(scale_bar_fit_notices(&[small, loss]).len(), 2, "a notice a kind"); - // Drawn without ink, its labels show nothing and aren't measured, as a text's. - if let Some(ElementKind::ScaleBar { color, .. }) = l.element_mut(bar).map(|e| &mut e.kind) { - *color = Rgba::new(0, 0, 0, 0); - } - assert!(text_loss(&l, &maps, 96.0, &info, bar).is_none(), "a bar without ink"); - l.element_mut(bar).unwrap().visible = false; - assert!(clipped_text(&l, &maps, 96.0, &info).is_empty(), "a hidden bar draws nothing"); - } - - /// A 100 x 60 mm page with a 90 x 20 mm frame at its foot showing a map at 1:10,000,000: the - /// map, the page and the frame's id. - fn colour_test_page() -> (Vec, Layout, u32) { - let maps = vec![Map::new("m")]; - let mut l = Layout::new("Layout", 100.0, 60.0); - let frame = l.add( - "Map", - (5.0, 35.0, 90.0, 20.0), - ElementKind::MapFrame { - map: "m".into(), - center: Coord::new(0.0, 0.0), - scale: 10_000_000.0, - shape: FrameShape::Rectangle, - grid: None, - extent_of: None, - extent_color: rustgis_map::layout::INDICATOR_COLOR, - extent_width: rustgis_map::layout::INDICATOR_WIDTH, - border_color: rustgis_map::layout::FRAME_BORDER_COLOR, - border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, - bearing: 0.0, - pitch: 0.0, - }, - ); - (maps, l, frame) - } - - /// A page draws a scale bar in its own colour and fill: the element's, through `draw_page`. - #[test] - fn a_page_draws_its_scale_bar_in_its_colours() { - let (mut maps, mut l, frame) = colour_test_page(); - let (crimson, navy) = (Rgba::rgb(0xD0, 0x10, 0x10), Rgba::rgb(0x10, 0x10, 0xD0)); - let mut bar = ElementKind::scale_bar(frame); - if let ElementKind::ScaleBar { color, fill, .. } = &mut bar { - (*color, *fill) = (crimson, navy); - } - l.add("Scale Bar", (5.0, 5.0, 90.0, 20.0), bar); - let pm = render(&l, &mut maps, 96.0, &PageInfo::default()).unwrap(); - // Above the frame (30 mm of the page's 60): the bar's divisions in its colour and fill, and - // nothing in the default ink. - let above = pm.height() / 2; - let count = |hit: fn(tiny_skia::PremultipliedColorU8) -> bool| { - (0..above).flat_map(|y| (0..pm.width()).map(move |x| (x, y))).filter(|&(x, y)| pm.pixel(x, y).is_some_and(hit)).count() - }; - assert!(count(red) > 100, "red divisions and labels"); - assert!(count(|p| p.blue() > 180 && p.red() < 90 && p.green() < 90) > 100, "blue divisions"); - assert_eq!(count(ink), 0, "no default ink"); - } - - #[test] - fn scale_numbers_have_decimals_and_thousands() { - // Auto: as each label needs, with no separators, exactly as before. - assert_eq!(bar_number(5000.0, 1000.0, None, false), "5000"); - assert_eq!(bar_number(0.0125, 0.0125, None, false), "0.0125"); - assert_eq!(bar_number(-500.0, 500.0, None, false), "-500"); - assert_eq!(bar_number(2.5, 1.25, None, true), "2,5"); - // Fixed decimals with their thousands apart, the marks swapped under a decimal comma. - assert_eq!(bar_number(5000.0, 1000.0, Some(0), false), "5,000"); - assert_eq!(bar_number(5000.0, 1000.0, Some(0), true), "5.000"); - assert_eq!(bar_number(3.75, 1.25, Some(0), false), "4", "fixed at none, rounded"); - assert_eq!(bar_number(1250.0, 250.0, Some(2), false), "1,250.00"); - assert_eq!(bar_number(1250.0, 250.0, Some(2), true), "1.250,00"); - assert_eq!(bar_number(12500.0, 2500.0, Some(3), true), "12.500,000"); - assert_eq!(bar_number(-1500.0, 500.0, Some(1), true), "-1.500,0"); - assert_eq!(bar_number(0.0, 5.0, Some(2), false), "0.00"); - assert_eq!(bar_number(-0.001, 5.0, Some(1), false), "0.0", "no sign on a zero"); - assert_eq!(bar_number(f64::NAN, 1.0, Some(2), false), "0.00", "never a panic"); - assert_eq!(bar_number(1250.0, 250.0, Some(9), false), "1,250.000", "at most 3"); - } - - #[test] - fn scale_bars_draw_subdivisions_and_place_labels_above_or_below() { - let with = |f: &dyn Fn(&mut BarOptions<'static>)| { - let mut b = BarOptions::default(); - f(&mut b); - draw_bar(&b, 300) - }; - let above = with(&|_| {}); - let rows = bar_ink_rows(&above); - assert!(rows.iter().any(|&y| y < 32) && rows.iter().all(|&y| y < 42), "labels over the bar: {rows:?}"); - let below = with(&|b| b.label_position = ScaleLabelPosition::Below); - let rows = bar_ink_rows(&below); - assert!(rows.iter().all(|&y| y >= 18) && rows.iter().any(|&y| y > 28), "labels under it: {rows:?}"); - // Subdivisions aren't labelled: the first ink row stays where the labels put it. - let cut = with(&|b| b.subdivisions = 3); - assert_eq!(bar_ink_rows(&cut).first(), bar_ink_rows(&above).first()); - // A bigger label is taller; decimals change the labels. - assert!(bar_ink_rows(&with(&|b| b.text_size = 16.0)).len() > rows.len() + 4); - assert_ne!(with(&|b| b.decimals = Some(2)).data(), above.data()); - assert_ne!(with(&|b| b.divisions_before_zero = 1).data(), above.data()); - } - - #[test] - fn unit_labels_sit_after_the_bar_when_asked() { - let draw = |text: Option<&'static str>, at| { - draw_bar(&BarOptions { unit_label: text, unit_label_position: at, units: ScaleUnits::Kilometers, ..BarOptions::default() }, 300) - }; - let right_of = - |pm: &Pixmap| (0..pm.height()).filter_map(|y| (0..pm.width()).rev().find(|&x| pm.pixel(x, y).is_some_and(ink))).max(); - let none = draw(Some(""), UnitLabelPosition::AfterBar); - let feet = draw(Some("Feet"), UnitLabelPosition::AfterBar); - let (_, bare_end) = marked_span(&none, 37).unwrap(); - let (_, word_end) = marked_span(&feet, 37).unwrap(); - assert!(word_end > bare_end + 15, "level with the bar, after it: {word_end} against {bare_end}"); - // Left out, the abbreviation follows the last label; "" prints none. - let default = draw(None, UnitLabelPosition::AfterLabels); - let blank = draw(Some(""), UnitLabelPosition::AfterLabels); - assert!(right_of(&default) > right_of(&blank)); - // Above or below, on a line of its own. - let top = |pm: &Pixmap| bar_ink_rows(pm).first().copied().unwrap_or(0); - let bottom = |pm: &Pixmap| bar_ink_rows(pm).last().copied().unwrap_or(0); - assert!(top(&draw(Some("Feet"), UnitLabelPosition::Above)) < top(&blank)); - assert!(bottom(&draw(Some("Feet"), UnitLabelPosition::Below)) > bottom(&blank)); - assert_ne!(draw(Some("FEET"), UnitLabelPosition::AfterBar).data(), feet.data(), "verbatim"); - // Other scripts and emoji draw without a panic. - for text in ["距離 km", "مسافة", "🚶"] { - for at in UnitLabelPosition::ALL { - let _ = draw(Some(text), at); - } - } - // A label of spaces prints nothing and takes no room: after the bar or on a line of its own. - assert_eq!(draw(Some(" "), UnitLabelPosition::AfterBar).data(), none.data()); - assert_eq!(draw(Some(" "), UnitLabelPosition::Above).data(), draw(Some(""), UnitLabelPosition::Above).data()); - // A 100-character unit stays inside a 93 px element wherever it is placed. - let long: String = "Kilometres ".repeat(10).chars().take(100).collect(); - let narrow = |text: &str, at| { - draw_bar( - &BarOptions { unit_label: Some(text), unit_label_position: at, units: ScaleUnits::Kilometers, ..BarOptions::default() }, - 93, - ) - }; - let marked = |p: tiny_skia::PremultipliedColorU8| p.red() < 200 || p.green() < 200 || p.blue() < 200; - for at in UnitLabelPosition::ALL { - let pm = narrow(&long, at); - let past: Vec<(u32, u32)> = (0..pm.height()) - .flat_map(|y| (92..pm.width()).map(move |x| (x, y))) - .filter(|&(x, y)| pm.pixel(x, y).is_some_and(marked)) - .collect(); - assert!(past.is_empty(), "{at:?}: ink past the element at {past:?}"); - assert_ne!(pm.data(), narrow("", at).data(), "{at:?}: the unit is drawn, shortened"); - } - // After the labels, the unit is shortened and the last label's number kept whole: the ink - // columns of the number drawn alone are all there, moved left with the label. - let columns = |pm: &Pixmap| -> Vec { (0..pm.width()).map(|x| (0..33).any(|y| pm.pixel(x, y).is_some_and(ink))).collect() }; - let bare = columns(&narrow("", UnitLabelPosition::AfterLabels)); - let long_cols = columns(&narrow(&long, UnitLabelPosition::AfterLabels)); - let end = bare.iter().rposition(|&c| c).unwrap(); - // The last number: back from its right edge to a 3 px gap. - let start = (0..end).rev().find(|&x| x >= 2 && !bare[x] && !bare[x - 1] && !bare[x - 2]).map_or(0, |x| x + 1); - let number = &bare[start..=end]; - let found = (0..=start).any(|d| long_cols[start - d..=end - d] == *number); - assert!(found, "the last number {start}..={end} is drawn whole: {long_cols:?}"); - } - - /// A long unit after the labels of a short bar, centred on its end, stays inside both edges of - /// the element, the last number drawn whole. - #[test] - fn a_unit_after_the_labels_of_a_short_bar_stays_inside_both_edges() { - let long = "k".repeat(100); - // 79 px to use at 250 m a point, 19.8 km: four 2 km divisions, a 32 px bar ending nearer - // the left edge than the right. - let draw = |unit: &str| { - let bar = BarOptions { - units: ScaleUnits::Kilometers, - fit: ScaleBarFit::AdjustWidth, - unit_label: Some(unit), - ..BarOptions::default() - }; - let mut pm = Pixmap::new(93, 60).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let r = Rect::from_xywh(0.0, 0.0, 93.0, 60.0).unwrap(); - crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 250.0, &bar, DEFAULT_COLORS, 1.0, false)); - pm - }; - let (pm, bare) = (draw(&long), draw("")); - // The first label, "0", reaches the left edge as on every bar: the long unit adds nothing - // there, nor anything at the right edge. - let at = |pm: &Pixmap, x: u32| (0..pm.height()).map(|y| pm.pixel(x, y).is_some_and(ink)).collect::>(); - assert_eq!(at(&pm, 0), at(&bare, 0), "nothing more at the left edge"); - assert!(at(&pm, 92).iter().all(|d| !d), "nothing at the right edge"); - // The last number: its ink columns (rows above the bar) drawn alone are all there. - let columns = |pm: &Pixmap| -> Vec { (0..pm.width()).map(|x| (0..33).any(|y| pm.pixel(x, y).is_some_and(ink))).collect() }; - let (bare, long_cols) = (columns(&bare), columns(&pm)); - let end = bare.iter().rposition(|&c| c).unwrap(); - let start = (0..end).rev().find(|&x| x >= 2 && !bare[x] && !bare[x - 1] && !bare[x - 2]).map_or(0, |x| x + 1); - let number = &bare[start..=end]; - let found = (0..=start).any(|d| long_cols[start - d..=end - d] == *number); - assert!(found, "the last number {start}..={end} is drawn whole: {long_cols:?}"); - } - - #[test] - fn a_wide_unit_label_after_the_bar_keeps_the_bar() { - let long = "Kilometres of ground distance, as measured on the map ".repeat(2); - for width in [12u32, 40, 93, 300] { - for height in [8u32, 60] { - let bar = BarOptions { - unit_label: Some(long.as_str()), - unit_label_position: UnitLabelPosition::AfterBar, - units: ScaleUnits::Kilometers, - ..BarOptions::default() - }; - let mut pm = Pixmap::new(width, height).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let r = Rect::from_xywh(0.0, 0.0, width as f32, height as f32).unwrap(); - // Filled in its colour throughout, so along its middle the bar is one solid run. - let solid = (DEFAULT_COLORS.0, DEFAULT_COLORS.0); - crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, &bar, solid, 1.0, false)); - if width >= 40 && height == 60 { - let marked = |x: u32| pm.pixel(x, 37).is_some_and(|p| p.red() < 200 || p.green() < 200 || p.blue() < 200); - let a = (0..width).find(|&x| marked(x)).unwrap_or(width); - // The bar ends where the 3 px gap before its unit begins; the unit follows. - let gap = (a..width).find(|&x| (x..x + 3).all(|x| !marked(x))).unwrap_or(width); - let end = gap.saturating_sub(1); - let unit = (gap..width).find(|&x| marked(x)); - // Half the 85 % room is the bar's; its round length is at least 40 % of that. - let room = width as f32 * 0.85 * 0.5; - let (least, most) = ((room * 0.4) as u32 - 2, (room + 2.0) as u32); - assert!(end >= a + least && end <= a + most, "width {width}: the bar keeps half its room, {a}..{end}"); - // Shortened to the room kept for it, the unit stays inside the bar's room and - // the element; at 40 px it may not fit at all and is left out. - if width > 40 { - assert!(unit.is_some_and(|x| x >= end + 3), "width {width}: the unit after the bar, from {unit:?}"); - } - let inside = (BAR_INSET + width as f32 * 0.85 + 1.0).min(width as f32 - 1.0) as u32; - let past = (inside..width).find(|&x| marked(x)); - assert!(past.is_none(), "width {width}: the unit stays in the bar's room, ink at {past:?}"); - } - } - } - } - - #[test] - fn a_unit_label_after_the_bar_is_shortened_to_its_room() { - let measure = |s: &str| s.chars().count() as f32 * 10.0; - assert_eq!(shortened("Feet", 40.0, measure).as_deref(), Some("Feet")); - assert_eq!(shortened("Kilometres", 40.0, measure).as_deref(), Some("Kil…")); - assert_eq!(shortened("Kilo metres", 60.0, measure).as_deref(), Some("Kilo…"), "no space before the ellipsis"); - assert_eq!(shortened("Kilometres", 20.0, measure).as_deref(), Some("K…")); - assert_eq!(shortened("Kilometres", 19.0, measure), None, "nothing when not even a letter fits"); - assert_eq!(shortened("", -1.0, measure), None); - // A long unit takes a handful of measurements, not one a character. - let calls = std::cell::Cell::new(0); - let counted = |s: &str| { - calls.set(calls.get() + 1); - measure(s) - }; - let long = "k".repeat(100); - assert_eq!(shortened(&long, 105.0, counted).as_deref(), Some("kkkkkkkkk…")); - assert!(calls.get() <= 9, "{} measurements", calls.get()); - // After the last label, only the unit is shortened, never the number. - assert_eq!(last_label("25", "Kilometres", 130.0, measure), ("25 Kilometres".into(), None)); - assert_eq!(last_label("25", "Kilometres", 80.0, measure), ("25 Kilo…".into(), Some(UnitLabelCut::Shortened))); - assert_eq!( - last_label("25", "Kilometres", 40.0, measure), - ("25".into(), Some(UnitLabelCut::LeftOut)), - "the number alone when not a letter fits" - ); - assert_eq!(last_label("1,250", "km", 10.0, measure), ("1,250".into(), Some(UnitLabelCut::LeftOut)), "the number is never cut"); - } - - /// A unit label shortened with an ellipsis, or left out with no room for it, is said, as a cut - /// text is, wherever it is placed; one drawn whole, or a plain bar's abbreviation, is not. - #[test] - fn a_shortened_or_left_out_unit_label_is_said() { - let long = "Kilometres ".repeat(9); - let cut = |w: f32, unit: Option<&str>, unit_label_position| { - let bar = BarOptions { unit_label: unit, unit_label_position, units: ScaleUnits::Kilometers, ..BarOptions::default() }; - bar_layout(Rect::from_xywh(0.0, 0.0, w, 60.0).unwrap(), 100.0, &bar, 1.0, false).unwrap().unit_cut - }; - for at in UnitLabelPosition::ALL { - assert_eq!(cut(200.0, Some(&long), at), Some(UnitLabelCut::Shortened), "{at:?}"); - assert_eq!(cut(400.0, Some("Km"), at), None, "{at:?}: drawn whole"); - assert_eq!(cut(200.0, None, at), None, "{at:?}: the abbreviation"); - } - // Not even a letter of it fits after the bar's last label in a box this narrow. - assert_eq!(cut(20.0, Some(&long), UnitLabelPosition::AfterLabels), Some(UnitLabelCut::LeftOut)); - let loss = |name: &str, unit_label| TextLoss { - id: 1, - name: name.into(), - left_out: 0, - at_least: false, - below_box: false, - past_limit: false, - off_page: false, - unit_label, - }; - let said = scale_bar_fit_notices(&[loss("A", Some(UnitLabelCut::Shortened))]); - assert_eq!(said.len(), 1); - assert!(said[0].starts_with("Scale bar \"A\": its unit label is shortened to fit"), "{said:?}"); - let said = scale_bar_fit_notices(&[loss("A", Some(UnitLabelCut::LeftOut)), loss("B", Some(UnitLabelCut::LeftOut))]); - assert!(said.len() == 1 && said[0].starts_with("2 scale bars (\"A\", \"B\"): their unit labels are left out"), "{said:?}"); - assert!(scale_bar_fit_notices(&[loss("A", None)]).is_empty()); - } - - /// A bar whose lines just fit its box, so none is written smaller, still draws them all inside it. - #[test] - fn a_scale_bar_rows_stay_inside_a_box_they_just_fit() { - let bar = BarOptions { - unit_label: Some("Kilometres"), - unit_label_position: UnitLabelPosition::Above, - label_position: ScaleLabelPosition::Above, - text_size: 24.0, - units: ScaleUnits::Kilometers, - ..BarOptions::default() - }; - // The 93 x 88 box in the middle of a taller page, so ink outside it would show. - let mut pm = Pixmap::new(93, 128).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let r = Rect::from_xywh(0.0, 20.0, 93.0, 88.0).unwrap(); - crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, &bar, DEFAULT_COLORS, 1.0, false)); - let marked = |p: tiny_skia::PremultipliedColorU8| p.red() < 200 || p.green() < 200 || p.blue() < 200; - let rows: Vec = (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| pm.pixel(x, y).is_some_and(marked))).collect(); - assert!(!rows.is_empty() && rows.iter().all(|&y| (20..108).contains(&y)), "every line inside the box: {rows:?}"); - } - - /// A bar in a box too short for its lines draws them at their size and is said, as a bar too - /// short for its labels at their text size is (#2581): its labels below and its unit above - /// count, where a plain bar's labels alone fit. A box tall enough draws them all inside it. - #[test] - fn a_scale_bar_unit_label_row_in_a_short_box_is_said() { - let bar = BarOptions { - unit_label: Some("Kilometres"), - unit_label_position: UnitLabelPosition::Above, - label_position: ScaleLabelPosition::Below, - units: ScaleUnits::Kilometers, - ..BarOptions::default() - }; - let short = Rect::from_xywh(0.0, 20.0, 300.0, 20.0).unwrap(); - let placed = bar_layout(short, 100.0, &bar, 1.0, false).unwrap(); - assert!(placed.cramped, "too short for its lines"); - assert_eq!(placed.px, SCALE_BAR_TEXT_PT as f32 * 1.33, "drawn at its size, not smaller"); - assert!(!bar_layout(short, 100.0, &BarOptions::default(), 1.0, false).unwrap().cramped, "a plain bar fits"); - // In a box tall enough, every line inside it: the unit above and the labels under the bar. - let mut pm = Pixmap::new(300, 80).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let r = Rect::from_xywh(0.0, 20.0, 300.0, 40.0).unwrap(); - assert!(!bar_layout(r, 100.0, &bar, 1.0, false).unwrap().cramped); - crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, &bar, DEFAULT_COLORS, 1.0, false)); - let marked = |x: u32, y: u32| pm.pixel(x, y).is_some_and(|p| p.red() < 250 || p.green() < 250 || p.blue() < 250); - let rows: Vec = (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| marked(x, y))).collect(); - assert!(!rows.is_empty() && rows.iter().all(|y| (20..60).contains(y)), "inside the box: {rows:?}"); - // On a page, the short box is told as the text size's is: too small for its labels. - let maps = vec![Map::new("m")]; - let mut l = Layout::new("Page", 120.0, 90.0); - let frame = l.add( - "Frame", - (10.0, 30.0, 100.0, 50.0), - serde_json::from_value(serde_json::json!({"MapFrame":{"map":"m", "center":{"x":0,"y":0}, "scale":1000000}})).unwrap(), - ); - let id = l.add("Scale Bar", (10.0, 0.0, 100.0, 12.0), ElementKind::scale_bar(frame)); - let info = PageInfo::default(); - let set = |l: &mut Layout, size: f64, rows: bool| { - if let Some(ElementKind::ScaleBar { text_size, label_position, unit_label_position, .. }) = - l.element_mut(id).map(|e| &mut e.kind) - { - *text_size = size; - (*label_position, *unit_label_position) = if rows { - (ScaleLabelPosition::Below, UnitLabelPosition::Above) - } else { - (ScaleLabelPosition::Above, UnitLabelPosition::AfterLabels) - }; - } - }; - set(&mut l, 20.0, false); - assert!(text_loss(&l, &maps, 96.0, &info, id).is_none(), "a plain bar's labels at 20 points fit"); - set(&mut l, 20.0, true); - let loss = text_loss(&l, &maps, 96.0, &info, id).unwrap(); - assert!(loss.below_box && scale_bar_fit_notices(std::slice::from_ref(&loss))[0].contains("its box is too small"), "{loss:?}"); - set(&mut l, SCALE_BAR_TEXT_PT, true); - assert!(text_loss(&l, &maps, 96.0, &info, id).is_none(), "its rows at 8 points fit"); - } - - /// A page draws its scale bar's details through `draw_page`: the unit label in the bar's colour. - #[test] - fn a_page_draws_a_scale_bar_with_its_details() { - let (mut maps, mut l, frame) = colour_test_page(); - let mut bar = ElementKind::scale_bar(frame); - if let ElementKind::ScaleBar { - color, label_position, unit_label, unit_label_position, subdivisions, divisions_before_zero, .. - } = &mut bar - { - *color = Rgba::rgb(0xD0, 0x10, 0x10); - (*label_position, *unit_label, *unit_label_position) = - (ScaleLabelPosition::Below, Some("Kilometres".into()), UnitLabelPosition::Above); - (*subdivisions, *divisions_before_zero) = (4, 1); - } - l.add("Scale Bar", (5.0, 5.0, 90.0, 20.0), bar.clone()); - let pm = render(&l, &mut maps, 96.0, &PageInfo::default()).unwrap(); - let rows = |from: u32, to: u32, hit: fn(tiny_skia::PremultipliedColorU8) -> bool| { - (from..to).flat_map(|y| (0..pm.width()).map(move |x| (x, y))).filter(|&(x, y)| pm.pixel(x, y).is_some_and(hit)).count() - }; - // The strip of the bar's 20 mm box over the bar (its middle at 15 mm, its top 4 px above) - // holds the unit label, in the bar's colour. - let mm = pm.height() as f32 / 60.0; - assert!(rows((5.0 * mm) as u32, (13.5 * mm) as u32, red) > 30, "the unit label over the bar, crimson"); - assert_eq!(rows(0, pm.height() / 2, ink), 0, "no default ink"); - // The same bar without its details draws differently on the same page. - let (mut maps2, mut plain, frame2) = colour_test_page(); - let mut same = ElementKind::scale_bar(frame2); - if let ElementKind::ScaleBar { color, .. } = &mut same { - *color = Rgba::rgb(0xD0, 0x10, 0x10); - } - plain.add("Scale Bar", (5.0, 5.0, 90.0, 20.0), same); - assert_ne!(pm.data(), render(&plain, &mut maps2, 96.0, &PageInfo::default()).unwrap().data()); - } - - #[test] - fn scale_numbers_are_short() { - assert_eq!(scale_number(5.0, 1.25), "5"); - assert_eq!(scale_number(2.5, 1.25), "2.5"); - assert_eq!(scale_number(1.25, 1.25), "1.25"); - assert_eq!(scale_number(0.0, 1.25), "0"); - assert_eq!(scale_number(100.0, 50.0), "100"); - // Small totals keep their precision: 0.05 km in four divisions. - assert_eq!(scale_number(0.0125, 0.0125), "0.0125"); - assert_eq!(scale_number(0.0375, 0.0125), "0.0375"); - assert_eq!(scale_number(0.125, 0.125), "0.125"); - // A step that never comes out even keeps two significant digits of it. - assert_eq!(scale_number(1.0 / 3.0, 1.0 / 3.0), "0.33"); - assert_eq!(scale_number(2.0 / 3.0, 1.0 / 3.0), "0.67"); - assert_eq!(scale_number(1.0, 1.0 / 3.0), "1"); - assert_eq!(scale_number(20.0 / 3.0, 10.0 / 3.0), "6.7"); - assert_eq!(scale_number(200.0 / 3.0, 100.0 / 3.0), "67"); - assert_eq!(scale_number(0.01 / 3.0, 0.01 / 3.0), "0.0033"); - } - - /// Graticule labels: meridians along the top and bottom and parallels along the sides come - /// first; a slanting meridian leaving through a side is labelled there only clear of the - /// parallels' labels, and none lands by a corner. - #[test] - fn graticule_labels_keep_clear_of_each_other() { - let along = |_: Edge, s: &str| s.len() as f32 * 5.0; - let label = |edge, at: f32, s: &str, lon| (edge, at, s.to_string(), lon); - let labels = vec![ - // A meridian leaving through the right edge just by a parallel's label (put first, so - // only the order fixes it), and another well clear of any. - label(Edge::Right, 205.0, "36°W", true), - label(Edge::Right, 200.0, "6°S", false), - label(Edge::Right, 400.0, "34°W", true), - label(Edge::Top, 150.0, "42°W", true), - // A parallel curving out through the top near a meridian's label: clear of it, but - // too close to read as its own. - label(Edge::Top, 185.0, "2°S", false), - // By a corner: left out, and a side's label within two label heights of the top. - label(Edge::Top, 4.0, "44°W", true), - label(Edge::Right, 15.0, "2°S", false), - ]; - let kept: Vec = - kept_labels(labels.clone(), (600.0, 500.0), (along, |_: Edge, _: &str| 20.0), 10.0, 1.0).into_iter().map(|(.., s)| s).collect(); - assert_eq!(kept, ["6°S", "42°W", "34°W"]); - // Labels reaching further in than a short frame is across are left out, not cut by it: - // on a frame 30 pixels tall, the top's; the sides', 600 wide, keep theirs. - let kept: Vec = kept_labels(labels, (600.0, 30.0), (along, |_: Edge, _: &str| 40.0), 10.0, 1.0) - .into_iter() - .filter(|(edge, ..)| *edge == Edge::Top) - .map(|(.., s)| s) - .collect(); - assert!(kept.is_empty(), "{kept:?}"); - // And on a frame 15 pixels wide, the sides' labels, whose flat labels reach their width in. - let across = |edge: Edge, s: &str| if matches!(edge, Edge::Left | Edge::Right) { s.len() as f32 * 5.0 + 6.0 } else { 6.0 }; - let side = vec![label(Edge::Right, 200.0, "6°S", false), label(Edge::Left, 250.0, "8°S", false)]; - assert_eq!(kept_labels(side.clone(), (600.0, 500.0), (along, across), 10.0, 1.0).len(), 2, "a wide frame keeps them"); - assert!(kept_labels(side, (15.0, 500.0), (along, across), 10.0, 1.0).is_empty(), "a narrow one leaves them out"); - } - - /// A text's layer statistics (#2853) fill in from the frame's map, written as a chart's values - /// with the layout's decimal mark, beside `{scale}`; a token with no figure, or with no frame, - /// is drawn as written. What each such token is missing is said, once. - #[test] - fn a_text_shows_its_layers_statistics() { - use rustgis_data::{Dataset, Field, FieldType, GeometryType, Value}; - let mut ds = - Dataset::new("Plants", GeometryType::None, vec![Field::new("mw", FieldType::Double), Field::new("name", FieldType::Text)]); - for mw in [12_000.5, 11_553.25] { - ds.push(None, vec![Value::Float(mw), Value::Text("x".into())]); - } - let mut map = Map::new("m"); - map.add_dataset(ds); - let cam = frame_camera(&map, Coord::new(0.0, 0.0), 6_300_000.0, 0.0, 0.0); - let info = PageInfo { page: 1, pages: 1, page_name: String::new() }; - let mut layout = Layout::new("L", 100.0, 100.0); - let text = "{count:Plants} plants, {sum:Plants:mw} MW, mean {mean:Plants:mw}; {sum:Plants:name} {count:Nowhere}"; - assert_eq!( - expand(text, &layout, &info, Some((&map, cam))), - "2 plants, 23,553.75 MW, mean 11,776.88; {sum:Plants:name} {count:Nowhere}" - ); - layout.decimal_comma = true; - assert_eq!( - expand(text, &layout, &info, Some((&map, cam))), - "2 plants, 23.553,75 MW, mean 11.776,88; {sum:Plants:name} {count:Nowhere}" - ); - // Without a frame, every token as written, and said so; a text without tokens says nothing. - assert_eq!(expand("{count:Plants} plants", &layout, &info, None), "{count:Plants} plants"); - let maps = [map]; - assert_eq!( - statistic_notices(&layout, &maps, "{count:Plants} and {count:Plants}"), - vec!["{count:Plants} shows as written: the layout has no map frame whose map it would read".to_string()] - ); - assert_eq!(statistic_notices(&layout, &maps, "Plants at {scale}"), Vec::::new()); - let kind = - serde_json::from_value(serde_json::json!({"MapFrame": {"map": "m", "center": {"x": 0, "y": 0}, "scale": 6300000}})).unwrap(); - layout.add("Frame", (0.0, 0.0, 50.0, 50.0), kind); - let said = - statistic_notices(&layout, &maps, "{sum:Plants:name} {sum:Plants:name} {count:Nowhere} {min:Plants:nosuch} {count:Plants}"); - assert_eq!( - said, - vec![ - "{sum:Plants:name} shows as written: 'name' of 'Plants' holds no numbers".to_string(), - "{count:Nowhere} shows as written: the map of the layout's first frame has no layer named 'Nowhere'".to_string(), - "{min:Plants:nosuch} shows as written: 'Plants' has no field named 'nosuch'".to_string(), - ] - ); - } - - /// A layer read in place holds only the features loaded, so a figure over it is partial: said - /// when the text is set (#2853), as is a layer that holds everything not. - #[test] - fn a_streamed_layers_statistic_says_it_covers_what_is_loaded() { - use rustgis_data::{Dataset, Field, FieldType, GeometryType, Value}; - let layer = |name: &str| { - let fields = vec![Field::new("mw", FieldType::Double), Field::new("blank", FieldType::Double)]; - let mut ds = Dataset::new(name, GeometryType::None, fields); - ds.push(None, vec![Value::Float(1.0), Value::Null]); - ds - }; - let mut map = Map::new("m"); - map.add_dataset(layer("Held")); - map.add_dataset(layer("Streamed")); - map.layers.iter_mut().find(|l| l.name == "Streamed").unwrap().source = Some(Default::default()); - let mut layout = Layout::new("L", 100.0, 100.0); - let kind = - serde_json::from_value(serde_json::json!({"MapFrame": {"map": "m", "center": {"x": 0, "y": 0}, "scale": 6300000}})).unwrap(); - layout.add("Frame", (0.0, 0.0, 50.0, 50.0), kind); - let maps = [map]; - assert_eq!( - statistic_notices(&layout, &maps, "{count:Held} {count:Streamed} {count:Streamed} {sum:Streamed:mw} {sum:Streamed:no} {max:Streamed:blank}"), - vec![ - "{count:Streamed} covers only the features of 'Streamed' that are loaded: it is read in place".to_string(), - "{sum:Streamed:mw} covers only the features of 'Streamed' that are loaded: it is read in place".to_string(), - "{sum:Streamed:no} shows as written: 'Streamed' has no field named 'no'".to_string(), - // No number loaded yet, but a later load may bring some: the scope is said as well. - "{max:Streamed:blank} covers only the features of 'Streamed' that are loaded: it is read in place".to_string(), - "{max:Streamed:blank} shows as written: no feature of 'Streamed' its definition query keeps has a number in 'blank', or the figure is past a number's range".to_string(), - ] - ); - } - - /// A raster layer has no features, so a figure over it has none to give: drawn as written and - /// said (#2853), never a 0 that reads like a count. - #[test] - fn a_raster_layers_statistic_is_drawn_as_written() { - use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; - let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1.0, pixel_height: -1.0 }; - let r = Raster::new("e", 1, 1, vec![vec![1.0]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); - let mut map = Map::new("m"); - map.add_raster("Elevation", rustgis_map::RasterLayer::from_path(r, "e.tif")); - let cam = frame_camera(&map, Coord::new(0.0, 0.0), 6_300_000.0, 0.0, 0.0); - let info = PageInfo { page: 1, pages: 1, page_name: String::new() }; - let mut layout = Layout::new("L", 100.0, 100.0); - assert_eq!(expand("{count:Elevation}", &layout, &info, Some((&map, cam))), "{count:Elevation}"); - let kind = - serde_json::from_value(serde_json::json!({"MapFrame": {"map": "m", "center": {"x": 0, "y": 0}, "scale": 6300000}})).unwrap(); - layout.add("Frame", (0.0, 0.0, 50.0, 50.0), kind); - let maps = [map]; - assert_eq!( - statistic_notices(&layout, &maps, "{count:Elevation}"), - vec!["{count:Elevation} shows as written: 'Elevation' is a raster layer, which has no features".to_string()] - ); - // The same figures over a map given directly, as a presentation map page's title is. - assert_eq!( - map_statistic_notices(&maps[0], "the page's map", "{count:Elevation}"), - vec!["{count:Elevation} shows as written: 'Elevation' is a raster layer, which has no features".to_string()] - ); - } - - /// A frame whose map the project doesn't hold is told apart from a layout with no frame (#2853). - #[test] - fn a_statistic_names_a_frame_whose_map_is_missing() { - let mut layout = Layout::new("L", 100.0, 100.0); - let said = |layout: &Layout| statistic_notices(layout, &[Map::new("m")], "{count:Cities}"); - assert_eq!(said(&layout), vec!["{count:Cities} shows as written: the layout has no map frame whose map it would read".to_string()]); - let kind = - serde_json::from_value(serde_json::json!({"MapFrame": {"map": "gone", "center": {"x": 0, "y": 0}, "scale": 6300000}})).unwrap(); - layout.add("Frame", (0.0, 0.0, 50.0, 50.0), kind); - assert_eq!( - said(&layout), - vec!["{count:Cities} shows as written: the map of the layout's first frame is not in the project".to_string()] - ); - } - - /// A figure written without its field (`{sum:Plants}`) is drawn as written, which is no token for - /// the page, and is said (#2853), as one with a field the layer lacks is. - #[test] - fn a_statistic_without_its_field_is_said() { - use rustgis_data::{Dataset, Field, FieldType, GeometryType}; - let mut map = Map::new("m"); - map.add_dataset(Dataset::new("Plants", GeometryType::None, vec![Field::new("mw", FieldType::Double)])); - let mut layout = Layout::new("L", 100.0, 100.0); - let kind = - serde_json::from_value(serde_json::json!({"MapFrame": {"map": "m", "center": {"x": 0, "y": 0}, "scale": 6300000}})).unwrap(); - layout.add("Frame", (0.0, 0.0, 50.0, 50.0), kind); - let maps = [map]; - assert_eq!( - statistic_notices(&layout, &maps, "{sum:Plants} {count:Plants} {max:Nowhere} {mean:Plants:mw}"), - vec![ - "{sum:Plants} shows as written: a sum takes a field: write {sum:Plants:field}".to_string(), - "{max:Nowhere} shows as written: the map of the layout's first frame has no layer named 'Nowhere'".to_string(), - "{mean:Plants:mw} shows as written: no feature of 'Plants' its definition query keeps has a number in 'mw', or the figure is past a number's range".to_string(), - ] - ); - } - - /// A layout with a decimal comma swaps the marks of the numbers it prints, `{scale}` included, - /// and leaves other text alone. - #[test] - fn a_decimal_comma_swaps_the_marks() { - assert_eq!(decimal("0.05".into(), true), "0,05"); - assert_eq!(decimal("6,300,000".into(), true), "6.300.000"); - assert_eq!(decimal("0.05".into(), false), "0.05"); - let map = Map::new("m"); - let cam = frame_camera(&map, Coord::new(0.0, 0.0), 6_300_000.0, 0.0, 0.0); - let info = PageInfo { page: 1, pages: 1, page_name: String::new() }; - let mut layout = Layout::new("L", 100.0, 100.0); - let point = expand("Scale {scale}, page {page}.", &layout, &info, Some((&map, cam))); - layout.decimal_comma = true; - let comma = expand("Scale {scale}, page {page}.", &layout, &info, Some((&map, cam))); - // "Scale 1:6,300,000, page 1." and "Scale 1:6.300.000, page 1.": the scale's marks swap, the - // text's comma stays. - let scale = point.strip_prefix("Scale ").and_then(|t| t.strip_suffix(", page 1.")).unwrap_or_else(|| panic!("{point}")); - assert!(scale.starts_with("1:") && scale.contains(','), "{point}"); - assert_eq!(comma, format!("Scale {}, page 1.", scale.replace(',', "."))); - } - - /// A map of one point layer, one point, set by `edit`. - fn point_legend_map(edit: impl FnOnce(&mut rustgis_map::Layer)) -> Map { - use rustgis_data::{Dataset, Geometry}; - let mut map = Map::new("m"); - let mut d = Dataset::new("pts", GeometryType::Point, vec![]); - d.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![]); - map.add_dataset(d); - if let Some(l) = map.layers.last_mut() { - edit(l); - } - map - } - - /// The legend of `map` at 1:1e6, every class, on white. - fn point_legend(map: &Map) -> Pixmap { - let mut pm = Pixmap::new(200, 200).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 200.0, 200.0).unwrap(), map, ("", 1), None, opts, 1.0)); - pm - } - - /// The legend of `map` at 1:1e6 recorded for a vector export, on a page of `side` pixels, drawn - /// back on white. - fn recorded_legend(map: &Map, side: u32) -> Pixmap { - let mut c = Canvas::recording(side, side).unwrap(); - let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - legend(&mut c, Rect::from_xywh(0.0, 0.0, side as f32, side as f32).unwrap(), map, ("", 1), None, opts, 1.0); - let (_, _, items) = c.into_drawing().unwrap().finish(); - let mut pm = Pixmap::new(side, side).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - crate::vector::replay(&items, &mut pm, Transform::identity()); - pm - } - - /// What the map's code draws for a point at (`x`, `y`) on white. - fn drawn_point(s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke], (x, y): (f32, f32), ppp: f32) -> Pixmap { - let mut pm = Pixmap::new(200, 200).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - crate::canvas::with_canvas(&mut pm, |c| { - if strokes.is_empty() { - crate::draw_marker(c, x, y, s, 1.0, None, ppp); - } else { - point_marks::draw(c, x, y, s, strokes, 0.0, None, ppp); - } - }); - pm - } - - /// What the map's code draws for a point at (`x`, `y`), composited as one at `opacity`, on - /// white. - fn drawn_see_through( - s: &rustgis_map::Symbol, - strokes: &[rustgis_map::LineStroke], - (x, y): (f32, f32), - ppp: f32, - opacity: f32, - ) -> Pixmap { - let mut own = Pixmap::new(200, 200).unwrap(); - crate::canvas::with_canvas(&mut own, |c| draw_point(c, (x, y), s, strokes, ppp)); - let mut pm = Pixmap::new(200, 200).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - pm.draw_pixmap(0, 0, own.as_ref(), &PixmapPaint { opacity, ..PixmapPaint::default() }, Transform::identity(), None); - pm - } - - /// Whether two pictures differ by no more than a rounding over `w` × `h` from the top left - /// corner. - fn near_corner(a: &Pixmap, b: &Pixmap, w: u32, h: u32) -> bool { - (0..h).all(|y| { - (0..w).all(|x| match (a.pixel(x, y), b.pixel(x, y)) { - (Some(p), Some(q)) => p.red().abs_diff(q.red()).max(p.green().abs_diff(q.green())).max(p.blue().abs_diff(q.blue())) <= 2, - _ => false, - }) - }) - } - - /// Whether two pictures are the same over `w` × `h` from the top left corner. - fn same_corner(a: &Pixmap, b: &Pixmap, w: u32, h: u32) -> bool { - (0..h).all(|y| (0..w).all(|x| a.pixel(x, y) == b.pixel(x, y))) - } - - /// A stacked stroke: a square of `size` points in `color`, with no outline. - fn square_mark(color: Rgba, size: f32) -> rustgis_map::LineStroke { - let markers = rustgis_map::LineMarkers { - mark: rustgis_map::LineMark::Marker(rustgis_map::Marker::Square), - size, - ..rustgis_map::LineMarkers::default() - }; - rustgis_map::LineStroke { color: Some(color), width: Some(0.0), markers: Some(markers), ..rustgis_map::LineStroke::default() } - } - - /// Every marker, tiny and ordinary, with an outline and without, at the pixels the map's code - /// gives it. - #[test] - fn a_legend_draws_a_point_as_the_map_does() { - let red = Rgba::rgb(255, 0, 0); - let base = - rustgis_map::Symbol { fill: red, stroke: Rgba::rgb(0, 0, 255), ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; - // Every shape, tiny and ordinary, with no outline and with one. - for marker in rustgis_map::Marker::ALL { - for (size, stroke_width) in [(2.0, 0.0), (10.0, 0.0), (10.0, 1.0)] { - let s = rustgis_map::Symbol { marker, size, stroke_width, ..base }; - let map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s)); - // The first row, 15 points tall, its swatch 16 wide. - let want = drawn_point(&s, &[], (8.0, 7.5), 1.0); - assert!(same_corner(&point_legend(&map), &want, 16, 15), "{marker:?} of {size} pt, outline {stroke_width} pt"); - } - } - // A class's symbol too, indented under its layer's name. - let s = rustgis_map::Symbol { marker: rustgis_map::Marker::Triangle, size: 10.0, stroke_width: 0.0, ..base }; - let map = point_legend_map(|l| { - l.renderer = rustgis_map::Renderer::Unique { - field: "g".into(), - classes: vec![("a".to_string(), s)], - other: s, - ramp: rustgis_map::Ramp::Ember, - class_labels: Default::default(), - other_label: None, - class_strokes: Default::default(), - other_strokes: Vec::new(), - class_fills: Default::default(), - other_fills: Vec::new(), - expression: None, - }; - }); - let got = point_legend(&map); - let want = drawn_point(&s, &[], (6.0 + 8.0, 15.0 + 7.5), 1.0); - assert!((15..30).all(|y| (6..22).all(|x| got.pixel(x, y) == want.pixel(x, y))), "the class's triangle"); - } - - /// An outline under half a pixel is as thin in a legend as on the map. - #[test] - fn a_legend_draws_a_hairline_outline_as_the_map_does() { - // Thinner than half a pixel: the map's marker strokes it at its width, with no minimum. - let s = rustgis_map::Symbol { - size: 10.0, - stroke: Rgba::rgb(0, 0, 255), - stroke_width: 0.1, - ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) - }; - let map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s)); - assert!(same_corner(&point_legend(&map), &drawn_point(&s, &[], (8.0, 7.5), 1.0), 16, 15)); - } - - /// A layer's stacked marks replace its marker, in a row that holds them. - #[test] - fn a_legend_draws_a_points_stacked_marks() { - let strokes = vec![square_mark(Rgba::rgb(255, 0, 0), 12.0), square_mark(Rgba::rgb(0, 0, 0), 4.0)]; - let s = rustgis_map::Symbol::default_for(GeometryType::Point, 0); - let map = point_legend_map(|l| { - l.renderer = rustgis_map::Renderer::Single(s); - l.line_strokes = strokes.clone(); - }); - // 12 pt squares reach 7.2 pt: the row is 15 points tall still. - assert!(same_corner(&point_legend(&map), &drawn_point(&s, &strokes, (8.0, 7.5), 1.0), 16, 15)); - } - - /// Stacked marks at the opacity of a layer and its groups, on pixels and in a recording. - #[test] - fn a_see_through_point_is_composited_as_one_with_its_groups() { - let s = rustgis_map::Symbol { size: 10.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; - let strokes = vec![square_mark(Rgba::rgb(255, 0, 0), 12.0), square_mark(Rgba::rgb(0, 0, 0), 12.0)]; - let mut map = point_legend_map(|l| { - l.renderer = rustgis_map::Renderer::Single(s); - l.line_strokes = strokes.clone(); - l.transparency = 50.0; - }); - let middle = |map: &Map| point_legend(map).pixel(8, 7).map(|p| (p.red(), p.green(), p.blue())).unwrap(); - // Black at half over white: grey, with none of the red under it showing. - let (r, g, b) = middle(&map); - assert!((120..=135).contains(&r) && r == g && g == b, "{r} {g} {b}"); - // Its group's transparency applies too: half of half. - let id = map.layers[0].id; - let mut group = rustgis_map::LayerGroup::new("g"); - group.transparency = 50.0; - group.children.push(id); - map.add_group(group); - let (r, g, b) = middle(&map); - assert!((185..=197).contains(&r) && r == g && g == b, "{r} {g} {b}"); - // Recorded for a vector export, it is half of half too. - let p = recorded_legend(&map, 200).pixel(8, 7).unwrap(); - let (r, g, b) = (p.red(), p.green(), p.blue()); - assert!((185..=197).contains(&r) && r == g && g == b, "recorded: {r} {g} {b}"); - } - - /// A square turned by its own angle reaches past 0.6 of its size: its row holds its corners, - /// which the picture of a see-through symbol would cut. - #[test] - fn a_see_through_mark_with_its_own_angle_keeps_its_corners() { - let s = rustgis_map::Symbol { size: 10.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; - let mut mark = square_mark(Rgba::rgb(0, 0, 255), 40.0); - if let Some(m) = &mut mark.markers { - m.angle = 45.0; - } - let strokes = vec![mark]; - let map = point_legend_map(|l| { - l.renderer = rustgis_map::Renderer::Single(s); - l.line_strokes = strokes.clone(); - l.transparency = 50.0; - }); - let side = 2.0 * point_marks::reach(&s, &strokes); - assert!(side > 50.0, "{side}"); - let drawn = drawn_see_through(&s, &strokes, (side / 2.0, side / 2.0), 1.0, 0.5); - assert!(near_corner(&point_legend(&map), &drawn, side.ceil() as u32, side.ceil() as u32)); - } - - /// A plain point at half its opacity, its outline over its fill: composited as one, so the fill - /// doesn't show through the outline. - #[test] - fn a_see_through_plain_point_is_composited_as_the_map_composites_a_layer() { - let s = rustgis_map::Symbol { - fill: Rgba::rgb(255, 0, 0), - stroke: Rgba::rgb(0, 0, 255), - stroke_width: 1.0, - size: 8.0, - marker: rustgis_map::Marker::Square, - }; - let map = point_legend_map(|l| { - l.renderer = rustgis_map::Renderer::Single(s); - l.transparency = 50.0; - }); - assert!(near_corner(&point_legend(&map), &drawn_see_through(&s, &[], (8.0, 7.5), 1.0, 0.5), 16, 15)); - } - - /// A large symbol takes a taller row and a wider column in a legend's size; an ordinary one - /// doesn't. - #[test] - fn a_legend_grows_to_hold_a_large_point() { - let mm = 25.4 / 96.0; - let s = |size| rustgis_map::Symbol { size, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; - let label = f64::from(6.0 + text::measure("pts", 9.0, false)); - // An ordinary symbol keeps the row and the swatch's column. - let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(10.0))); - let [(w, h), ..] = legend_sizes_mm(&mut map, 1e6, true, false, (&[], &NO_LABELS)).unwrap(); - assert!((h - f64::from(LEGEND_ROW) * mm).abs() < 1e-6, "{h} mm"); - // Its width within a rounding: it is summed in f32, past a name as wide as its font makes it. - assert!((w - (f64::from(LEGEND_SWATCH) + label) * mm).abs() < 1e-4, "{w} mm"); - // One of 40 pt reaches 24 pt from its point: 48 pt each way. - let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(40.0))); - let [(w, h), ..] = legend_sizes_mm(&mut map, 1e6, true, false, (&[], &NO_LABELS)).unwrap(); - assert!((h - 48.0 * mm).abs() < 1e-6, "{h} mm"); - assert!((w - (48.0 + label) * mm).abs() < 1e-4, "{w} mm"); - assert!(same_corner(&point_legend(&map), &drawn_point(&s(40.0), &[], (24.0, 24.0), 1.0), 48, 48)); - // A frame too short for the row draws no part of it. - let mut pm = Pixmap::new(200, 200).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let blank = pm.clone(); - let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 200.0, 47.0).unwrap(), &map, ("", 1), None, opts, 1.0)); - assert!(pm.data() == blank.data()); - // A size no page could hold stays a size a legend can take. - let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(f32::MAX))); - let [(w, h), ..] = legend_sizes_mm(&mut map, 1e6, true, false, (&[], &NO_LABELS)).unwrap(); - assert!(w.is_finite() && h.is_finite(), "{w} × {h} mm"); - } - - /// A legend's text size (#2581) scales its text, rows, swatches and gaps, and its title's room, - /// from 9 points; a point symbol keeps the size the map draws it at, its row growing only as - /// far as it needs. - #[test] - fn a_legends_text_size_scales_its_rows_but_not_its_point_symbols() { - let mm = 25.4 / 96.0; - let s = |size| rustgis_map::Symbol { size, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; - let sized = - |map: &mut Map, pt: f64| legend_sizes_with_no_data_mm(map, 1e6, true, false, (false, pt), (&[], &NO_LABELS)).unwrap()[0]; - // An ordinary symbol at 18 points: the row, the swatch's column, the gap and the name twice - // their size at 9. - let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(10.0))); - let (w, h) = sized(&mut map, 18.0); - assert!((h - f64::from(2.0 * LEGEND_ROW) * mm).abs() < 1e-6, "{h} mm"); - let label = f64::from(12.0 + text::measure("pts", 18.0, false)); - assert!((w - (f64::from(2.0 * LEGEND_SWATCH) + label) * mm).abs() < 1e-4, "{w} mm"); - assert_eq!( - sized(&mut map, rustgis_map::layout::LEGEND_TEXT_PT), - legend_sizes_mm(&mut map, 1e6, true, false, (&[], &NO_LABELS)).unwrap()[0] - ); - // One of 40 points keeps its 48: the row (30 at 18 points) and the column grow to it. - let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(40.0))); - let (w, h) = sized(&mut map, 18.0); - assert!((h - 48.0 * mm).abs() < 1e-6, "{h} mm"); - assert!((w - (48.0 + label) * mm).abs() < 1e-4, "{w} mm"); - let mut pm = Pixmap::new(200, 200).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 2.0 }; - crate::canvas::with_canvas(&mut pm, |c| { - legend(c, Rect::from_xywh(0.0, 0.0, 200.0, 200.0).unwrap(), &map, ("", 1), None, opts, 1.0) - }); - assert!(same_corner(&pm, &drawn_point(&s(40.0), &[], (24.0, 24.0), 1.0), 48, 48), "the symbol as the map draws it"); - // A polygon's swatch is twice as wide, as its column is. - let red = Rgba::rgb(255, 0, 0); - let fill = rustgis_map::Symbol { fill: red, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) }; - let map = shape_legend_map(GeometryType::Polygon, |l| l.renderer = rustgis_map::Renderer::Single(fill)); - let across = |size: f32| { - let mut pm = Pixmap::new(200, 200).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let opts = LegendOptions { size, ..opts }; - crate::canvas::with_canvas(&mut pm, |c| { - legend(c, Rect::from_xywh(0.0, 0.0, 200.0, 200.0).unwrap(), &map, ("", 1), None, opts, 1.0) - }); - (0..pm.width()).filter(|&x| (0..pm.height()).any(|y| pm.pixel(x, y).is_some_and(|p| (p.red(), p.green()) == (255, 0)))).count() - }; - // Its fill inside its outline's edge pixels: 16 points more across, at twice the size. - let (one, two) = (across(1.0), across(2.0)); - assert_eq!(two - one, 16, "{one} and {two} px"); - // A line wider than its row, at a small size, is cut to its row (#2518): nothing above the - // box. - let small = LegendOptions { size: 4.0 / 9.0, ..opts }; - let drawn = |map: &Map, at: (f32, f32), opts: LegendOptions| { - let mut pm = Pixmap::new(200, 200).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - crate::canvas::with_canvas(&mut pm, |c| { - legend(c, Rect::from_xywh(at.0, at.1, 200.0 - at.0, 200.0 - at.1).unwrap(), map, ("", 1), None, opts, 1.0) - }); - pm - }; - // The first row and column `colour` takes. - let ink = |pm: &Pixmap, (r, g, b): (u8, u8, u8)| { - let at = |x: u32, y: u32| pm.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == (r, g, b)); - ((0..pm.height()).find(|&y| (0..pm.width()).any(|x| at(x, y))), (0..pm.width()).find(|&x| (0..pm.height()).any(|y| at(x, y)))) - }; - let wide = rustgis_map::Symbol { stroke: red, stroke_width: 20.0, ..rustgis_map::Symbol::default_for(GeometryType::Polyline, 0) }; - let map = shape_legend_map(GeometryType::Polyline, |l| l.renderer = rustgis_map::Renderer::Single(wide)); - let (top, _) = ink(&drawn(&map, (0.0, 50.0), small), (255, 0, 0)); - assert!(top.is_some_and(|y| y >= 50), "drawn, nothing above the legend's box: {top:?}"); - // A thin one stays within its row and keeps the plain swatch it always had. - let thin = rustgis_map::Symbol { stroke_width: 1.0, ..wide }; - let row = (0.0, 0.0, LEGEND_SWATCH, LEGEND_ROW); - let b = swatch_ink(row, GeometryType::Polyline, (&thin, &[], &[]), (LEGEND_SWATCH, 1.0)).unwrap(); - assert!(b.top() >= 0.0 && b.bottom() <= LEGEND_ROW, "{b:?}"); - // A polygon's wide outline is cut at its row's top and bottom, plain or stacked, and on the - // left at the legend's edge, where nothing lies before its column. - let blue = Rgba::rgb(0, 0, 255); - let outlined = rustgis_map::Symbol { - fill: red, - stroke: blue, - stroke_width: 12.0, - ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) - }; - let solid = rustgis_map::fills::FillLayer { color: Some(red), pattern: rustgis_map::fills::FillPattern::Solid }; - // (The stacked one at the default size: a stack is always composited, and cut, as #2518 set.) - for (fills, opts) in [(vec![], small), (vec![solid], LegendOptions { size: 1.0, ..opts })] { - let stacked = !fills.is_empty(); - let map = shape_legend_map(GeometryType::Polygon, |l| { - l.renderer = rustgis_map::Renderer::Single(outlined); - l.fill_layers = fills; - }); - let (top, left) = ink(&drawn(&map, (50.0, 50.0), opts), (0, 0, 255)); - assert!(top.is_some_and(|y| y >= 50), "stacked {stacked}: nothing above the legend's box: {top:?}"); - assert_eq!(left, Some(50), "stacked {stacked}: drawn to the legend's edge, not past it"); - } - // Left of a column that has room before it (a class's indent, the gap between columns as - // drawn), the outline reaches into that room and no further. - let map = shape_legend_map(GeometryType::Polygon, |l| l.renderer = rustgis_map::Renderer::Single(outlined)); - for lead in [6.0f32, 2.0] { - let mut pm = Pixmap::new(100, 60).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - crate::canvas::with_canvas(&mut pm, |c| { - swatch( - c, - (50.0, 20.0, LEGEND_SWATCH, LEGEND_ROW), - &map.layers[0], - (&outlined, &[], &[]), - 1.0, - 1e6, - (1.0, LEGEND_SWATCH, (lead, 6.0)), - ) - }); - let (_, left) = ink(&pm, (0, 0, 255)); - assert_eq!(left, Some(50 - lead as u32), "room {lead}: its outer half, 6 points, as far as its room"); - } - // The title's room follows; a size past the range, or none at all, is brought into it. - assert!((legend_title_mm(18.0) - 2.0 * legend_title_mm(9.0)).abs() < 1e-12); - assert_eq!(legend_size(1e9), 100.0 / 9.0); - assert_eq!((legend_size(f64::NAN), legend_size(9.0)), (1.0, 1.0)); - } - - /// A layer's reference scale sizes its symbol at the frame's scale. - #[test] - fn a_legend_scales_a_point_with_its_reference_scale() { - let s = rustgis_map::Symbol { size: 10.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; - // Twice as large at 1:1e6: 10 pt reaches 12 pt from its point, in a row of 24. - let map = point_legend_map(|l| { - l.renderer = rustgis_map::Renderer::Single(s); - l.reference_scale = Some(2e6); - }); - assert!(same_corner(&point_legend(&map), &drawn_point(&s, &[], (12.0, 12.0), 2.0), 24, 24)); - } - - /// A diagram's categories on a point layer with stacked marks: each row shows its own colour, - /// not the layer's marks. - #[test] - fn a_diagrams_rows_keep_their_own_mark_on_a_layer_with_stacked_marks() { - let (red, green) = (Rgba::rgb(255, 0, 0), Rgba::rgb(0, 255, 0)); - let category = |field: &str, colour| rustgis_map::DiagramCategory { field: field.into(), colour }; - let map = point_legend_map(|l| { - l.line_strokes = vec![square_mark(Rgba::rgb(0, 0, 0), 12.0)]; - l.diagram = Some(rustgis_map::DiagramSettings { - kind: rustgis_map::DiagramKind::Pie, - categories: vec![category("a", red), category("b", green)], - size: rustgis_map::DiagramSize::Fixed(12.0), - start_angle: 0.0, - background: None, - stroke: rustgis_map::DiagramSettings::default_stroke(), - stroke_width: 0.75, - labels: rustgis_map::DiagramLabel::None, - }); - }); - let pm = point_legend(&map); - let at = |x, y| pm.pixel(x, y).map(|p| (p.red(), p.green(), p.blue())); - // The layer's name, then a row each, the swatch 6 points in. - assert_eq!(at(14, 22), Some((255, 0, 0))); - assert_eq!(at(14, 37), Some((0, 255, 0))); - } - - /// A one-feature line or polygon layer, edited by `edit`. - fn shape_legend_map(gt: GeometryType, edit: impl FnOnce(&mut rustgis_map::Layer)) -> Map { - use rustgis_data::{Dataset, Geometry}; - let mut map = Map::new("m"); - let mut d = Dataset::new("shapes", gt, vec![]); - let (a, b, c) = (Coord::new(0.0, 0.0), Coord::new(1.0, 0.0), Coord::new(1.0, 1.0)); - let g = match gt { - GeometryType::Polyline => Geometry::Line(vec![vec![a, c]]), - _ => Geometry::Polygon(vec![vec![vec![a, b, c, a]]]), - }; - d.push(Some(g), vec![]); - map.add_dataset(d); - if let Some(l) = map.layers.last_mut() { - edit(l); - } - map - } - - /// How many pixels in `xs` × `ys` are within 40 of `c` in every channel. - fn inked(pm: &Pixmap, xs: std::ops::Range, ys: std::ops::Range, c: Rgba) -> usize { - let near = |a: u8, b: u8| a.abs_diff(b) <= 40; - ys.flat_map(|y| xs.clone().map(move |x| (x, y))) - .filter(|(x, y)| pm.pixel(*x, *y).is_some_and(|p| near(p.red(), c.r()) && near(p.green(), c.g()) && near(p.blue(), c.b()))) - .count() - } - - /// A stacked stroke `width` points wide in `color`. - fn plain_stroke(color: Rgba, width: f32) -> rustgis_map::LineStroke { - rustgis_map::LineStroke { color: Some(color), width: Some(width), ..rustgis_map::LineStroke::default() } - } - - /// Hatch lines `spacing` points apart, a point wide, across. - fn hatch(color: Rgba, spacing: f32) -> rustgis_map::fills::FillLayer { - rustgis_map::fills::FillLayer { - color: Some(color), - pattern: rustgis_map::fills::FillPattern::Hatch { angle: 0.0, spacing, width: 1.0, offset: 0.0 }, - } - } - - /// A line or polygon layer with no stacked strokes or fills keeps the swatch it always had, - /// pixel for pixel (#2490): a line through three points, or a box with its outline. - #[test] - fn a_plain_line_or_polygon_keeps_its_swatch() { - let s = rustgis_map::Symbol { - fill: Rgba::rgb(255, 0, 0), - stroke: Rgba::rgb(0, 0, 255), - stroke_width: 2.0, - ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) - }; - for gt in [GeometryType::Polyline, GeometryType::Polygon] { - let map = shape_legend_map(gt, |l| l.renderer = rustgis_map::Renderer::Single(s)); - let mut want = Pixmap::new(200, 200).unwrap(); - want.fill(tiny_skia::Color::WHITE); - let stroke = Stroke { width: 2.0, ..Stroke::default() }; - crate::canvas::with_canvas(&mut want, |c| { - if gt == GeometryType::Polyline { - let mut pb = PathBuilder::new(); - pb.move_to(0.0, 10.5); - pb.line_to(6.4, 4.5); - pb.line_to(16.0, 9.0); - c.stroke_path(&pb.finish().unwrap(), &paint(s.stroke, 1.0), &stroke, Transform::identity(), None); - } else { - let b = Rect::from_xywh(0.0, 3.0, 16.0, 9.0).unwrap(); - c.fill_rect(b, &paint(s.fill, 1.0), Transform::identity(), None); - c.stroke_path(&PathBuilder::from_rect(b), &paint(s.stroke, 1.0), &stroke, Transform::identity(), None); - } - }); - assert!(same_corner(&point_legend(&map), &want, 16, 15), "{gt:?}"); - } - } - - /// A line's stacked strokes show in its swatch as on the map: a casing under its core, and - /// dashes (#2490). - #[test] - fn a_legend_draws_a_lines_casing_and_dashes() { - let (black, red) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0)); - let drawn = - |strokes: Vec| point_legend(&shape_legend_map(GeometryType::Polyline, |l| l.line_strokes = strokes)); - let cased = drawn(vec![plain_stroke(black, 8.0), plain_stroke(red, 2.0)]); - assert!(inked(&cased, 0..16, 0..15, black) > 20, "the casing"); - assert!(inked(&cased, 0..16, 0..15, red) > 5, "the core over it"); - let dashed = rustgis_map::LineStroke { - dash: rustgis_map::symbology::Dash::new(&[2.0, 4.0]), - cap: rustgis_map::LineCap::Butt, - ..plain_stroke(red, 2.0) - }; - let dashed = drawn(vec![plain_stroke(black, 8.0), dashed]); - assert!(inked(&dashed, 0..16, 0..15, red) * 3 < inked(&cased, 0..16, 0..15, red) * 2, "a dashed core shows less of it"); - // One plain stroke draws in its own colour alone. - assert_eq!(inked(&drawn(vec![plain_stroke(red, 2.0)]), 0..16, 0..15, black), 0); - } - - /// Markers along a line show in its swatch (#2490). - #[test] - fn a_legend_draws_markers_along_a_line() { - let blue = Rgba::rgb(0, 0, 255); - let map = shape_legend_map(GeometryType::Polyline, |l| { - l.line_strokes = vec![plain_stroke(Rgba::rgb(128, 128, 128), 1.0), square_mark(blue, 6.0)]; - }); - assert!(inked(&point_legend(&map), 0..16, 0..15, blue) > 10); - } - - /// With symbol levels on, a line's swatch draws its strokes level by level, as the map does. - #[test] - fn a_legend_draws_a_lines_strokes_by_level() { - let (black, red) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0)); - let drawn = |levels: bool| { - let map = shape_legend_map(GeometryType::Polyline, |l| { - l.line_strokes = vec![ - rustgis_map::LineStroke { level: Some(1), ..plain_stroke(red, 2.0) }, - rustgis_map::LineStroke { level: Some(0), ..plain_stroke(black, 8.0) }, - ]; - l.stroke_levels = levels; - }); - inked(&point_legend(&map), 0..16, 0..15, red) - }; - assert!(drawn(true) > 5, "the core's level is above the casing's"); - assert_eq!(drawn(false), 0, "in their order, the casing covers the core"); - } - - /// A stroke shifted past its row is cut at the swatch's box, not drawn over the next row. - #[test] - fn a_legend_cuts_a_shifted_stroke_at_its_box() { - let red = Rgba::rgb(255, 0, 0); - for (offset, shows) in [(4.0, true), (30.0, false)] { - let map = shape_legend_map(GeometryType::Polyline, |l| { - l.line_strokes = vec![rustgis_map::LineStroke { offset, ..plain_stroke(red, 3.0) }]; - }); - let pm = point_legend(&map); - assert_eq!(inked(&pm, 0..16, 0..15, red) > 0, shows, "offset {offset}"); - assert_eq!(inked(&pm, 0..200, 15..200, red), 0, "offset {offset}: nothing below its row"); - } - // One plain stroke wider than the row is cut at it too. - let map = shape_legend_map(GeometryType::Polyline, |l| l.line_strokes = vec![plain_stroke(red, 30.0)]); - let pm = point_legend(&map); - assert!(inked(&pm, 0..16, 0..15, red) > 50); - assert_eq!(inked(&pm, 0..200, 15..200, red), 0, "a wide stroke: nothing below its row"); - // Its round ends reach into the gap before the text, 6 points, and no further (#2581): a - // label beside it keeps its own pixels. The same for a plain polygon's wide outline. - assert!(inked(&pm, 16..22, 0..15, red) > 0, "into the gap"); - assert_eq!(inked(&pm, 22..200, 0..200, red), 0, "nothing where the text starts"); - let outline = rustgis_map::Symbol { stroke: red, stroke_width: 30.0, ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) }; - let map = shape_legend_map(GeometryType::Polygon, |l| l.renderer = rustgis_map::Renderer::Single(outline)); - let pm = point_legend(&map); - assert!(inked(&pm, 16..22, 0..15, red) > 0, "a plain outline into the gap"); - assert_eq!(inked(&pm, 22..200, 0..200, red), 0, "a plain outline: nothing where the text starts"); - } - - /// A polygon's stacked fills show in its swatch: a hatch over a fill, and a class's own fills - /// in its row, the other classes' plain (#2490). - #[test] - fn a_legend_draws_a_polygons_stacked_fills() { - let (black, red, white) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0), Rgba::rgb(255, 255, 255)); - let solid = rustgis_map::fills::FillLayer { color: Some(Rgba::rgb(0, 200, 0)), pattern: rustgis_map::fills::FillPattern::Solid }; - let map = shape_legend_map(GeometryType::Polygon, |l| l.fill_layers = vec![solid, hatch(black, 3.0)]); - let pm = point_legend(&map); - assert!(inked(&pm, 1..15, 4..11, black) > 5, "the hatch"); - assert!(inked(&pm, 1..15, 4..11, Rgba::rgb(0, 200, 0)) > 5, "the fill under it"); - // Classes: only the first has fills of its own, and the layer none. - let s = rustgis_map::Symbol { fill: red, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) }; - let map = shape_legend_map(GeometryType::Polygon, |l| { - l.renderer = rustgis_map::Renderer::Unique { - field: "g".into(), - classes: vec![("a".to_string(), s), ("b".to_string(), s)], - other: s, - ramp: rustgis_map::Ramp::Ember, - class_labels: Default::default(), - other_label: None, - class_strokes: Default::default(), - other_strokes: Vec::new(), - class_fills: [("a".to_string(), vec![hatch(black, 3.0)])].into_iter().collect(), - other_fills: Vec::new(), - expression: None, - }; - }); - let pm = point_legend(&map); - // The layer's name, then a row a class, the swatch 6 points in. - assert!(inked(&pm, 7..21, 19..26, black) > 5, "class a's hatch"); - assert_eq!(inked(&pm, 7..21, 19..26, red), 0, "a hatch with no fill under it leaves the paper"); - assert!(inked(&pm, 7..21, 19..26, white) > 5); - assert_eq!(inked(&pm, 7..21, 34..41, black), 0, "class b has none"); - assert!(inked(&pm, 7..21, 34..41, red) > 50, "its symbol's fill"); - } - - /// A polygon's outline is drawn over its stacked fills, as on the map (#2490). - #[test] - fn a_legend_draws_a_polygons_outline_over_its_fills() { - let (blue, green) = (Rgba::rgb(0, 0, 255), Rgba::rgb(0, 200, 0)); - let s = rustgis_map::Symbol { stroke: blue, stroke_width: 2.0, ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) }; - let solid = rustgis_map::fills::FillLayer { color: Some(green), pattern: rustgis_map::fills::FillPattern::Solid }; - let map = shape_legend_map(GeometryType::Polygon, |l| { - l.renderer = rustgis_map::Renderer::Single(s); - l.fill_layers = vec![solid]; - }); - let pm = point_legend(&map); - // The box's top edge, 3 points down, under the 2-point outline; its inside, the fill. - assert!(inked(&pm, 1..15, 3..4, blue) > 10, "the outline"); - assert_eq!(inked(&pm, 1..15, 3..4, green), 0, "no fill over it"); - assert!(inked(&pm, 2..14, 5..10, green) > 50, "the fill inside"); - } - - /// A diagram's categories keep their own colour on a layer with stacked strokes or fills. - #[test] - fn a_diagrams_rows_keep_their_colour_on_lines_and_polygons() { - let (black, red, green) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0), Rgba::rgb(0, 255, 0)); - let category = |field: &str, colour| rustgis_map::DiagramCategory { field: field.into(), colour }; - for gt in [GeometryType::Polyline, GeometryType::Polygon] { - let map = shape_legend_map(gt, |l| { - l.line_strokes = vec![plain_stroke(black, 8.0)]; - l.fill_layers = vec![hatch(black, 3.0)]; - l.diagram = Some(rustgis_map::DiagramSettings { - kind: rustgis_map::DiagramKind::Pie, - categories: vec![category("a", red), category("b", green)], - size: rustgis_map::DiagramSize::Fixed(12.0), - start_angle: 0.0, - background: None, - stroke: rustgis_map::DiagramSettings::default_stroke(), - stroke_width: 0.75, - labels: rustgis_map::DiagramLabel::None, - }); - }); - let pm = point_legend(&map); - assert_eq!(inked(&pm, 6..22, 15..45, black), 0, "{gt:?}: not the layer's stack"); - // A one-point line is mostly part-covered pixels: its hue tells it. - let tinted = |ys: std::ops::Range, hue: fn(tiny_skia::PremultipliedColorU8) -> bool| { - ys.flat_map(|y| (6..22).map(move |x| (x, y))).filter(|(x, y)| pm.pixel(*x, *y).is_some_and(hue)).count() - }; - assert!(tinted(15..30, |p| p.red() > p.green().saturating_add(60)) > 5, "{gt:?}: red"); - assert!(tinted(30..45, |p| p.green() > p.red().saturating_add(60)) > 5, "{gt:?}: green"); - } - } - - /// A see-through line or polygon layer's swatch is see-through too, as its points' are. - #[test] - fn a_legend_draws_a_see_through_polygon_see_through() { - let s = rustgis_map::Symbol { - fill: Rgba::rgb(255, 0, 0), - stroke_width: 0.0, - ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) - }; - let map = shape_legend_map(GeometryType::Polygon, |l| { - l.renderer = rustgis_map::Renderer::Single(s); - l.transparency = 50.0; - }); - let p = point_legend(&map).pixel(8, 7).unwrap(); - assert_eq!(p.red(), 255); - assert!((100..160).contains(&p.green()), "{}", p.green()); - } - - /// A line grows with its layer's reference scale in the swatch, as on the map. - #[test] - fn a_legend_scales_a_line_with_its_reference_scale() { - let blue = Rgba::rgb(0, 0, 255); - let drawn = |reference: Option| { - let map = shape_legend_map(GeometryType::Polyline, |l| { - l.line_strokes = vec![plain_stroke(blue, 2.0)]; - l.reference_scale = reference; - }); - inked(&point_legend(&map), 0..16, 0..15, blue) - }; - // Drawn at 1:1e6: a reference of 1:2e6 makes it twice as wide. - assert!(drawn(Some(2e6)) * 2 > drawn(None) * 3, "{} against {}", drawn(Some(2e6)), drawn(None)); - } - - /// A vector export draws the stacked fills and strokes a raster one does. - #[test] - fn a_recorded_legend_draws_stacked_fills_and_strokes() { - let (black, red) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0)); - let map = shape_legend_map(GeometryType::Polygon, |l| l.fill_layers = vec![hatch(black, 3.0)]); - assert!(inked(&recorded_legend(&map, 200), 1..15, 4..11, black) > 5); - let map = shape_legend_map(GeometryType::Polyline, |l| l.line_strokes = vec![plain_stroke(black, 8.0), plain_stroke(red, 2.0)]); - let pm = recorded_legend(&map, 200); - assert!(inked(&pm, 0..16, 0..15, black) > 20 && inked(&pm, 0..16, 0..15, red) > 5); - } - - /// A box off the pixel grid: a recording cuts its symbol at the box, not at the whole pixels - /// round it, so the pixel its edge crosses is half covered. - #[test] - fn a_recorded_point_is_cut_at_its_box() { - let s = rustgis_map::Symbol { - fill: Rgba::rgb(0, 0, 255), - size: 3000.0, - stroke_width: 0.0, - marker: rustgis_map::Marker::Square, - ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) - }; - let map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s)); - let mut c = Canvas::recording(2100, 2100).unwrap(); - let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - legend(&mut c, Rect::from_xywh(0.5, 0.5, 2099.0, 2099.0).unwrap(), &map, ("", 1), None, opts, 1.0); - let (_, _, items) = c.into_drawing().unwrap().finish(); - let mut pm = Pixmap::new(2100, 2100).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - crate::vector::replay(&items, &mut pm, Transform::identity()); - // The box runs from 0.5 to 2048.5. - let red = |x, y| pm.pixel(x, y).map_or(0, |p| p.red()); - assert_eq!(red(10, 10), 0); - assert!((60..200).contains(&red(2048, 10)), "{}", red(2048, 10)); - assert!((60..200).contains(&red(10, 2048)), "{}", red(10, 2048)); - } - - /// An upright square's and triangle's corners lie further than 0.6 of their size from their - /// centre, but along each axis, which is what the box holds, they stay inside it. - #[test] - fn an_upright_mark_stays_in_its_row() { - let s = rustgis_map::Symbol { size: 10.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; - for marker in [rustgis_map::Marker::Square, rustgis_map::Marker::Triangle] { - let mut mark = square_mark(Rgba::rgb(0, 0, 255), 40.0); - if let Some(m) = &mut mark.markers { - m.mark = rustgis_map::LineMark::Marker(marker); - } - let map = point_legend_map(|l| { - l.renderer = rustgis_map::Renderer::Single(s); - l.line_strokes = vec![mark]; - }); - let pm = point_legend(&map); - let white = |x, y| pm.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == (255, 255, 255)); - // A box of 48 points: its edges are clear, and the mark is in it. - assert!((0..48).all(|i| white(i, 0) && white(i, 47) && white(0, i) && white(47, i)), "{marker:?}"); - assert!(!white(24, 24), "{marker:?}"); - } - } - - /// A class's row draws the marks the map gives its features, else its layer's. - #[test] - fn a_legend_draws_a_class_with_its_own_marks() { - let s = rustgis_map::Symbol::default_for(GeometryType::Point, 0); - let (own, others, layers) = ( - vec![square_mark(Rgba::rgb(255, 0, 0), 12.0)], - vec![square_mark(Rgba::rgb(0, 255, 0), 12.0)], - vec![square_mark(Rgba::rgb(0, 0, 255), 12.0)], - ); - let map = point_legend_map(|l| { - l.line_strokes = layers.clone(); - l.renderer = rustgis_map::Renderer::Unique { - field: "g".into(), - classes: vec![("a".to_string(), s), ("b".to_string(), s)], - other: s, - ramp: rustgis_map::Ramp::Ember, - class_labels: Default::default(), - other_label: None, - class_strokes: [("a".to_string(), own.clone())].into_iter().collect(), - other_strokes: others.clone(), - class_fills: Default::default(), - other_fills: Vec::new(), - expression: None, - }; - }); - let got = point_legend(&map); - // Under the layer's name, each row 15 points tall, its swatch 6 in: class a has its own, - // class b takes the layer's, and the fallback has its own. - for (row, strokes) in [(1u32, &own), (2, &layers), (3, &others)] { - let top = row * 15; - let want = drawn_point(&s, strokes, (14.0, top as f32 + 7.5), 1.0); - assert!((top..top + 15).all(|y| (6..22).all(|x| got.pixel(x, y) == want.pixel(x, y))), "row {row}"); - } - } - - /// A large point widens the column: a line or a box stays a swatch wide, and the names line up. - #[test] - fn a_wide_column_keeps_lines_and_boxes_a_swatch_wide_in_its_middle() { - use rustgis_data::Dataset; - let blue = Rgba::rgb(0, 0, 255); - let point = - rustgis_map::Symbol { fill: blue, size: 40.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; - for gt in [GeometryType::Polyline, GeometryType::Polygon] { - // A point of 40 pt makes the column 48 wide: a swatch of 16 in its middle runs from 16 to 32. - let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(point)); - let id = map.add_dataset(Dataset::new("line", gt, vec![])); - let red = Rgba::rgb(255, 0, 0); - if let Some(l) = map.layer_mut(id) { - l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { - fill: red, - stroke: red, - stroke_width: 2.0, - ..rustgis_map::Symbol::default_for(gt, 0) - }); - } - let pm = point_legend(&map); - let columns = |ink: &dyn Fn(u8, u8, u8) -> bool| -> Vec { - (0..pm.width()) - .filter(|&x| { - (0..pm.height()).any(|y| pm.pixel(x, y).is_some_and(|p| p.alpha() > 0 && ink(p.red(), p.green(), p.blue()))) - }) - .collect() - }; - let swatch = columns(&|r, g, b| r > 200 && g < 60 && b < 60); - let (left, right) = (swatch.first().copied().unwrap_or(0), swatch.last().copied().unwrap_or(0)); - assert!((14..=17).contains(&left) && (31..=34).contains(&right), "{gt:?}: {left} to {right}"); - // Both names start past the column, where the blue point has no part in it. - let names = columns(&|r, g, b| r < 100 && g < 100 && b < 100); - assert!(names.first().is_some_and(|x| (53..60).contains(x)), "{gt:?}: {names:?}"); - } - } - - /// A symbol past the limit fills its box and stays in it, on pixels and in a recording. - #[test] - fn an_oversized_point_stays_in_its_row() { - let blue = Rgba::rgb(0, 0, 255); - let s = rustgis_map::Symbol { - fill: blue, - size: 3000.0, - stroke_width: 0.0, - marker: rustgis_map::Marker::Square, - ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) - }; - // Opaque and see-through: a row and a column of 2048 pt, which the square fills. - for transparency in [0.0, 50.0] { - let map = point_legend_map(|l| { - l.renderer = rustgis_map::Renderer::Single(s); - l.transparency = transparency; - }); - let mut pm = Pixmap::new(2100, 2100).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - crate::canvas::with_canvas(&mut pm, |c| { - legend(c, Rect::from_xywh(0.0, 0.0, 2100.0, 2100.0).unwrap(), &map, ("", 1), None, opts, 1.0) - }); - // Drawn, and recorded for a vector export, where only its clip cuts it. - for pm in [pm, recorded_legend(&map, 2100)] { - let white = |x, y| pm.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == (255, 255, 255)); - assert!(!white(10, 10) && !white(2040, 2040), "transparency {transparency}: it fills the box"); - assert!(white(10, 2060) && white(2060, 10), "transparency {transparency}: it stays in the box"); - } - } - } - - /// A legend starting off the canvas: a symbol larger than the canvas still covers all of it. - #[test] - fn a_see_through_point_larger_than_the_canvas_covers_it_from_off_its_edge() { - let s = rustgis_map::Symbol { - fill: Rgba::rgb(0, 0, 255), - size: 3000.0, - stroke_width: 0.0, - marker: rustgis_map::Marker::Square, - ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) - }; - let map = point_legend_map(|l| { - l.renderer = rustgis_map::Renderer::Single(s); - l.transparency = 50.0; - }); - let mut pm = Pixmap::new(300, 300).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; - crate::canvas::with_canvas(&mut pm, |c| { - legend(c, Rect::from_xywh(-50.0, -50.0, 2100.0, 2100.0).unwrap(), &map, ("", 1), None, opts, 1.0) - }); - // Its box runs from -50 to 1998: every corner of the canvas is in it. - for (x, y) in [(5, 5), (295, 5), (5, 295), (295, 295)] { - let white = pm.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == (255, 255, 255)); - assert!(!white, "({x}, {y})"); - } - } - - /// A class's large symbol counts in a legend's size as a plain row's does. - #[test] - fn a_class_row_takes_the_wide_column_in_a_legends_size() { - let mm = 25.4 / 96.0; - let s = rustgis_map::Symbol { size: 40.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; - let mut map = point_legend_map(|l| { - l.renderer = rustgis_map::Renderer::Unique { - field: "g".into(), - classes: vec![("a".to_string(), s)], - other: s, - ramp: rustgis_map::Ramp::Ember, - class_labels: Default::default(), - other_label: None, - class_strokes: Default::default(), - other_strokes: Vec::new(), - class_fills: Default::default(), - other_fills: Vec::new(), - expression: None, - }; - }); - // The layer's name over the class: a row of 15 and one of 48, 6 + 48 + 6 before its label. - let [(w, h), ..] = legend_sizes_mm(&mut map, 1e6, true, true, (&[], &NO_LABELS)).unwrap(); - assert!((h - f64::from(LEGEND_ROW + 48.0) * mm).abs() < 1e-6, "{h} mm"); - assert!((w - f64::from(48.0 + 12.0 + text::measure("a", 8.5, false)) * mm).abs() < 1e-4, "{w} mm"); - } - - /// An element's background (#2257) is drawn under it on the page, grown by its padding and - /// turned with a turned text; drawn alone, as an SVG's picture of it, the element leaves it to - /// the SVG's own shape. - #[test] - fn a_background_is_drawn_under_its_element_and_turns_with_it() { - use rustgis_map::layout::Background; - let px = |mm: f64| (mm * 96.0 / 25.4).round() as u32; - let red = |pm: &Pixmap, x: f64, y: f64| rgb(pm, px(x), px(y)) == (255, 0, 0); - let page = |turn: f64, background: Option| { - let mut l = Layout::new("L", 100.0, 100.0); - let mut kind = ElementKind::text("", 12.0, Rgba::rgb(0, 0, 0), false); - if let ElementKind::Text { rotation, .. } = &mut kind { - *rotation = turn; - } - let id = l.add("T", (40.0, 40.0, 20.0, 10.0), kind); - l.element_mut(id).unwrap().background = background; - (l, id) - }; - let back = Background { padding: 5.0, ..Background::filled(Rgba::rgb(255, 0, 0)) }; - let (plain, _) = page(0.0, None); - assert!(!red(&render(&plain, &mut [], 96.0, &PageInfo::default()).unwrap(), 45.0, 45.0), "none by default"); - let (l, id) = page(0.0, Some(back)); - let pm = render(&l, &mut [], 96.0, &PageInfo::default()).unwrap(); - assert!(red(&pm, 45.0, 45.0), "inside the box"); - assert!(red(&pm, 37.0, 37.0), "in the padding"); - assert!(!red(&pm, 33.0, 45.0), "past the padding"); - // Turned 90°, the box (and so its background) stands upright about its centre (50, 45). - let (turned, _) = page(90.0, Some(Background::filled(Rgba::rgb(255, 0, 0)))); - let pm = render(&turned, &mut [], 96.0, &PageInfo::default()).unwrap(); - assert!(red(&pm, 50.0, 37.0), "above the unturned box, inside the turned one"); - assert!(!red(&pm, 42.0, 45.0), "left of the turned box"); - // Clockwise, as the text turns: at 30° the box's right end dips below its centre line, at - // -30° it rises (90° alone would look the same either way). - let at = |turn: f64| { - red( - &render(&page(turn, Some(Background::filled(Rgba::rgb(255, 0, 0)))).0, &mut [], 96.0, &PageInfo::default()).unwrap(), - 59.0, - 46.0, - ) - }; - assert!(at(30.0) && !at(-30.0), "turned clockwise"); - // Alone, the element's picture holds no background. - let (alone, _) = render_element(&l, id, &mut [], 96.0, (&PageInfo::default(), &Env::default()), &mut None).unwrap().unwrap(); - assert!(alone.pixels().iter().all(|c| c.alpha() == 0 || c.green() > 0), "no red in the element's own picture"); - } -} +mod tests; diff --git a/crates/render/src/layout/chart.rs b/crates/render/src/layout/chart.rs new file mode 100644 index 0000000000..ceb6d25b2a --- /dev/null +++ b/crates/render/src/layout/chart.rs @@ -0,0 +1,395 @@ +//! The chart element: bars, values and key. + +use super::*; + +/// A bar chart of `data`'s bars ([`ElementKind::chart_data`]) drawn as `look` says, its title, +/// labels and values in `dark`, its values with a decimal comma when `comma`. With a negative +/// value, bars run either way from a zero line (#2487). Stacked, each bar is drawn as its +/// stretches in the colours of the key under the title, those above zero from it on and those +/// below from it back, its value past the end of the side it ends on. +pub(super) fn chart(pm: &mut Canvas, r: Rect, data: &rustgis_map::layout::ChartData, look: &ChartLook, dark: Rgba, ppp: f64, comma: bool) { + let ppp = ppp as f32; + let vals = &data.bars; + let (min, reach) = chart_span(data); + // A fixed maximum is the far end of the bars' room, whatever they reach (#2487 part 4). + let max = look.max.unwrap_or(reach); + if vals.is_empty() || (reach <= 0.0 && min >= 0.0) { + placeholder(pm, r, "Chart", ppp as f64); + return; + } + let px = 7.5 * 1.33 * ppp; + let Some((title_h, key_h)) = chart_head(r, data, look, px, ppp) else { + placeholder(pm, r, "Chart", ppp as f64); + return; + }; + if !data.title.is_empty() { + text::text_at(pm, &data.title, r.x(), r.y() + title_h / 2.0, px * 1.15, dark, true, text::Align::Left, false); + } + chart_key(Some(pm), r, r.y() + title_h, &data.key, px, ppp, dark); + // Each bar's value as written past its end, when it has them. + let values: Vec = if look.values { + vals.iter().map(|(v, _)| decimal(rustgis_map::layout::chart_value_text(*v, look.decimals), comma)).collect() + } else { + Vec::new() + }; + let bars = ChartBars { + r, + title_h: title_h + key_h, + vals, + values: &values, + colors: &data.colors, + stretches: &data.stretches, + key: &data.key, + min, + max, + px, + ppp, + dark, + look, + }; + let labelled = data.labelled && !look.hide_labels; + match look.orientation { + Orientation::Horizontal => bars.across(pm, labelled), + Orientation::Vertical => bars.columns(pm, labelled), + } +} + +/// The span a chart's bars run over: from the most a bar reaches below zero to the most above, +/// stacked its stretches below zero added up and those above. +pub fn chart_span(data: &rustgis_map::layout::ChartData) -> (f64, f64) { + data.bars + .iter() + .enumerate() + .map(|(i, (v, _))| data.stretches.get(i).filter(|s| !s.is_empty()).map_or_else(|| reach(&[*v]), |s| reach(s))) + .fold((0.0_f64, 0.0_f64), |(lo, hi), (l, h)| (lo.min(l), hi.max(h))) +} + +/// The heights of a chart's title and key over its bars in `r`, its text `px` high: no title +/// leaves its room to the bars. Stacked, a box too short to leave the bars a line under its title +/// and key has none (it draws its placeholder rather than a key past its bottom and bars with no +/// room); as columns, the bars' line is past the room their labels and values may take (written +/// at most `px` high, [`ChartBars::columns`]), so they always have it. Not stacked, it draws as +/// before. +pub(super) fn chart_head(r: Rect, data: &rustgis_map::layout::ChartData, look: &ChartLook, px: f32, ppp: f32) -> Option<(f32, f32)> { + let title_h = if data.title.is_empty() { 0.0 } else { px * 1.6 }; + let key_h = chart_key(None, r, 0.0, &data.key, px, ppp, INK); + let line = px * 1.4; + let below = match look.orientation { + Orientation::Horizontal => 0.0, + Orientation::Vertical => { + let (min, max) = chart_span(data); + let values = |on: bool| if look.values && on { line } else { 0.0 }; + (if data.labelled && !look.hide_labels { line } else { 0.0 }) + values(max > 0.0) + values(min < 0.0) + } + }; + (data.key.is_empty() || title_h + key_h + line + below <= r.height()).then_some((title_h, key_h)) +} + +/// Whether a chart with bars to draw, `w` × `h` mm in its look, draws its placeholder instead as +/// its title and key leave the bars no room ([`chart_head`]): what the commands warn of, so the page and the commands +/// never tell it apart. +pub fn chart_crowded(data: &rustgis_map::layout::ChartData, look: &ChartLook, w: f64, h: f64) -> bool { + let Some(r) = Rect::from_xywh(0.0, 0.0, (w * PT_PER_MM).max(1.0) as f32, (h * PT_PER_MM).max(1.0) as f32) else { return false }; + !data.bars.is_empty() && chart_head(r, data, look, 7.5 * 1.33, 1.0).is_none() +} + +/// How far a bar's stretches reach below zero (its negative ones added up) and above it. +pub(super) fn reach(stretches: &[f64]) -> (f64, f64) { + stretches.iter().fold((0.0, 0.0), |(lo, hi), v| if *v < 0.0 { (lo + v, hi) } else { (lo, hi + v) }) +} + +/// A stacked chart's key from `top`: a swatch in each value's colour and its name, in rows as +/// wide as the box, a name cut to fit one; the height it takes, 0 without a key, infinite in a +/// box narrower than a swatch. Without a canvas it only measures. +pub(super) fn chart_key(mut pm: Option<&mut Canvas>, r: Rect, top: f32, key: &[(String, Rgba)], px: f32, ppp: f32, dark: Rgba) -> f32 { + if key.is_empty() { + return 0.0; + } + let size = px * 0.9; + let line_h = px * 1.4; + let (sw, gap) = (size * 0.8, 2.0 * ppp); + // A box narrower than a swatch has no room for the key at all. + if r.width() < sw + gap { + return f32::INFINITY; + } + let (mut x, mut y) = (r.x(), top); + for (name, colour) in key { + let t = fit_label(name, |t| sw + gap + text::measure(t, size / 1.33, false) > r.width()); + let w = sw + gap + text::measure(&t, size / 1.33, false); + // A name that doesn't fit after the others starts a row of its own. + if x > r.x() && x + w > r.right() { + (x, y) = (r.x(), y + line_h); + } + if let Some(pm) = pm.as_deref_mut() { + fill(pm, *colour, x, y + (line_h - sw) / 2.0, sw, sw); + text::text_at(pm, &t, x + sw + gap, y + line_h / 2.0, size, dark, false, text::Align::Left, false); + } + x += w + 3.0 * gap; + } + y + line_h - top +} + +/// `name`'s first 30 characters, cut from their end while `too_wide` says they don't fit. +pub(super) fn fit_label(name: &str, too_wide: impl Fn(&str) -> bool) -> String { + let mut t: String = name.chars().take(30).collect(); + while !t.is_empty() && too_wide(&t) { + t.pop(); + } + t +} + +/// What [`chart`] draws its bars from: its box, the height of its title (and key) over the bars, +/// the bars and their values written out (none without), each bar's own colour (none: the look's +/// bar colour), stacked each bar's stretches and the key that colours them, the least a bar +/// reaches and the value at the far end of the bars' room (the greatest a bar reaches, or a fixed +/// maximum in its place; 0 among them), its text size and pixels per point. +pub(super) struct ChartBars<'a> { + pub(super) r: Rect, + pub(super) title_h: f32, + pub(super) vals: &'a [(f64, String)], + pub(super) values: &'a [String], + pub(super) colors: &'a [Option], + pub(super) stretches: &'a [Vec], + pub(super) key: &'a [(String, Rgba)], + pub(super) min: f64, + pub(super) max: f64, + pub(super) px: f32, + pub(super) ppp: f32, + pub(super) dark: Rgba, + pub(super) look: &'a ChartLook, +} + +impl ChartBars<'_> { + /// Bar `i` (of value `v`) as the stretches it is drawn in, each with the share of the span + /// ([`ChartBars::share`]) where it starts from zero, its own share (negative running back) and + /// its colour. A whole bar (none stacked, or no stretches) is one stretch, in its own colour or + /// the look's; a stacked one a stretch per value of the key, those above zero on from it and + /// those below back from it, one of 0 not drawn. + pub(super) fn stretches(&self, i: usize, v: f64) -> Vec<(f32, f32, Rgba)> { + let Some(s) = self.stretches.get(i).filter(|s| !s.is_empty()) else { + return vec![(0.0, self.share(v.min(self.max)), self.colors.get(i).copied().flatten().unwrap_or(self.look.bar_color))]; + }; + let (mut lo, mut hi) = (0.0_f64, 0.0_f64); + // Past a fixed maximum a stretch above zero is cut at it, and one wholly past it isn't + // drawn; one running back from zero is drawn whole. + s.iter() + .zip(self.key) + .filter(|(v, _)| **v != 0.0) + .filter_map(|(v, (_, c))| { + let end = if *v < 0.0 { &mut lo } else { &mut hi }; + let from = *end; + *end += v; + if *v < 0.0 { + return Some((self.share(from), self.share(*v), *c)); + } + let len = (from + v).min(self.max) - from; + (len > 0.0).then(|| (self.share(from), self.share(len), *c)) + }) + .collect() + } + + /// What part `v` is of the span from the lowest value (or zero) to the highest (or zero). A span + /// past a number's range (the largest number and its opposite) is taken by halves. + pub(super) fn share(&self, v: f64) -> f32 { + let span = self.max - self.min; + (if span.is_finite() { v / span } else { (v / 2.0) / (self.max / 2.0 - self.min / 2.0) }) as f32 + } + + /// The widest of the values written at `size` pixels past the bars running one way: + /// positive ones, or negative ones (`negative`); 0 without values. + pub(super) fn widest(&self, size: f32, negative: bool) -> f32 { + self.vals + .iter() + .zip(self.values) + .filter(|((v, _), _)| (*v < 0.0) == negative) + .map(|(_, t)| text::measure(t, size / 1.33, false)) + .fold(0.0, f32::max) + } + + /// Bars running across, labels in a column at their left, each value past its bar's end with + /// room kept for it at the side its bar runs to. + pub(super) fn across(&self, pm: &mut Canvas, labelled: bool) { + let (r, ppp, px) = (self.r, self.ppp, self.px); + let label_w = if labelled { r.width() * 0.32 } else { 0.0 }; + let bh = ((r.height() - self.title_h) / self.vals.len() as f32).min(18.0 * ppp); + let size = px.min(bh * 0.9); + let gap = 2.0 * ppp; + let room = |negative: bool, size: f32| { + let w = self.widest(size, negative); + if w > 0.0 { w + gap } else { 0.0 } + }; + // Values take at most half the width beside the labels, written smaller past that. + let beside = r.width() - label_w - 4.0; + let mut value_size = size; + let (mut room_lo, mut room_hi) = (room(true, size), room(false, size)); + if room_lo + room_hi > beside * 0.5 { + // Only the text grows smaller: the gaps beside it stay as they are. + let gaps = [room_lo, room_hi].iter().filter(|w| **w > 0.0).count() as f32 * gap; + let text = room_lo + room_hi - gaps; + value_size = (size * (beside * 0.5 - gaps) / text).max(0.0); + (room_lo, room_hi) = (room(true, value_size), room(false, value_size)); + } + let bar_area = beside - room_lo - room_hi; + // Where the bars start: the left of the bar area when none is negative. + let zero = r.x() + label_w + room_lo + bar_area * self.share(-self.min); + let right = self.look.label_align == TextAlign::Right; + // Laid out the usual way, then placed as its mirror image when mirrored: a box from `x`, + // `w` wide, and a text written from `x`, the text itself reading as ever. + let edges = r.x() + r.right(); + let place = |x: f32, w: f32| if self.look.mirror { edges - x - w } else { x }; + let write = |x: f32, align: text::Align| if self.look.mirror { (edges - x, mirrored(align)) } else { (x, align) }; + for (i, (v, name)) in self.vals.iter().enumerate() { + let y = r.y() + self.title_h + bh * i as f32; + // Each stretch at least a pixel wide, running back from its start below zero; where the + // bar ends at its left and at its right. + let (mut left, mut right_end) = (zero, zero); + let mut drawn = Vec::new(); + for (start, share, colour) in self.stretches(i, *v) { + let w = (bar_area * share.abs()).max(1.0); + let x = zero + bar_area * start - if share < 0.0 { w } else { 0.0 }; + drawn.push((place(x, w), w, colour)); + (left, right_end) = (left.min(x), right_end.max(x + w)); + } + self.bar(pm, &drawn, (y + bh * 0.15, bh * 0.7), true); + if labelled { + let t = fit_label(name, |t| text::measure(t, 7.5, false) * ppp > label_w - 4.0 * ppp); + // At the column's right, the label ends where the bars' side begins. + let (lx, align) = if right { (r.x() + label_w - 2.0 * ppp, text::Align::Right) } else { (r.x(), text::Align::Left) }; + let (lx, align) = write(lx, align); + text::text_at(pm, &t, lx, y + bh / 2.0, size, self.dark, false, align, false); + } + if let Some(t) = self.values.get(i) { + let (vx, align) = if *v < 0.0 { (left - gap, text::Align::Right) } else { (right_end + gap, text::Align::Left) }; + let (vx, align) = write(vx, align); + text::text_at(pm, t, vx, y + bh / 2.0, value_size, self.dark, false, align, false); + } + } + if self.min < 0.0 + && let Some(line) = + Rect::from_xywh(place(zero - 0.375 * ppp, 0.75 * ppp), r.y() + self.title_h, 0.75 * ppp, bh * self.vals.len() as f32) + { + pm.fill_rect(line, &paint(self.dark, 1.0), Transform::identity(), None); + } + } + + /// Columns standing on a zero line, each label centred under its column and cut to its width, + /// each value over a column (under one going down), made smaller to fit a narrow column. + pub(super) fn columns(&self, pm: &mut Canvas, labelled: bool) { + let (r, ppp, px) = (self.r, self.ppp, self.px); + let slot = r.width() / self.vals.len() as f32; + let widest = self.widest(px, false).max(self.widest(px, true)); + let value_px = if widest > slot * 0.95 { px * slot * 0.95 / widest } else { px }; + let value_h = value_px * 1.4; + let room_hi = if self.max > 0.0 && !self.values.is_empty() { value_h } else { 0.0 }; + let room_lo = if self.min < 0.0 && !self.values.is_empty() { value_h } else { 0.0 }; + let label_h = if labelled { px * 1.4 } else { 0.0 }; + let top = r.y() + self.title_h + room_hi; + let plot_h = r.bottom() - label_h - room_lo - top; + if plot_h <= 0.0 { + placeholder(pm, r, "Chart", ppp as f64); + return; + } + // Where the columns stand: the bottom of the plot when none is negative. + let zero = top + plot_h * self.share(self.max); + // Laid out the usual way under its title, then placed upside down there when mirrored: a box + // from `y`, `h` high, and a text centred on `y`, the text itself reading as ever. + let edges = r.y() + self.title_h + r.bottom(); + let place = |y: f32, h: f32| if self.look.mirror { edges - y - h } else { y }; + let write = |y: f32| if self.look.mirror { edges - y } else { y }; + for (i, (v, name)) in self.vals.iter().enumerate() { + let cx = r.x() + slot * (i as f32 + 0.5); + // Each stretch at least a pixel high, standing up from its start above zero and hanging + // down below it; where the column ends at its top and at its bottom. + let (mut top_end, mut bottom) = (zero, zero); + let mut drawn = Vec::new(); + for (start, share, colour) in self.stretches(i, *v) { + let h = (plot_h * share.abs()).max(1.0); + let y = zero - plot_h * start - if share < 0.0 { 0.0 } else { h }; + drawn.push((place(y, h), h, colour)); + (top_end, bottom) = (top_end.min(y), bottom.max(y + h)); + } + self.bar(pm, &drawn, (cx - slot * 0.35, slot * 0.7), false); + if let Some(t) = self.values.get(i) { + let vy = if *v < 0.0 { bottom + value_h / 2.0 } else { top_end - value_h / 2.0 }; + text::text_at(pm, t, cx, write(vy), value_px, self.dark, false, text::Align::Center, false); + } + if labelled { + let t = fit_label(name, |t| text::measure(t, px / 1.33, false) > slot - 2.0 * ppp); + text::text_at(pm, &t, cx, write(r.bottom() - label_h / 2.0), px, self.dark, false, text::Align::Center, false); + } + } + if self.min < 0.0 + && let Some(line) = Rect::from_xywh(r.x(), place(zero - 0.375 * ppp, 0.75 * ppp), r.width(), 0.75 * ppp) + { + pm.fill_rect(line, &paint(self.dark, 1.0), Transform::identity(), None); + } + } +} + +/// A text's alignment in a chart's mirror image: from the right where it was from the left. +pub(super) fn mirrored(align: text::Align) -> text::Align { + match align { + text::Align::Left => text::Align::Right, + text::Align::Right => text::Align::Left, + other => other, + } +} + +impl ChartBars<'_> { + /// A bar, filled stretch by stretch, with the look's outline round it (#2487 part 4b). Each + /// stretch is its start and length along the bar and its colour; `cross` is where the bar + /// starts across its run and how thick it is, and `across` says it runs across (else down). + /// The line runs just inside the bar's edge, so it takes no room the bars leave to their + /// values, labels and title, and is laid once between two stretches, centred where they meet, + /// so a see-through one reads the same everywhere. So that every stretch keeps its colour, the + /// edge's line narrows to a third of the bar's thickness, across each end to a third of the + /// stretch there too, and each line between two stretches to a third of either, kept within + /// the edge's line. + pub(super) fn bar(&self, pm: &mut Canvas, stretches: &[(f32, f32, Rgba)], cross: (f32, f32), across: bool) { + // A box from where it starts and how long it is along the run, and across it. + let rect = |along: f32, run: f32, across_at: f32, thick: f32| { + if across { (along, across_at, run, thick) } else { (across_at, along, thick, run) } + }; + for (at, len, colour) in stretches { + let (x, y, w, h) = rect(*at, *len, cross.0, cross.1); + fill(pm, *colour, x, y, w, h); + } + let Some(o) = self.look.bar_outline else { return }; + let mut order: Vec<_> = stretches.iter().map(|(at, len, _)| (*at, *len)).collect(); + order.sort_by(|a, b| a.0.total_cmp(&b.0)); + let (Some(first), Some(last)) = (order.first(), order.last()) else { return }; + let (lo, hi) = (first.0, last.0 + last.1); + let line = (o.width as f32 * self.ppp).min(cross.1 / 3.0); + if line <= 0.0 { + return; + } + // Across the ends, narrowed only there by the stretch it would cover. + let (start, end) = (line.min(first.1 / 3.0), line.min(last.1 / 3.0)); + // The whole line, round the bar and between its stretches, is one shape filled once: boxes + // filled each on its own would cover a pixel they share in part twice over, leaving a + // lighter seam where they meet and a darker spot where they overlap. Boxes, not a stroke: + // a stroke thinner than a pixel is drawn a pixel wide, past the bar's end. + let mut shape = PathBuilder::new(); + let mut boxed = |(x, y, w, h): (f32, f32, f32, f32)| { + if let Some(b) = Rect::from_xywh(x, y, w, h) { + shape.push_rect(b); + } + }; + boxed(rect(lo, hi - lo, cross.0, line)); + boxed(rect(lo, hi - lo, cross.0 + cross.1 - line, line)); + boxed(rect(lo, start, cross.0 + line, cross.1 - 2.0 * line)); + boxed(rect(hi - end, end, cross.0 + line, cross.1 - 2.0 * line)); + // Between two stretches, inside the edge's line, and kept there along the bar too: a + // stretch drawn a pixel long though its share is shorter has the next start inside it, + // near the bar's end. + for pair in order.windows(2) { + let &[(_, a), (at, b)] = pair else { continue }; + let d = line.min(a / 3.0).min(b / 3.0); + let (from, to) = ((at - d / 2.0).max(lo + start), (at + d / 2.0).min(hi - end)); + boxed(rect(from, to - from, cross.0 + line, cross.1 - 2.0 * line)); + } + if let Some(shape) = shape.finish() { + pm.fill_path(&shape, &paint(o.color, 1.0), FillRule::Winding, Transform::identity(), None); + } + } +} diff --git a/crates/render/src/layout/colorbar.rs b/crates/render/src/layout/colorbar.rs new file mode 100644 index 0000000000..4ed80107a1 --- /dev/null +++ b/crates/render/src/layout/colorbar.rs @@ -0,0 +1,275 @@ +//! The colorbar and its title. + +use super::*; + +/// How a colorbar is laid out. +pub(super) struct Bar<'a> { + pub(super) title: &'a str, + pub(super) orientation: Orientation, + pub(super) ticks: usize, + pub(super) side: TickSide, + pub(super) reverse: bool, + /// Labels with a decimal comma ([`Layout::decimal_comma`]). + pub(super) comma: bool, + /// Its title, outline, ticks and labels (#2257). + pub(super) ink: Rgba, +} + +/// `n` values from `lo` to `hi`, the ends included, with the fewest decimals that keep each within +/// a twentieth of the step of its value. +pub(super) fn tick_labels(lo: f64, hi: f64, n: usize) -> Vec<(f64, String)> { + if !(lo.is_finite() && hi.is_finite()) { + return Vec::new(); + } + let n = if hi > lo { n.clamp(2, rustgis_map::layout::MAX_COLORBAR_TICKS) } else { 1 }; + let step = if n > 1 { (hi - lo) / (n - 1) as f64 } else { 0.0 }; + let values: Vec = (0..n).map(|i| if i + 1 == n { hi } else { lo + step * i as f64 }).collect(); + if values.iter().any(|v| v.abs() >= 1e6) { + return values.into_iter().map(|v| (v, rustgis_map::symbology::fmt_num(v))).collect(); + } + let tol = if step > 0.0 { step * 0.05 } else { (lo.abs() * 1e-3).max(1e-9) }; + let decimals = (0..=6) + .find(|d| { + let k = 10f64.powi(*d); + values.iter().all(|v| ((v * k).round() / k - v).abs() <= tol) + }) + .unwrap_or(6) as usize; + // Rounded first, then + 0.0, so a value rounded to zero isn't printed "-0". + let k = 10f64.powi(decimals as i32); + values.into_iter().map(|v| (v, format!("{:.*}", decimals, (v * k).round() / k + 0.0))).collect() +} + +/// A colorbar laid out in its element ([`colorbar_plan`]): what [`colorbar`] draws, and what the +/// page's cut-off check ([`text_losses`]) says of it, from one layout. +pub(super) struct ColorbarPlan { + /// The title's lines drawn, each with the middle of its line (pixels). + pub(super) title: Vec<(String, f32)>, + /// The bar's blocks or samples, low to high, and its rectangle (x, y, width, height). + pub(super) blocks: Vec, + pub(super) rect: (f32, f32, f32, f32), + /// The bar runs down the page, and from high to low along it (its start is left or top). + pub(super) vertical: bool, + pub(super) flip: bool, + /// The labels drawn: each one's text, its tick's two ends, where it is drawn, and whether + /// centred on it (else from its left). + pub(super) labels: Vec<(String, [(f32, f32); 2], (f32, f32), bool)>, + /// Labels left out because they would spill out of the element (#2638), not those thinned + /// for clearing the one before: a short or narrow element, or one with no room for a bar. + pub(super) spilled: usize, +} + +/// A colorbar in `r` at `ppp` (#2638): its title's lines that fit over the bar's own room +/// ([`colorbar_title_drawn`]), the bar, leaving room for the labels on their side and for the end +/// labels to stand past its ends, and each label drawn only if it clears the one before and stays +/// inside the element. +pub(super) fn colorbar_plan(r: Rect, scale: &ColorScale, bar: &Bar, ppp: f32) -> ColorbarPlan { + let px = 8.0 * 1.33 * ppp; + let width = |s: &str| text::measure(s, px / 1.33, false); + let (mut top, bottom) = (r.y(), r.y() + r.height()); + let mut title = Vec::new(); + if !bar.title.is_empty() { + let tpx = COLORBAR_TITLE_PT as f32 * 1.33 * ppp; + // Wrapped to the element's width (#2493). + let lines = colorbar_title_lines(bar.title, f64::from(r.width()) / (f64::from(ppp) * PT_PER_MM)); + let drawn = colorbar_title_drawn(lines.len(), top, bottom - colorbar_bar_room(ppp, bar.orientation), tpx); + title = lines.into_iter().take(drawn).enumerate().map(|(i, line)| (line, top + tpx * (0.6 + 1.25 * i as f32))).collect(); + // A title held back whole takes no room: the bar starts at the element's top. + if drawn > 0 { + top += tpx * (1.4 + 1.25 * (drawn - 1) as f32); + } + } + // Where each block or sample sits along the bar (0 low to 1 high), and the labels with theirs. + let (blocks, labels): (Vec, Vec<(f32, String)>) = match scale { + ColorScale::Ramp { lo, hi, colors } => { + let span = hi - lo; + let labels = tick_labels(*lo, *hi, bar.ticks) + .into_iter() + .map(|(v, s)| ((if span > 0.0 { (v - lo) / span } else { 0.5 }) as f32, s)) + .collect(); + (colors.clone(), labels) + } + ColorScale::Steps { edges, colors } => { + let n = colors.len().max(1) as f32; + let labels = edges.iter().enumerate().map(|(i, v)| (i as f32 / n, rustgis_map::symbology::fmt_num(*v))).collect(); + (colors.clone(), labels) + } + ColorScale::Values(v) => { + let n = v.len().max(1) as f32; + let labels = v.iter().enumerate().map(|(i, (val, _))| ((i as f32 + 0.5) / n, rustgis_map::symbology::fmt_num(*val))).collect(); + (v.iter().map(|(_, c)| *c).collect(), labels) + } + }; + let vertical = bar.orientation == Orientation::Vertical; + let flip = if vertical { !bar.reverse } else { bar.reverse }; + let mut plan = ColorbarPlan { title, blocks: Vec::new(), rect: (0.0, 0.0, 0.0, 0.0), vertical, flip, labels: Vec::new(), spilled: 0 }; + if blocks.is_empty() { + return plan; + } + // No room for a bar: none is drawn, nor its labels. + if r.width() < 2.0 || bottom - top < 2.0 { + plan.spilled = labels.len(); + return plan; + } + let labels: Vec<(f32, String)> = labels.into_iter().map(|(at, s)| (at, decimal(s, bar.comma))).collect(); + let tick = 2.5 * ppp; + let gap = 1.5 * ppp; + let (bx, by, bw, bh) = if vertical { + let label_w = labels.iter().map(|(_, s)| width(s)).fold(0.0f32, f32::max); + let bw = (r.width() - label_w - tick - gap).clamp(2.0 * ppp, (r.width() * 0.45).max(2.0 * ppp)).min(r.width()); + let inset = (px / 2.0).min((bottom - top) * 0.25); + let bx = if bar.side == TickSide::Start { r.x() + r.width() - bw } else { r.x() }; + (bx, top + inset, bw, (bottom - top - 2.0 * inset).max(1.0)) + } else { + let ends = labels.first().map(|(_, s)| width(s)).unwrap_or(0.0).max(labels.last().map(|(_, s)| width(s)).unwrap_or(0.0)); + let inset = (ends / 2.0).min(r.width() * 0.25); + // Too short for its labels (left out below, and said), the bar fills the element. + let bh = match bottom - top - px * 1.2 - tick - gap { + h if h >= 3.0 * ppp => h, + _ => bottom - top, + }; + let by = if bar.side == TickSide::Start { bottom - bh } else { top }; + (r.x() + inset, by, (r.width() - 2.0 * inset).max(1.0), bh) + }; + plan.blocks = blocks; + plan.rect = (bx, by, bw, bh); + let len = if vertical { bh } else { bw }; + let along = |t: f32| if flip { (1.0 - t) * len } else { t * len }; + // A label (and its tick) is left out where it would spill out of a short or narrow element. + let inside = + |x: f32, y: f32, w: f32, h: f32| x >= r.x() - 1.0 && y >= r.y() - 1.0 && x + w <= r.right() + 1.0 && y + h <= r.bottom() + 1.0; + // Labels in order along the bar, each drawn only if it clears the one before. + let mut last_end = f32::NEG_INFINITY; + let mut ordered: Vec<(f32, String)> = labels.into_iter().map(|(t, s)| (along(t.clamp(0.0, 1.0)), s)).collect(); + ordered.sort_by(|a, b| a.0.total_cmp(&b.0)); + for (d, label) in ordered { + let lw = width(&label); + let extent = if vertical { px } else { lw }; + if d - extent / 2.0 < last_end + gap { + continue; + } + let (tick_ends, at, centred, fits) = if vertical { + let (y, x0) = (by + d, if bar.side == TickSide::Start { bx } else { bx + bw }); + let x1 = if bar.side == TickSide::Start { x0 - tick } else { x0 + tick }; + let lx = if bar.side == TickSide::Start { x1 - gap - lw } else { x1 + gap }; + ([(x0, y), (x1, y)], (lx, y), false, inside(lx, y - px / 2.0, lw, px)) + } else { + let (x, y0) = (bx + d, if bar.side == TickSide::Start { by } else { by + bh }); + let y1 = if bar.side == TickSide::Start { y0 - tick } else { y0 + tick }; + let ly = if bar.side == TickSide::Start { y1 - gap - px * 0.5 } else { y1 + gap + px * 0.5 }; + ([(x, y0), (x, y1)], (x, ly), true, inside(x - lw / 2.0, ly - px / 2.0, lw, px)) + }; + // Only a label drawn takes room: one left out doesn't thin the next. + if fits { + last_end = d + extent / 2.0; + plan.labels.push((label, tick_ends, at, centred)); + } else { + plan.spilled += 1; + } + } + plan +} + +/// A colorbar: the bar, ticks and labels along it, and its title above, as [`colorbar_plan`] lays +/// them out. Title lines and labels left out are said with the page's cut-off texts +/// ([`text_losses`]). +pub(super) fn colorbar(pm: &mut Canvas, r: Rect, scale: &ColorScale, bar: &Bar, ppp: f64) { + let ppp = ppp as f32; + let dark = bar.ink; + let px = 8.0 * 1.33 * ppp; + let plan = colorbar_plan(r, scale, bar, ppp); + let tpx = COLORBAR_TITLE_PT as f32 * 1.33 * ppp; + for (line, y) in &plan.title { + text::text_at(pm, line, r.x(), *y, tpx, dark, true, text::Align::Left, false); + } + if plan.blocks.is_empty() { + return; + } + let (bx, by, bw, bh) = plan.rect; + let len = if plan.vertical { bh } else { bw }; + let along = |t: f32| if plan.flip { (1.0 - t) * len } else { t * len }; + let n = plan.blocks.len(); + for (i, c) in plan.blocks.iter().enumerate() { + let (a, b) = (along(i as f32 / n as f32), along((i + 1) as f32 / n as f32)); + let (s0, s1) = (a.min(b), a.max(b)); + // A touch longer than its share, so neighbours leave no seam. + let rect = + if plan.vertical { Rect::from_xywh(bx, by + s0, bw, s1 - s0 + 0.6) } else { Rect::from_xywh(bx + s0, by, s1 - s0 + 0.6, bh) }; + if let Some(rect) = rect.and_then(|q| q.intersect(&Rect::from_xywh(bx, by, bw, bh)?)) { + pm.fill_rect(rect, &paint(*c, 1.0), Transform::identity(), None); + } + } + let line = Stroke { width: 0.6 * ppp, ..Stroke::default() }; + if let Some(b) = Rect::from_xywh(bx, by, bw, bh) { + pm.stroke_path(&PathBuilder::from_rect(b), &paint(dark, 1.0), &line, Transform::identity(), None); + } + for (label, [(x0, y0), (x1, y1)], (x, y), centred) in &plan.labels { + let align = if *centred { text::Align::Center } else { text::Align::Left }; + text::text_at(pm, label, *x, *y, px, dark, false, align, false); + let mut pb = PathBuilder::new(); + pb.move_to(*x0, *y0); + pb.line_to(*x1, *y1); + if let Some(p) = pb.finish() { + pm.stroke_path(&p, &paint(dark, 1.0), &line, Transform::identity(), None); + } + } +} + +/// A colorbar's title's size in points; it is drawn bold. +pub const COLORBAR_TITLE_PT: f64 = 9.0; + +/// A colorbar's title's style, as [`colorbar_title_lines`] measures it: bold, from the left edge. +pub(super) fn colorbar_title_style() -> TextStyle { + TextStyle { + face: text::Face { bold: true, ..Default::default() }, + align: TextAlign::Left, + spacing: 0.0, + valign: TextVAlign::Top, + line_spacing: USUAL_LINE_SPACING, + } +} + +/// A colorbar's title's width in mm, its widest line, measured as [`colorbar_title_lines`] breaks +/// it. +pub fn colorbar_title_width_mm(title: &str) -> f64 { + let px = (COLORBAR_TITLE_PT * 1.33 * WRAP_PX_PER_MM / PT_PER_MM) as f32; + let face = colorbar_title_style().face; + title.lines().map(|line| f64::from(text::styled_extent(line, px, face, 0.0).1)).fold(0.0, f64::max) / WRAP_PX_PER_MM +} + +/// The slack a colorbar's title gets on its width, in mm: a box made exactly as wide as the title +/// still takes it on one line once its width is rounded, or laid out in whole pixels. +pub(super) const COLORBAR_TITLE_SLACK_MM: f64 = 0.01; + +/// A colorbar's title as the lines it is drawn in (#2493): broken at spaces to fit `width` mm, a +/// word wider than that across lines, as a wrapped text is ([`wrapped`]), at one resolution +/// whatever it is drawn at, so the page, each export and a publication's sizing break it alike. A +/// title of one line that fits is that line, as it is. Past 200 lines, one more line with text +/// says it goes on, as for a wrapped text. +pub fn colorbar_title_lines(title: &str, width: f64) -> Vec { + let width = width + COLORBAR_TITLE_SLACK_MM; + if !title.contains('\n') && colorbar_title_width_mm(title) <= width { + return vec![title.to_string()]; + } + wrapped(title, width, COLORBAR_TITLE_PT, colorbar_title_style()).lines().map(str::to_string).collect() +} + +/// How many of a colorbar's `lines` of title it draws in an element from `top` (pixels), its +/// title at `px` pixels (#2493): each line only when the room it takes ends by `limit`, the +/// element's bottom less the bar's own room ([`colorbar_bar_room`]), the first too, so the bar +/// always keeps its labels (#2638); at most 200. The page's cut-off check ([`text_losses`]) +/// counts the lines left out the same way, so a colorbar too short for its title says so. +pub(super) fn colorbar_title_drawn(lines: usize, top: f32, limit: f32, px: f32) -> usize { + (0..lines.min(200)).take_while(|i| top + px * (1.4 + 1.25 * *i as f32) <= limit).count() +} + +/// The least room a colorbar's bar takes under its title, in pixels at `ppp` (#2638), as +/// [`colorbar`] lays it out: a horizontal bar 3 pixels thick (at 96 dpi) with its ticks and +/// 8-point labels under it; a vertical one, whose labels are at its side, two labels' height, so +/// its end labels, centred on the bar's ends, stay inside the element. A title stops short of it, +/// so its lines never leave the bar without its labels. +pub(super) fn colorbar_bar_room(ppp: f32, orientation: Orientation) -> f32 { + match orientation { + Orientation::Horizontal => (8.0 * 1.33 * 1.2 + 2.5 + 1.5 + 3.0) * ppp, + Orientation::Vertical => 2.0 * 8.0 * 1.33 * ppp, + } +} diff --git a/crates/render/src/layout/coverage.rs b/crates/render/src/layout/coverage.rs new file mode 100644 index 0000000000..d39a8aca75 --- /dev/null +++ b/crates/render/src/layout/coverage.rs @@ -0,0 +1,221 @@ +//! How much of a map frame its layers cover. + +use super::*; + +/// The renderer's scale denominator for a frame showing `map` at paper scale 1:`scale` (the one +/// [`legend_sizes_mm`] takes). +pub fn frame_render_scale(map: &Map, center: Coord, scale: f64) -> f64 { + let cam = frame_camera(map, center, scale, 0.0, 0.0); + map.ground_res_at(&cam) / rustgis_geom::PIXEL_M +} + +/// Whether a layer only outlines its polygons, with no fill and no labels: context around a map's +/// data, such as the neighbouring states' borders, which a surround can sit on. No Fill counts, +/// whatever the renderer; a transparent symbol under stacked fills such as a hatch (the layer's or a +/// class's), a fill by expression, diagrams or extrusion are more than an outline. +pub(super) fn only_outlines(l: &rustgis_map::Layer) -> bool { + use rustgis_map::NoFill; + let hollow = l.no_fill == Some(NoFill::Override) + || (!l.has_fills() + && (l.no_fill == Some(NoFill::Symbols) || matches!(&l.renderer, rustgis_map::Renderer::Single(s) if s.fill.0[3] == 0))); + l.geometry_type() == GeometryType::Polygon + && !l.labels.enabled + && hollow + && l.symbol_by.fill.is_none() + && l.diagram.is_none() + && l.extrusion.is_none() +} + +/// Whether a layer fills its polygons in one colour, with no labels and nothing else: beside a layer +/// drawn by classes or a raster it is context too, such as the neighbouring states in grey. +pub(super) fn plain_fill(l: &rustgis_map::Layer) -> bool { + l.geometry_type() == GeometryType::Polygon + && !l.labels.enabled + && !l.has_fills() + && matches!(&l.renderer, rustgis_map::Renderer::Single(_)) + && l.symbol_by.fill.is_none() + && l.diagram.is_none() + && l.extrusion.is_none() +} + +/// Where a frame showing `map` at 1:`scale` draws its layers: a grid of about `cells` cells across +/// the frame's longer side, row by row from the top, each `true` where a layer (or its labels) +/// drew. The basemap is left out, so the frame's background isn't counted, and so are layers that +/// only outline their polygons ([`only_outlines`]) unless nothing else is shown, and those that +/// fill them in one colour ([`plain_fill`]) beside a layer drawn by classes or a raster, when they +/// run on past the frame, as neighbouring states do: one inside it, such as a study area, is what +/// the map shows. For keeping a layout's surrounds off what its map shows. `None` when the frame +/// can't be drawn. +/// +/// The map itself is drawn, not a copy of it (every layer's features): its basemap, web tiles +/// (a background, like the basemap) and graticule are set aside for the drawing and put back, +/// however it ends, as is a label lock waiting to be filled, which the coarse drawing would +/// otherwise fill. +pub fn frame_coverage(map: &mut Map, center: Coord, scale: f64, w_mm: f64, h_mm: f64, cells: u32) -> Option<(u32, u32, Vec)> { + frame_coverage_judged_on(map, center, scale, (w_mm, h_mm), (w_mm, h_mm), cells) +} + +/// The visible layers a frame showing `map` at 1:`scale` around `center` takes as context around +/// its data, by id: those that only outline their polygons ([`only_outlines`]) unless nothing else +/// is shown, and those that fill them in one colour ([`plain_fill`]) beside a layer drawn by classes +/// or a raster, when they run on past a frame `judged` (mm) wide and tall, as neighbouring states +/// do. [`frame_coverage`] leaves them out of what the map draws; a publication's legend leaves them +/// out too (#1379). +pub fn context_layers(map: &Map, center: Coord, scale: f64, judged: (f64, f64)) -> Vec { + let at = frame_render_scale(map, center, scale); + if map.layers.iter().filter(|l| map.draws_at(l, at)).all(only_outlines) { + return Vec::new(); + } + let classes = + map.layers.iter().any(|l| map.draws_at(l, at) && (l.is_raster() || !matches!(&l.renderer, rustgis_map::Renderer::Single(_)))); + let judged_view = View { + width: judged.0 * PT_PER_MM, + height: judged.1 * PT_PER_MM, + pixels_per_point: 1.0, + camera: frame_camera(map, center, scale, 0.0, 0.0), + sky: false, + }; + let frame = crate::view_lonlat(map, &judged_view); + let past_the_frame = |l: &rustgis_map::Layer| { + let e = l.shown_extent(); + !e.is_empty() && (e.min_x < frame.min_x || e.max_x > frame.max_x || e.min_y < frame.min_y || e.max_y > frame.max_y) + }; + map.layers.iter().filter(|l| l.visible && (only_outlines(l) || (classes && plain_fill(l) && past_the_frame(l)))).map(|l| l.id).collect() +} + +/// [`frame_coverage`] of a frame `size` (mm), with what runs on past the frame judged on a frame +/// `judged` (mm) with the same centre: a drawing wider than the frame asked for, cut for frames +/// moved inside it, leaves out the same one-colour layers as that frame does. +pub fn frame_coverage_judged_on( + map: &mut Map, + center: Coord, + scale: f64, + (w_mm, h_mm): (f64, f64), + judged: (f64, f64), + cells: u32, +) -> Option<(u32, u32, Vec)> { + if !(w_mm > 0.0 && h_mm > 0.0 && judged.0 > 0.0 && judged.1 > 0.0) { + return None; + } + 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 }; + // Put back when this ends, a panic in the drawing included. + struct Aside<'a> { + basemap: rustgis_map::Basemap, + paper: Option, + tiles: Vec, + graticule: bool, + lock: Option>, + anchors: std::collections::HashMap, + outlines: Vec, + map: &'a mut Map, + } + impl Drop for Aside<'_> { + fn drop(&mut self) { + for l in self.map.layers.iter_mut().filter(|l| self.outlines.contains(&l.id)) { + l.visible = true; + } + self.map.basemap = self.basemap; + self.map.paper = self.paper; + self.map.tiles = std::mem::take(&mut self.tiles); + self.map.graticule = self.graticule; + self.map.label_lock = self.lock.take(); + self.map.label_lock_line_anchors = std::mem::take(&mut self.anchors); + } + } + // The space a globe is drawn on here: the blank basemap's, light. + let space = map.projection.is_globe().then(|| crate::globe_space(false)).map(|c| (c.r(), c.g(), c.b())); + let outlines = context_layers(map, center, scale, judged); + for l in map.layers.iter_mut().filter(|l| outlines.contains(&l.id)) { + l.visible = false; + } + let aside = Aside { + outlines, + basemap: std::mem::replace(&mut map.basemap, rustgis_map::Basemap::Blank), + // Judged on white paper: a blank basemap's paper colour (#2532) would count as drawn. + paper: map.paper.take(), + tiles: std::mem::take(&mut map.tiles), + graticule: std::mem::replace(&mut map.graticule, false), + lock: map.label_lock.take(), + anchors: std::mem::take(&mut map.label_lock_line_anchors), + map, + }; + let pm = crate::render(&mut *aside.map, &view)?.pixmap; + drop(aside); + let (gw, gh) = (pm.width(), pm.height()); + // Anything not the blank basemap's paper, pure opaque white (the graticule set aside too): a + // pale or translucent fill counts (only a fill of that very white, invisible on it, doesn't). + // On a globe, the space around it is paper too: counted, it took every cell and the surrounds + // landed on the globe (#2337). The atmosphere's glow at the rim is not, which keeps them off + // the globe's edge. + let paper = |r: u8, g: u8, b: u8| (r, g, b) == (255, 255, 255) || space == Some((r, g, b)); + let drawn = pm.pixels().iter().map(|p| p.alpha() > 0 && !(p.alpha() == 255 && paper(p.red(), p.green(), p.blue()))).collect(); + Some((gw, gh, drawn)) +} + +/// Whether a frame showing `map` at 1:`scale` around `center`, `size` (mm) wide and tall, shows +/// one light 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 }; + // A publication's legend has no ink (#2257): its text stays dark grey (INK), so dark water + // or land must keep its paper backing. + let background = [water, land] + .iter() + .any(|c| (c.0[0], c.0[1], c.0[2], 255) == first && u16::from(c.r()) + u16::from(c.g()) + u16::from(c.b()) > 3 * 160); + background && seen.all(|p| rgba(p) == first) +} diff --git a/crates/render/src/layout/dynamic_text.rs b/crates/render/src/layout/dynamic_text.rs new file mode 100644 index 0000000000..974e54658f --- /dev/null +++ b/crates/render/src/layout/dynamic_text.rs @@ -0,0 +1,185 @@ +//! The tokens a layout's texts hold: page, scale and a layer's statistics. + +use super::*; + +/// A scale as `{scale}` prints it: `1:6,300,000`, or `1:6.300.000` with a decimal comma. +pub fn scale_ratio_text(scale: f64, comma: bool) -> String { + let ratio = rustgis_map::graphics::scale_ratio(scale); + if comma { decimal(ratio, true) } else { ratio } +} + +/// Expands layout text tokens: the page ones here, the map ones from the first frame. +pub fn expand(t: &str, layout: &Layout, info: &PageInfo, frame: Option<(&Map, rustgis_map::Camera)>) -> String { + // The frame's scale, worked out once for both its forms below. + let scale = frame.map(|(m, cam)| m.ground_res_at(&cam) / rustgis_map::layout::PAPER_M_PER_PT); + // The layer statistics first, read from the text as written: a page or layout name put in + // below isn't read as one. + let t = statistics(t, layout.decimal_comma, frame.map(|(m, _)| m)); + // A layout with a decimal comma prints its scale with points between thousands: put in first, + // so a page or layout name holding "{scale}" isn't read as the token. + let t = match scale { + Some(scale) if layout.decimal_comma => t.replace("{scale}", &scale_ratio_text(scale, true)), + _ => t, + }; + let t = t + .replace("{page}", &info.page.max(1).to_string()) + .replace("{pages}", &info.pages.max(1).to_string()) + .replace("{pageName}", &info.page_name) + .replace("{layout}", &layout.name); + let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let v = match frame { + Some((m, cam)) => rustgis_map::graphics::TokenValues { + map: m.name.clone(), + scale: scale.unwrap_or(0.0), + crs: m.projection.label(), + layers: m.layers.iter().filter(|l| !l.graphics).count(), + center: m.to_lonlat(cam.center).unwrap_or_default(), + now, + }, + None => rustgis_map::graphics::TokenValues { + map: String::new(), + scale: 0.0, + crs: String::new(), + layers: 0, + center: Coord::default(), + now, + }, + }; + rustgis_map::graphics::expand(&t, &v) +} + +/// What the layer statistics in `text` (#2853) are missing, one line per token, each once: no map +/// frame, the first frame's map not in the project, no such layer in it, or what +/// [`rustgis_map::layout::layer_statistic`] finds missing (each drawn as written by [`expand`]); and +/// a figure over a layer read in place, which covers only the features loaded, has a line for that +/// as well. +pub fn statistic_notices(layout: &Layout, maps: &[Map], text: &str) -> Vec { + let map = layout.first_frame().and_then(|f| match &layout.element(f)?.kind { + ElementKind::MapFrame { map, .. } => maps.get(map_index(maps, map)?), + _ => None, + }); + let no_map = match layout.first_frame() { + Some(_) => "the map of the layout's first frame is not in the project", + None => "the layout has no map frame whose map it would read", + }; + notices_over(map.ok_or(no_map), "the map of the layout's first frame", text) +} + +/// [`statistic_notices`] for a text whose figures are read from `map`, which the notices call +/// `whose`: a presentation map page's title, drawn over that page's own map. +pub fn map_statistic_notices(map: &Map, whose: &str, text: &str) -> Vec { + notices_over(Ok(map), whose, text) +} + +/// The notices of `text`'s figures over `map`, or why there is none to read. +pub(super) fn notices_over(map: Result<&Map, &str>, whose: &str, text: &str) -> Vec { + use rustgis_map::layout::StatMissing; + let mut said: Vec = Vec::new(); + let tokens = distinct_stat_tokens(text, true); + // Each layer's figures in one pass, whatever their number. + let figures: Vec)>>> = match map { + Ok(m) => figures_of(m, &tokens).into_iter().map(Some).collect(), + Err(_) => vec![None; tokens.len()], + }; + for (t, found) in tokens.iter().zip(figures) { + let (layer, field) = (t.layer, t.field.unwrap_or_default()); + // A layer read in place holds only what is loaded, so its figure is partial, and one with + // no number yet gets some as more is loaded. + if let Some(Some((true, Ok(_) | Err(StatMissing::NoValue)))) = found { + said.push(format!("{} covers only the features of '{layer}' that are loaded: it is read in place", t.token)); + } + let why = match found.map(|l| l.map(|(_, figure)| figure)) { + None => map.err().unwrap_or_default().to_string(), + Some(None) => format!("{whose} has no layer named '{layer}'"), + Some(Some(Ok(_))) => continue, + Some(Some(Err(StatMissing::Raster))) => format!("'{layer}' is a raster layer, which has no features"), + Some(Some(Err(StatMissing::Field))) if t.field.is_none() => { + format!("a {} takes a field: write {{{}:{layer}:field}}", t.stat.code(), t.stat.code()) + } + Some(Some(Err(StatMissing::Field))) => format!("'{layer}' has no field named '{field}'"), + Some(Some(Err(StatMissing::NotNumeric))) => format!("'{field}' of '{layer}' holds no numbers"), + Some(Some(Err(StatMissing::NoValue))) => { + format!( + "no feature of '{layer}' its definition query keeps has a number in '{field}', or the figure is past a number's range" + ) + } + }; + said.push(format!("{} shows as written: {why}", t.token)); + } + said +} + +/// `t` with its layer statistics (#2853) from `map`, the first frame's, written as a chart writes +/// its values ([`rustgis_map::layout::chart_value_text`]) with `comma` the decimal mark; a token +/// with no figure stays as written ([`statistic_notices`] says why). +pub(super) fn statistics(t: &str, comma: bool, map: Option<&Map>) -> String { + let Some(m) = map else { return t.to_string() }; + let mut out = t.to_string(); + // `replace` below puts in every occurrence, so a repeated token is worked out once, and the + // figures of one layer in one pass over it. + let tokens = distinct_stat_tokens(t, false); + for (s, figure) in tokens.iter().zip(figures_of(m, &tokens)) { + if let Some((_, Ok(v))) = figure { + out = out.replace(s.token, &decimal(rustgis_map::layout::chart_value_text(v, None), comma)); + } + } + out +} + +/// The layer statistics of `texts` (#2853) as the page draws them from `map`, as (token, figure) +/// pairs for the tokens that have a figure, each token once: what a publication measures its texts +/// with, so a box is sized for the figures it will show, not for the tokens written. +pub fn statistic_figures(map: &Map, comma: bool, texts: &[&str]) -> Vec<(String, String)> { + let mut pairs: Vec<(String, String)> = Vec::new(); + for text in texts { + let tokens = distinct_stat_tokens(text, false); + for (s, figure) in tokens.iter().zip(figures_of(map, &tokens)) { + if let Some((_, Ok(v))) = figure + && !pairs.iter().any(|(token, _)| token == s.token) + { + pairs.push((s.token.to_string(), decimal(rustgis_map::layout::chart_value_text(v, None), comma))); + } + } + } + pairs +} + +/// The statistic tokens of `text`, each once, in the order they come; with `gaps`, the figures +/// written without their field too. +pub(super) fn distinct_stat_tokens(text: &str, gaps: bool) -> Vec> { + let mut tokens: Vec> = Vec::new(); + let read = if gaps { rustgis_map::layout::stat_tokens_and_gaps(text) } else { rustgis_map::layout::stat_tokens(text) }; + for t in read { + if !tokens.iter().any(|seen| seen.token == t.token) { + tokens.push(t); + } + } + tokens +} + +/// The figure of each of `tokens` in `map`, with whether its layer is read in place; none for a token +/// whose layer the map lacks. The figures of one layer are worked out in one pass over its rows +/// ([`rustgis_map::layout::layer_statistics`]), so a text with many figures costs a pass for each +/// layer, not for each figure. +pub(super) fn figures_of( + map: &Map, + tokens: &[rustgis_map::layout::StatToken<'_>], +) -> Vec)>> { + let mut out = vec![None; tokens.len()]; + let mut done = vec![false; tokens.len()]; + for i in 0..tokens.len() { + if done[i] { + continue; + } + let same: Vec = (i..tokens.len()).filter(|j| !done[*j] && tokens[*j].layer.eq_ignore_ascii_case(tokens[i].layer)).collect(); + for j in &same { + done[*j] = true; + } + let Some(layer) = map.layer_by_name(tokens[i].layer) else { continue }; + let wanted: Vec<_> = same.iter().map(|j| (tokens[*j].stat, tokens[*j].field)).collect(); + for (j, figure) in same.iter().zip(rustgis_map::layout::layer_statistics(layer, &wanted)) { + out[*j] = Some((layer.is_streamed(), figure)); + } + } + out +} diff --git a/crates/render/src/layout/frame.rs b/crates/render/src/layout/frame.rs new file mode 100644 index 0000000000..0b650842e1 --- /dev/null +++ b/crates/render/src/layout/frame.rs @@ -0,0 +1,552 @@ +//! Map frames: their picture, outline and georeferenced viewports. + +use super::*; + +/// A map frame's map, `w` × `h` points at `ppp` pixels a point, labels and attribution included: +/// what a frame shows before its grid, indicator and outline. It waits for the map's tiles, as a +/// page needs them all. Refuses a linked archive changed during the complete frame. +pub fn frame_map(map: &mut Map, camera: rustgis_map::Camera, w: f64, h: f64, ppp: f64) -> Result { + let revisions = crate::archive_revisions([&*map]); + let mut failed_source = None; + let view = View { width: w, height: h, pixels_per_point: ppp, camera, sky: false }; + let result = frame_canvas(map, &view, false, &mut false, None, &mut failed_source, &Env::default()).map(Canvas::into_pixmap); + revisions.finish(map, failed_source, result, "could not draw the map frame") +} + +/// [`frame_map`] on a canvas: one that records (see [`crate::canvas`]) when `record` and the +/// frame can be kept as vectors (flat, north up, without view effects), else its pixels; with +/// `grid` (and whether the layout writes a decimal comma) drawn on it under the attribution. +/// `pending` is set when some of its tiles, or a read of its streamed layers or rasters, were +/// still on their way (in the browser, which doesn't wait for them). +pub(super) fn frame_canvas( + map: &mut Map, + view: &View, + record: bool, + pending: &mut bool, + grid: Option<(&Grid, bool)>, + failed_source: &mut Option, + env: &Env, +) -> Option { + // Why its layers were drawn without their cast shadows is kept for the page's caller (see + // `crate::shadows_said`). + let (img, shadows) = crate::frame_with_shadows_to_come(|| crate::complete(map, view, record, failed_source, env)); + let img = img?; + *pending |= img.tiles_pending || img.data_pending || shadows; + Some(finish_frame(img, view.pixels_per_point, grid.map(|(g, comma)| (&*map, view, g, comma)))) +} + +/// [`frame_map`] without waiting for tiles still on their way, for a preview drawn while the +/// interface waits: a pan's preview, whose size is more than the frame's for the overscan slid +/// under the pointer. +pub fn frame_map_preview(map: &mut Map, camera: rustgis_map::Camera, w: f64, h: f64, ppp: f64) -> Option { + frame_map_preview_with(map, camera, w, h, ppp, &Env::default()) +} + +/// Map preview during a layout pan, using the same expression context as its page. +pub fn frame_map_preview_with(map: &mut Map, camera: rustgis_map::Camera, w: f64, h: f64, ppp: f64, env: &Env) -> Option { + let view = View { width: w, height: h, pixels_per_point: ppp, camera, sky: false }; + crate::render_cpu(map, &view, false, false, &mut None, env).map(|img| finish_frame(img, ppp, None).into_pixmap()) +} + +/// A rendered frame map with its labels, its `grid` (drawn on `map` in `view`, with a decimal +/// comma or not) and its attribution drawn on it: on its recording when it was recorded, else on +/// its pixels. The attribution keeps clear of the grid's labels. +pub(super) fn finish_frame(img: crate::Rendered, ppp: f64, grid: Option<(&Map, &View, &Grid, bool)>) -> Canvas { + let crate::Rendered { pixmap, recorded, labels, unplaced, label_layers, attribution, .. } = img; + let mut pm = recorded.unwrap_or_else(|| Canvas::from_pixmap(pixmap)); + crate::draw_labels(&mut pm, (&unplaced, &labels, &label_layers), ppp as f32); + // The grid is a layer of its own (#1815). + pm.layer(grid.is_some().then_some("Grid")); + let grid_labels = grid.map(|(map, view, g, comma)| draw_grid(&mut pm, map, view, g, comma)).unwrap_or_default(); + pm.layer(None); + let (w, h) = (pm.width() as f32 / ppp as f32, pm.height() as f32 / ppp as f32); + let inset = crate::attribution_text(&attribution).map_or((0.0, 0.0), |(_, tw)| attribution_inset((w, h), tw, &grid_labels)); + crate::draw_attribution(&mut pm, &attribution, ppp as f32, inset); + pm +} + +/// How far further in (up from the bottom, in from the right, in points) the attribution `tw` +/// points wide goes on a frame `w` × `h` points, so it covers none of the grid's bottom and right +/// `labels` (each one's edge, and its box in points: left, top, right, bottom). It goes above a +/// bottom label under it. Beside a right label, it goes left of it when it still fits in the frame +/// there, else above it; when neither fits, as far left as the frame holds it. Where none is in +/// the way, it stays in the corner. +pub(super) fn attribution_inset((w, h): (f32, f32), tw: f32, labels: &[(Edge, [f32; 4])]) -> (f32, f32) { + let size = crate::ATTRIBUTION_SIZE; + // Half the credit's height, its halo included, and the gap it keeps from a label. + let (half, gap) = (size * 0.8, 2.0); + let (mut bottom, mut right) = (0.0f32, 0.0f32); + // The credit's foot set `gap` above a label's top `y`: how far up from the bottom that is. + let above = |y: f32| h - size * 0.9 + half - y + gap; + // Each move clears the label for good (the credit only goes up and left), so each label is + // met once at most; the last resort ends the search. + for _ in 0..=labels.len() { + // Its whole width, where it is drawn: a credit wider than the frame runs past both edges. + let (cx, cy) = (crate::attribution_center(w, tw, right), h - bottom - size * 0.9); + let (x0, x1, y0, y1) = (cx - tw / 2.0, cx + tw / 2.0, cy - half, cy + half); + let hit = labels + .iter() + .filter(|(e, _)| matches!(e, Edge::Bottom | Edge::Right)) + .find(|(_, b)| x0 < b[2] && b[0] < x1 && y0 < b[3] && b[1] < y1); + match hit { + // Left of the label, its right end `gap` short of it, when all of it stays in. + Some((Edge::Right, b)) if b[0] - gap - tw >= 0.0 => right += x1 - (b[0] - gap), + // Above the label, when all of it stays in. + Some((Edge::Right, b)) if b[1] - gap - 2.0 * half >= 0.0 => bottom = above(b[1]), + // Neither: as far left as the frame holds it (a credit wider than the frame stays put). + Some((Edge::Right, _)) => { + right += x0.max(0.0); + break; + } + Some((_, b)) => bottom = above(b[1]), + None => break, + } + } + (bottom, right) +} + +pub(super) fn shape_path(shape: &FrameShape, r: Rect) -> Option { + match shape { + FrameShape::Rectangle => Some(PathBuilder::from_rect(r)), + FrameShape::Circle => { + let d = r.width().min(r.height()); + PathBuilder::from_oval(Rect::from_xywh(r.x() + (r.width() - d) / 2.0, r.y() + (r.height() - d) / 2.0, d, d)?) + } + FrameShape::Ellipse => PathBuilder::from_oval(r), + FrameShape::Polygon(_) => { + let mut pb = PathBuilder::new(); + for (i, (u, v)) in shape.outline().into_iter().enumerate() { + let (px, py) = (r.x() + u as f32 * r.width(), r.y() + v as f32 * r.height()); + if i == 0 { pb.move_to(px, py) } else { pb.line_to(px, py) } + } + pb.close(); + pb.finish() + } + } +} + +/// The lon/lat outline of what a frame shows, `None` where an edge has no place on the Earth (off +/// the disc of a frame on the globe, or outside a custom projection's domain): the outline breaks +/// there rather than cutting across the map it is drawn on, and reaches the place where the edge +/// leaves it (#2369). +pub(super) fn frame_outline_lonlat(map: &Map, cam: &rustgis_map::Camera, w: f64, h: f64) -> Vec> { + let n = 16; + let edge = |t: f64, side: usize| match side { + 0 => (t * w, 0.0), + 1 => (w, t * h), + 2 => ((1.0 - t) * w, h), + _ => (0.0, (1.0 - t) * h), + }; + // A frame on the globe is read through the globe as it draws it (#2348), with a gap where an + // edge runs off the disc: one that shows the globe whole has no edge on it, and no outline. + let globe = map.projection.is_globe().then(|| rustgis_map::globe::Globe::new(cam, w, h)); + let at = |(sx, sy): (f64, f64)| match &globe { + Some(g) => g.inverse(sx, sy), + None => map.to_lonlat(cam.to_map(sx, sy, w, h)), + }; + // A frame on the globe has its longitudes kept continuous, a turn added or taken where they + // cross ±180°, so on a flat frame the outline doesn't jump across the map there. A flat + // frame's are drawn where they are. + let mut last: Option = None; + let mut ring = Vec::with_capacity(4 * n + 8); + let mut push = |c: Option| { + let c = match (globe.is_some(), c, last) { + (true, Some(c), Some(p)) => Some(Coord::new(c.x + 360.0 * ((p - c.x) / 360.0).round(), c.y)), + _ => c, + }; + if let Some(c) = c { + last = Some(c.x); + } + ring.push(c); + }; + let mut first = None; + let mut prev: Option<((f64, f64), Option)> = None; + // Every side's samples, and the first again to close the ring. + for i in 0..=4 * n { + let p = edge((i % n) as f64 / n as f64, (i / n) % 4); + let c = match first { + Some(f) if i == 4 * n => f, + _ => at(p), + }; + first.get_or_insert(c); + // Between a sample with a place and one without, the place where the edge leaves the + // Earth, found by bisecting (24 halvings take a sixteenth of the edge to well under a + // millionth of it): without it the outline stops up to a sample short of it. + if let Some((q, b)) = prev + && b.is_some() != c.is_some() + { + let (mut inside, mut outside, mut found) = if b.is_some() { (q, p, b) } else { (p, q, c) }; + for _ in 0..24 { + let mid = ((inside.0 + outside.0) / 2.0, (inside.1 + outside.1) / 2.0); + match at(mid) { + Some(m) => (inside, found) = (mid, Some(m)), + None => outside = mid, + } + } + push(found); + } + push(c); + prev = Some((p, c)); + } + ring +} + +/// The map frames of a page georeferenced for a PDF ([`frame_viewports`], #1191). +#[derive(Debug, Default)] +pub struct Georeferenced { + /// The georeferenced frames, in drawing order, each in the rectangles no frame drawn over it + /// covers (`uncovered`): no two overlap, so a reader never has two to choose from. + pub viewports: Vec, + /// The frames that couldn't be, by id and name, with why. + pub left_out: Vec<(u32, String, &'static str)>, + /// The frames whose coordinate system can't be written as WKT (a grid shift, or a projection + /// WKT1 has no name for), by id and name: + /// georeferenced by their corners in longitude/latitude, which put the places of a 9 × 9 grid + /// over the frame within [`MAX_CORNER_FIT_MM`] of where they are drawn (`corner_fit_mm`). + pub by_corners: Vec<(u32, String)>, +} + +/// How far, on paper, a frame georeferenced by its corners in longitude/latitude may put a place +/// from where the frame draws it: past it, the frame is left out (#1191). +pub const MAX_CORNER_FIT_MM: f64 = 0.5; + +/// Each visible map frame of `layout` as a PDF viewport ([`crate::pdf::Viewport`]): its place on +/// the page as a page drawn at `dpi` places it, its corners' latitude and longitude, and its +/// map's coordinate system as WKT. A frame on the globe or tilted shows no flat map to measure +/// on, so it is left out, as is one on another body than the Earth, one whose map is missing, +/// one with a corner off the Earth, one across its projection's edge (the 180° meridian) and one +/// whose system has no WKT and whose corners alone would misplace it. A frame drawn over another, +/// left out or not, is cut out of the other's viewport, so that the other's coordinates don't show +/// through it: a viewport without coordinates would do it by the standard (the last viewport +/// holding a point is taken, ISO 32000-1, 12.9.2), but Acrobat Reader doesn't take one. +pub fn frame_viewports(layout: &Layout, maps: &[Map], dpi: f64) -> Georeferenced { + let mut out = Georeferenced::default(); + // A frame is drawn from a whole pixel of the page ([`draw_page`]), whose pixels are stretched + // over its paper: the viewport is that box, in millimetres. + let (wpx, hpx, k) = page_geometry(layout, dpi); + let (sx, sy) = (layout.width / f64::from(wpx.max(1)), layout.height / f64::from(hpx.max(1))); + let frames: Vec<_> = layout + .elements + .iter() + .filter(|e| e.visible && matches!(e.kind, ElementKind::MapFrame { .. })) + // Rounded as `draw_page` rounds them, in single precision, so the box is the drawn one. + .map(|e| (e, [f64::from(((e.x * k) as f32).round()) * sx, f64::from(((e.y * k) as f32).round()) * sy, e.w * k * sx, e.h * k * sy])) + .collect(); + for (i, (e, placed)) in frames.iter().enumerate() { + let ElementKind::MapFrame { map, center, scale, bearing, pitch, shape, .. } = &e.kind else { continue }; + // A viewport is a rectangle: one for a shaped frame over another would give its places + // where the page shows the other's map, around the shape. (It still cuts the other.) + let over = + |[x, y, w, h]: [f64; 4]| x < placed[0] + placed[2] && placed[0] < x + w && y < placed[1] + placed[3] && placed[1] < y + h; + if *shape != rustgis_map::layout::FrameShape::Rectangle && frames[..i].iter().any(|(_, r)| over(*r)) { + out.left_out.push(( + e.id, + e.name.clone(), + "it isn't a rectangle and is drawn over another frame, whose map shows around its shape", + )); + continue; + } + let Some(m) = map_index(maps, map).and_then(|i| maps.get(i)) else { + out.left_out.push((e.id, e.name.clone(), "its map is missing")); + continue; + }; + if !placed.iter().all(|v| v.is_finite()) { + out.left_out.push((e.id, e.name.clone(), "its place on the page isn't a number")); + continue; + } + // What the frames drawn over it leave of it. + let mut shown = vec![*placed]; + for (_, over) in &frames[i + 1..] { + shown = shown.into_iter().flat_map(|r| uncovered(r, *over)).collect(); + // Past the most, it is left out: cutting on would only make more. + if shown.len() > MAX_VIEWPORTS_A_FRAME { + break; + } + } + if shown.is_empty() { + out.left_out.push((e.id, e.name.clone(), "the frames drawn over it cover all of it")); + continue; + } + if shown.len() > MAX_VIEWPORTS_A_FRAME { + out.left_out.push((e.id, e.name.clone(), "too many frames are drawn over it")); + continue; + } + match frame_viewport(e, *placed, &shown, m, rustgis_map::layout::frame_camera(m, *center, *scale, *bearing, *pitch)) { + Ok((v, exact)) => { + if !exact { + out.by_corners.push((e.id, e.name.clone())); + } + out.viewports.extend(v); + } + Err(why) => out.left_out.push((e.id, e.name.clone(), why)), + } + } + out +} + +/// The most rectangles a frame's viewport is cut into by the frames drawn over it; past it, the +/// frame is left out. +pub(super) const MAX_VIEWPORTS_A_FRAME: usize = 64; + +/// A strip narrower than this, in millimetres, left of a frame beside one drawn over it, is +/// dropped: no one points into it. +pub(super) const MIN_STRIP_MM: f64 = 0.01; + +/// Rectangle `r` (x, y, width, height) without `cut`: up to four rectangles, the bands above and +/// below the cut, and beside it between them. +pub(super) fn uncovered(r: [f64; 4], cut: [f64; 4]) -> Vec<[f64; 4]> { + let (x0, y0, x1, y1) = (r[0], r[1], r[0] + r[2], r[1] + r[3]); + let (cx0, cy0, cx1, cy1) = (cut[0].max(x0), cut[1].max(y0), (cut[0] + cut[2]).min(x1), (cut[1] + cut[3]).min(y1)); + if cx0 >= cx1 || cy0 >= cy1 { + return vec![r]; + } + [(x0, y0, x1, cy0), (x0, cy1, x1, y1), (x0, cy0, cx0, cy1), (cx1, cy0, x1, cy1)] + .into_iter() + .filter(|(a, b, c, d)| c - a >= MIN_STRIP_MM && d - b >= MIN_STRIP_MM) + .map(|(a, b, c, d)| [a, b, c - a, d - b]) + .collect() +} + +/// How far, in millimetres on paper, a reader that fits a frame's corners in longitude/latitude +/// (`corners`, latitude then longitude, clockwise from the top-left) puts the places on a 9 × 9 +/// grid over it, its edges included, from where the frame, `w` × `h` points seen by `cam`, draws +/// them: the worst of them, the fit being exact at the corners. `None` when one of them isn't on +/// the map. +pub(super) fn corner_fit_mm(corners: &[(f64, f64); 4], map: &Map, cam: &rustgis_map::Camera, w: f64, h: f64) -> Option { + let [tl, tr, br, bl] = *corners; + let mut worst: f64 = 0.0; + // A 9 × 9 grid over the frame, its edges included (the corners are exact). + let grid = (0..=8).flat_map(|i| (0..=8).map(move |j| (f64::from(i) / 8.0, f64::from(j) / 8.0))); + for (u, t) in grid { + // Between the corners, as the unit square's (`/LPTS`) is filled: bilinearly. + let mix = |a: f64, b: f64, c: f64, d: f64| (1.0 - u) * (1.0 - t) * a + u * (1.0 - t) * b + u * t * c + (1.0 - u) * t * d; + let (lat, lon) = (mix(tl.0, tr.0, br.0, bl.0), mix(tl.1, tr.1, br.1, bl.1)); + let at = map.to_map(Coord::new((lon + 540.0).rem_euclid(360.0) - 180.0, lat))?; + let (x, y) = cam.try_to_screen(at, w, h)?; + // `f64::max` ignores NaN: a sample that isn't a number is no fit. + let off = (x - u * w).hypot(y - t * h); + if !off.is_finite() { + return None; + } + worst = worst.max(off); + } + (worst.is_finite()).then_some(worst / PT_PER_MM) +} + +/// Frame `e` of `map`, placed at `placed` (millimetres: x, y, width, height) and seen by `cam`, as +/// a viewport for each rectangle of it in `shown`, and whether it is in the map's own coordinate +/// system (else in longitude/latitude, by its corners). +pub(super) fn frame_viewport( + e: &rustgis_map::layout::Element, + placed: [f64; 4], + shown: &[[f64; 4]], + map: &Map, + cam: rustgis_map::Camera, +) -> Result<(Vec, bool), &'static str> { + use rustgis_data::raster::{crs, wkt}; + if map.projection.is_globe() { + return Err("it shows the globe"); + } + // Its coordinates are another body's, which an Earth system would misplace. + if !map.body().is_earth() { + return Err("it is on another body than the Earth"); + } + if cam.pitch.abs() > 1e-9 { + return Err("it is tilted"); + } + // The map's coordinate system: its WKT and EPSG code, and its PROJ definition (whose datum + // the corners are given on). + let (system, def) = match &map.projection { + rustgis_map::Projection::Custom(code) => { + let (def, label) = rustgis_map::projection::lookup(code).map_err(|_| "its projection can't be read")?; + let lower = code.trim().to_ascii_lowercase(); + let digits = lower.strip_prefix("epsg").map_or(lower.as_str(), |r| r.trim_start_matches([':', ' '])); + let epsg = digits.parse::().ok().filter(|_| digits.bytes().all(|b| b.is_ascii_digit())); + let text = match epsg { + Some(c) => wkt::to_wkt(crs::Crs::Epsg(c)), + None => wkt::proj4_to_wkt(&def, &label), + }; + (text.map(|t| (t, epsg)), Some(def)) + } + _ => (wkt::to_wkt(crs::Crs::WebMercator).map(|t| (t, Some(3857))), None), + }; + let (w, h) = (e.w * PT_PER_MM, e.h * PT_PER_MM); + // The latitude and longitude of the frame's point `(sx, sy)` (points from its top-left). + let place = |sx: f64, sy: f64| -> Result<(f64, f64), &'static str> { + let m = cam.try_to_map(sx, sy, w, h).ok_or("a corner is off the Earth")?; + let c = map.to_lonlat(m).ok_or("a corner is off the Earth")?; + // A corner past the projection's edge (Web Mercator's world repeated across 180°) is at a + // longitude past ±180°, or comes back elsewhere: a reader, which takes longitudes within + // ±180°, would put it on the other side of the world. (In longitude/latitude, below, the + // corners are kept within half a turn of each other instead.) + let back = map.to_map(c).ok_or("a corner is off the Earth")?; + let elsewhere = (back.x - m.x).abs() > 1e-6 * m.x.abs().max(1.0) || (back.y - m.y).abs() > 1e-6 * m.y.abs().max(1.0); + if elsewhere || (system.is_some() && c.x.abs() > 180.0) { + return Err("it crosses its projection's edge (the 180° meridian)"); + } + // On the system's own datum, as a reader that takes its WKT reads them. + let c = match (&system, &def) { + (Some(_), Some(def)) => crs::lonlat_on_datum_of(def, c).ok_or("its corners can't be moved onto its datum")?, + _ => c, + }; + // A value no PDF number can be (from a hostile project) is no place. + if !(c.x.is_finite() && c.y.is_finite()) { + return Err("a corner is off the Earth"); + } + Ok((c.y, c.x)) + }; + // Clockwise from the top-left, as `/LPTS` takes them. + let corners_of = |[x0, y0, x1, y1]: [f64; 4]| -> Result<[(f64, f64); 4], &'static str> { + Ok([place(x0, y0)?, place(x1, y0)?, place(x1, y1)?, place(x0, y1)?]) + }; + let mut corners = corners_of([0.0, 0.0, w, h])?; + let exact = system.is_some(); + let (wkt, epsg) = match &system { + Some((text, code)) => (text.clone(), *code), + None => { + // In longitude/latitude the corners are fitted as they are: across 180° they are kept + // within half a turn of the first, so that the frame isn't taken to span the world. + let first = corners[0].1; + for c in &mut corners { + c.1 = first + ((c.1 - first + 540.0).rem_euclid(360.0) - 180.0); + } + // A reader is right at the corners only: the frame is written if, between them, it + // puts no place more than half a millimetre on paper from where the frame draws it. + match corner_fit_mm(&corners, map, &cam, w, h) { + Some(off) if off <= MAX_CORNER_FIT_MM => {} + Some(_) => { + return Err( + "its coordinate system can't be written as WKT, and its corners alone would put places more than 0.5 mm off", + ); + } + None => return Err("its coordinate system can't be written as WKT, and a place between its corners is off the map"), + } + (wkt::to_wkt(crs::Crs::LonLat).ok_or("its projection can't be read")?, Some(4326)) + } + }; + let first = corners[0].1; + let mut viewports = Vec::with_capacity(shown.len()); + for r in shown { + // The rectangle's corners in the frame's points, the frame being `placed` on the page. + let to = |mm: f64, from: f64, size: f64, pts: f64| (mm - from) / size * pts; + let (x0, y0) = (to(r[0], placed[0], placed[2], w), to(r[1], placed[1], placed[3], h)); + let (x1, y1) = (to(r[0] + r[2], placed[0], placed[2], w), to(r[1] + r[3], placed[1], placed[3], h)); + let mut corners = if *r == placed { corners } else { corners_of([x0, y0, x1, y1])? }; + if !exact { + for c in &mut corners { + c.1 = first + ((c.1 - first + 540.0).rem_euclid(360.0) - 180.0); + } + } + let measure = crate::pdf::GeoMeasure { corners, wkt: wkt.clone(), projected: exact, epsg }; + viewports.push(crate::pdf::Viewport { name: e.name.clone(), rect_mm: *r, measure }); + } + Ok((viewports, exact)) +} + +/// A ring (longitude, latitude), broken at each `None`, placed on a flat map for drawing: where its +/// points go on the map's world, whose middle (its camera's centre) is at `mid`. `from_globe`: the +/// ring is a frame on the globe's, its longitudes run on across ±180° rather than kept in a world. +/// +/// A frame on the globe has its whole ring shifted a turn east or west if that brings the middle +/// of its longitudes nearer the map's middle, as they run on from its first point (#2348), which +/// can be on the other side of ±180° from it: one shift for all keeps it in one piece on a map +/// that doesn't wrap. A flat frame's ring is placed where it is. Then a ring that a map can't show in one piece +/// is cut at the map's edge as the map cuts features (#209), each piece brought into the map's +/// world and running to the edge (#2369): any ring on a world projection, which wraps at its edge +/// (on Robinson centred on 150°E at -30°, with its datum's margin), and on Web Mercator, which +/// doesn't, a globe frame's around a pole, which runs a whole turn, at ±180°. +pub(super) fn ring_on_flat(map: &Map, mid: Option, ring: &[Option], from_globe: bool) -> Vec> { + use rustgis_data::Geometry; + let (west, east) = ring.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(w, e), c| (w.min(c.x), e.max(c.x))); + let around_pole = from_globe && east - west >= 360.0 - 1e-6; + let shift = match (from_globe && !around_pole && west <= east, mid) { + (true, Some(mid)) => 360.0 * ((mid.x - (west + east) / 2.0) / 360.0).round(), + _ => 0.0, + }; + let shifted = ring.iter().map(|c| c.map(|c| Coord::new(c.x + shift, c.y))); + let flat = map.flat(); + let edge = match &flat { + rustgis_map::projection::Flat::Custom(p) => p.edge().copied(), + rustgis_map::projection::Flat::Mercator => None, + }; + if edge.is_none() && !around_pole { + return shifted.collect(); + } + let shifted: Vec> = shifted.collect(); + let runs = shifted.split(Option::is_none).map(|r| r.iter().flatten().copied().collect()).collect(); + let (lon0, margin) = edge.map_or((0.0, None), |e| (e.lon - 180.0, Some(e))); + let margin = |lat: f64| margin.map_or(0.0, |e| e.stray_at(lat)); + // A line cut is a line: the `else` is never taken. + let Geometry::Line(pieces) = rustgis_map::antimeridian::cut_with_margin(&Geometry::Line(runs), lon0, &margin) else { + return shifted; + }; + pieces.into_iter().flat_map(|p| p.into_iter().map(Some).chain([None])).collect() +} + +/// Strokes the ring `ring` (longitude, latitude) on a frame's map `width` points wide: another +/// frame's extent, as an extent indicator shows it, broken at each `None`. `from_globe`: the ring +/// is a frame on the globe's, its longitudes run on across ±180° rather than kept in a world. +pub(super) fn outline_lonlat(pm: &mut Canvas, map: &Map, view: &View, ring: &[Option], from_globe: bool, color: Rgba, width: f32) { + let ppp = view.pixels_per_point as f32; + // On a globe, through the globe as the frame draws it, breaking behind its horizon (#2348): + // through the flat camera the outline lands off the area once it is away from the centre. + let globe = map.projection.is_globe().then(|| rustgis_map::globe::Globe::new(&view.camera, view.width, view.height)); + let placed; + let ring = match globe { + Some(_) => ring, + None => { + placed = ring_on_flat(map, map.to_lonlat(view.camera.center), ring, from_globe); + &placed[..] + } + }; + let project = |c: Coord| match &globe { + Some(g) => g.forward(c), + // A tilted frame's outline breaks where it passes behind the eye, and any frame's where + // its projection can't show the place (#2369). + None => map.to_map(c).and_then(|m| view.camera.try_to_screen(m, view.width, view.height)), + }; + let mut pb = PathBuilder::new(); + let mut first = true; + let mut push = |at: Option<(f64, f64)>| { + let Some((x, y)) = at else { + first = true; + return; + }; + let (x, y) = (x as f32 * ppp, y as f32 * ppp); + if first { + pb.move_to(x, y); + first = false; + } else { + pb.line_to(x, y); + } + }; + let mut previous: Option<(Coord, Option<(f64, f64)>)> = None; + for &c in ring { + let at = c.and_then(project); + if globe.is_none() + && let (Some((last, last_at)), Some(c)) = (previous, c) + && last_at.is_some() != at.is_some() + { + // Reach the overview's projection boundary, rather than stop at the last sample + // inside it (#2433). Keep the valid side of 24 halvings, as frame_outline_lonlat + // does for the source frame's boundary. An explicit gap never enters this search. + let (mut inside, mut outside, mut found) = if last_at.is_some() { (last, c, last_at) } else { (c, last, at) }; + for _ in 0..24 { + // Samples can straddle ±180° on a regional projection without a wrapping edge: + // follow their short arc rather than bisect across the other side of the map. + let lon = inside.x + ((outside.x - inside.x + 540.0).rem_euclid(360.0) - 180.0) / 2.0; + let mid = Coord::new(lon, (inside.y + outside.y) / 2.0); + match project(mid) { + Some(point) => (inside, found) = (mid, Some(point)), + None => outside = mid, + } + } + push(found); + } + push(at); + previous = c.map(|c| (c, at)); + } + if let Some(p) = pb.finish() { + pm.stroke_path(&p, &paint(color, 1.0), &Stroke { width: width * ppp, ..Stroke::default() }, Transform::identity(), None); + } +} diff --git a/crates/render/src/layout/grid.rs b/crates/render/src/layout/grid.rs new file mode 100644 index 0000000000..4331df384f --- /dev/null +++ b/crates/render/src/layout/grid.rs @@ -0,0 +1,502 @@ +//! A map frame's grid: graticule, measured and MGRS lines, and their labels. + +use super::*; + +/// A graticule label as [`Grid::label`] writes it, with plain `'` and `"` for minutes and seconds +/// when the label font has no prime marks. +pub(super) fn grid_label(g: &Grid, v: f64, lon: bool, step: f64) -> String { + let s = g.label(v, lon, step); + if text::covers(&s, false) { s } else { s.replace('′', "'").replace('″', "\"") } +} + +/// A graticule's lines over `ext` (longitude/latitude), each with its label. +pub(super) fn graticule_lines(g: &Grid, ext: Extent, comma: bool, lines: &mut Vec<(Vec, String, bool)>) { + if ext.is_empty() { + return; + } + let span = ext.width().max(ext.height()); + let step = if g.step > 0.0 { + g.step.max(0.001) + } else { + *[0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 15.0, 30.0, 45.0].iter().find(|s| span / **s <= 8.0).unwrap_or(&60.0) + }; + // Lines run a little past the frame so they cross its edges rather than end on them. + let pad = span * 0.02; + let (lat0, lat1) = ((ext.min_y - pad).max(-89.9), (ext.max_y + pad).min(89.9)); + let (lon0, lon1) = (ext.min_x - pad, ext.max_x + pad); + let mut n = 0; + let mut lon = (ext.min_x / step).floor() * step; + while lon <= ext.max_x + step * 1e-9 && n < 200 { + let pts = (0..=48).map(|i| Coord::new(lon, lat0 + (lat1 - lat0) * i as f64 / 48.0)).collect(); + lines.push((pts, decimal(grid_label(g, lon, true, step), comma), true)); + lon += step; + n += 1; + } + let mut lat = (ext.min_y / step).floor() * step; + while lat <= ext.max_y + step * 1e-9 && n < 400 { + if lat.abs() <= 90.0 { + let pts = (0..=48).map(|i| Coord::new(lon0 + (lon1 - lon0) * i as f64 / 48.0, lat)).collect(); + lines.push((pts, decimal(grid_label(g, lat, false, step), comma), false)); + } + lat += step; + n += 1; + } +} + +/// The most lines a measured grid draws each way: past them its step is widened to draw at most +/// [`WIDENED_LINES`]. +pub(super) const MAX_MEASURED_LINES: f64 = 100.0; +/// About how many lines a step too fine for the frame is widened to. +pub(super) const WIDENED_LINES: f64 = 50.0; + +/// A measured grid's lines over the frame whose edges are `lonlats`, in the coordinate system of +/// `tr`: eastings (north–south) and northings, each back in longitude/latitude, with its label. +pub(crate) fn measured_lines( + g: &Grid, + tr: &rustgis_data::raster::Transformer, + lonlats: &[Coord], + comma: bool, + lines: &mut Vec<(Vec, String, bool)>, +) { + let mut ext = Extent::EMPTY; + for c in lonlats.iter().filter_map(|c| tr.from_lonlat(*c)) { + ext.expand(c); + } + if ext.is_empty() || !(ext.width().is_finite() && ext.height().is_finite()) { + return; + } + let span = ext.width().max(ext.height()); + let given = g.step.clamp(0.0, rustgis_map::layout::MAX_MEASURED_STEP); + let step = if given > 0.0 { + given.max(rustgis_map::layout::MIN_MEASURED_STEP) + } else if g.mgrs { + // (At most 100 km apart, so MGRS's squares are drawn whole.) + nice_step(span, rustgis_map::layout::MIN_MEASURED_STEP).min(100_000.0) + } else { + nice_step(span, rustgis_map::layout::MIN_MEASURED_STEP) + }; + // A step too fine for the frame (a 1 m grid over a country) is widened, not drawn as a blur. + let step = if span / step > MAX_MEASURED_LINES { nice_step(span * 8.0 / WIDENED_LINES, step) } else { step }; + let pad = span * 0.02; + let (x0, x1, y0, y1) = (ext.min_x - pad, ext.max_x + pad, ext.min_y - pad, ext.max_y + pad); + let back = |x: f64, y: f64| tr.to_lonlat(Coord::new(x, y)); + // Counted too: at coordinates far larger than the step, adding it may not move a line on. + let most = 2 * MAX_MEASURED_LINES as usize; + let first = |min: f64| (min / step).floor() * step; + for (i, x) in + std::iter::successors(Some(first(ext.min_x)), |x| Some(x + step)).take_while(|x| *x <= ext.max_x + step * 1e-9).enumerate() + { + if i >= most { + break; + } + // (A point that doesn't convert is left out.) + let pts: Vec = (0..=48).filter_map(|i| back(x, y0 + (y1 - y0) * f64::from(i) / 48.0)).collect(); + lines.push((pts, decimal(g.measured_label(x, step), comma), true)); + } + for (i, y) in + std::iter::successors(Some(first(ext.min_y)), |y| Some(y + step)).take_while(|y| *y <= ext.max_y + step * 1e-9).enumerate() + { + if i >= most { + break; + } + let pts: Vec = (0..=48).filter_map(|i| back(x0 + (x1 - x0) * f64::from(i) / 48.0, y)).collect(); + lines.push((pts, decimal(g.measured_label(y, step), comma), false)); + } +} + +/// Where a polyline (in pixels) crosses the edges of a `w` × `h` frame, as (edge, position along +/// it): the top and bottom edges give x, the left and right ones y. +pub(super) fn edge_crossings(pts: &[(f32, f32)], w: f32, h: f32) -> Vec<(Edge, f32)> { + let mut out = Vec::new(); + for pair in pts.windows(2) { + let &[(x0, y0), (x1, y1)] = pair else { continue }; + for (edge, a, b, at) in [(Edge::Top, y0, y1, 0.0), (Edge::Bottom, y0, y1, h), (Edge::Left, x0, x1, 0.0), (Edge::Right, x0, x1, w)] { + let (da, db) = (a - at, b - at); + // Counted once where a vertex sits on the edge, and never along it. + if !((da <= 0.0 && db > 0.0) || (da > 0.0 && db <= 0.0)) { + continue; + } + let t = da / (da - db); + let (along, limit) = match edge { + Edge::Top | Edge::Bottom => (x0 + (x1 - x0) * t, w), + Edge::Left | Edge::Right => (y0 + (y1 - y0) * t, h), + }; + if along.is_finite() && (0.0..=limit).contains(&along) { + out.push((edge, along)); + } + } + } + out +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Edge { + Top, + Bottom, + Left, + Right, +} + +/// The coordinate system of a measured grid on `map`: the grid's own, else the map's when it is +/// projected, else the WGS 84 UTM zone at `center` (longitude/latitude). With MGRS labels, only a +/// WGS 84 UTM zone: the one named, else the map's when it is one, else MGRS's zone at `center`. +/// `None` for one that can't be read or isn't projected. +pub fn measured_crs(g: &Grid, map: &Map, center: Coord) -> Option { + use rustgis_data::raster::Crs; + use rustgis_map::layout::utm_zone_of; + let utm = |(zone, north): (u8, bool)| Crs::from_epsg(if north { 32_600 } else { 32_700 } + u32::from(zone)); + let named = g.crs.as_deref().map(str::trim).filter(|c| !c.is_empty()); + let crs = match named { + // (One longer than a command keeps, from a crafted project, isn't read each frame.) + Some(c) if c.chars().count() > rustgis_map::layout::MAX_GRID_CRS => return None, + Some(c) if g.mgrs => utm(utm_zone_of(c)?)?, + Some(c) => Crs::parse(c).ok()?, + // The map's own: its code (a preset, EPSG:, ESRI: or local:) as its PROJ definition. + None => match &map.projection { + rustgis_map::Projection::Custom(code) if g.mgrs => utm_zone_of(code).and_then(utm), + rustgis_map::Projection::Custom(code) => rustgis_map::projection::lookup(code) + .ok() + .and_then(|(def, _)| Crs::parse(&def).ok()) + .or_else(|| Crs::parse(code).ok()) + .filter(|c| !c.is_geographic()), + _ => None, + } + .map_or_else( + || { + // MGRS's zone at the centre keeps southern Norway's and Svalbard's wider zones. + let c = Coord::new((center.x + 180.0).rem_euclid(360.0) - 180.0, center.y); + match rustgis_geom::utm::utm_zone(c).filter(|_| g.mgrs) { + Some(zone) => utm((zone, center.y >= 0.0)), + None => Crs::from_epsg(rustgis_map::layout::utm_epsg(center.x, center.y)), + } + }, + Some, + )?, + }; + (!crs.is_geographic()).then_some(crs) +} + +/// A step that draws about eight lines across `span`: 1, 2 or 5 times a power of ten. +pub(crate) fn nice_step(span: f64, smallest: f64) -> f64 { + let rough = (span / 8.0).max(smallest); + let p = 10f64.powf(rough.log10().floor()); + [1.0, 2.0, 5.0, 10.0].iter().map(|k| k * p).find(|s| *s >= rough).unwrap_or(10.0 * p) +} + +/// A grid over a frame: lines across it, ticks along its edges or both, labelled at the edges the +/// grid names. A graticule's lines are latitudes and longitudes; a measured grid's are eastings and +/// northings in its coordinate system, bent through it onto the map. Gives the labels drawn: each +/// one's edge and its box in points (left, top, right, bottom). +pub(super) fn draw_grid(pm: &mut Canvas, map: &Map, view: &View, g: &Grid, comma: bool) -> Vec<(Edge, [f32; 4])> { + let ppp = view.pixels_per_point as f32; + // Its labels' size against the default (#2581): their room from the edge and between them, + // and MGRS squares' names, follow in proportion, a point at the default being `unit` pixels. + let k = layout_text_scale(g.label_size, GRID_LABEL_PT) as f32; + let unit = ppp * k; + let (w, h) = (view.width, view.height); + // On a globe, through the globe as the frame draws it (#2337): through the flat camera the + // lines would be laid out as a flat world around it. + let globe = map.projection.is_globe().then(|| rustgis_map::globe::Globe::new(&view.camera, w, h)); + let lonlat_at = |sx: f64, sy: f64| crate::mapgrid::at(map, view, globe.as_ref(), sx, sy); + // The frame's edges in longitude/latitude: its corners and points along each side. + let mut edge_points = Vec::new(); + for i in 0..=8 { + let t = f64::from(i) / 8.0; + edge_points.extend([(w * t, 0.0), (w * t, h), (0.0, h * t), (w, h * t)]); + } + let mut lonlats: Vec = edge_points.iter().filter_map(|&(sx, sy)| lonlat_at(sx, sy)).collect(); + // A frame with an edge past the globe's rim sees the globe's limb: its graticule is the whole + // Earth's, the lines behind the globe left out where they are drawn. A measured grid takes its + // bounds from the part of the globe inside the frame too, the edges missing it. + let rim = globe.is_some() && lonlats.len() < edge_points.len(); + if rim { + for i in 0..=16 { + for j in 0..=16 { + lonlats.extend(lonlat_at(w * f64::from(i) / 16.0, h * f64::from(j) / 16.0)); + } + } + } + let world = Extent::new(-180.0, -90.0, 180.0, 90.0); + let mut ext = if rim { world } else { Extent::EMPTY }; + for c in &lonlats { + ext.expand(*c); + } + if ext.is_empty() { + return Vec::new(); + } + // Each line: its points in longitude/latitude, its label, and whether it runs north–south + // (labelled along the top and bottom first). + let mut lines: Vec<(Vec, String, bool)> = Vec::new(); + // A measured grid's MGRS squares: each one's name and middle, in the frame's points. + let mut squares = Vec::new(); + match g.kind { + GridKind::Graticule => { + // Over the extent of the frame's corners and midpoints, as it always was (its step and + // lines unchanged for the layouts made before measured grids). + let mut corners = if rim { world } else { Extent::EMPTY }; + for (sx, sy) in [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h), (w / 2.0, 0.0), (w / 2.0, h), (0.0, h / 2.0), (w, h / 2.0)] { + if let Some(c) = lonlat_at(sx, sy) { + corners.expand(c); + } + } + graticule_lines(g, corners, comma, &mut lines); + } + GridKind::Measured => { + let center = lonlat_at(w / 2.0, h / 2.0).unwrap_or_else(|| ext.center()); + let Some(crs) = measured_crs(g, map, center) else { return Vec::new() }; + let Ok(tr) = crs.transformer() else { return Vec::new() }; + measured_lines(g, &tr, &lonlats, comma, &mut lines); + if g.mgrs + && g.labels + && let Some((zone, _)) = rustgis_map::layout::utm_zone_of(&crs.epsg().to_string()) + { + let size = |s: &str| (text::measure(s, MGRS_LABEL_PT * k, true), MGRS_LABEL_PT * k * 1.33 * 1.2); + squares = mgrs_squares(map, view, globe.as_ref(), zone, &tr, size); + } + } + } + // A tilted frame's lines break where they pass behind the eye, a globe's behind its horizon. + let to_px = |c: Coord| { + match &globe { + Some(on) => on.forward(c), + None => map.to_map(c).and_then(|m| view.camera.try_to_screen(m, w, h)), + } + .map(|(x, y)| (x as f32 * ppp, y as f32 * ppp)) + .filter(|(x, y)| x.is_finite() && y.is_finite()) + }; + let (pw, ph) = (pm.width() as f32, pm.height() as f32); + let paint_line = paint(g.color, 1.0); + let stroke = Stroke { width: g.width.max(0.0) as f32 * ppp, ..Stroke::default() }; + let tick = if g.style.ticks() { (g.tick_length * PT_PER_MM) as f32 * ppp } else { 0.0 }; + let label_px = GRID_LABEL_PT as f32 * 1.33 * unit; + let label_color = Rgba::rgb(0x20, 0x20, 0x20); + let vertical = g.label_orientation == Orientation::Vertical; + let mut pb = PathBuilder::new(); + // Each label's edge, place along it, text, and whether it is a meridian's. + let mut labels: Vec<(Edge, f32, String, bool)> = Vec::new(); + let mut draw_line = |pb: &mut PathBuilder, pts: Vec, label: String, lon: bool| { + let px: Vec> = pts.into_iter().map(to_px).collect(); + // Runs of points that projected, so a line breaks where its projection does. + for run in px.split(|p| p.is_none()) { + let run: Vec<(f32, f32)> = run.iter().flatten().copied().collect(); + if g.style.lines() { + for (i, (x, y)) in run.iter().enumerate() { + if i == 0 { pb.move_to(*x, *y) } else { pb.line_to(*x, *y) } + } + } + for (edge, at) in edge_crossings(&run, pw, ph) { + if tick > 0.0 { + let (a, b) = match edge { + Edge::Top => ((at, 0.0), (at, tick)), + Edge::Bottom => ((at, ph), (at, ph - tick)), + Edge::Left => ((0.0, at), (tick, at)), + Edge::Right => ((pw, at), (pw - tick, at)), + }; + pb.move_to(a.0, a.1); + pb.line_to(b.0, b.1); + } + let shown = match edge { + Edge::Top => g.edges.top, + Edge::Bottom => g.edges.bottom, + Edge::Left => g.edges.left, + Edge::Right => g.edges.right, + }; + if g.labels && shown { + labels.push((edge, at, label.clone(), lon)); + } + } + } + }; + for (pts, label, lon) in lines { + draw_line(&mut pb, pts, label, lon); + } + if let Some(p) = pb.finish() { + pm.stroke_path(&p, &paint_line, &stroke, Transform::identity(), None); + } + for (s, x, y) in squares { + text::text_at(pm, &s, x * ppp, y * ppp, MGRS_LABEL_PT * 1.33 * unit, label_color, true, text::Align::Center, true); + } + // Labels sit just inside the frame, past the ticks. + let inset = tick + 3.0 * unit; + let along = |edge: Edge, s: &str| match edge { + Edge::Left | Edge::Right if !vertical => label_px, + _ => text::measure(s, label_px / 1.33, false), + }; + // How far a label reaches in from its edge: past the inset, its height, or a side's flat + // label its width. + let across = |edge: Edge, s: &str| { + inset + + match edge { + Edge::Left | Edge::Right if !vertical => text::measure(s, label_px / 1.33, false), + _ => label_px, + } + }; + let mut drawn = Vec::new(); + for (edge, at, s) in kept_labels(labels, (pw, ph), (along, across), label_px, unit) { + let tw = text::measure(&s, label_px / 1.33, false); + // Its centre, and half its size across and down (its halo and descenders included). + let (flat, upright) = ((tw / 2.0, label_px * 0.6), (label_px * 0.6, tw / 2.0)); + let (cx, cy, (hw, hh)) = match edge { + Edge::Top => (at, inset + label_px * 0.4, flat), + Edge::Bottom => (at, ph - inset - label_px * 0.4, flat), + Edge::Left if vertical => (inset + label_px * 0.4, at, upright), + Edge::Right if vertical => (pw - inset - label_px * 0.4, at, upright), + Edge::Left => (inset + tw / 2.0, at, flat), + Edge::Right => (pw - inset - tw / 2.0, at, flat), + }; + if matches!(edge, Edge::Left | Edge::Right) && vertical { + rotated_text(pm, &s, cx, cy, label_px, label_color); + } else { + text::text_at(pm, &s, cx, cy, label_px, label_color, false, text::Align::Center, true); + } + drawn.push((edge, [(cx - hw) / ppp, (cy - hh) / ppp, (cx + hw) / ppp, (cy + hh) / ppp])); + } + drawn +} + +/// The size of a measured grid's MGRS square labels, in points. +pub(super) const MGRS_LABEL_PT: f32 = 10.0; +/// The places across and down a frame where [`mgrs_squares`] looks which square shows. +pub(super) const MGRS_SAMPLES: u32 = 32; + +/// Where a measured grid in UTM zone `zone` (`tr` its transformer) names its MGRS 100 km squares on +/// a frame showing `map` in `view` (through `globe` on a globe, as its lines): each square of the +/// zone, and of each latitude band, that shows, by its grid zone designation and letters +/// (`32T MT`), at the middle of what shows of it, in the frame's points. Only where all of the +/// label, `size(text)` points across and down, stays in its square and well inside the frame, +/// clear of the edge labels. Squares the zone's eastings reach past its edges (a frame across two +/// zones) are named in the other zone, so not here. +pub(super) fn mgrs_squares( + map: &Map, + view: &View, + globe: Option<&rustgis_map::globe::Globe>, + zone: u8, + tr: &rustgis_data::raster::Transformer, + size: impl Fn(&str) -> (f32, f32), +) -> Vec<(String, f32, f32)> { + use rustgis_geom::utm; + let (w, h) = (view.width, view.height); + // The square, and band, a place on the frame is in: none outside the zone. On a globe, the + // place the globe draws there, as the grid's lines (#2337). + let square = |sx: f64, sy: f64| -> Option<(i64, i64, char)> { + let c = crate::mapgrid::at(map, view, globe, sx, sy)?; + // (A copy of the world past ±180° is the same place.) + let c = Coord::new((c.x + 180.0).rem_euclid(360.0) - 180.0, c.y); + if utm::utm_zone(c)? != zone { + return None; + } + let band = utm::latitude_band(c.y)?; + let p = tr.from_lonlat(c)?; + // Across the Equator from the grid's hemisphere, the northing MGRS gives there: the other + // hemisphere's, 10,000 km apart. + let y = match (c.y < 0.0, p.y) { + (true, y) if y < 0.0 => y + 10_000_000.0, + (false, y) if y >= 10_000_000.0 => y - 10_000_000.0, + (_, y) => y, + }; + let (e, n) = ((p.x / 100_000.0).floor(), (y / 100_000.0).floor()); + (e.is_finite() && n.is_finite()).then_some((e as i64, n as i64, band)) + }; + // Each square's samples: their sum across and down, and how many. + let mut seen: std::collections::BTreeMap<(i64, i64, char), (f64, f64, u32)> = std::collections::BTreeMap::new(); + for i in 0..MGRS_SAMPLES { + for j in 0..MGRS_SAMPLES { + let (sx, sy) = (w * (f64::from(i) + 0.5) / f64::from(MGRS_SAMPLES), h * (f64::from(j) + 0.5) / f64::from(MGRS_SAMPLES)); + if let Some(k) = square(sx, sy) { + let e = seen.entry(k).or_default(); + *e = (e.0 + sx, e.1 + sy, e.2 + 1); + } + } + } + let mut out = Vec::new(); + for ((e, n, band), (sx, sy, count)) in seen { + let mid = |k: i64| (k as f64 + 0.5) * 100_000.0; + let Some((column, row)) = utm::square_letters(zone, mid(e), mid(n)) else { continue }; + let text = format!("{zone:02}{band} {column}{row}"); + let (tw, th) = size(&text); + let (cx, cy) = (sx / f64::from(count), sy / f64::from(count)); + let (hw, hh) = (f64::from(tw) / 2.0 + 2.0, f64::from(th) / 2.0 + 2.0); + // Clear of the edges' labels: three label heights in from each edge. + let margin = 3.0 * f64::from(th); + if cx - hw < margin || cx + hw > w - margin || cy - hh < margin || cy + hh > h - margin { + continue; + } + let corners = [(cx - hw, cy - hh), (cx + hw, cy - hh), (cx - hw, cy + hh), (cx + hw, cy + hh)]; + if corners.iter().all(|&(x, y)| square(x, y) == Some((e, n, band))) { + out.push((text, cx as f32, cy as f32)); + } + } + out +} + +/// The graticule labels drawn, of those at each edge crossing (`labels`: edge, place along it, +/// text, a meridian's or not) on a frame `size` pixels, `label_h` tall: away from the corners (all +/// of a label, `along` its edge, fits, and none at a side's ends by a top or bottom label), within +/// the frame across (how far it reaches in from its edge, `across`, at most the frame's other side: +/// one reaching further in is left out, at any size, rather than cut by the frame), and none over +/// another. Meridians are labelled along the top and bottom and parallels along the sides first; a +/// line that leaves the frame through the other edges (a slanting meridian on a projected map) is +/// labelled there only well clear of the labels already set on that edge. Their room from the +/// corners and between them is in `unit`s, a point at the labels' default size in pixels, so it +/// follows their size. +/// A label left out for want of room is thinning, as on any map, not a loss to report: the grid +/// still shows its lines, and the user guide says labels go where there is room. +pub(super) fn kept_labels( + mut labels: Vec<(Edge, f32, String, bool)>, + (pw, ph): (f32, f32), + (along, across): (impl Fn(Edge, &str) -> f32, impl Fn(Edge, &str) -> f32), + label_h: f32, + unit: f32, +) -> Vec<(Edge, f32, String)> { + let own_edge = |edge: Edge, lon: bool| matches!(edge, Edge::Top | Edge::Bottom) == lon; + labels.sort_by_key(|(edge, _, _, lon)| !own_edge(*edge, *lon)); + let mut taken: Vec<(Edge, f32, f32)> = Vec::new(); + let mut kept = Vec::new(); + for (edge, at, s, lon) in labels { + let length = along(edge, &s); + let side = matches!(edge, Edge::Left | Edge::Right); + let (limit, room) = if side { (ph, pw) } else { (pw, ph) }; + if across(edge, &s) > room { + continue; + } + // A side's labels keep two label heights from the corners, below the top's labels and + // above the bottom's, so a corner holds no two. + let margin = (length / 2.0 + 3.0 * unit).max(12.0 * unit).max(if side { 2.0 * label_h } else { 0.0 }); + if at < margin || at > limit - margin { + continue; + } + let (a, z) = (at - length / 2.0 - 2.0 * unit, at + length / 2.0 + 2.0 * unit); + // Off its own edge, a label keeps a further length of its own clear of the others, so + // it doesn't read as one of theirs. + let clear = if own_edge(edge, lon) { 0.0 } else { length }; + if taken.iter().any(|(e, ta, tz)| *e == edge && a - clear < *tz && *ta < z + clear) { + continue; + } + taken.push((edge, a, z)); + kept.push((edge, at, s)); + } + kept +} + +/// One line of haloed text centred on (`cx`, `cy`), turned to read from bottom to top. +pub(super) fn rotated_text(pm: &mut Canvas, s: &str, cx: f32, cy: f32, px: f32, color: Rgba) { + // Whole pixels throughout, so the quarter turn moves pixels without resampling them. + let tw = (text::measure(s, px / 1.33, false) + px * 0.4).ceil().max(1.0); + let th = (px * 1.6).ceil().max(1.0); + let (x, y) = ((cx - th / 2.0).round(), (cy + tw / 2.0).round()); + let t = Transform::from_row(0.0, -1.0, 1.0, 0.0, x, y); + if pm.is_recording() { + pm.with_transform(t, |c| text::text_at(c, s, tw / 2.0, th / 2.0, px, color, false, text::Align::Center, true)); + return; + } + let Some(mut tmp) = Canvas::new(tw as u32, th as u32) else { return }; + text::text_at(&mut tmp, s, tw / 2.0, th / 2.0, px, color, false, text::Align::Center, true); + pm.draw_pixmap( + 0, + 0, + tmp.pixmap().as_ref(), + &PixmapPaint { quality: tiny_skia::FilterQuality::Nearest, ..PixmapPaint::default() }, + t, + None, + ); +} diff --git a/crates/render/src/layout/legend.rs b/crates/render/src/layout/legend.rs new file mode 100644 index 0000000000..46ced5dcad --- /dev/null +++ b/crates/render/src/layout/legend.rs @@ -0,0 +1,789 @@ +//! The legend: its rows, columns, sizes and the wait for service legend pictures. + +use super::*; + +/// Each visible layer's legend for what it draws at a scale denominator (#207), by layer id; a +/// layer that draws nothing there isn't listed. The scale is the one the renderer draws the frame +/// at (the one its layers' scale ranges and display filters see), not the paper scale `{scale}` +/// prints, so the legend follows what the frame actually shows. +pub(super) fn shown_legends(map: &Map, scale: f64, show_no_data: bool, env: &Env) -> Vec<(u32, Vec)> { + map.layers + .iter() + .filter(|l| map.draws_at(l, scale) && legend_lists(l)) + .filter_map(|l| layer_shown(l, scale, show_no_data, env).map(|entries| (l.id, entries))) + .collect() +} + +/// Whether a legend can list a layer: a vector layer, by its symbols, or a raster drawn by classes +/// (a colour table, unique values, class breaks), by its classes (#1679). Not a graphics layer, +/// nor a raster on a ramp or in RGB bands, which a colorbar keys or nothing does. +pub fn legend_lists(l: &rustgis_map::Layer) -> bool { + !l.graphics && l.raster.as_ref().is_none_or(|r| r.style.renderer.draws_classes()) +} + +/// What a layer a legend lists draws at 1:`scale` ([`rustgis_map::Layer::shown_legend`]); for a +/// classified raster, the classes it holds ([`raster_classes`]). `None` when it draws nothing +/// there. +pub(super) fn layer_shown(l: &rustgis_map::Layer, scale: f64, show_no_data: bool, env: &Env) -> Option> { + if l.is_raster() { + return raster_classes(l, false).filter(|classes| l.in_scale_range(scale) && !classes.is_empty()); + } + let mut entries = l.shown_legend_with(scale, env)?; + if show_no_data { + entries.extend(l.renderer.no_data_legend(&l.dataset, Some(&l.drawn_rows_with(scale, env)))); + } + Some(entries) +} + +/// A classified raster's classes as legend rows (#1679), as the Layers pane draws them +/// ([`rustgis_map::RasterLayer::legend_classes`]): a filled swatch with a thin outline, and its +/// label. `None` for a raster on a ramp or in RGB bands, and for a vector layer. +pub(super) fn raster_classes(l: &rustgis_map::Layer, all_classes: bool) -> Option> { + let classes = l.raster.as_ref()?.legend_classes(all_classes)?; + let symbol = |fill| rustgis_map::Symbol { fill, stroke: RASTER_SWATCH_EDGE, stroke_width: 0.5, size: 0.0, marker: Default::default() }; + Some(classes.into_iter().map(|(fill, label)| LegendEntry::plain(label, symbol(fill))).collect()) +} + +/// Names only the source whose read stopped this page, leaving unrelated failures generic. +pub(super) fn failed_source_error(map: &Map, failed_source: Option) -> Option { + let id = failed_source?; + let layer = map.layers.iter().find(|layer| layer.instance_id() == id)?; + layer.source.as_ref()?.read_error().map(|why| format!("{}: {why}", layer.name)) +} + +/// Complete-source legends retain one minimal value per used class, never its geometry. +/// A failed traversal returns its live layer identity for the page's source-error report. +pub(super) fn complete_shown_legends( + map: &mut Map, + scale: f64, + show_no_data: bool, + failed_source: &mut Option, + env: &Env, +) -> Option)>> { + *failed_source = None; + if !map.layers.iter().any(|l| l.source.as_ref().and_then(|s| s.chunk_source()).is_some()) { + return Some(shown_legends(map, scale, show_no_data, env)); + } + let style_env = env.at_scale(Some(scale)); + let wanted: Vec = + map.layers.iter().enumerate().filter(|(_, l)| map.draws_at(l, scale) && legend_lists(l)).map(|(i, _)| i).collect(); + let mut out = Vec::new(); + for index in wanted { + let layer = map.layers.get_mut(index)?; + let Some(source) = layer.source.as_ref().and_then(|s| s.chunk_source()) else { + if let Some(entries) = layer_shown(layer, scale, show_no_data, env) { + out.push((layer.id, entries)); + } + continue; + }; + let unique = match &layer.renderer { + rustgis_map::Renderer::Unique { field, classes, .. } => Some((field, classes)), + _ => None, + }; + // By expression: a feature of each class seen is kept whole, for the legend to class again. + let by_expression = layer.renderer.expression().is_some(); + let fi = unique.filter(|_| !by_expression).and_then(|(field, _)| layer.dataset.field_index(field)); + let fields = if by_expression { + layer.dataset.fields.clone() + } else { + unique + .filter(|_| fi.is_some()) + .map_or_else(Vec::new, |(field, _)| vec![rustgis_data::Field::new(field, rustgis_data::FieldType::Text)]) + }; + let mut sample = rustgis_data::Dataset::new("legend", layer.geometry_type(), fields); + let mut used = std::collections::HashSet::new(); + let mut any = false; + let mut no_data = None; + let mut chunk = layer.clone(); + chunk.source = None; + // Its chunks come in the source's own system. + chunk.dataset.held_in = source.coord_crs(); + chunk.clear_cache(); + let result = crate::visit_complete(source.as_ref(), &mut |features| { + chunk.dataset.features = features.into(); + let rows = chunk.drawn_rows_with(scale, env); + if show_no_data && no_data.is_none() { + no_data = chunk.renderer.no_data_legend(&chunk.dataset, Some(&rows)); + } + let classer = by_expression.then(|| chunk.renderer.classer_with(&chunk.dataset, style_env.clone())); + for row in rows.iter().enumerate().filter_map(|(row, keep)| keep.then_some(row)) { + any = true; + if let Some(c) = &classer { + let key = chunk.renderer.unique_class(&chunk.dataset, row, c).unwrap_or(usize::MAX); + // Kept with its id ($id), without its geometry. + if used.insert(key) + && let Some(f) = chunk.dataset.features.get(row) + { + let mut f = f.clone(); + f.geometry = None; + sample.features.push(f); + } + } else if let Some((_, classes)) = unique { + let value = fi.map(|fi| chunk.dataset.value(row, fi).to_string()); + let key = value.as_ref().and_then(|v| classes.iter().position(|(k, _)| k == v)).unwrap_or(classes.len()); + if used.insert(key) { + sample.push(None, value.map_or_else(Vec::new, |v| vec![rustgis_data::Value::Text(v)])); + } + } + } + chunk.dataset.features = Vec::new().into(); + Ok(()) + }); + if let Err(e) = result { + if let Some(source) = &mut layer.source { + source.error = Some(e.to_string()); + } + *failed_source = Some(layer.instance_id()); + return None; + } + if let Some(source) = &mut layer.source { + source.clear_error(); + } + if any { + // (A sample of the classes seen: classed again at this scale, by expression.) + let mut entries = layer.with_size_legend(layer.renderer.legend_with(&sample, &[], style_env.clone())); + entries.extend(no_data); + out.push((layer.id, entries)); + } + } + Some(out) +} + +/// What a legend leaves out: ``, and layers by name; the labels it shows for +/// layers instead of their names; the scale denominator whose legend pictures a WMS or WMTS +/// layer shows; and how many times its default size its text is ([`legend_size`]). +#[derive(Clone, Copy)] +pub(super) struct LegendOptions<'a> { + pub(super) hide_other: bool, + pub(super) show_no_data: bool, + pub(super) exclude: &'a [String], + pub(super) labels: &'a BTreeMap, + pub(super) scale: f64, + pub(super) size: f32, +} + +/// How many times the default a legend of `text_size` points draws its text, rows, swatches and +/// gaps (#2581): 1 at [`rustgis_map::layout::LEGEND_TEXT_PT`], as legends have always been drawn. +/// A point symbol keeps the size the map draws it at, so a legend of sizes still matches the map. +pub(super) fn legend_size(text_size: f64) -> f32 { + layout_text_scale(text_size, rustgis_map::layout::LEGEND_TEXT_PT) as f32 +} + +impl<'a> LegendOptions<'a> { + /// What the legend shows for the layer named `name`: its label (by name, any case), or the + /// name when it has none (#1654). + pub(super) fn shown(&self, name: &'a str) -> &'a str { + let label = self.labels.get(name).or_else(|| self.labels.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, l)| l)); + label.map(String::as_str).filter(|l| !l.trim().is_empty()).unwrap_or(name) + } +} + +/// A row of a legend: a layer drawn in one symbol (its swatch and name), a layer's name over its +/// classes, or one of them, or a WMS or WMTS layer's legend picture (under its name). The name is +/// the one the legend shows: the layer's label, if the legend gives it one. +pub(super) enum LegendRow<'a> { + Plain(&'a rustgis_map::Layer, &'a str), + Head(&'a str), + Class(&'a rustgis_map::Layer, LegendEntry), + Picture(std::sync::Arc), +} + +impl LegendRow<'_> { + /// The side of the square its point symbol takes at 1:`scale`, in points, as far as its marks + /// reach ([`point_marks::reach`]); 0 for any other row. No larger than a legend picture. + pub(super) fn symbol_side(&self, scale: f64) -> f32 { + let (LegendRow::Plain(l, _) | LegendRow::Class(l, _)) = self else { return 0.0 }; + if l.geometry_type() != GeometryType::Point { + return 0.0; + } + let (s, strokes) = match self { + LegendRow::Class(_, en) => (en.symbol, row_strokes(l, en)), + _ => (l.renderer.symbol_for(&l.dataset, 0), l.line_strokes.as_slice()), + }; + (2.0 * point_marks::reach(&s, strokes) * l.size_factor(scale)).min(MAX_LEGEND_SIDE as f32) + } + + /// Its height at 1:`scale` in a legend `size` times the default ([`legend_size`]), in points: + /// a picture's a pixel a point at the default size, as the Layers pane shows it; a row grows to + /// hold its point symbol. + pub(super) fn height(&self, scale: f64, size: f32) -> f32 { + match self { + LegendRow::Picture(p) => picture_size(p).1 * size, + _ => (LEGEND_ROW * size).max(self.symbol_side(scale)), + } + } + + /// Its width beside a column of swatches `column` points wide ([`swatch_column`]) in a legend + /// `size` times the default, in points. + pub(super) fn width(&self, column: f32, size: f32) -> f32 { + match self { + LegendRow::Plain(_, name) => column + LEGEND_INDENT * size + text::measure(name, LEGEND_NAME_PT * size, false), + LegendRow::Head(name) => text::measure(name, LEGEND_NAME_PT * size, true), + LegendRow::Class(_, en) => column + LEGEND_LABEL_INDENT * size + text::measure(&en.label, LEGEND_LABEL_PT * size, false), + LegendRow::Picture(p) => (LEGEND_INDENT + picture_size(p).0) * size, + } + } +} + +/// Rows at 1:`scale` in a legend `size` times the default laid into at most `columns` columns +/// `limit` points high: the row each column starts at, and whether they all fit. A layer's name +/// stays with the row under it; a row taller than `limit` has a column to itself, and the last +/// column takes what is left. +pub(super) fn flow(rows: &[LegendRow], columns: usize, limit: f32, (scale, size): (f64, f32)) -> (Vec, bool) { + // A thousandth of a row's slack, as the rows have when drawn. + let limit = limit + LEGEND_ROW * size * 1e-3; + let (mut starts, mut used, mut fits, mut i) = (vec![0], 0.0f32, true, 0); + while i < rows.len() { + let end = if matches!(rows[i], LegendRow::Head(_)) { (i + 2).min(rows.len()) } else { i + 1 }; + let part: f32 = rows[i..end].iter().map(|row| row.height(scale, size)).sum(); + if used > 0.0 && used + part > limit && starts.len() < columns { + starts.push(i); + used = 0.0; + } + used += part; + fits &= used <= limit; + i = end; + } + (starts, fits) +} + +/// The rows at 1:`scale` in a legend `size` times the default laid into at most `columns` columns +/// as evenly as they go: where each starts ([`flow`]), and the height of the tallest, in points. +pub(super) fn balanced(rows: &[LegendRow], columns: usize, at: (f64, f32)) -> (Vec, f32) { + let (scale, size) = at; + let total: f32 = rows.iter().map(|row| row.height(scale, size)).sum(); + let (mut low, mut high) = (total / columns as f32, total); + for _ in 0..24 { + let middle = (low + high) / 2.0; + if flow(rows, columns, middle, at).1 { + high = middle; + } else { + low = middle; + } + } + let starts = flow(rows, columns, high, at).0; + let tallest = column_parts(rows, &starts).map(|part| part.iter().map(|row| row.height(scale, size)).sum()).fold(0.0f32, f32::max); + (starts, tallest) +} + +/// The rows of each column, from where they start. +pub(super) fn column_parts<'r, 'a>(rows: &'r [LegendRow<'a>], starts: &'r [usize]) -> impl Iterator]> { + starts.iter().enumerate().map(|(k, &start)| &rows[start..starts.get(k + 1).copied().unwrap_or(rows.len())]) +} + +/// The widest of a column's `rows` at 1:`scale` in a legend `size` times the default, in points. +pub(super) fn widest(rows: &[LegendRow], at: (f64, f32)) -> f32 { + let column = swatch_column(rows, at); + rows.iter().map(|row| row.width(column, at.1)).fold(0.0, f32::max) +} + +/// The stacked strokes a legend's class row draws: its class's own, else its layer's, as +/// [`rustgis_map::Layer::strokes`] finds them for a feature. +pub(super) fn row_strokes<'a>(l: &'a rustgis_map::Layer, en: &'a LegendEntry) -> &'a [rustgis_map::LineStroke] { + if en.strokes.is_empty() { &l.line_strokes } else { &en.strokes } +} + +/// The stacked fills a legend's class row draws: its class's own, else its layer's, as +/// [`rustgis_map::Layer::fills`] finds them for a feature. +pub(super) fn row_fills<'a>(l: &'a rustgis_map::Layer, en: &'a LegendEntry) -> &'a [rustgis_map::fills::FillLayer] { + if en.fills.is_empty() { &l.fill_layers } else { &en.fills } +} + +/// The width of a legend's column of swatches at 1:`scale` in a legend `size` times the default, +/// in points: it grows to hold the widest point symbol, so the labels line up. +pub(super) fn swatch_column(rows: &[LegendRow], (scale, size): (f64, f32)) -> f32 { + rows.iter().map(|row| row.symbol_side(scale)).fold(LEGEND_SWATCH * size, f32::max) +} + +/// A legend picture's size in points (a pixel a point). +pub(super) fn picture_size(p: &rustgis_tiles::cache::Payload) -> (f32, f32) { + match p { + rustgis_tiles::cache::Payload::Image(pm) => (pm.width() as f32, pm.height() as f32), + _ => (0.0, 0.0), + } +} + +/// Whether a legend lists a WMS or WMTS layer: drawn, and with a legend. +pub(super) fn tile_listed(t: &rustgis_map::TileLayer) -> bool { + t.draws() && t.opacity > 0.0 && !t.legends.is_empty() +} + +/// A WMS or WMTS layer's legend picture for the map at 1:`scale`, as the Layers pane shows it: +/// the first of its legends there that is a picture. `None` while the one to show is still on +/// its way (`pending` then set), or when none can be shown. The addresses come from a service or +/// a project, so they are checked as the layer's own are. +pub(super) fn tile_legend( + t: &rustgis_map::TileLayer, + scale: f64, + pending: &mut bool, +) -> Option> { + use rustgis_tiles::cache::{self, Payload, State, Want}; + for l in rustgis_data::ogc::legends_at(&t.legends, scale) { + if rustgis_tiles::address::check(&l.url, Some(&t.url)).is_err() { + continue; + } + match cache::get(&l.url, Want::Image) { + // No larger than the Layers pane shows one. + State::Ready(p) if matches!(&*p, Payload::Image(pm) if pm.width() <= MAX_LEGEND_SIDE && pm.height() <= MAX_LEGEND_SIDE) => { + return Some(p); + } + State::Pending => { + *pending = true; + return None; + } + // The next, if there is one. + _ => {} + } + } + None +} + +/// Whether a legend picture `map`'s WMS and WMTS layers show at 1:`scale` is still on its way +/// (asking for those not yet asked for); those `exclude` names aren't listed, so aren't waited for. +pub fn tile_legends_pending(map: &Map, scale: f64, exclude: &[String]) -> bool { + let mut pending = false; + for t in map.tiles.iter().filter(|t| tile_listed(t) && !exclude.iter().any(|n| n.eq_ignore_ascii_case(&t.name))) { + let _ = tile_legend(t, scale, &mut pending); + } + pending +} + +/// Whether an element lies at least partly on `layout`'s page. The page's drawing and the redraw +/// gate ([`legends_pending`]) share this one test, in millimetres, so no drawing resolution can make +/// them disagree about a legend at the page's edge. +pub(super) fn on_page(layout: &Layout, e: &rustgis_map::layout::Element) -> bool { + e.x + e.w > 0.0 && e.y + e.h > 0.0 && e.x < layout.width && e.y < layout.height +} + +/// Whether a legend on the page `layout` lists a WMS or WMTS layer whose legend picture is still +/// on its way, at its frame's scale. The interactive page is drawn again once it lands. A legend +/// wholly off the page shows none of its pictures, so it is not waited for. +pub fn legends_pending(layout: &Layout, maps: &[Map]) -> bool { + layout.elements.iter().filter(|e| e.visible && on_page(layout, e)).any(|e| { + let ElementKind::Legend { frame, exclude, .. } = &e.kind else { return false }; + let Some(ElementKind::MapFrame { map, center, scale, bearing, pitch, .. }) = layout.element(*frame).map(|f| &f.kind) else { + return false; + }; + let Some(m) = maps.iter().find(|m| m.name.eq_ignore_ascii_case(map)) else { return false }; + let cam = frame_camera(m, *center, *scale, *bearing, *pitch); + tile_legends_pending(m, m.ground_res_at(&cam) / rustgis_geom::PIXEL_M, exclude) + }) +} + +/// Refuses an export stopped during a legend wait, or that drew a legend whose picture was still +/// on its way: it stays refused if the picture lands afterwards, as the file would still lack it. +/// The browser cannot wait; it asks the caller to export again once the pictures land. +pub(crate) fn finish_legends() -> Result<(), String> { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + if crate::cancel::requested() { + return Err(rustgis_data::DataError::Cancelled.to_string()); + } + if LEGEND_MISSING.get() { + return Err( + "legend pictures were still on their way when the export stopped waiting for them; export again once they arrive".into() + ); + } + Ok(()) +} + +/// How long an export waits, natively, for all the legend pictures it shows. +pub(super) const LEGEND_WAIT: web_time::Duration = web_time::Duration::from_secs(30); + +thread_local! { + /// While an export draws on this thread: `Some`, holding the deadline for its legend pictures + /// once its first legend has waited. Every page, element and fallback picture of that export + /// shares it. + pub(super) static LEGEND_BUDGET: std::cell::Cell>> = const { std::cell::Cell::new(None) }; + /// Whether a legend of the export drawing on this thread was drawn without a picture. + pub(super) static LEGEND_MISSING: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// A shorter [`LEGEND_WAIT`] for a test to reach. + #[cfg(test)] + pub(super) static TEST_LEGEND_WAIT: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Ends the budget [`legend_budget`] opened when dropped, even by a panic. +pub(crate) struct LegendBudget(bool); + +impl Drop for LegendBudget { + fn drop(&mut self) { + if self.0 { + LEGEND_BUDGET.set(None); + LEGEND_MISSING.set(false); + } + } +} + +/// Opens one legend-wait budget for the export drawing on this thread, unless one is open (an +/// export of several pages or elements, each drawn through its own call, shares it). +pub(crate) fn legend_budget() -> LegendBudget { + let opened = LEGEND_BUDGET.get().is_none(); + if opened { + LEGEND_BUDGET.set(Some(None)); + LEGEND_MISSING.set(false); + } + LegendBudget(opened) +} + +/// When the open budget's legend wait ends, started by the first legend that waits. +pub(super) fn legend_deadline() -> web_time::Instant { + #[cfg(test)] + let wait = TEST_LEGEND_WAIT.get().unwrap_or(LEGEND_WAIT); + #[cfg(not(test))] + let wait = LEGEND_WAIT; + let fresh = web_time::Instant::now() + wait; + match LEGEND_BUDGET.get() { + Some(Some(deadline)) => deadline, + Some(None) => { + LEGEND_BUDGET.set(Some(Some(fresh))); + fresh + } + None => fresh, + } +} + +/// Waits (natively, until `deadline`) for the legend pictures a legend of `map` at 1:`scale` +/// shows, as a frame waits for its tiles: a page needs them all. Only for those: not for the +/// cache's other fetches, nor for a layer the legend leaves out (`exclude`). `None` when the +/// run was cancelled meanwhile. +pub(super) fn wait_for_tile_legends(map: &Map, scale: f64, exclude: &[String], deadline: web_time::Instant) -> Option<()> { + // In the browser, which can't wait, the page draws what has arrived. + while cfg!(not(target_arch = "wasm32")) && web_time::Instant::now() < deadline && tile_legends_pending(map, scale, exclude) { + if crate::cancel::requested() || rustgis_data::progress::check().is_err() { + return None; + } + std::thread::sleep(std::time::Duration::from_millis(15)); + } + Some(()) +} + +/// The widest and tallest legend picture shown, in pixels, as in the Layers pane, and the largest +/// side of a legend's point symbol, in points. +pub(super) const MAX_LEGEND_SIDE: u32 = 2048; + +/// The outline of a raster class's swatch in a legend, as the Layers pane draws one around it. +pub(super) const RASTER_SWATCH_EDGE: Rgba = Rgba::rgb(0x80, 0x80, 0x80); +/// A legend row's height, in points. +pub(super) const LEGEND_ROW: f32 = 15.0; +/// A legend's title, layers' names and classes' labels, in points, at its default text size; the +/// room its title takes, in rows; and how far a class's swatch and a name's or label's text sit +/// in, in points. Measuring and drawing a legend both take them, times its size ([`legend_size`]). +pub(super) const LEGEND_TITLE_PT: f32 = 12.0; +pub(super) const LEGEND_NAME_PT: f32 = 9.0; +pub(super) const LEGEND_LABEL_PT: f32 = 8.5; +pub(super) const LEGEND_TITLE_ROWS: f32 = 1.3; +pub(super) const LEGEND_INDENT: f32 = 6.0; +pub(super) const LEGEND_LABEL_INDENT: f32 = 12.0; +/// A legend swatch's width, in points. +pub(super) const LEGEND_SWATCH: f32 = 16.0; +/// The room between a legend's columns, in points. +pub(super) const LEGEND_COLUMN_GAP: f32 = 10.0; + +/// The rows of the legend of a frame's map. With `drawn` (from [`shown_legends`]) it shows what the +/// frame draws: only the layers listed there, with their classes. Without, every class of every +/// visible layer. `opts` leaves out `` and the layers it names, either way. +pub(super) fn legend_rows<'a>(map: &'a Map, drawn: Option<&[(u32, Vec)]>, opts: &LegendOptions<'a>) -> Vec> { + legend_rows_missing(map, drawn, opts).0 +} + +/// [`legend_rows`], and whether a WMS or WMTS legend picture was still on its way when the lookup +/// that makes its rows was made (the row is then left out). +pub(super) fn legend_rows_missing<'a>( + map: &'a Map, + drawn: Option<&[(u32, Vec)]>, + opts: &LegendOptions<'a>, +) -> (Vec>, bool) { + let mut missing = false; + let excluded = |name: &str| opts.exclude.iter().any(|n| n.eq_ignore_ascii_case(name)); + let mut rows = Vec::new(); + // In the order the map draws them and the Layers pane lists them, top first. + for item in map.stack() { + let l = match item { + rustgis_map::Drawn::Layer(i) => match map.layers.get(i) { + Some(l) => l, + None => continue, + }, + // A WMS or WMTS layer's legend is its service's picture, whatever the frame draws of it. + rustgis_map::Drawn::Tile(i) => { + if let Some(t) = map.tiles.get(i).filter(|t| tile_listed(t) && !excluded(&t.name)) + && let Some(p) = tile_legend(t, opts.scale, &mut missing) + { + rows.push(LegendRow::Head(opts.shown(&t.name))); + rows.push(LegendRow::Picture(p)); + } + continue; + } + }; + if !(map.shows(l) && legend_lists(l) && !excluded(&l.name)) { + continue; + } + let mut entries = match drawn { + Some(d) => match d.iter().find(|(id, _)| *id == l.id) { + Some((_, entries)) => entries.clone(), + None => continue, + }, + // A classified raster's every class (#1679). + None if l.is_raster() => raster_classes(l, true).unwrap_or_default(), + None => l.with_size_legend(l.renderer.legend()), + }; + if drawn.is_none() && opts.show_no_data { + entries.extend(l.renderer.no_data_legend(&l.dataset, None)); + } + // The fallback row only (a class that happens to bear its name stays). + if opts.hide_other && entries.iter().any(|e| e.fallback) { + entries.retain(|e| !e.fallback); + // Nothing left to show for this layer: leave it out rather than draw its plain swatch + // (unless a diagram lists its categories below). + if entries.is_empty() && l.diagram.is_none() { + continue; + } + } + // A layer with a diagram lists its categories under its classes. + if let Some(d) = &l.diagram { + entries.extend(d.legend(l.geometry_type())); + } + if entries.is_empty() { + // A Unique Values layer that lists nothing draws nothing visible (#207); a raster has + // no symbol of its own to show. + if !l.is_raster() && !matches!(l.renderer, rustgis_map::Renderer::Unique { .. }) { + rows.push(LegendRow::Plain(l, opts.shown(&l.name))); + } + continue; + } + rows.push(LegendRow::Head(opts.shown(&l.name))); + rows.extend(entries.into_iter().map(|en| LegendRow::Class(l, en))); + } + (rows, missing) +} + +/// The legend of a frame's map: its title, and its rows ([`legend_rows`]) under it in `columns` +/// columns, each as wide as its widest row. As even as they go in the height the box leaves; in +/// less, each is filled in turn and the last rows are left out. In a box too narrow they close up, +/// so that none is left out for it: long labels run into the next, and the last column's past the +/// box, as a long label does in one column. +pub(super) fn legend_missing( + pm: &mut Canvas, + r: Rect, + map: &Map, + (title, columns): (&str, usize), + drawn: Option<&[(u32, Vec)]>, + opts: LegendOptions, + ink: Rgba, + ppp: f64, +) -> bool { + let ppp = ppp as f32; + let at = (opts.scale, opts.size); + let mut y = r.y(); + if !title.is_empty() { + let line = LEGEND_ROW * opts.size * ppp; + text::text_at(pm, title, r.x(), y + line / 2.0, LEGEND_TITLE_PT * opts.size * 1.33 * ppp, ink, true, text::Align::Left, false); + y += line * LEGEND_TITLE_ROWS; + } + let (rows, missing) = legend_rows_missing(map, drawn, &opts); + let columns = columns.clamp(1, MAX_LEGEND_COLUMNS); + let starts = flow(&rows, columns, balanced(&rows, columns, at).1.min((r.bottom() - y) / ppp), at).0; + let gap = LEGEND_COLUMN_GAP * opts.size; + let across = (column_parts(&rows, &starts).map(|part| widest(part, at)).sum::() + gap * (starts.len() - 1) as f32) * ppp; + let close_up = if across > r.width() { r.width() / across } else { 1.0 }; + let mut x = r.x(); + for (k, part) in column_parts(&rows, &starts).enumerate() { + // The last has the rest of the box's width. + let right = if k + 1 < starts.len() { x + widest(part, at) * ppp * close_up } else { r.right() }; + let Some(column) = Rect::from_ltrb(x, y, right, r.bottom()) else { break }; + // The room left of it that holds nothing: none at the box's edge, the gap between columns + // as drawn after it. + let lead = if k == 0 { 0.0 } else { gap * ppp * close_up }; + legend_column(pm, column, part, (columns > 1, lead), map, &opts, ink, ppp); + x = right + gap * ppp * close_up; + } + missing +} + +/// [`legend_missing`], for a legend whose missing pictures nobody asks about. +#[cfg(test)] +pub(super) fn legend( + pm: &mut Canvas, + r: Rect, + map: &Map, + title_columns: (&str, usize), + drawn: Option<&[(u32, Vec)]>, + opts: LegendOptions, + ppp: f64, +) { + legend_missing(pm, r, map, title_columns, drawn, opts, INK, ppp); +} + +/// A column of a legend: its rows from the top of `r`, as many as fit. With `name_with_class`, a +/// layer's name only with room for the class under it, as [`flow`] keeps them together. `lead` +/// pixels left of it hold nothing, which its swatches may reach into. +pub(super) fn legend_column( + pm: &mut Canvas, + r: Rect, + rows: &[LegendRow], + (name_with_class, lead): (bool, f32), + map: &Map, + opts: &LegendOptions, + dark: Rgba, + ppp: f32, +) { + let mut y = r.y(); + let size = opts.size; + let line = LEGEND_ROW * size * ppp; + let sw = swatch_column(rows, (opts.scale, size)) * ppp; + // A line's or polygon's swatch, across the column of swatches. + let across = LEGEND_SWATCH * size * ppp; + let mut rows = rows.iter().peekable(); + while let Some(row) = rows.next() { + if let LegendRow::Picture(p) = row { + match &**p { + rustgis_tiles::cache::Payload::Image(pic) => match legend_picture(pm, r, y, pic, ppp * size) { + Some((h, true)) => y += h, + // Cut at the bottom, or no room for it. + _ => break, + }, + _ => continue, + } + continue; + } + // The rectangle's own bottom, which a sum of its top and height can miss by a rounding, + // and a thousandth of a row's slack: a legend sized to its rows keeps the last one. + let height = row.height(opts.scale, size) * ppp; + if y + height > r.bottom() + line * 1e-3 { + break; + } + // A WMS or WMTS layer's name only with room for some of its picture under it. + if let (LegendRow::Head(_), Some(LegendRow::Picture(p))) = (&row, rows.peek()) + && let rustgis_tiles::cache::Payload::Image(pic) = &**p + && y + line + picture_scale(r, pic, ppp * size) > r.bottom() + line * 1e-3 + { + break; + } + if let (true, LegendRow::Head(_), Some(next)) = (name_with_class, &row, rows.peek()) + && matches!(next, LegendRow::Class(..)) + && y + height + next.height(opts.scale, size) * ppp > r.bottom() + line * 1e-3 + { + break; + } + match row { + LegendRow::Plain(l, name) => { + let s = l.renderer.symbol_for(&l.dataset, 0); + let sym = (&s, l.line_strokes.as_slice(), l.fill_layers.as_slice()); + // Its room: left of the column, and the gap before its name. + let room = (lead, LEGEND_INDENT * size * ppp); + swatch(pm, (r.x(), y, sw, height), l, sym, map.layer_opacity(l), opts.scale, (ppp, across, room)); + let (x, pt) = (r.x() + sw + LEGEND_INDENT * size * ppp, LEGEND_NAME_PT * size * 1.33 * ppp); + text::text_at(pm, name, x, y + height / 2.0, pt, dark, false, text::Align::Left, false); + } + LegendRow::Head(name) => { + text::text_at(pm, name, r.x(), y + line / 2.0, LEGEND_NAME_PT * size * 1.33 * ppp, dark, true, text::Align::Left, false); + } + LegendRow::Class(l, en) => { + swatch( + pm, + (r.x() + LEGEND_INDENT * size * ppp, y, sw, height), + l, + (&en.symbol, row_strokes(l, en), row_fills(l, en)), + map.layer_opacity(l), + opts.scale, + // Its room: its indent and what lies left of the column, and the gap before its label. + (ppp, across, (lead + LEGEND_INDENT * size * ppp, (LEGEND_LABEL_INDENT - LEGEND_INDENT) * size * ppp)), + ); + text::text_at( + pm, + &en.label, + r.x() + sw + LEGEND_LABEL_INDENT * size * ppp, + y + height / 2.0, + LEGEND_LABEL_PT * size * 1.33 * ppp, + dark, + false, + text::Align::Left, + false, + ); + } + LegendRow::Picture(_) => {} + } + y += height; + } +} + +/// The pixels a legend picture's pixel takes in the legend `r`: a pixel a point, narrowed to fit +/// across after its indent. +pub(super) fn picture_scale(r: Rect, pic: &Pixmap, ppp: f32) -> f32 { + ppp.min((r.right() - r.x() - 6.0 * ppp).max(0.0) / pic.width().max(1) as f32) +} + +/// Draws a WMS or WMTS layer's legend picture at `y` in the legend `r`, indented as a layer's +/// classes, a pixel a point, narrowed to fit across ([`picture_scale`]). One taller than the room +/// left is cut at the bottom. The height drawn and whether it all fitted; `None` when none of it +/// did. +pub(super) fn legend_picture(pm: &mut Canvas, r: Rect, y: f32, pic: &Pixmap, ppp: f32) -> Option<(f32, bool)> { + let x = r.x() + 6.0 * ppp; + let k = picture_scale(r, pic, ppp); + let room = r.bottom() - y; + // The source rows that fit, a thousandth of a row's slack, as the rows have. + let rows = if k > 0.0 { ((room + LEGEND_ROW * ppp * 1e-3) / k).floor().min(pic.height() as f32) } else { 0.0 }; + if rows < 1.0 { + return None; + } + let shown; + let src = if (rows as u32) < pic.height() { + shown = tiny_skia::IntRect::from_xywh(0, 0, pic.width(), rows as u32).and_then(|c| pic.clone_rect(c))?; + &shown + } else { + pic + }; + pm.draw_pixmap( + 0, + 0, + src.as_ref(), + &PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..PixmapPaint::default() }, + Transform::from_row(k, 0.0, 0.0, k, x, y), + None, + ); + Some((rows * k, (rows as u32) == pic.height())) +} + +/// The size a legend with no title takes in one column, in two and so on, in mm (width, height): +/// its rows as [`legend`] draws them, the classes a frame shows at the renderer's scale denominator +/// `scale` (as the layout finds it for a frame, a complete source read through as [`render`] reads +/// it), or every class with `all_classes`. For sizing a legend to its content. `None` when a +/// complete source can't be read, as [`render`] then draws no page. A WMS or WMTS layer's legend +/// picture still on its way isn't waited for, nor counted ([`tile_legends_pending`] says whether +/// one is). Its layers' rows are measured by the `labels` it shows for them, else their names. +pub fn legend_sizes_mm( + map: &mut Map, + scale: f64, + all_classes: bool, + hide_other: bool, + (exclude, labels): (&[String], &BTreeMap), +) -> Option<[(f64, f64); MAX_LEGEND_COLUMNS]> { + let text_size = rustgis_map::layout::LEGEND_TEXT_PT; + legend_sizes_with_no_data_mm(map, scale, all_classes, hide_other, (false, text_size), (exclude, labels)) +} + +/// Sizes of an optional no-data legend whose text is `text_size` points (#2581), using the same +/// rows and filters as the drawing. +pub fn legend_sizes_with_no_data_mm( + map: &mut Map, + scale: f64, + all_classes: bool, + hide_other: bool, + (show_no_data, text_size): (bool, f64), + (exclude, labels): (&[String], &BTreeMap), +) -> Option<[(f64, f64); MAX_LEGEND_COLUMNS]> { + let drawn = if all_classes { None } else { Some(complete_shown_legends(map, scale, show_no_data, &mut None, &Env::default())?) }; + let size = legend_size(text_size); + let rows = legend_rows(map, drawn.as_deref(), &LegendOptions { show_no_data, hide_other, exclude, labels, scale, size }); + let mm = 25.4 / 96.0; + Some(std::array::from_fn(|i| { + let (starts, height) = balanced(&rows, i + 1, (scale, size)); + let gap = LEGEND_COLUMN_GAP * size * (starts.len() - 1) as f32; + let width: f32 = column_parts(&rows, &starts).map(|part| widest(part, (scale, size))).sum::() + gap; + (f64::from(width) * mm, f64::from(height) * mm) + })) +} + +/// The height in mm [`legend`] gives a title above its rows, which [`legend_sizes_mm`] leaves out, +/// in a legend whose text is `text_size` points (#2581). +pub fn legend_title_mm(text_size: f64) -> f64 { + f64::from(LEGEND_ROW * legend_size(text_size)) * f64::from(LEGEND_TITLE_ROWS) * 25.4 / 96.0 +} diff --git a/crates/render/src/layout/losses.rs b/crates/render/src/layout/losses.rs new file mode 100644 index 0000000000..49b0d4576c --- /dev/null +++ b/crates/render/src/layout/losses.rs @@ -0,0 +1,423 @@ +//! What a page's texts lose: cut lines, boxes off the page, and the notices that say so. + +use super::*; + +/// Visible text elements (and legend and colorbar titles) whose ink crosses the page boundary, +/// or whose lines the text renderer omits at its box's vertical limit or its 200-line limit. +/// Text is not clipped horizontally to its element: a line wider than its box alone is not a +/// loss. Dynamic text uses this page and its first frame, rotated text is checked after its +/// turn, and a wrapped text (a colorbar's title too) by the lines it is broken into. +pub fn clipped_text(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo) -> Vec<(u32, String)> { + text_losses(layout, maps, dpi, info).into_iter().map(|l| (l.id, l.name)).collect() +} + +/// A text element (or a legend's title) [`clipped_text`] finds cut off, with the lines of it +/// left out of the page (#2346). +#[derive(Debug, Clone, PartialEq)] +pub struct TextLoss { + pub id: u32, + pub name: String, + /// Its lines with ink that aren't drawn: below its box, or past the 200 a text draws. 0 when + /// only its ink crosses the page's edge. + pub left_out: usize, + /// It has more lines left out than `left_out` counts: a wrapped text is broken only up to + /// the line past the 200 drawn ([`wrapped`]). + pub at_least: bool, + /// Some of them are left out below its box, among the first 200: a taller box or a smaller + /// text draws them. For a scale bar, its box is too small for its labels and bar + /// ([`BarLayout::cramped`]): its bar drawn below it, or its end label past its side or over + /// its first label. For a colorbar, also set, with no line counted, when its labels would + /// spill out of its box ([`colorbar_plan`]). + pub below_box: bool, + /// Some of them come past the 200 lines a text draws, whatever its box: only splitting the + /// text draws them. + pub past_limit: bool, + /// Some of its ink crosses the page's edge: a text's drawn lines, or a scale bar's labels. + pub off_page: bool, + /// A scale bar's unit label shortened with an ellipsis to fit its room, or left out with no + /// room for even its first character; `None` for a text, or a unit label drawn whole. + pub unit_label: Option, +} + +/// How a scale bar's unit label is cut to fit its room ([`TextLoss::unit_label`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UnitLabelCut { + /// Shortened with an ellipsis. + Shortened, + /// Left out: not even its first character fits. + LeftOut, +} + +/// [`clipped_text`], with how many of each text's lines are left out of its box ([`TextLoss`]): +/// what the layout view, an export and the commands say, so they never tell it apart. +pub fn text_losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo) -> Vec { + losses(layout, maps, dpi, info, None) +} + +/// [`text_losses`] for the element `id` alone, measuring no other: `None` when it isn't cut off. +pub fn text_loss(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, id: u32) -> Option { + losses(layout, maps, dpi, info, Some(id)).pop() +} + +/// Whether a scale bar `e` drawn in `r` puts a label's ink past the page's `size` in pixels, and +/// whether its box is too small for its labels and bar ([`BarLayout::cramped`]), its labels placed +/// by [`bar_layout`] as the drawing places them: their line's middle at `label_y`, each centred on +/// its advance as `text_at` draws it, and its unit label where it is drawn; and whether that unit +/// label is shortened or left out to fit ([`BarLayout::unit_cut`]). `None` when it draws no bar. +pub(super) fn bar_labels_cut( + layout: &Layout, + maps: &[Map], + e: &rustgis_map::layout::Element, + r: Rect, + ppp: f32, + size: (f32, f32), +) -> Option<(bool, bool, Option)> { + let ElementKind::ScaleBar { frame, .. } = &e.kind else { return None }; + let ElementKind::MapFrame { map, center, scale, bearing, pitch, .. } = &layout.element(*frame)?.kind else { return None }; + let m = maps.get(map_index(maps, map)?)?; + let ground = m.ground_res_at(&frame_camera(m, *center, *scale, *bearing, *pitch)); + let bar = bar_layout(r, ground, &BarOptions::of(&e.kind)?, f64::from(ppp), layout.decimal_comma)?; + let (w, h) = size; + // Its labels, centred on their divisions, and its unit label where it is drawn. + let unit = bar.unit.as_ref().map(|u| (u.x, u.y, u.text.as_str(), matches!(u.align, text::Align::Center))); + let drawn = bar.labels.iter().map(|(x, s)| (*x, bar.label_y, s.as_str(), true)).chain(unit); + let off_page = drawn.into_iter().any(|(x, y, s, centred)| { + let pen = if centred { x - text::measure(s, bar.px / 1.33, false) / 2.0 } else { x }; + text::styled_bounds(s, bar.px, text::Face::default(), 0.0) + .is_some_and(|ink| pen + ink.left() < 0.0 || y + ink.top() < 0.0 || pen + ink.right() > w || y + ink.bottom() > h) + }); + Some((off_page, bar.cramped, bar.unit_cut)) +} + +/// The texts cut off, of the whole page or of the element `only`. A text's lines are the ones the +/// page draws ([`drawn_text`]), placed as [`text_block`] places them: its block shifted down its +/// box by its alignment and stepped by its spaced pitch. A block taller than its box starts at its +/// top whatever its alignment, so the same trailing lines are left out and counted as for a text +/// at the top. +pub(super) fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option) -> Vec { + let (w, h, k) = page_geometry(layout, dpi); + let ppp = (k / PT_PER_MM) as f32; + let first = layout.first_frame().and_then(|id| layout.element(id)).and_then(|e| { + let ElementKind::MapFrame { map, center, scale, bearing, pitch, .. } = &e.kind else { return None }; + let m = maps.get(map_index(maps, map)?)?; + Some((m, frame_camera(m, *center, *scale, *bearing, *pitch))) + }); + layout + .elements + .iter() + .filter(|e| e.visible && only.is_none_or(|id| id == e.id)) + .filter_map(|e| { + // At least a pixel each way, as the page draws it. + let r = Rect::from_xywh((e.x * k) as f32, (e.y * k) as f32, ((e.w * k) as f32).max(1.0), ((e.h * k) as f32).max(1.0))?; + // A scale bar's labels where it draws them, at their size (#2581); a bar drawn without + // ink draws none, as a text without ink. + if let ElementKind::ScaleBar { color, .. } = &e.kind { + if color.a() == 0 { + return None; + } + let (off_page, cramped, unit_label) = bar_labels_cut(layout, maps, e, r, ppp, (w as f32, h as f32))?; + return (off_page || cramped || unit_label.is_some()).then(|| TextLoss { + id: e.id, + name: e.name.clone(), + left_out: 0, + at_least: false, + below_box: cramped, + past_limit: false, + off_page, + unit_label, + }); + } + // A colorbar's labels left out for want of height, said with its title (#2638). + let mut labels_cut = false; + // `fits`: how many of its lines the element draws, when it decides that itself. + let (s, size, face, align, spacing, rotation, title, broken, fits, block) = match &e.kind { + ElementKind::Text { + text: t, + size, + color, + bold, + italic, + align, + letter_spacing, + font, + font_name, + rotation, + wrap, + valign, + line_spacing, + case, + .. + } if color.a() > 0 => { + let style = + text_style(*bold, *italic, *font, font_name.as_deref(), *align, *letter_spacing).with_block(*valign, *line_spacing); + // Its lines as they are drawn: in its case, a wrapped text's broken to its box. + let s = drawn_text(expand(t, layout, info, first), *case, *wrap, e.w, *size, style); + ( + s, + *size as f32, + style.face, + *align, + *letter_spacing as f32, + *rotation as f32, + false, + *wrap, + None, + (style.valign, style.line_spacing), + ) + } + // Its title at the size it is drawn at, its legend's text size (#2581). + ElementKind::Legend { title, frame, text_size, .. } => { + let ElementKind::MapFrame { map, .. } = &layout.element(*frame)?.kind else { return None }; + map_index(maps, map)?; + let size = LEGEND_TITLE_PT * legend_size(*text_size); + ( + title.clone(), + size, + text::Face { bold: true, ..Default::default() }, + TextAlign::Left, + 0.0, + 0.0, + true, + false, + None, + (TextVAlign::Top, USUAL_LINE_SPACING), + ) + } + // A colorbar's title in the lines it is drawn in (#2493), when it draws one: its + // frame's map has a raster with a colour scale (else it draws a placeholder). + // Its labels, too, when they would spill out of the element (#2638), as the colorbar + // lays them out ([`colorbar_plan`]). + ElementKind::Colorbar { frame, layer, title, orientation, ticks, tick_side, reverse, .. } => { + let ElementKind::MapFrame { map, .. } = &layout.element(*frame)?.kind else { return None }; + let m = maps.get(map_index(maps, map)?)?; + let scale = rustgis_map::layout::colorbar_layer(m, layer.as_deref()) + .and_then(|l| l.raster.as_ref()) + .and_then(rustgis_map::layout::color_scale)?; + let bar = Bar { + title, + orientation: *orientation, + ticks: *ticks, + side: *tick_side, + reverse: *reverse, + comma: layout.decimal_comma, + ink: INK, + }; + let plan = colorbar_plan(r, &scale, &bar, ppp); + let lines = if title.is_empty() { Vec::new() } else { colorbar_title_lines(title, e.w) }; + let fits = plan.title.len(); + labels_cut = plan.spilled > 0; + if lines.is_empty() && !labels_cut { + return None; + } + let s = lines.join("\n"); + ( + s, + COLORBAR_TITLE_PT as f32, + colorbar_title_style().face, + TextAlign::Left, + 0.0, + 0.0, + false, + true, + Some(fits), + (TextVAlign::Top, USUAL_LINE_SPACING), + ) + } + _ => return None, + }; + let px = size.clamp(2.0, 400.0) * 1.33 * ppp; + // A legend's title sits in the middle of its first row, which grows with its size. + // A text's first line, where its block alignment puts it ([`block_shift`]). + let mut cy = if title { + r.y() + LEGEND_ROW * (size / LEGEND_TITLE_PT) * ppp / 2.0 + } else { + let shift = text_shift(block.0, f64::from(r.height()), f64::from(px), &s, f64::from(block.1)) as f32; + r.y() + shift + px * 0.6 + }; + let turn = Transform::from_rotate_at(rotation, r.x() + r.width() / 2.0, r.y() + r.height() / 2.0); + // Legend titles are drawn on one line, unlike text elements' explicit line breaks. + let lines = std::iter::once(s.as_str()).filter(|_| title).chain(s.lines().filter(|_| !title)); + let (mut cut, mut left_out, mut below_box, mut past_limit, mut off_page) = (false, 0, false, false, false); + for (i, line) in lines.enumerate() { + let drawn = match fits { + Some(n) => i < n, + None => i < 200 && (title || cy <= r.bottom() + px), + }; + // A line not drawn is only looked at for a letter, as a wrapped text tells its + // ink ([`crate::report::wrap_lines`]): a long text isn't shaped past its box. + if !drawn { + if line.chars().any(|c| !c.is_whitespace()) { + (cut, left_out) = (true, left_out + 1); + if i < 200 { + below_box = true; + } else { + past_limit = true; + } + } + continue; + } + let ink = text::styled_bounds(line, px, face, spacing * 1.33 * ppp); + off_page |= ink.is_some_and(|ink| { + let left = match align { + TextAlign::Left => r.x(), + TextAlign::Center => r.x() + (r.width() - ink.width()) / 2.0 - ink.left(), + TextAlign::Right => r.right() - ink.width() - ink.left(), + }; + let mut corners = [ + tiny_skia::Point::from_xy(left + ink.left(), cy + ink.top()), + tiny_skia::Point::from_xy(left + ink.right(), cy + ink.top()), + tiny_skia::Point::from_xy(left + ink.left(), cy + ink.bottom()), + tiny_skia::Point::from_xy(left + ink.right(), cy + ink.bottom()), + ]; + turn.map_points(&mut corners); + corners.iter().any(|p| p.x < 0.0 || p.y < 0.0 || p.x > w as f32 || p.y > h as f32) + }); + cy += px * 1.25 * block.1; + } + // A wrapped text ends at the line past the 200 drawn ([`wrapped`]): it may go on. + let at_least = broken && s.lines().nth(200).is_some(); + below_box |= labels_cut; + (cut || off_page || labels_cut).then(|| TextLoss { + id: e.id, + name: e.name.clone(), + left_out, + at_least, + below_box, + past_limit, + off_page, + unit_label: None, + }) + }) + .collect() +} + +/// One counted notice per kind, naming the affected elements by their stable address. Exports +/// can merge repeated element IDs across series pages before calling this, so a PDF's fallback +/// rendering and repeated pages never multiply the count. Its advice fits the texts of `layout` +/// named: breaking lines by hand or wrapping them for a text not wrapped (#2346), only the box or +/// the size when all are wrapped to their boxes, and line breaks without the wrap for a legend's +/// title, which has none. +pub fn clipped_text_notice(layout: &Layout, clipped: &[(u32, String)]) -> Option { + if clipped.is_empty() { + return None; + } + let mut names = clipped.iter().take(10).map(|(id, name)| format!("{name} ({id})")).collect::>().join(", "); + if clipped.len() > 10 { + names.push_str(&format!(" and {} more", clipped.len() - 10)); + } + // Each text's wrap; `None` for a legend's or a colorbar's title, or an element gone since, + // which keep the advice they always had. + let wraps = clipped + .iter() + .map(|(id, _)| match layout.element(*id).map(|e| &e.kind) { + Some(ElementKind::Text { wrap, .. }) => Some(*wrap), + _ => None, + }) + .collect::>(); + // Scale bars alone: their labels are no text to break (#2581). + let bars = clipped.iter().all(|(id, _)| matches!(layout.element(*id).map(|e| &e.kind), Some(ElementKind::ScaleBar { .. }))); + // Colorbars alone: their titles already wrap, and a tick label isn't fixed by a line break + // (#2638). + let colorbars = clipped.iter().all(|(id, _)| matches!(layout.element(*id).map(|e| &e.kind), Some(ElementKind::Colorbar { .. }))); + let advice = if bars && clipped.len() == 1 { + "move it inside the page or make its box larger, or reduce its text size" + } else if bars { + "move them inside the page or make their boxes larger, or reduce their text size" + } else if colorbars { + "make the colorbar larger or its title shorter, so its title lines and tick labels fit" + } else if wraps.contains(&Some(false)) { + "resize or move the text, reduce its size, add line breaks, or turn on Wrap to the box" + } else if wraps.iter().all(|w| *w == Some(true)) { + "resize or move the text, or reduce its size" + } else { + "resize or move the text, reduce its size, or add line breaks" + }; + Some(format!("Text is cut off in {} layout element(s): {names}; {advice}", clipped.len())) +} + +/// What scale bars whose labels don't fit are told (#2581), from their [`TextLoss`]es: one notice +/// a kind, with the bars' count and names. Their boxes too small for their labels and bars (a bar +/// drawn below its box, or an end label past its side), a label off the page, and a unit label +/// shortened or left out to fit ([`UnitLabelCut`]), each said of every bar it is true of. +pub fn scale_bar_fit_notices(losses: &[TextLoss]) -> Vec { + let said = |small: bool| { + let kind = |l: &&TextLoss| if small { l.below_box } else { l.off_page }; + let names: Vec = losses.iter().filter(kind).map(|l| format!("\"{}\"", l.name)).collect(); + let (n, names) = (names.len(), names.join(", ")); + match (n, small) { + (0, _) => None, + (1, true) => Some(format!( + "Scale bar {names}: its box is too small for its labels at their size, so they or its bar run past it; make it larger or reduce its text size" + )), + (1, false) => Some(format!("Scale bar {names}: a label runs off the page; move it inside the page or reduce its text size")), + (_, true) => Some(format!( + "{n} scale bars ({names}): their boxes are too small for their labels at their size, so they or their bars run past them; make them larger or reduce their text size" + )), + (_, false) => { + Some(format!("{n} scale bars ({names}): a label runs off the page; move them inside the page or reduce their text size")) + } + } + }; + // A unit label shortened to fit, or left out with no room for it. + let unit_said = |cut: UnitLabelCut| { + let names: Vec = losses.iter().filter(|l| l.unit_label == Some(cut)).map(|l| format!("\"{}\"", l.name)).collect(); + let (n, names) = (names.len(), names.join(", ")); + match (n, cut) { + (0, _) => None, + (1, UnitLabelCut::Shortened) => Some(format!( + "Scale bar {names}: its unit label is shortened to fit; make its box larger, reduce its text size or shorten the unit label" + )), + (1, UnitLabelCut::LeftOut) => Some(format!( + "Scale bar {names}: its unit label is left out, as there is no room for it; make its box larger, reduce its text size or shorten the unit label" + )), + (_, UnitLabelCut::Shortened) => Some(format!( + "{n} scale bars ({names}): their unit labels are shortened to fit; make their boxes larger, reduce their text size or shorten the unit labels" + )), + (_, UnitLabelCut::LeftOut) => Some(format!( + "{n} scale bars ({names}): their unit labels are left out, as there is no room for them; make their boxes larger, reduce their text size or shorten the unit labels" + )), + } + }; + [said(true), said(false), unit_said(UnitLabelCut::Shortened), unit_said(UnitLabelCut::LeftOut)].into_iter().flatten().collect() +} + +/// What a text that loses lines is told (#2346), from its [`TextLoss`]: `None` when none of its +/// lines is left out. Lines below its box want a taller box or a smaller text; lines past the 200 +/// a text draws, splitting the text, as no box draws them. +pub fn lines_left_out_notice(loss: &TextLoss) -> Option { + let n = loss.left_out; + if n == 0 && !loss.at_least { + return None; + } + let (count, one) = match (n, loss.at_least) { + (1, false) => ("1 line".to_string(), true), + (n, false) => (format!("{n} lines"), false), + (n, true) => (format!("{} or more lines", n.max(1)), false), + }; + let said = match (loss.below_box, loss.past_limit) { + (_, false) => { + let verbs = if one { "doesn't fit its box and isn't" } else { "don't fit its box and aren't" }; + format!("{verbs} drawn; make the box taller or the text smaller") + } + (false, true) => { + format!("{} drawn: a text draws at most 200 lines; split it into more than one text", if one { "isn't" } else { "aren't" }) + } + (true, true) => format!( + "{} drawn: make the box taller or the text smaller, and split it, as a text draws at most 200 lines", + if one { "isn't" } else { "aren't" } + ), + }; + Some(format!("{count} of the text \"{}\" ({}) {said}", loss.name, loss.id)) +} + +/// What a text whose ink crosses the page's edge is told (#2703), from its [`TextLoss`]: `None` +/// when none does. Its lines left out below its box are [`lines_left_out_notice`]'s: a text can +/// have both, and each is said. +pub fn off_page_notice(loss: &TextLoss) -> Option { + loss.off_page.then(|| { + format!( + "The text \"{}\" ({}) runs off the page, so part of it isn't drawn; move it inside the page, resize it or reduce its size", + loss.name, loss.id + ) + }) +} diff --git a/crates/render/src/layout/north.rs b/crates/render/src/layout/north.rs new file mode 100644 index 0000000000..93e062b865 --- /dev/null +++ b/crates/render/src/layout/north.rs @@ -0,0 +1,60 @@ +//! The north arrow. + +use super::*; + +/// A north arrow in `style`, with an `N` above it, pointing north on a map turned to `bearing` +/// (degrees clockwise from north): turned about the middle of `r`, the `N` kept upright. +pub(super) fn north_arrow(pm: &mut Canvas, r: Rect, style: ArrowStyle, fill: Rgba, outline: Rgba, ppp: f64, bearing: f64) { + let white = Rgba::rgb(0xFF, 0xFF, 0xFF); + let sw = 0.8 * ppp as f32; + let (cx, top) = (r.x() + r.width() / 2.0, r.y()); + let label_h = (r.height() * 0.25).min(14.0 * ppp as f32); + let (tip, base) = (top + label_h + 2.0, r.y() + r.height()); + // North lies `bearing` anticlockwise of the page's up. + let (sin, cos) = if bearing.is_finite() { (-bearing.to_radians()).sin_cos() } else { (0.0, 1.0) }; + let (sin, cos) = (sin as f32, cos as f32); + let (mx, my) = (cx, r.y() + r.height() / 2.0); + let turn = |(x, y): (f32, f32)| { + let (dx, dy) = (x - mx, y - my); + (mx + dx * cos - dy * sin, my + dx * sin + dy * cos) + }; + let shape = |pm: &mut Canvas, pts: &[(f32, f32)], fill: Rgba, outline: Rgba, sw: f32| { + let pts: Vec<(f32, f32)> = pts.iter().map(|p| turn(*p)).collect(); + shape(pm, &pts, fill, outline, sw) + }; + match style { + ArrowStyle::Classic => { + let s = (r.width() * 0.5).min(r.height() * 0.32); + let mid = tip + (base - tip) * 0.68; + shape(pm, &[(cx, tip), (cx - s, base), (cx, mid)], fill, fill, sw); + shape(pm, &[(cx, tip), (cx + s, base), (cx, mid)], white, outline, sw); + } + ArrowStyle::Triangle => { + let s = (r.width() * 0.4).min(r.height() * 0.25); + shape(pm, &[(cx, tip), (cx + s, base), (cx - s, base)], fill, outline, sw); + } + ArrowStyle::Compass | ArrowStyle::Star => { + let cy = (tip + base) / 2.0; + let rad = (r.width() / 2.0).min((base - tip) / 2.0); + let arm = |pm: &mut Canvas, angle: f32, len: f32, half: f32| { + // An arm from the centre, split down its length: one half filled, one light. + let (dx, dy) = (angle.sin(), -angle.cos()); + let end = (cx + dx * len, cy + dy * len); + let (lx, ly) = (cx + dy * half, cy - dx * half); + let (rx, ry) = (cx - dy * half, cy + dx * half); + shape(pm, &[(cx, cy), end, (lx, ly)], fill, outline, sw); + shape(pm, &[(cx, cy), end, (rx, ry)], white, outline, sw); + }; + if style == ArrowStyle::Star { + for k in 0..4 { + arm(pm, std::f32::consts::FRAC_PI_4 + k as f32 * std::f32::consts::FRAC_PI_2, rad * 0.6, rad * 0.14); + } + } + for k in 0..4 { + arm(pm, k as f32 * std::f32::consts::FRAC_PI_2, rad, rad * 0.2); + } + } + } + let (nx, ny) = turn((cx, top + label_h / 2.0)); + text::text_at(pm, "N", nx, ny, label_h * 1.1, outline, true, text::Align::Center, false); +} diff --git a/crates/render/src/layout/scale_bar.rs b/crates/render/src/layout/scale_bar.rs new file mode 100644 index 0000000000..9c7daf4720 --- /dev/null +++ b/crates/render/src/layout/scale_bar.rs @@ -0,0 +1,646 @@ +//! The scale bar: its plan, fit and drawing. + +use super::*; + +/// A scale bar label for `v`, a multiple of `step`: with the decimals the step needs (up to 6), so +/// 0.0125 km stays 0.0125 rather than rounding to 0.01. A step with no exact decimal (a third) +/// keeps two significant digits of it. +pub(super) fn scale_number(v: f64, step: f64) -> String { + let places = (0..6usize) + .find(|&n| { + let k = step * 10f64.powi(n as i32); + (k - k.round()).abs() < 1e-9 * k.abs().max(1.0) + }) + .unwrap_or_else(|| { + let mag = if step.is_finite() && step > 0.0 { step.log10().floor() } else { 0.0 }; + (1.0 - mag).clamp(0.0, 6.0) as usize + }); + let s = format!("{v:.prec$}", prec = places); + if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s } +} + +/// A scale bar's number for `v`, a multiple of `step`, with a decimal comma when `comma`. With no +/// `decimals` (auto), as [`scale_number`] prints it and no thousands separators, as bars always +/// printed; with 0 to [`MAX_SCALE_DECIMALS`](rustgis_map::layout::MAX_SCALE_DECIMALS), that many +/// places and the thousands apart. A minus only in front of a digit other than zero; NaN and +/// infinity print 0. +pub(super) fn bar_number(v: f64, step: f64, decimals: Option, comma: bool) -> String { + let v = if v.is_finite() { v } else { 0.0 }; + let body = match decimals { + None => decimal(scale_number(v.abs(), step), comma), + Some(d) => { + let places = d.min(rustgis_map::layout::MAX_SCALE_DECIMALS); + let s = format!("{:.*}", places, v.abs()); + let (whole, part) = s.split_once('.').unwrap_or((s.as_str(), "")); + let whole = rustgis_map::graphics::thousands(whole.parse().unwrap_or(0.0)); + if part.is_empty() { decimal(whole, comma) } else { decimal(format!("{whole}.{part}"), comma) } + } + }; + if v < 0.0 && body.chars().any(|c| matches!(c, '1'..='9')) { format!("-{body}") } else { body } +} + +/// The share of its element's width a scale bar's length may take. +pub(super) const BAR_SHARE: f64 = 0.85; +/// How far a scale bar starts in from the element's left edge at its labels' default size, in +/// pixels. [`scale_bar_width_pt`] counts that inset as as many points: when a point is a pixel or +/// more, a pixel is no larger than a point, so the box is never too narrow. It follows the labels' +/// size, as their room does (#2581). +pub(super) const BAR_INSET: f32 = 2.0; +/// How far a scale bar label's digits rise above the middle of their line, in label sizes: what +/// the room over the bar holds. +pub(super) const BAR_LABEL_RISE: f32 = 0.5; +/// How far the middle of a scale bar's labels' line sits over the bar's top, in label sizes. +pub(super) const BAR_LABEL_MID: f32 = 0.7; + +/// What a scale bar counts: its whole length in its unit, that unit in metres and its abbreviation. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct BarPlan { + pub(super) total: f64, + pub(super) unit_m: f64, + pub(super) abbr: &'static str, +} + +/// The bar a scale bar draws in an element `width_pt` points wide at `ground_per_pt` ground metres +/// a point: the roundest length within [`BAR_SHARE`] of the width. `None` when it draws none. +pub(super) fn bar_plan(ground_per_pt: f64, width_pt: f64, units: ScaleUnits) -> Option { + if !(ground_per_pt.is_finite() && ground_per_pt > 0.0 && width_pt.is_finite()) { + return None; + } + let room_m = ground_per_pt * width_pt * BAR_SHARE; + let (unit_m, abbr) = units.resolve(rustgis_geom::nice_distance(room_m)); + let total = rustgis_geom::nice_distance(room_m / unit_m); + (total > 0.0).then_some(BarPlan { total, unit_m, abbr }) +} + +/// A scale bar's label at division `i` of `divisions`, the last with the unit. +pub(super) fn bar_label(total: f64, divisions: usize, i: usize, abbr: &str, comma: bool) -> String { + let v = decimal(scale_number(total * i as f64 / divisions as f64, total / divisions as f64), comma); + if i == divisions { format!("{v} {abbr}") } else { v } +} + +/// The narrowest element, in points, in which a scale bar draws the same bar as in one `width_pt` +/// wide (its length, unit and divisions), its last label at its `text_size` and `pad_pt` after it +/// included, so a box can be the size of its bar (#1379). `width_pt` when no narrower one draws +/// that bar; `None` when it draws none. +pub fn scale_bar_width_pt(ground_per_pt: f64, width_pt: f64, bar: (ScaleUnits, usize, f64), comma: bool, pad_pt: f64) -> Option { + let (units, divisions, text_size) = bar; + let k = layout_text_scale(text_size, SCALE_BAR_TEXT_PT); + let plan = bar_plan(ground_per_pt, width_pt, units)?; + let divisions = divisions.clamp(1, rustgis_map::layout::MAX_SCALE_DIVISIONS); + let len = plan.total * plan.unit_m / ground_per_pt; + let last = bar_label(plan.total, divisions, divisions, plan.abbr, comma); + let half = f64::from(text::measure(&last, (SCALE_BAR_TEXT_PT * k) as f32, false)) / 2.0; + let inset = f64::from(bar_inset(&bar_label(plan.total, divisions, 0, plan.abbr, comma), k as f32, 1.0)); + // A little over the share the bar takes, so the f32 rectangle an export rebuilds the width + // from (its error growing with the element's place on the page) doesn't pick the next shorter + // length: a ten-thousandth, 0.003 mm on a 30 mm box. + let w = (len / BAR_SHARE * (1.0 + 1e-4)).max(inset + len + half + pad_pt); + Some(if w < width_pt && bar_plan(ground_per_pt, w, units) == Some(plan) { w } else { width_pt }) +} + +/// [`scale_bar_width_pt`] for the scale bar `bar` as it is set: the narrowest element, in points, +/// in which it draws the same bar as in one `width_pt` wide, with every setting it has (its +/// subdivisions, divisions before zero, labels, unit label and where it sits, decimals, fit and +/// text size), its ink and `pad_pt` after it included, as [`bar_layout`] places it for the +/// drawing. A bar without the details is measured as [`scale_bar_width_pt`] measures it, so its +/// box is the one it always had. `width_pt` when no narrower one draws that bar; `None` when it +/// draws none, or `bar` is no scale bar. +pub fn scale_bar_box_width_pt(ground_per_pt: f64, width_pt: f64, bar: &ElementKind, comma: bool, pad_pt: f64) -> Option { + let options = BarOptions::of(bar)?; + if !bar.scale_bar_uses_details() { + return scale_bar_width_pt(ground_per_pt, width_pt, (options.units, options.divisions, options.text_size), comma, pad_pt); + } + // At a point a pixel; the height leaves the width as it is. + let place = |w: f64| Rect::from_xywh(0.0, 0.0, w as f32, 60.0).and_then(|r| bar_layout(r, ground_per_pt, &options, 1.0, comma)); + let wide = place(width_pt)?; + let unit = |b: &BarLayout| b.unit.as_ref().map(|u| u.text.clone()); + let labels = |b: &BarLayout| b.labels.iter().map(|(_, s)| s.clone()).collect::>(); + // The same bar: its length and divisions, each label and its unit label written in full as + // they are in the wider box, and its ink and padding inside the box. + let same = |w: f64| { + place(w).is_some_and(|b| { + b.total == wide.total + && b.divs == wide.divs + && labels(&b) == labels(&wide) + && unit(&b) == unit(&wide) + && f64::from(b.right) + pad_pt <= w + }) + }; + if !same(width_pt) { + return Some(width_pt); + } + // A narrower box draws a bar no longer: the narrowest one that draws this one, halved for, to + // a hundredth of a point: a frame dragged measures its box on every move, so no further. + let (mut lo, mut hi) = (0.0, width_pt); + for _ in 0..48 { + if hi - lo <= 0.01 { + break; + } + let mid = (lo + hi) / 2.0; + if same(mid) { hi = mid } else { lo = mid } + } + // A little over, as for a plain bar, so the f32 rectangle an export rebuilds the width from + // doesn't pick the next shorter length. + let w = hi * (1.0 + 1e-4); + Some(if w < width_pt && same(w) { w } else { width_pt }) +} + +/// How far a scale bar starts in from its box's left side, in pixels, for its first label `first` +/// at `k` times the default size (#2581): [`BAR_INSET`] in proportion, or more, so that label +/// reaches no further past the side than it does at the default size, as the bar moves down to +/// keep its labels from reaching higher. At the default size, [`BAR_INSET`]: pixels, as the +/// drawing has always placed the bar, not following `ppp`, which only the labels' widths do. +pub(super) fn bar_inset(first: &str, k: f32, ppp: f32) -> f32 { + let half = |k: f32| text::measure(first, SCALE_BAR_TEXT_PT as f32 * k * ppp, false) / 2.0; + (BAR_INSET * k).max(half(k) - (half(1.0) - BAR_INSET).max(0.0)) +} + +/// A scale bar's look: the fields of [`ElementKind::ScaleBar`] but its frame and colours. +#[derive(Clone, Copy, Debug)] +pub(super) struct BarOptions<'a> { + pub(super) units: ScaleUnits, + pub(super) divisions: usize, + pub(super) style: ScaleBarStyle, + pub(super) subdivisions: usize, + pub(super) divisions_before_zero: usize, + pub(super) label_position: ScaleLabelPosition, + pub(super) unit_label: Option<&'a str>, + pub(super) unit_label_position: UnitLabelPosition, + pub(super) decimals: Option, + pub(super) text_size: f64, + pub(super) fit: ScaleBarFit, +} + +impl<'a> BarOptions<'a> { + /// A scale bar element's look; `None` for any other element. + pub(super) fn of(kind: &'a ElementKind) -> Option> { + let ElementKind::ScaleBar { + units, + divisions, + style, + subdivisions, + divisions_before_zero, + label_position, + unit_label, + unit_label_position, + decimals, + text_size, + fit, + .. + } = kind + else { + return None; + }; + Some(BarOptions { + units: *units, + divisions: *divisions, + style: *style, + subdivisions: *subdivisions, + divisions_before_zero: *divisions_before_zero, + label_position: *label_position, + unit_label: unit_label.as_deref(), + unit_label_position: *unit_label_position, + decimals: *decimals, + text_size: *text_size, + fit: *fit, + }) + } +} + +/// A new scale bar's look. +#[cfg(test)] +impl Default for BarOptions<'_> { + fn default() -> Self { + static PLAIN: std::sync::LazyLock = std::sync::LazyLock::new(|| ElementKind::scale_bar(0)); + BarOptions::of(&PLAIN).expect("a scale bar") + } +} + +/// How long a scale bar is and how it divides: its whole length in its unit, any divisions before +/// zero included, and its divisions after zero. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct BarFit { + pub(super) total: f64, + pub(super) after: usize, +} + +/// A scale bar of `before` divisions before zero and `after` after it, counting in a unit `unit_m` +/// metres long, fitted to `room_m` ground metres by `fit`: the roundest length divided as asked +/// (`AdjustDivisionValue`, the length [`bar_plan`] takes), as many round divisions as fit +/// (`AdjustDivision`), or the asked divisions each a round length (`AdjustWidth`); under every fit +/// at most ten in all, the divisions before zero included. `None` when it draws none. +pub(super) fn bar_fit(room_m: f64, unit_m: f64, fit: ScaleBarFit, before: usize, after: usize) -> Option { + // Ten in all under every fit, the divisions before zero among them, and at least one after zero. + let most = rustgis_map::layout::MAX_SCALE_DIVISIONS.saturating_sub(before).max(1); + let after = after.clamp(1, most); + let count = (before + after) as f64; + let (total, after) = match fit { + ScaleBarFit::AdjustDivisionValue => (rustgis_geom::nice_distance(room_m / unit_m), after), + ScaleBarFit::AdjustDivision => { + let most = most as f64; + let fits = |value: f64| (room_m / unit_m / value + 1e-9).floor() - before as f64; + // More than ten would fit: the next round division (1, 2, 5, 10 …) until ten do, so + // the bar fills its room as far as a round value allows rather than stopping short. + let mut value = rustgis_geom::nice_distance(room_m / unit_m / count); + for _ in 0..64 { + if !(fits(value) > most && value.is_finite() && value > 0.0) { + break; + } + value = rustgis_geom::nice_distance(value * 2.5); + } + let after = fits(value).clamp(1.0, most) as usize; + (value * (before + after) as f64, after) + } + ScaleBarFit::AdjustWidth => (rustgis_geom::nice_distance(room_m / unit_m / count) * count, after), + }; + (total.is_finite() && total > 0.0).then_some(BarFit { total, after }) +} + +/// Where a scale bar draws its bar and labels, from [`bar_layout`]. +pub(super) struct BarLayout { + /// Where the bar starts, its top, its length and its height, in pixels. + pub(super) x0: f32, + pub(super) y0: f32, + pub(super) len: f32, + pub(super) bar_h: f32, + /// Its labels' size in pixels, the middle of their line, and each drawn: its centre across + /// and its text. One that would touch its neighbour is left out, never the ends. + pub(super) px: f32, + pub(super) label_y: f32, + pub(super) labels: Vec<(f32, String)>, + /// Its divisions before zero, all its divisions, the parts the first after zero is cut + /// into, and its whole length in its unit: what it draws. + pub(super) before: usize, + pub(super) divs: usize, + pub(super) parts: usize, + pub(super) total: f64, + /// Its unit label when it isn't the last label's: after the bar or on a line of its own. + pub(super) unit: Option, + /// The furthest right its ink reaches, in pixels: its bar, its last label or its unit label. + pub(super) right: f32, + /// Its unit label shortened with an ellipsis or left out to fit its room: said, as a cut text. + pub(super) unit_cut: Option, + /// Its box is too small for its labels and bar: too short, the bar drawn below it or its + /// lines below the bar past its foot, or too narrow, an end label reaching past its side + /// further than the default size's does or, above the default size, over its first label. + pub(super) cramped: bool, +} + +/// A scale bar's unit label on a line of its own or after the bar: the middle of its line, its +/// place across (its start or its centre, as `align` says) and its text. +pub(super) struct BarUnit { + pub(super) x: f32, + pub(super) y: f32, + pub(super) text: String, + pub(super) align: text::Align, +} + +/// Where a scale bar in `r` draws as `bar` asks, at `ground_per_pt` ground metres a point of +/// paper: the drawing and the text-cut check ([`losses`]) take the same, so they agree. `None` +/// when it draws no bar. A label that would touch its neighbour is left out, as on any map: the +/// ends always show, and the user guide says each step is labelled where there is room. That is +/// thinning, not a loss to report. +/// +/// Its labels, their room and its unit label follow its text size (#2581). Its lines above the +/// bar reach no higher than the box's top, or than a plain bar's labels reach at the default size +/// when that is higher (a publication's short box): the bar moves down to give them room. Its +/// lines below the bar reach no lower than the box's foot, the bar moving up as far as its lines +/// above leave it room. A box too short for its lines and bar is [`BarLayout::cramped`], which is +/// said, rather than any line drawn smaller. A bar with none of the details draws where it always +/// was at the default size. +pub(super) fn bar_layout(r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, ppp: f64, comma: bool) -> Option { + use rustgis_map::layout::{ + MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DECIMALS, MAX_SCALE_DIVISIONS, MAX_SCALE_SUBDIVISIONS, MAX_UNIT_LABEL_CHARS, + }; + if !(ground_per_pt.is_finite() && ground_per_pt > 0.0 && ppp.is_finite() && ppp > 0.0) { + return None; + } + let p = ppp as f32; + let k = layout_text_scale(bar.text_size, SCALE_BAR_TEXT_PT) as f32; + let after = bar.divisions.clamp(1, MAX_SCALE_DIVISIONS); + let before = bar.divisions_before_zero.min(MAX_SCALE_BEFORE_ZERO); + // One part is the division whole. + let parts = bar.subdivisions.clamp(1, MAX_SCALE_SUBDIVISIONS); + let width_pt = f64::from(r.width()) / ppp; + let BarPlan { unit_m, abbr, .. } = bar_plan(ground_per_pt, width_pt, bar.units)?; + let decimals = bar.decimals.map(|d| usize::from(d).min(MAX_SCALE_DECIMALS)); + // The unit's words: its abbreviation unless the bar names it, on one line. + let unit: String = match bar.unit_label { + None => abbr.to_string(), + Some(t) => t.chars().take(MAX_UNIT_LABEL_CHARS).map(|c| if matches!(c, '\n' | '\r') { ' ' } else { c }).collect(), + }; + let has_unit = !unit.trim().is_empty(); + let unit_at = bar.unit_label_position; + let rows = bar_rows(bar.label_position, unit_at, has_unit); + let bar_h = (r.height() * 0.28).min(6.0 * p); + // Its labels' size, and the default's, in pixels. + let (px, px8) = (SCALE_BAR_TEXT_PT as f32 * k * 1.33 * p, SCALE_BAR_TEXT_PT as f32 * 1.33 * p); + let measure_at = |s: &str, px: f32| text::measure(s, px / 1.33, false); + let measure = |s: &str| measure_at(s, px); + let half = |s: &str| measure(s) / 2.0; + let gap = 3.0 * k * p; + // The pixels a unit after the bar takes from it, at most half the bar's room. + let beside = if has_unit && unit_at == UnitLabelPosition::AfterBar { + (measure(&unit) + gap + p).min(r.width() * BAR_SHARE as f32 * 0.5) + } else { + 0.0 + }; + // Division `k` from zero of a bar `total` long in `divs` divisions. + let number = |total: f64, divs: usize, k: isize| bar_number(total * k as f64 / divs as f64, total / divs as f64, decimals, comma); + // Left of zero the first label is a negative one, centred on the bar's end: the bar starts far + // enough in for it, at labels `px` high and `k` times the default. It takes at most half the + // bar's room, as a unit after the bar does: a wider one reaches left of the box rather than + // leave the bar a sliver. + let most_pad = ((r.width() * BAR_SHARE as f32 - beside) * 0.5).max(0.0); + let pad_at = |f: &BarFit, px: f32, k: f32| { + if before > 0 { + let first = number(f.total, before + f.after, -(before as isize)); + (measure_at(&first, px) / 2.0 - BAR_INSET * k).clamp(0.0, most_pad) + } else { + 0.0 + } + }; + let pad_of = |f: &BarFit| pad_at(f, px, k); + // The bar in what's left of its room once `taken` pixels of the box are its labels'. + let fitted = |taken: f32| { + let taken_pt = f64::from(taken) / ppp; + let room_m = ground_per_pt * width_pt * BAR_SHARE - ground_per_pt * taken_pt; + bar_fit(room_m, unit_m, bar.fit, before, after) + }; + let first = fitted(beside)?; + // The room left of zero follows the bar's length: fitted again with the first label's, and once + // more if the shorter bar's first label is wider ("-1.25" for "-1"). Where a refit leaves no + // room, the fit before it draws, its first label perhaps starting a little left of the box. + let (fit, pad) = if before > 0 { + let reserved = pad_of(&first); + match fitted(beside + reserved) { + Some(f) if pad_of(&f) > reserved => match fitted(beside + pad_of(&f)) { + // A refit whose own first label is wider still would start past the room it was + // fitted to: the fit before it draws instead. + Some(g) if pad_of(&g) <= pad_of(&f) => (g, pad_of(&g)), + _ => (f, reserved), + }, + Some(f) => (f, pad_of(&f)), + None => (first, 0.0), + } + } else { + (first, 0.0) + }; + let BarFit { total, after } = fit; + let divs = before + after; + let len = (total * unit_m / ground_per_pt * ppp) as f32; + // How far in the bar starts for labels `k` times the default size: past a first label before + // zero, or as far as the first label at zero needs ([`bar_inset`]). + let zero = number(total, divs, 0); + let inset_at = |k: f32, pad: f32| if before > 0 { BAR_INSET * k + pad } else { bar_inset(&zero, k, p) }; + let x0 = r.x() + inset_at(k, pad); + // The box less the insets the bar keeps. + let (inner_left, inner_right) = (r.x() + BAR_INSET, r.right() - BAR_INSET); + // Division `j` counts `j - before` from zero. Its label, the last with the unit when it follows + // the labels: a unit the bar names shortened so the label, centred on the bar's end, ends + // inside the box, and left out when not even a letter of it fits. The abbreviation, short, + // follows the number as it always has. + let label = |j: usize| { + let v = number(total, divs, j as isize - before as isize); + if j == divs && has_unit && unit_at == UnitLabelPosition::AfterLabels { + // Centred on the bar's end: half of it each side, inside the nearer edge. + let room = 2.0 * (inner_right - (x0 + len)).min((x0 + len) - inner_left); + if bar.unit_label.is_some() { last_label(&v, &unit, room, measure) } else { (format!("{v} {unit}"), None) } + } else { + (v, None) + } + }; + // Each line above the bar moves it down, each below up; labels over it alone leave it where it + // always was. + let centre = 0.62 + 0.12 * (rows.up as f32 - 1.0 - rows.down as f32); + let at = r.y() + r.height() * centre - bar_h / 2.0; + // How far `n` lines of labels `px` high reach out from the bar: the middle of the last, and + // its digits past it. + let reach = |n: usize, px: f32| if n == 0 { 0.0 } else { px * (BAR_LABEL_MID + 1.25 * (n - 1) as f32 + BAR_LABEL_RISE) }; + // The highest its lines may reach: the box's top, or where a plain bar's labels reach at the + // default size when that is higher (a publication's short box), as they always have. Below + // the bar, the box's foot. + let plain_at = r.y() + r.height() * 0.62 - bar_h / 2.0; + let (top, foot) = (r.y().min(plain_at - reach(1, px8)), r.bottom()); + let highest = top + reach(rows.up, px); + let mut y0 = at.max(highest); + if rows.down > 0 { + y0 = y0.min(foot - bar_h - reach(rows.down, px)).max(highest); + } + // The middle of text line `n` out from the bar. + let row = |n: usize| (BAR_LABEL_MID + 1.25 * n as f32) * px; + let seg = len / divs as f32; + let label_y = if bar.label_position == ScaleLabelPosition::Below { y0 + bar_h + row(0) } else { y0 - row(0) }; + // The last label's unit, cut to fit or not. + let mut unit_cut = None; + let all: Vec<(f32, String)> = (0..=divs) + .map(|j| { + let (s, cut) = label(j); + unit_cut = unit_cut.or(cut); + (x0 + seg * j as f32, s) + }) + .collect(); + let last = all.last().map(|(x, s)| x - half(s)).unwrap_or(f32::MAX); + let mut right_label = f32::MIN; + let mut labels = Vec::new(); + for (i, (x, s)) in all.into_iter().enumerate() { + let end = i == divs; + if !end && (x - half(&s) < right_label + gap || x + half(&s) + gap > last) && i != 0 { + continue; + } + right_label = x + half(&s); + labels.push((x, s)); + } + // The unit after the bar, level with its middle, or centred over or under it on a line of its + // own: after the bar in the room kept for it; on a line of its own in the box's width, moved + // in as far as it must be to stay inside it. Shortened with an ellipsis, or left out when not + // even its first character fits. + let place_unit = || { + let mid = x0 + len / 2.0; + let (x, y, align) = match unit_at { + UnitLabelPosition::AfterLabels => return (None, None), + UnitLabelPosition::AfterBar => (x0 + len + gap + p, y0 + bar_h / 2.0, text::Align::Left), + UnitLabelPosition::Above => (mid, y0 - row(rows.unit_row), text::Align::Center), + UnitLabelPosition::Below => (mid, y0 + bar_h + row(rows.unit_row), text::Align::Center), + }; + let room = if unit_at == UnitLabelPosition::AfterBar { beside - gap - p } else { inner_right - inner_left }; + let Some(text) = shortened(&unit, room, measure) else { return (None, Some(UnitLabelCut::LeftOut)) }; + let cut = (text != unit).then_some(UnitLabelCut::Shortened); + let x = if matches!(align, text::Align::Center) { + let w = measure(&text) / 2.0; + x.min(inner_right - w).max(inner_left + w) + } else { + x + }; + (Some(BarUnit { x, y, text, align }), cut) + }; + let (unit, placed_cut) = if has_unit { place_unit() } else { (None, None) }; + let unit_cut = unit_cut.or(placed_cut); + let unit_right = + unit.as_ref().map_or(f32::MIN, |u| if matches!(u.align, text::Align::Left) { u.x + measure(&u.text) } else { u.x + half(&u.text) }); + let right = (x0 + len).max(right_label).max(unit_right); + // Sideways the bar keeps its length: its first label is kept within its reach by the inset, + // and its last reaches no further past the box's right side than the default size's does, or + // than the side itself; further out, the box is too narrow for it, as it is too short when the + // bar is below it. + let half8 = |s: &str| measure_at(s, px8) / 2.0; + let x8 = r.x() + inset_at(1.0, pad_at(&fit, px8, 1.0)); + let past_side = labels.last().is_some_and(|(x, s)| x + half(s) > r.right().max(x8 + (x - x0) + half8(s)) + 0.01); + let low = y0 + bar_h + reach(rows.down, px) > foot + 0.01; + // Its end label is drawn as its first is, whatever the room: above the default size, running + // into the first, the box is too narrow for them too. + let clash = k > 1.0 + && match (labels.first(), labels.last()) { + (Some((fx, fs)), Some((ex, es))) if labels.len() > 1 => ex - half(es) < fx + half(fs), + _ => false, + }; + let cramped = low || past_side || clash; + Some(BarLayout { x0, y0, len, bar_h, px, label_y, labels, before, divs, parts, total, unit, right, unit_cut, cramped }) +} + +/// A scale bar filling most of the element's width as `bar` asks, placed by [`bar_layout`]: its +/// divisions after zero (and any before it) labelled, the first after zero split into its +/// subdivisions. `ground_per_pt` is ground metres per logical point of paper; `colors` are its +/// lines, dark divisions and labels, then the alternating bar's light divisions. +pub(super) fn scale_bar(pm: &mut Canvas, r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, colors: (Rgba, Rgba), ppp: f64, comma: bool) { + let Some(BarLayout { x0, y0, len, bar_h, px, label_y, labels, before, divs, parts, unit, .. }) = + bar_layout(r, ground_per_pt, bar, ppp, comma) + else { + return; + }; + let (dark, light) = colors; + let seg = len / divs as f32; + let zero_x = x0 + seg * before as f32; + // Where the first division after zero is cut into its subdivisions. + let cuts: Vec = (1..parts).map(|p| zero_x + seg * p as f32 / parts as f32).collect(); + let dark_at = |j: usize| (j as isize - before as isize).rem_euclid(2) == 0; + // An alternating bar's fills alternate from zero, the cut division's parts counted one by one: + // the first part dark, the divisions after them going on from the last part. + let filled_dark = |j: usize| if j < before { dark_at(j) } else { (parts - 1 + (j - before)).is_multiple_of(2) }; + let line = Stroke { width: 0.6 * ppp as f32, ..Stroke::default() }; + let stroke = |pm: &mut Canvas, pts: &[(f32, f32)], w: &Stroke| { + let mut pb = PathBuilder::new(); + for (i, (x, y)) in pts.iter().enumerate() { + if i == 0 { pb.move_to(*x, *y) } else { pb.line_to(*x, *y) } + } + if let Some(p) = pb.finish() { + pm.stroke_path(&p, &paint(dark, 1.0), w, Transform::identity(), None); + } + }; + match bar.style { + ScaleBarStyle::Alternating => { + for j in 0..divs { + let x = x0 + seg * j as f32; + if j == before && parts > 1 { + // Alternating parts from zero, the first dark. + let part = seg / parts as f32; + for p in 0..parts { + let c = if p.is_multiple_of(2) { dark } else { light }; + if let Some(b) = Rect::from_xywh(x + part * p as f32, y0, part, bar_h) { + pm.fill_rect(b, &paint(c, 1.0), Transform::identity(), None); + } + } + } else if let Some(b) = Rect::from_xywh(x, y0, seg, bar_h) { + let c = if filled_dark(j) { dark } else { light }; + pm.fill_rect(b, &paint(c, 1.0), Transform::identity(), None); + } + } + if let Some(b) = Rect::from_xywh(x0, y0, len, bar_h) { + pm.stroke_path(&PathBuilder::from_rect(b), &paint(dark, 1.0), &line, Transform::identity(), None); + } + } + ScaleBarStyle::Stepped => { + let mut pts = vec![(x0, y0 + bar_h)]; + // Its upper steps are an alternating bar's dark divisions; the cut division is upper. + for j in 0..divs { + let y = if j == before || filled_dark(j) { y0 } else { y0 + bar_h }; + let (a, b) = (x0 + seg * j as f32, x0 + seg * (j + 1) as f32); + pts.extend([(a, y), (b, y)]); + } + pts.push((x0 + len, y0 + bar_h)); + stroke(pm, &pts, &Stroke { width: 1.0 * ppp as f32, ..Stroke::default() }); + // The first division after zero is on the upper step: its ticks hang from it. + for &x in &cuts { + stroke(pm, &[(x, y0), (x, y0 + bar_h * 0.5)], &line); + } + } + ScaleBarStyle::Line => { + let base = y0 + bar_h; + stroke(pm, &[(x0, base), (x0 + len, base)], &Stroke { width: 1.0 * ppp as f32, ..Stroke::default() }); + // Tall ticks at the ends and at zero. + for j in 0..=divs { + let tall = if j == 0 || j == divs || j == before { bar_h } else { bar_h * 0.6 }; + let x = x0 + seg * j as f32; + stroke(pm, &[(x, base), (x, base - tall)], &line); + } + for &x in &cuts { + stroke(pm, &[(x, base), (x, base - bar_h * 0.3)], &line); + } + } + } + // Labels at the divisions, over or under the bar, and the unit label where it is asked. + for (x, s) in &labels { + text::text_at(pm, s, *x, label_y, px, dark, false, text::Align::Center, false); + } + if let Some(BarUnit { x, y, text: shown, align }) = unit { + text::text_at(pm, &shown, x, y, px, dark, false, align, false); + } +} + +/// The last label of a scale bar, its number `v` followed by `unit`, as it fits `room` pixels +/// measured by `measure`: the unit shortened with an ellipsis, never the number, and left out when +/// not even its first character fits, with how it was cut. +pub(super) fn last_label(v: &str, unit: &str, room: f32, measure: impl Fn(&str) -> f32) -> (String, Option) { + let whole = format!("{v} {unit}"); + if measure(&whole) <= room { + return (whole, None); + } + let after = measure(&format!("{v} ")); + match shortened(unit, room - after, &measure) { + Some(u) => (format!("{v} {u}"), Some(UnitLabelCut::Shortened)), + None => (v.to_string(), Some(UnitLabelCut::LeftOut)), + } +} + +/// `t` as it fits `room` pixels measured by `measure`: whole, or cut a character at a time and +/// ended with an ellipsis, keeping at least one character. `None` when not even that fits. A +/// longer prefix measures no less, so the longest that fits is found by halving. +pub(super) fn shortened(t: &str, room: f32, measure: impl Fn(&str) -> f32) -> Option { + if measure(t) <= room { + return Some(t.to_string()); + } + let chars: Vec = t.chars().collect(); + let cut = |n: usize| format!("{}…", chars.iter().take(n).collect::().trim_end()); + // The fewest characters, from 1, that don't fit: `chars.len()` when all shorter ones do. + let (mut lo, mut hi) = (1, chars.len()); + while lo < hi { + let mid = lo + (hi - lo) / 2; + if measure(&cut(mid)) <= room { lo = mid + 1 } else { hi = mid } + } + (lo > 1).then(|| cut(lo - 1)) +} + +/// The text lines a scale bar has above and below it, and the line its unit takes on its side +/// (0 next to the bar, 1 past its labels). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct BarRows { + pub(super) up: usize, + pub(super) down: usize, + pub(super) unit_row: usize, +} + +/// The lines of a scale bar with its labels at `labels` and its unit (if `has_unit`) at `unit`. +pub(super) fn bar_rows(labels: ScaleLabelPosition, unit: UnitLabelPosition, has_unit: bool) -> BarRows { + let labels_up = labels == ScaleLabelPosition::Above; + // The side the unit has a line of its own on: true above. + let unit_up = match unit { + UnitLabelPosition::Above if has_unit => Some(true), + UnitLabelPosition::Below if has_unit => Some(false), + _ => None, + }; + BarRows { + up: usize::from(labels_up) + usize::from(unit_up == Some(true)), + down: usize::from(!labels_up) + usize::from(unit_up == Some(false)), + unit_row: usize::from(unit_up == Some(labels_up)), + } +} diff --git a/crates/render/src/layout/swatch.rs b/crates/render/src/layout/swatch.rs new file mode 100644 index 0000000000..326163b5bf --- /dev/null +++ b/crates/render/src/layout/swatch.rs @@ -0,0 +1,257 @@ +//! The symbol a legend row shows. + +use super::*; + +/// A legend entry's symbol `s` of the layer `l` in the box (`x`, `y`, `w`, `h`), with its stacked +/// `strokes` and `fills` (#2490): a point as [`point_swatch`] draws it, or a line or a filled box a +/// swatch wide in the middle of the box (`across` pixels: [`LEGEND_SWATCH`] in the legend's size), +/// by the paths the map draws its features with, its widths at `ppp`. A line or polygon swatch's +/// ink ([`swatch_ink`]) is held to its row's top and bottom and, at its sides, to the `room` (left, +/// right, in pixels) its row leaves empty: left, its indent and what lies left of its column, none +/// at the legend's edge; right, the gap before its text. Stacked, see-through (`opacity`), grown +/// with the layer's reference scale at 1:`scale` or reaching past that, it is composited as one and +/// cut there. +pub(super) fn swatch( + pm: &mut Canvas, + (x, y, w, h): (f32, f32, f32, f32), + l: &rustgis_map::Layer, + (s, strokes, fills): (&rustgis_map::Symbol, &[rustgis_map::LineStroke], &[rustgis_map::fills::FillLayer]), + opacity: f32, + scale: f64, + (ppp, across, (lead, gap)): (f32, f32, (f32, f32)), +) { + let gt = l.geometry_type(); + let k = l.size_factor(scale); + if gt == GeometryType::Point { + point_swatch(pm, (x, y, w, h), (s, strokes), opacity, ppp * k); + return; + } + // Every line or polygon swatch is cut to its row's top and bottom, so a line wider than its row, + // or shifted off it, doesn't paint over the rows beside it (#2518), and at its sides to the room + // its row leaves empty, so it doesn't paint over its label, the column before or past the + // legend's edge; within those it keeps its ink, as wide as the map draws it (#2581). + let plain = if gt == GeometryType::Polyline { strokes.is_empty() } else { fills.is_empty() }; + let ink = swatch_ink((x, y, w, h), gt, (s, strokes, fills), (across, ppp * k)); + let (lo, hi) = (x - lead, x + w + gap); + let within = ink.is_none_or(|b| b.top() >= y - 0.01 && b.bottom() <= y + h + 0.01 && b.left() >= lo - 0.01 && b.right() <= hi + 0.01); + if plain && opacity >= 0.999 && k == 1.0 && within { + // A layer with no stack, within its row: the swatch it always had. + flat_swatch(pm, (x, y, w, h), gt, s, (across, ppp)); + return; + } + let (left, right) = ink.map_or((x, x + w), |b| (x.min(b.left()).max(lo), (x + w).max(b.right()).min(hi))); + composited(pm, (left, y, right - left, h), opacity, |c, (cl, ct)| { + let cell = (x - cl, y - ct, w, h); + if plain { + flat_swatch(c, cell, gt, s, (across, ppp * k)); + } else { + stacked_swatch(c, cell, l, (s, strokes, fills), (ppp, across), k); + } + }); +} + +/// Where a line or polygon swatch drawn in `cell`, `across` pixels wide, its widths at `wppp`, +/// puts ink: a plain one's line stroked as [`flat_swatch`] strokes it (its joins too); a stacked +/// line's `strokes` the map draws, as it strokes them ([`crate::line_stroke`]), an offset one as +/// wide as its width and twice its offset, mitred, as its shifted line's corners are +/// (`offset_polyline`), a marked one as far as [`crate::line_markers::reach`]; a stacked polygon's +/// box and its outline. `None` for no shape. [`swatch`] keeps it within its row and the room its +/// row leaves empty. +pub(super) fn swatch_ink( + cell: (f32, f32, f32, f32), + gt: GeometryType, + (s, strokes, fills): (&rustgis_map::Symbol, &[rustgis_map::LineStroke], &[rustgis_map::fills::FillLayer]), + (across, wppp): (f32, f32), +) -> Option { + let line = gt == GeometryType::Polyline; + if (line && strokes.is_empty()) || (!line && fills.is_empty()) { + let (p, stroke) = flat_swatch_outline(cell, gt, s, (across, wppp))?; + return p.stroke(&stroke, 1.0).map(|p| p.bounds()); + } + if !line { + let b = swatch_box(cell, across)?; + let o = if s.stroke.a() > 0 { s.stroke_width.max(0.0) * wppp / 2.0 } else { 0.0 }; + return Rect::from_ltrb(b.left() - o, b.top() - o, b.right() + o, b.bottom() + o); + } + let path = swatch_line_path(cell, across)?; + let b = path.bounds(); + strokes + .iter() + .filter_map(|st| { + let (c, w) = st.resolve(s); + let w = if w.is_finite() { w.max(0.0) } else { 0.0 }; + if st.markers.is_some() { + let r = crate::line_markers::reach(std::slice::from_ref(st), w) * wppp; + return Rect::from_ltrb(b.left() - r, b.top() - r, b.right() + r, b.bottom() + r); + } + // One the map skips (no width or no colour) puts no ink. + if w <= 0.0 || c.a() == 0 { + return None; + } + let mut stroke = crate::line_stroke(st, (w * wppp).max(0.5) + 2.0 * st.offset.abs() * wppp); + if st.offset != 0.0 { + stroke.line_join = tiny_skia::LineJoin::Miter; + } + path.stroke(&stroke, 1.0).map(|p| p.bounds()) + }) + .reduce(|a, c| { + Rect::from_ltrb(a.left().min(c.left()), a.top().min(c.top()), a.right().max(c.right()), a.bottom().max(c.bottom())).unwrap_or(a) + }) +} + +/// A line swatch's zigzag ([`swatch_line`]) as a path. +pub(super) fn swatch_line_path(cell: (f32, f32, f32, f32), across: f32) -> Option { + let [a, b, c] = swatch_line(cell, across); + let mut pb = PathBuilder::new(); + pb.move_to(a.0, a.1); + pb.line_to(b.0, b.1); + pb.line_to(c.0, c.1); + pb.finish() +} + +/// A plain line or polygon swatch's line, `across` pixels wide in the box: a line's zigzag or a +/// polygon's box, and the stroke it is drawn with, its width at `wppp`. +pub(super) fn flat_swatch_outline( + cell: (f32, f32, f32, f32), + gt: GeometryType, + s: &rustgis_map::Symbol, + (across, wppp): (f32, f32), +) -> Option<(tiny_skia::Path, Stroke)> { + if gt == GeometryType::Polyline { + Some((swatch_line_path(cell, across)?, Stroke { width: s.stroke_width.max(1.0) * wppp, ..Stroke::default() })) + } else { + Some((PathBuilder::from_rect(swatch_box(cell, across)?), Stroke { width: s.stroke_width.max(0.5) * wppp, ..Stroke::default() })) + } +} + +/// The part of the box (`x`, `w`) a line or polygon swatch `across` pixels wide takes, in its +/// middle. +pub(super) fn swatch_across(x: f32, w: f32, across: f32) -> (f32, f32) { + (x + (w - across) / 2.0, across) +} + +/// The three points of a line swatch `across` pixels wide in the box, in pixels. +pub(super) fn swatch_line((x, y, w, h): (f32, f32, f32, f32), across: f32) -> [(f32, f32); 3] { + let (x, w) = swatch_across(x, w, across); + let cy = y + h / 2.0; + [(x, cy + h * 0.2), (x + w * 0.4, cy - h * 0.2), (x + w, cy + h * 0.1)] +} + +/// A polygon swatch's box, `across` pixels wide, in the box, in pixels. +pub(super) fn swatch_box((x, y, w, h): (f32, f32, f32, f32), across: f32) -> Option { + let (x, w) = swatch_across(x, w, across); + Rect::from_xywh(x, y + h * 0.2, w, h * 0.6) +} + +/// A line or polygon swatch of the symbol `s` alone, `across` pixels wide, its widths at `wppp`. +pub(super) fn flat_swatch(pm: &mut Canvas, cell: (f32, f32, f32, f32), gt: GeometryType, s: &rustgis_map::Symbol, at: (f32, f32)) { + let Some((p, stroke)) = flat_swatch_outline(cell, gt, s, at) else { return }; + if gt != GeometryType::Polyline { + pm.fill_rect(p.bounds(), &paint(s.fill, 1.0), Transform::identity(), None); + } + pm.stroke_path(&p, &paint(s.stroke, 1.0), &stroke, Transform::identity(), None); +} + +/// A line or polygon swatch with its stacked `strokes` or `fills`, drawn by the map's own paths +/// for a feature of that shape: [`crate::stroke_paths::Paths`] and [`crate::Ctx::filled`], `across` +/// pixels wide, at `ppp` and the layer's reference scale `k`. The canvas stands for a view whose +/// map units are its points, y up, so the shape's pixels are its coordinates. +pub(super) fn stacked_swatch( + pm: &mut Canvas, + cell: (f32, f32, f32, f32), + l: &rustgis_map::Layer, + (s, strokes, fills): (&rustgis_map::Symbol, &[rustgis_map::LineStroke], &[rustgis_map::fills::FillLayer]), + (ppp, across): (f32, f32), + k: f32, +) { + let (w, h) = (f64::from(pm.width()) / f64::from(ppp), f64::from(pm.height()) / f64::from(ppp)); + let camera = rustgis_map::Camera::new(Coord::new(w / 2.0, -h / 2.0), 1.0); + let view = View { width: w, height: h, pixels_per_point: f64::from(ppp), camera, sky: false }; + let ctx = crate::Ctx { + view: &view, + ppp: ppp * k, + wireframe: false, + // (The swatch's own view: the stroke and fill paths don't cull today, and one that does + // still keeps the swatch, where an empty extent would drop it.) + cull: crate::cull_extent(&view, crate::CULL_MARGIN), + globe: None, + sprites: Default::default(), + bursts: Default::default(), + }; + let at = |(x, y): (f32, f32)| Coord::new(f64::from(x / ppp), -f64::from(y / ppp)); + if l.geometry_type() == GeometryType::Polyline { + // Drawn level by level, as the map draws a feature's strokes with symbol levels on. + let mut ordered: Vec<(usize, rustgis_map::LineStroke)> = strokes.iter().copied().enumerate().collect(); + if l.stroke_levels { + ordered.sort_by_key(|(i, st)| st.level_at(*i)); + } + let ordered: Vec = ordered.into_iter().map(|(_, st)| st).collect(); + let part: Vec = swatch_line(cell, across).into_iter().map(at).collect(); + crate::stroke_paths::Paths::default().draw(&ctx, pm, &[part], s, &ordered); + } else if let Some(b) = swatch_box(cell, across) { + let ring: Vec = + [(b.left(), b.top()), (b.right(), b.top()), (b.right(), b.bottom()), (b.left(), b.bottom()), (b.left(), b.top())] + .into_iter() + .map(at) + .collect(); + ctx.filled(pm, &[vec![ring]], s, fills); + } +} + +/// A point's symbol at (`x`, `y`), unturned, by the path the map takes for it: its marker, or +/// `strokes`' stacked marks. +pub(super) fn draw_point(pm: &mut Canvas, (x, y): (f32, f32), s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke], ppp: f32) { + if point_marks::plain(strokes, 0.0) { + crate::draw_marker(pm, x, y, s, 1.0, None, ppp); + } else { + point_marks::draw(pm, x, y, s, strokes, 0.0, None, ppp); + } +} + +/// A point layer's symbol in the middle of the box, as the map draws its points: `strokes`' stacked +/// marks or its marker, at `ppp` (with the layer's reference scale), unturned. See-through, the +/// marks are composited as one, as the map composites the layer, in a picture no larger than the +/// page. So are those too large for the box (past [`LegendRow::symbol_side`]'s limit), which the +/// picture cuts to it. +pub(super) fn point_swatch( + pm: &mut Canvas, + (x, y, w, h): (f32, f32, f32, f32), + (s, strokes): (&rustgis_map::Symbol, &[rustgis_map::LineStroke]), + opacity: f32, + ppp: f32, +) { + let (cx, cy) = (x + w / 2.0, y + h / 2.0); + // A thousandth of slack: the box's size went through a rounding of its own. + let fits = 2.0 * point_marks::reach(s, strokes) * ppp <= w.min(h) * 1.001; + if opacity >= 0.999 && fits { + draw_point(pm, (cx, cy), s, strokes, ppp); + return; + } + composited(pm, (x, y, w, h), opacity, |c, (left, top)| draw_point(c, (cx - left, cy - top), s, strokes, ppp)); +} + +/// Draws by `draw` into a picture of the box (`x`, `y`, `w`, `h`), no larger than the page, and +/// composites it as one at `opacity`, cut to the box. `draw` gets the picture and where its corner +/// sits on the canvas, in pixels. +pub(super) fn composited(pm: &mut Canvas, (x, y, w, h): (f32, f32, f32, f32), opacity: f32, draw: impl FnOnce(&mut Canvas, (f32, f32))) { + // Kept on the canvas: a picture as large as the canvas then covers all of it that shows. + let (left, top) = (x.floor().max(0.0), y.floor().max(0.0)); + let (cw, ch) = (((x + w).ceil() - left) as u32, ((y + h).ceil() - top) as u32); + let (cw, ch) = (cw.min(pm.width()), ch.min(pm.height())); + if let Some(mut picture) = pm.sub(cw, ch) { + draw(&mut picture, (left, top)); + let Some(r) = Rect::from_xywh(x, y, w, h) else { return }; + let clip = if picture.is_recording() { + // A recording keeps what lies past its picture's edge, so it is cut here, at the box. + Some(crate::vector::Clip { path: PathBuilder::from_rect(r), rule: FillRule::Winding, transform: Transform::identity() }) + } else { + // Pixels are cut in the picture, by a mask its size rather than the page's. + if let Some(mut m) = Mask::new(cw, ch) { + m.fill_path(&PathBuilder::from_rect(r), FillRule::Winding, true, Transform::from_translate(-left, -top)); + picture.pixels().apply_mask(&m); + } + None + }; + pm.place(picture, Transform::from_translate(left, top), opacity, rustgis_map::effects::Blend::Normal, clip); + } +} diff --git a/crates/render/src/layout/table.rs b/crates/render/src/layout/table.rs new file mode 100644 index 0000000000..31d8d7ddb0 --- /dev/null +++ b/crates/render/src/layout/table.rs @@ -0,0 +1,71 @@ +//! The attribute table element. + +use super::*; + +/// The first `rows` rows of a table, with as many columns as fit: on white cells in dark grey, or +/// with an `ink` (#2257) in it on no paper of its own, its header and stripes a tint of the ink, so +/// it reads on whatever is behind it (a dark page, or the element's background). +pub(super) fn table(pm: &mut Canvas, r: Rect, ds: &rustgis_data::Dataset, rows: usize, ink: Option, ppp: f64) { + let ppp = ppp as f32; + let px = 8.0 * 1.33 * ppp; + let row_h = px * 1.6; + let col_w = (90.0 * ppp).min(r.width()); + let cols = ((r.width() / col_w).floor() as usize).clamp(1, ds.fields.len().max(1)); + let n = rows.min(ds.features.len()).min(((r.height() / row_h) as usize).saturating_sub(1)); + let dark = ink.unwrap_or(INK); + // Without an ink, the white paper, header and stripes it always had, so a table drawn before + // draws to the same pixels. With one, white cells could hide a light ink. + let ((header, header_alpha), (stripe, stripe_alpha)) = match ink { + None => ((Rgba::rgb(0xE4, 0xE8, 0xEE), 1.0), (Rgba::rgb(0xF5, 0xF6, 0xF8), 1.0)), + Some(c) => ((c, 0.18), (c, 0.08)), + }; + if ink.is_none() + && let Some(bg) = Rect::from_xywh(r.x(), r.y(), col_w * cols as f32, row_h * (n + 1) as f32) + { + pm.fill_rect(bg, &paint(Rgba::rgb(0xFF, 0xFF, 0xFF), 1.0), Transform::identity(), None); + } + if let Some(hdr) = Rect::from_xywh(r.x(), r.y(), col_w * cols as f32, row_h) { + pm.fill_rect(hdr, &paint(header, header_alpha), Transform::identity(), None); + } + let fit = |s: &str| -> String { + let mut t: String = s.chars().take(40).collect(); + while !t.is_empty() && text::measure(&t, 8.0, false) * ppp > col_w - 6.0 * ppp { + t.pop(); + } + t + }; + for (c, f) in ds.fields.iter().take(cols).enumerate() { + text::text_at( + pm, + &fit(f.display()), + r.x() + c as f32 * col_w + 3.0 * ppp, + r.y() + row_h / 2.0, + px, + dark, + true, + text::Align::Left, + false, + ); + } + for row in 0..n { + let y = r.y() + row_h * (row + 1) as f32; + if row % 2 == 1 + && let Some(b) = Rect::from_xywh(r.x(), y, col_w * cols as f32, row_h) + { + pm.fill_rect(b, &paint(stripe, stripe_alpha), Transform::identity(), None); + } + for c in 0..cols { + text::text_at( + pm, + &fit(&ds.value(row, c).to_string()), + r.x() + c as f32 * col_w + 3.0 * ppp, + y + row_h / 2.0, + px, + dark, + false, + text::Align::Left, + false, + ); + } + } +} diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs new file mode 100644 index 0000000000..ccabb070e2 --- /dev/null +++ b/crates/render/src/layout/tests.rs @@ -0,0 +1,6820 @@ +use super::*; + +/// A chart element of layer "t" on frame 1, with `extra` keys (its field among them). +fn chart_kind(extra: serde_json::Value) -> ElementKind { + let mut chart = serde_json::json!({"frame": 1, "layer": "t"}); + if let (Some(c), Some(e)) = (chart.as_object_mut(), extra.as_object()) { + c.extend(e.clone()); + } + serde_json::from_value(serde_json::json!({ "Chart": chart })).unwrap() +} + +/// The chart as it was drawn before charts were grouped, ordered or cut by choice, kept to +/// show a chart saved then still draws to the same pixels. +fn chart_before(pm: &mut Canvas, r: Rect, ds: &rustgis_data::Dataset, field: &str, label: Option<&str>, dark: Rgba, ppp: f64) { + let ppp = ppp as f32; + let Some(fi) = ds.field_index(field) else { + placeholder(pm, r, "Chart", ppp as f64); + return; + }; + let li = label.and_then(|l| ds.field_index(l)); + let mut vals: Vec<(f64, String)> = (0..ds.features.len()) + .filter_map(|row| { + ds.value(row, fi).as_f64().filter(|v| v.is_finite()).map(|v| (v, li.map(|i| ds.value(row, i).to_string()).unwrap_or_default())) + }) + .collect(); + vals.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)); + vals.truncate(20); + let max = vals.iter().map(|v| v.0).fold(0.0_f64, f64::max); + if vals.is_empty() || max <= 0.0 { + placeholder(pm, r, "Chart", ppp as f64); + return; + } + let px = 7.5 * 1.33 * ppp; + let title_h = px * 1.6; + text::text_at(pm, field, r.x(), r.y() + title_h / 2.0, px * 1.15, dark, true, text::Align::Left, false); + let label_w = if li.is_some() { r.width() * 0.32 } else { 0.0 }; + let bar_area = r.width() - label_w - 4.0; + let bh = ((r.height() - title_h) / vals.len() as f32).min(18.0 * ppp); + for (i, (v, name)) in vals.iter().enumerate() { + let y = r.y() + title_h + bh * i as f32; + let w = (bar_area * (*v / max) as f32).max(1.0); + if let Some(b) = Rect::from_xywh(r.x() + label_w, y + bh * 0.15, w, bh * 0.7) { + pm.fill_rect(b, &paint(Rgba::rgb(0x3B, 0x82, 0xC4), 1.0), Transform::identity(), None); + } + if li.is_some() { + let mut t: String = name.chars().take(30).collect(); + while !t.is_empty() && text::measure(&t, 7.5, false) * ppp > label_w - 4.0 * ppp { + t.pop(); + } + text::text_at(pm, &t, r.x(), y + bh / 2.0, px.min(bh * 0.9), dark, false, text::Align::Left, false); + } + } +} + +/// A chart saved before grouping, order and limits draws to the same pixels: with labels or +/// without, past 20 features, with rows with no number, a missing label field, all zero. +#[test] +fn a_chart_saved_before_draws_to_the_same_pixels() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; + let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new("name", FieldType::Text), Field::new("n", FieldType::Double)]); + for i in 0..27 { + let n = match i { + 3 => Value::Null, + 5 => Value::Float(f64::NAN), + _ => Value::Float(((i * 37) % 23) as f64 + 0.5), + }; + ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text(format!("Place {i}")), n]); + } + let mut zeros = Dataset::new("t", GeometryType::Point, vec![Field::new("n", FieldType::Double)]); + zeros.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Float(0.0)]); + let r = Rect::from_xywh(7.0, 5.0, 230.0, 170.0).unwrap(); + for (ds, label, ppp) in [(&ds, Some("name"), 1.0), (&ds, None, 2.0), (&ds, Some("gone"), 1.5), (&zeros, None, 1.0)] { + let draw = |f: &dyn Fn(&mut Canvas)| { + let mut c = Canvas::new(480, 360).unwrap(); + f(&mut c); + c + }; + let before = draw(&|c| chart_before(c, r, ds, "n", label, INK, ppp)); + let kind = chart_kind(serde_json::json!({"field": "n", "label": label})); + let now = draw(&|c| match kind.chart_data(ds) { + Some(data) => chart(c, r, &data, &ChartLook::default(), INK, ppp, false), + None => placeholder(c, r, "Chart", ppp), + }); + assert!(before.pixmap().data() == now.pixmap().data(), "{label:?} at {ppp}"); + } +} + +/// A negative value runs left of a zero line in the ink; a positive one right of it. +#[test] +fn a_chart_with_a_negative_value_draws_from_a_zero_line() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; + let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new("n", FieldType::Double)]); + for n in [3.0, -1.0] { + ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Float(n)]); + } + let data = chart_kind(serde_json::json!({"field": "n"})).chart_data(&ds).unwrap(); + let mut c = Canvas::new(200, 120).unwrap(); + let r = Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(); + chart(&mut c, r, &data, &ChartLook::default(), INK, 1.0, false); + // Bar area 196 px over a span of 4: zero at 49 px. Rows of 18 px under a 16 px title, + // their bars from 18.7 to 30.6 px and from 36.7 to 48.6 px down. + assert!(bar_blue(&c, 150, 25) && !bar_blue(&c, 30, 25), "3 runs right of zero"); + assert!(bar_blue(&c, 30, 43) && !bar_blue(&c, 70, 43), "-1 runs left of zero"); + // Between the bars, the zero line (0.75 px wide, so partly covering its pixel). + let line = c.pixmap().pixel(49, 34).unwrap(); + assert!(line.alpha() > 60 && line.blue() < 60, "the zero line: {line:?}"); +} + +/// A chart of `vals` (value and name, labelled by the name) drawn with the keys `extra` on a +/// 200 × 120 canvas filling it. +fn chart_drawn(vals: &[(f64, &str)], extra: serde_json::Value) -> Canvas { + use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; + let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new("name", FieldType::Text), Field::new("n", FieldType::Double)]); + for (n, name) in vals { + ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text((*name).into()), Value::Float(*n)]); + } + let mut keys = serde_json::json!({"field": "n", "order": "layer"}); + if let (Some(k), Some(e)) = (keys.as_object_mut(), extra.as_object()) { + k.extend(e.clone()); + } + let kind = chart_kind(keys); + let data = kind.chart_data(&ds).unwrap(); + let mut c = Canvas::new(200, 120).unwrap(); + let r = Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(); + chart(&mut c, r, &data, &kind.chart_look().unwrap(), INK, 1.0, false); + c +} + +/// Each bar in its own colour (#2487 part 3), a bar without one in the look's: across and as +/// columns. +#[test] +fn chart_bars_take_their_own_colours() { + let red = Rgba::rgb(0xD0, 0x10, 0x10); + let data = rustgis_map::layout::ChartData { + bars: vec![(10.0, String::new()), (10.0, String::new())], + labelled: false, + left_out: 0, + out_of_range: 0, + no_number: 0, + title: String::new(), + colors: vec![Some(red), None], + ..Default::default() + }; + let is_red = |c: &Canvas, x: u32, y: u32| c.pixmap().pixel(x, y).is_some_and(|p| p.red() > 150 && p.blue() < 60); + for orientation in [Orientation::Horizontal, Orientation::Vertical] { + let look = ChartLook { orientation, ..ChartLook::default() }; + let mut c = Canvas::new(200, 120).unwrap(); + chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &data, &look, INK, 1.0, false); + // Across, two rows 18 px high from the top; as columns, two slots 100 px wide. + let ((x0, y0), (x1, y1)) = match orientation { + Orientation::Horizontal => ((20, 9), (20, 27)), + Orientation::Vertical => ((50, 100), (150, 100)), + }; + assert!(is_red(&c, x0, y0), "{orientation:?}: the first bar in its own colour"); + assert!(bar_blue(&c, x1, y1) && !is_red(&c, x1, y1), "{orientation:?}: the second in the look's"); + } +} + +/// Stacked (#2487 part 3b), a bar is drawn as its stretches in the key's colours, those above +/// zero from it on and those below from it back, with the key over the bars: across and as +/// columns. +#[test] +fn stacked_bars_draw_their_stretches_and_key() { + let (red, green) = (Rgba::rgb(0xD0, 0x10, 0x10), Rgba::rgb(0x10, 0xC0, 0x10)); + let is = |c: &Canvas, x: u32, y: u32, want: Rgba| { + c.pixmap() + .pixel(x, y) + .is_some_and(|p| p.red().abs_diff(want.0[0]) < 30 && p.green().abs_diff(want.0[1]) < 30 && p.blue().abs_diff(want.0[2]) < 30) + }; + let stacked = |stretches: Vec| rustgis_map::layout::ChartData { + bars: vec![(stretches.iter().sum(), String::new())], + key: vec![("a".into(), red), ("b".into(), green)], + stretches: vec![stretches], + ..Default::default() + }; + let draw = |data: &rustgis_map::layout::ChartData, orientation: Orientation| { + let mut c = Canvas::new(200, 120).unwrap(); + let look = ChartLook { orientation, ..ChartLook::default() }; + chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), data, &look, INK, 1.0, false); + c + }; + // The key's row (14 px) over a bar 18 px high: 6 of 10 in red from the left, 4 in green. + let c = draw(&stacked(vec![6.0, 4.0]), Orientation::Horizontal); + assert!(is(&c, 3, 7, red), "the key's first swatch"); + assert!(is(&c, 50, 23, red) && is(&c, 150, 23, green), "the stretches along the bar"); + assert!(!is(&c, 50, 7, red), "the bar starts under the key"); + // As a column from the bottom up: red at its foot, green over it. + let c = draw(&stacked(vec![6.0, 4.0]), Orientation::Vertical); + assert!(is(&c, 100, 100, red) && is(&c, 100, 30, green), "the stretches up the column"); + // Mirrored (#2487 part 4), the stretches run from the right, the key staying where it is. + let mut c = Canvas::new(200, 120).unwrap(); + let look = ChartLook { mirror: true, ..ChartLook::default() }; + chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &stacked(vec![6.0, 4.0]), &look, INK, 1.0, false); + assert!(is(&c, 3, 7, red) && is(&c, 150, 23, red) && is(&c, 50, 23, green), "red from the right, green past it"); + // On a fixed maximum a stretch past it is cut at it, and one wholly past it isn't drawn. + for (max, far) in [(8.0, green), (5.0, red)] { + let mut c = Canvas::new(200, 120).unwrap(); + let look = ChartLook { max: Some(max), ..ChartLook::default() }; + chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &stacked(vec![6.0, 4.0]), &look, INK, 1.0, false); + assert!(is(&c, 190, 23, far) && !is(&c, 199, 23, far), "{max}: the bar ends at the maximum"); + } + // At 5 the green stretch, from 6 on, is wholly past it: none of it is drawn, anywhere. + let mut c = Canvas::new(200, 120).unwrap(); + let look = ChartLook { max: Some(5.0), ..ChartLook::default() }; + chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &stacked(vec![6.0, 4.0]), &look, INK, 1.0, false); + assert!((0..200).all(|x| !is(&c, x, 23, green)), "no green along the bar"); + // One running back from zero is drawn whole on a fixed maximum too: 2 of a span of 7 (from + // -2 to 5) left of zero, red cut at 5 on the right. + let mut c = Canvas::new(200, 120).unwrap(); + chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &stacked(vec![6.0, -2.0]), &look, INK, 1.0, false); + assert!(is(&c, 30, 23, green) && is(&c, 150, 23, red) && !is(&c, 199, 23, red), "back from zero, cut at the maximum"); + // Stretches all below zero run back from it, the first one too: red 6 of 10 from the + // right, green past it. + let c = draw(&stacked(vec![-6.0, -4.0]), Orientation::Horizontal); + assert!(is(&c, 150, 23, red) && is(&c, 50, 23, green), "both stretches back from zero"); + // A negative stretch runs back from zero: 2 of a span of 8 left of it, 6 right. + let c = draw(&stacked(vec![6.0, -2.0]), Orientation::Horizontal); + assert!(is(&c, 20, 23, green) && is(&c, 100, 23, red), "either way from zero"); + // A bar with no stretches (they add up past the largest number) is drawn whole. + let mut whole = stacked(vec![6.0, 4.0]); + whole.stretches = vec![Vec::new()]; + let c = draw(&whole, Orientation::Horizontal); + assert!(is(&c, 50, 23, ChartLook::default().bar_color) && is(&c, 150, 23, ChartLook::default().bar_color), "whole"); + // A key of a row a value, taller than a short box leaves the bars, draws neither: the + // placeholder instead, nothing past the box. + let mut long = stacked(vec![6.0, 4.0]); + long.key = (0..8).map(|k| (format!("{k} a value with a long name to fill a row"), red)).collect(); + long.stretches = vec![vec![1.0; 8]]; + for orientation in [Orientation::Horizontal, Orientation::Vertical] { + let mut c = Canvas::new(200, 120).unwrap(); + let look = ChartLook { orientation, ..ChartLook::default() }; + chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 60.0).unwrap(), &long, &look, INK, 1.0, false); + assert!(is(&c, 100, 50, Rgba::rgb(0xF0, 0xF1, 0xF3)) && !is(&c, 5, 50, red), "the placeholder"); + assert!(c.pixmap().pixel(5, 90).is_some_and(|p| p.alpha() == 0), "nothing under the box"); + } + // As columns, the head leaves the bars a line past their labels and values: 40 pt high, + // one key row, labelled and valued, is crowded so, not across; and the commands say so as + // the page draws it. + let mut short = stacked(vec![6.0, 4.0]); + short.key.truncate(1); + short.stretches = vec![vec![10.0]]; + short.labelled = true; + let (w, h) = (200.0 / PT_PER_MM, 40.0 / PT_PER_MM); + let valued = |orientation| ChartLook { orientation, values: true, ..ChartLook::default() }; + assert!(chart_crowded(&short, &valued(Orientation::Vertical), w, h)); + assert!(!chart_crowded(&short, &valued(Orientation::Horizontal), w, h)); + assert!(!chart_crowded(&stacked(vec![6.0, 4.0]), &ChartLook::default(), w, 120.0 / PT_PER_MM)); + // A box narrower than a swatch draws the placeholder too, nothing past its right. + // Sample above the centered "Chart" label so system font glyph shapes at y=60 don't mask the fill. + let mut c = Canvas::new(200, 120).unwrap(); + chart(&mut c, Rect::from_xywh(0.0, 0.0, 5.0, 120.0).unwrap(), &stacked(vec![6.0, 4.0]), &ChartLook::default(), INK, 1.0, false); + assert!(is(&c, 2, 10, Rgba::rgb(0xF0, 0xF1, 0xF3)) && (6..20).all(|x| c.pixmap().pixel(x, 7).is_some_and(|p| p.alpha() == 0))); +} + +fn bar_blue(c: &Canvas, x: u32, y: u32) -> bool { + c.pixmap().pixel(x, y).is_some_and(|p| p.blue() > 150 && p.red() < 100) +} + +/// Ink (dark, opaque enough) in the pixels `xs` × `ys`, read unpremultiplied: a bar's +/// half-covered edge is its own colour, not a dark one. +fn chart_inked(c: &Canvas, xs: std::ops::Range, ys: std::ops::Range) -> bool { + xs.flat_map(|x| ys.clone().map(move |y| (x, y))) + .any(|(x, y)| c.pixmap().pixel(x, y).map(|p| p.demultiply()).is_some_and(|p| p.alpha() > 80 && p.blue() < 90 && p.red() < 90)) +} + +/// Columns stand on the bottom, a slot each, 70 % of it wide; with no title they take its room. +#[test] +fn a_vertical_chart_draws_columns() { + let c = chart_drawn(&[(3.0, "a"), (1.0, "b")], serde_json::json!({"orientation": "Vertical", "title": ""})); + // Slots of 100 px, columns from 15 to 85 and 115 to 185; 3 fills the 120 px, 1 a third. + assert!(bar_blue(&c, 50, 10) && bar_blue(&c, 50, 110), "3 fills its slot's height"); + assert!(!bar_blue(&c, 150, 60) && bar_blue(&c, 150, 100), "1 stands a third as high"); + assert!(!bar_blue(&c, 100, 110) && !bar_blue(&c, 5, 110), "gaps between and beside the columns"); + // A negative one hangs from a zero line in the ink. + let c = chart_drawn(&[(3.0, "a"), (-1.0, "b")], serde_json::json!({"orientation": "Vertical", "title": ""})); + assert!(bar_blue(&c, 50, 60) && !bar_blue(&c, 50, 100), "3 stands above zero at 90 px"); + assert!(bar_blue(&c, 150, 105) && !bar_blue(&c, 150, 60), "-1 hangs below it"); + // Labelled, the labels sit under the columns, centred on them. + let c = chart_drawn(&[(3.0, "a"), (1.0, "b")], serde_json::json!({"orientation": "Vertical", "label": "name", "title": ""})); + assert!(chart_inked(&c, 40..60, 108..120) && chart_inked(&c, 140..160, 108..120) && !bar_blue(&c, 50, 112)); +} + +/// Values are written past each bar's end, the bars kept short enough to leave them room; +/// a negative one's past its left end. +#[test] +fn a_charts_values_are_written_past_its_bars() { + let plain = chart_drawn(&[(3.0, "a")], serde_json::json!({})); + let valued = chart_drawn(&[(3.0, "a")], serde_json::json!({"values": true})); + // One row of 18 px under a 16 px title: the bar from 18.7 to 30.6 px down. + assert!(bar_blue(&plain, 194, 25) && !chart_inked(&plain, 150..200, 18..32)); + assert!(!bar_blue(&valued, 194, 25) && bar_blue(&valued, 150, 25) && chart_inked(&valued, 185..200, 18..32), "3 at the bar's end"); + let negative = chart_drawn(&[(3.0, "a"), (-1.0, "b")], serde_json::json!({"values": true})); + assert!(chart_inked(&negative, 0..40, 36..50), "-1 left of its bar"); +} + +/// Values too wide for the chart are written smaller, leaving the bars half its width. +#[test] +fn a_charts_wide_values_leave_its_bars_room() { + let c = chart_drawn(&[(1e12, "a"), (-1e12, "b")], serde_json::json!({"values": true})); + // The bars of 1e12 and -1e12 take the bar area between them: at least half of the 196 px. + let blue = (0..200).filter(|x| bar_blue(&c, *x, 25) || bar_blue(&c, *x, 43)).count(); + assert!(blue >= 97, "{blue} px of bar"); + assert!(chart_inked(&c, 150..200, 18..32), "its value beside it"); +} + +/// The largest number and its opposite span past a number's range: each bar still takes its +/// half of the chart, across or as columns. +#[test] +fn a_charts_bars_past_a_numbers_range_take_their_half() { + let across = chart_drawn(&[(f64::MAX, "a"), (-f64::MAX, "b")], serde_json::json!({})); + let row = |y: u32| (0..200).filter(|x| bar_blue(&across, *x, y)).count(); + assert!(row(25) > 50 && row(43) > 50, "{} and {} px", row(25), row(43)); + let columns = chart_drawn(&[(f64::MAX, "a"), (-f64::MAX, "b")], serde_json::json!({"orientation": "Vertical"})); + let up = (0..120).filter(|y| bar_blue(&columns, 50, *y)).count(); + let down = (0..120).filter(|y| bar_blue(&columns, 150, *y)).count(); + assert!(up > 30 && down > 30, "{up} and {down} px"); +} + +/// No title gives its room to the bars; a bar colour is drawn as given. +#[test] +fn a_chart_without_a_title_and_with_a_bar_colour() { + let titled = chart_drawn(&[(3.0, "a")], serde_json::json!({})); + let untitled = chart_drawn(&[(3.0, "a")], serde_json::json!({"title": ""})); + assert!(!bar_blue(&titled, 150, 8) && bar_blue(&untitled, 150, 8)); + assert!(chart_inked(&titled, 0..20, 0..16) && !chart_inked(&untitled, 0..20, 0..16), "the title, or none"); + let rose = chart_drawn(&[(3.0, "a")], serde_json::json!({"bar_color": [194, 24, 91, 255]})); + let p = rose.pixmap().pixel(150, 25).unwrap(); + assert!(p.red() > 180 && p.green() < 40 && p.blue() > 80 && p.blue() < 100, "{p:?}"); +} + +/// Labels at the right of their column end against the bars; at its left, from its edge. +#[test] +fn a_charts_labels_sit_left_or_against_the_bars() { + let left = chart_drawn(&[(3.0, "Madrid")], serde_json::json!({"label": "name"})); + let right = chart_drawn(&[(3.0, "Madrid")], serde_json::json!({"label": "name", "label_align": "Right"})); + // The labels' column is 64 px wide. + assert!(chart_inked(&left, 0..6, 18..32) && !chart_inked(&left, 56..63, 18..32)); + assert!(!chart_inked(&right, 0..6, 18..32) && chart_inked(&right, 50..63, 18..32)); +} + +/// Mirrored (#2487 part 4), a chart is drawn as its mirror image, its text read as ever: bars +/// run from the right, their labels' column at the right, values past the bars' left ends, a +/// negative bar to the right of zero; columns hang from the top, their labels over them. +#[test] +fn a_mirrored_chart_runs_the_other_way() { + use serde_json::json; + let plain = chart_drawn(&[(3.0, "a"), (1.0, "b")], json!({})); + let mirrored = chart_drawn(&[(3.0, "a"), (1.0, "b")], json!({"mirror": true})); + // Rows of 18 px under a 16 px title. The bar area is 196 px, kept 4 px from the left when + // mirrored; 1 takes a third of it. + assert!(bar_blue(&plain, 20, 43) && !bar_blue(&plain, 180, 43), "1 runs right from the left"); + assert!(bar_blue(&mirrored, 180, 43) && !bar_blue(&mirrored, 20, 43), "1 runs left from the right"); + assert!(bar_blue(&mirrored, 10, 25) && !bar_blue(&mirrored, 1, 25), "3 fills the bar area"); + // Labelled, the 64 px column is at the right; the label at its outer edge, the right. + let labelled = chart_drawn(&[(3.0, "Madrid")], json!({"label": "name", "mirror": true})); + assert!(bar_blue(&labelled, 10, 25) && !bar_blue(&labelled, 140, 25), "the bars left of the labels"); + assert!(chart_inked(&labelled, 190..200, 18..32) && !chart_inked(&labelled, 0..40, 18..32), "the label at the right"); + // Values past the bar's left end. + let valued = chart_drawn(&[(3.0, "a")], json!({"values": true, "mirror": true})); + assert!(chart_inked(&valued, 0..15, 18..32) && !chart_inked(&valued, 185..200, 18..32)); + // Zero 49 px from the right: 3 runs left of it, -1 right. + let negative = chart_drawn(&[(3.0, "a"), (-1.0, "b")], json!({"mirror": true})); + assert!(bar_blue(&negative, 50, 25) && !bar_blue(&negative, 170, 25), "3 left of zero"); + assert!(bar_blue(&negative, 170, 43) && !bar_blue(&negative, 50, 43), "-1 right of zero"); + // Columns hang from the top: 1 a third of the 120 px down. + let columns = chart_drawn(&[(3.0, "a"), (1.0, "b")], json!({"orientation": "Vertical", "title": "", "mirror": true})); + assert!(bar_blue(&columns, 150, 10) && !bar_blue(&columns, 150, 100), "1 hangs from the top"); + assert!(bar_blue(&columns, 50, 110), "3 fills its slot"); + let labelled = chart_drawn(&[(3.0, "a"), (1.0, "b")], json!({"orientation": "Vertical", "title": "", "label": "name", "mirror": true})); + assert!(chart_inked(&labelled, 40..60, 0..12) && !chart_inked(&labelled, 40..60, 108..120), "labels over the columns"); +} + +/// A fixed maximum is the far end of the bar area, so charts given the same one share a +/// scale; a bar past it runs to that end. A maximum not above zero isn't read. +#[test] +fn a_charts_maximum_sets_its_scale() { + use serde_json::json; + let own = chart_drawn(&[(50.0, "a")], json!({})); + let shared = chart_drawn(&[(50.0, "a")], json!({"max": 100.0})); + assert!(bar_blue(&own, 150, 25), "50 fills the 196 px on its own"); + assert!(bar_blue(&shared, 90, 25) && !bar_blue(&shared, 110, 25), "50 of 100 takes half of them"); + let past = chart_drawn(&[(150.0, "a"), (50.0, "b")], json!({"max": 100.0})); + assert!(bar_blue(&past, 194, 25) && !bar_blue(&past, 198, 25), "150 runs to the end, no further"); + assert!(bar_blue(&past, 90, 43) && !bar_blue(&past, 110, 43), "50 still half"); + // A column of one 140 px slot, 120 px high: 50 of 100 stands half as high. + let columns = chart_drawn(&[(50.0, "a")], json!({"orientation": "Vertical", "title": "", "max": 100.0})); + assert!(bar_blue(&columns, 100, 100) && !bar_blue(&columns, 100, 40)); + for bad in [json!(0.0), json!(-5.0)] { + assert!(bar_blue(&chart_drawn(&[(50.0, "a")], json!({"max": bad})), 150, 25), "{bad}"); + } + // Bars all at zero still draw the placeholder, as they do on their own scale. + let zeros = |extra| chart_drawn(&[(0.0, "a"), (0.0, "b")], extra).pixmap().data().to_vec(); + assert_eq!(zeros(json!({"max": 100.0})), zeros(json!({}))); +} + +/// A bar outline (#2487 part 4b) runs round each bar, across, mirrored and as columns, and +/// round each stretch of a stacked bar; none where it isn't given. +#[test] +fn a_charts_bar_outline_runs_round_each_bar() { + use serde_json::json; + let red = |c: &Canvas, x: u32, y: u32| c.pixmap().pixel(x, y).is_some_and(|p| p.red() > 150 && p.blue() < 100); + let outline = json!({"bar_outline": {"color": [208, 16, 16, 255], "width": 2.0}}); + let plain = chart_drawn(&[(50.0, "a")], json!({})); + assert!(!red(&plain, 100, 19) && bar_blue(&plain, 100, 25), "no outline unless given"); + let c = chart_drawn(&[(50.0, "a")], outline.clone()); + assert!(red(&c, 100, 19) && red(&c, 100, 30) && bar_blue(&c, 100, 25), "inside its top and bottom, filled within"); + let mut mirrored = outline.clone(); + mirrored["mirror"] = json!(true); + let c = chart_drawn(&[(50.0, "a"), (25.0, "b")], mirrored); + assert!(red(&c, 199, 25) && red(&c, 150, 37) && bar_blue(&c, 150, 43), "round the bars from the right"); + assert!(red(&c, 102, 43) && !bar_blue(&c, 50, 43), "the shorter bar's line where it ends, on the left"); + // Within each bar: a wide line paints nothing the bars leave blank, so it never runs into + // their values, labels or title, nor past the chart's room. + let blank = |c: &Canvas, x: u32, y: u32| c.pixmap().pixel(x, y).is_some_and(|p| p.alpha() < 16); + for look in [json!({"values": true}), json!({"mirror": true}), json!({"orientation": "Vertical", "values": true})] { + let vals = [(50.0, "a"), (25.0, "b"), (0.5, "c")]; + let plain = chart_drawn(&vals, look.clone()); + let mut wide = look.clone(); + wide["bar_outline"] = json!({"color": [208, 16, 16, 255], "width": 5.0}); + let c = chart_drawn(&vals, wide); + let spilt = (0..200).flat_map(|x| (0..120).map(move |y| (x, y))).filter(|(x, y)| blank(&plain, *x, *y) && red(&c, *x, *y)).count(); + assert_eq!(spilt, 0, "{look}"); + } + let mut columns = outline.clone(); + (columns["orientation"], columns["title"]) = (json!("Vertical"), json!("")); + let c = chart_drawn(&[(50.0, "a")], columns); + assert!(red(&c, 100, 0) && red(&c, 30, 60) && red(&c, 169, 60) && bar_blue(&c, 100, 60), "round the column"); + // Round each stretch: a line between the two of a bar split 6 to 4. + let stacked = rustgis_map::layout::ChartData { + bars: vec![(10.0, String::new())], + key: vec![("a".into(), Rgba::rgb(0x10, 0x10, 0xD0)), ("b".into(), Rgba::rgb(0x10, 0x10, 0xD0))], + stretches: vec![vec![6.0, 4.0]], + ..Default::default() + }; + let look = ChartLook { + bar_outline: Some(rustgis_map::layout::ChartOutline { color: Rgba::rgb(0xD0, 0x10, 0x10), width: 2.0 }), + ..ChartLook::default() + }; + let mut c = Canvas::new(200, 120).unwrap(); + chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &stacked, &look, INK, 1.0, false); + // The divider's footprint: what isn't the bars' blue where the two stretches meet. One + // line of the outline's width, 2 px off the pixel grid touching 3, not one from each + // stretch (5). + let divider = (100..140).filter(|x| !bar_blue(&c, *x, 23)).count(); + assert_eq!(divider, 3, "one line of the outline's width between the stretches"); + // A see-through line is laid once everywhere: as red between the stretches as along the + // bar's edge, not twice over on one side of the divider. + let half_red = ChartLook { + bar_outline: Some(rustgis_map::layout::ChartOutline { color: Rgba([208, 16, 16, 128]), width: 3.0 }), + ..ChartLook::default() + }; + let mut c = Canvas::new(200, 120).unwrap(); + chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &stacked, &half_red, INK, 1.0, false); + let reddest = |xs: std::ops::Range, y: u32| xs.filter_map(|x| c.pixmap().pixel(x, y)).map(|p| p.red()).max().unwrap_or(0); + let (edge, between) = (reddest(0..8, 25), reddest(100..140, 25)); + assert!(edge > 60 && between.abs_diff(edge) <= 3, "edge {edge}, between {between}"); + // Bars thinner than the line, and a stretch thinner than it, keep their colour: the line + // narrows to a third of them rather than covering them. + let thin = json!({"bar_outline": {"color": [208, 16, 16, 255], "width": 5.0}}); + let c = chart_drawn(&[(50.0, "a"); 20], thin); + // Down the bars' middle, blue outweighs red at least once a bar (none when the line + // covered them). + let blue = (0..120).filter(|y| c.pixmap().pixel(100, *y).is_some_and(|p| p.alpha() > 0 && p.blue() > p.red())).count(); + assert!(blue >= 20, "every bar keeps its blue, {blue} px"); + let green = Rgba::rgb(0x10, 0xC0, 0x10); + let sliver = rustgis_map::layout::ChartData { + bars: vec![(10.0, String::new())], + key: vec![("a".into(), Rgba::rgb(0x10, 0x10, 0xD0)), ("b".into(), green)], + stretches: vec![vec![9.85, 0.15]], + ..Default::default() + }; + let look = ChartLook { + bar_outline: Some(rustgis_map::layout::ChartOutline { color: Rgba::rgb(0xD0, 0x10, 0x10), width: 5.0 }), + ..ChartLook::default() + }; + let mut c = Canvas::new(200, 120).unwrap(); + chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &sliver, &look, INK, 1.0, false); + // In the bar's rows, those it paints down its middle, which the key's green swatch is not in. + let rows: Vec = (0..120).filter(|y| c.pixmap().pixel(100, *y).is_some_and(|p| p.alpha() > 0)).collect(); + assert!(rows.len() > 5, "the bar's rows, {rows:?}"); + let greens = (0..200) + .flat_map(|x| rows.iter().map(move |y| (x, *y))) + .filter(|(x, y)| c.pixmap().pixel(*x, *y).is_some_and(|p| p.green() > 150 && p.red() < 100)) + .count(); + assert!(greens > 0, "the thin stretch keeps its green"); + // A first stretch drawn a pixel long though its share is far shorter: the next starts + // inside it, and the line, a third of a pixel, still stays inside the bar, between the + // stretches and round them (a stroke that thin is drawn a pixel wide), across and as + // columns. + let tiny = rustgis_map::layout::ChartData { stretches: vec![vec![0.001, 9.999]], ..sliver }; + for orientation in [rustgis_map::layout::Orientation::Horizontal, rustgis_map::layout::Orientation::Vertical] { + let mut plain = Canvas::new(200, 120).unwrap(); + let bare = ChartLook { bar_outline: None, orientation, ..look }; + chart(&mut plain, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &tiny, &bare, INK, 1.0, false); + let mut lined = Canvas::new(200, 120).unwrap(); + chart(&mut lined, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &tiny, &ChartLook { orientation, ..look }, INK, 1.0, false); + // Nothing where the bar itself paints nothing. + let spilt = (0..200) + .flat_map(|x| (0..120).map(move |y| (x, y))) + .filter(|(x, y)| plain.pixmap().pixel(*x, *y).is_some_and(|p| p.alpha() == 0)) + .filter(|(x, y)| lined.pixmap().pixel(*x, *y).is_some_and(|p| p.alpha() > 0 && p.red() > p.green())) + .count(); + assert_eq!(spilt, 0, "{orientation:?}: the lines round and between the stretches stay inside the bar"); + } + // Only the bar's end next to that stretch narrows: along the rest of the bar, the edge + // keeps its width. + let mut c = Canvas::new(200, 120).unwrap(); + chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &tiny, &look, INK, 1.0, false); + let lined = (0..120).filter(|y| c.pixmap().pixel(100, *y).is_some_and(|p| p.red() > 150 && p.blue() < 100)).count(); + assert!(lined >= 6, "both edges of the bar a few pixels wide, {lined} rows"); + // The edge is one shape: where its sides meet off the pixel grid, the shared pixel is + // covered once, not twice in part with the bar's blue showing through between them. + let one = rustgis_map::layout::ChartData { + bars: vec![(10.0, String::new())], + key: vec![("a".into(), Rgba::rgb(0x10, 0x10, 0xD0))], + stretches: vec![vec![10.0]], + ..Default::default() + }; + let mut c = Canvas::new(200, 120).unwrap(); + chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &one, &look, INK, 1.0, false); + // The bar's rows, below the key's swatch: those its end's line reaches. + let red = |y: &u32| c.pixmap().pixel(2, *y).is_some_and(|p| p.red() > 100); + let (Some(top), Some(bottom)) = ((0..120).find(red), (0..120).rev().find(red)) else { panic!("no line") }; + let seams = (top + 1..bottom).filter(|y| c.pixmap().pixel(2, *y).is_some_and(|p| p.blue() > 20)).count(); + assert!(bottom - top > 5 && seams == 0, "inside the bar's end, all line: {seams} rows show the bar"); + // Lines between twenty stretches too thin to part them overlap: a see-through colour + // covers the overlap once, never redder than along the edge. + let mut thin = vec![0.0005; 20]; + thin.insert(0, 5.0); + thin.push(4.99); + let crowded = rustgis_map::layout::ChartData { + key: (0..thin.len()).map(|i| (i.to_string(), if i % 2 == 0 { Rgba::rgb(0x10, 0x10, 0xD0) } else { green })).collect(), + stretches: vec![thin], + ..one + }; + let mut c = Canvas::new(200, 120).unwrap(); + chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(), &crowded, &half_red, INK, 1.0, false); + let reddest = |xs: std::ops::Range, y: u32| xs.filter_map(|x| c.pixmap().pixel(x, y)).map(|p| p.red()).max().unwrap_or(0); + // The middle of the bar, below the key. + let lined: Vec = (0..120).filter(|y| reddest(0..3, *y) > 60).collect(); + let row = lined.get(lined.len() / 2).copied().unwrap_or(0); + let (edge, between) = (reddest(0..8, row), reddest(8..190, row)); + assert!(edge > 60 && between <= edge + 3, "edge {edge}, between {between}"); +} + +/// Hidden labels leave their column, or their row under columns, to the bars. +#[test] +fn a_charts_hidden_labels_leave_their_room_to_the_bars() { + use serde_json::json; + let shown = chart_drawn(&[(3.0, "Madrid")], json!({"label": "name"})); + let hidden = chart_drawn(&[(3.0, "Madrid")], json!({"label": "name", "hide_labels": true})); + assert!(!bar_blue(&shown, 30, 25) && chart_inked(&shown, 0..6, 18..32)); + assert!(bar_blue(&hidden, 30, 25) && !chart_inked(&hidden, 0..60, 18..32)); + let columns = chart_drawn(&[(3.0, "Madrid")], json!({"orientation": "Vertical", "title": "", "label": "name", "hide_labels": true})); + assert!(bar_blue(&columns, 100, 115), "the column down to the bottom"); +} + +/// Both map frames share the index feature, even though the locator draws a different map. +/// A page using expressions draws exactly like the same page with its values written inline. +#[test] +fn series_style_follows_the_index_feature_in_both_frames() { + use rustgis_data::{Dataset, Feature, Field, FieldType, Geometry, Value}; + use rustgis_map::layout::MapSeries; + + let mut ds = Dataset::new("Tracts", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); + for (x, id, name) in [(-0.18, 71, "West"), (0.04, 295, "East")] { + let ring = [(x, -0.06), (x + 0.14, -0.06), (x + 0.14, 0.06), (x, 0.06), (x, -0.06)]; + ds.features.push(Feature { + id, + geometry: Some(Geometry::Polygon(vec![vec![ring.map(|(x, y)| Coord::new(x, y)).to_vec()]])), + attrs: vec![Value::Text(name.into())], + }); + } + let mut main = Map::new("Main"); + let mut locator = Map::new("Locator"); + main.add_dataset(ds.clone()); + locator.add_dataset(ds); + let mut maps = [main, locator]; + let mut layout = Layout::new("Atlas", 140.0, 75.0); + let [frame, _] = std::array::from_fn(|i| { + let m = &maps[i]; + let frame = serde_json::from_value(serde_json::json!({"MapFrame": { + "map": m.name, "center": {"x": 0, "y": 0}, "scale": 1_000_000 + }})) + .unwrap(); + layout.add(&m.name, (5.0 + i as f64 * 70.0, 5.0, 60.0, 65.0), frame) + }); + let base = render(&layout, &mut maps, 72.0, &PageInfo::default()).unwrap(); + layout.series = Some(MapSeries { frame, layer: "Tracts".into(), name_field: "name".into(), margin: 0.1, page: 0 }); + let info = PageInfo::default(); + let unchanged = render(&layout, &mut maps, 72.0, &info).unwrap(); + assert_eq!(base.data(), unchanged.data()); + + let style = |maps: &mut [Map], id: &str, name: &str, number: &str| { + for (i, map) in maps.iter_mut().enumerate() { + let layer = map.layers.first_mut().unwrap(); + let page_feature = format!("$id = {id}"); + layer.definition_query = Some(format!("{number} > 0")); + layer.symbol_by.stroke_width = Some(format!("if({page_feature}, 3, 0.6)")); + if i == 0 { + layer.symbol_by.fill = Some(format!("if({page_feature}, '#8bbce8', '#e5e7eb')")); + } else { + // The locator keeps the two classes by a rule expression and filters by page. + let mut renderer = rustgis_map::Renderer::unique( + &layer.dataset, + &[], + "name", + rustgis_map::Ramp::Harbour, + rustgis_map::Symbol::default_for(GeometryType::Polygon, 0), + ) + .unwrap(); + let rustgis_map::Renderer::Unique { expression, .. } = &mut renderer else { panic!() }; + *expression = Some(format!("CASE WHEN {page_feature} THEN 'West' ELSE 'East' END")); + layer.renderer = renderer; + layer.display_filters = vec![rustgis_map::effects::DisplayFilter { + name: "Current tract".into(), + min_scale: None, + max_scale: None, + where_: page_feature.clone(), + }]; + } + layer.labels.enabled = true; + layer.labels.default.where_ = Some(page_feature); + layer.labels.default.by.text = Some(format!("{name} || ' ' || {number}")); + } + }; + let mut previous = base; + for (row, id, name) in [(0, "71", "'West'"), (1, "295", "'East'")] { + layout.series.as_mut().unwrap().page = row; + style(&mut maps, "@page_feature_id", "@page_name", "@page_number"); + let (page, _) = render_pending(&layout, &mut maps, 72.0, &info).unwrap(); + let svg = crate::svg::layout_svg(&layout, &mut maps, 72.0, &info).unwrap().0; + style(&mut maps, id, name, &(row + 1).to_string()); + let mut ordinary = layout.clone(); + ordinary.series = None; + let expected = render(&ordinary, &mut maps, 72.0, &info).unwrap(); + assert!(page.data() == expected.data(), "series page {} differs from the literal expressions", row + 1); + assert_ne!(page.data(), previous.data()); + assert_eq!(svg, crate::svg::layout_svg(&ordinary, &mut maps, 72.0, &info).unwrap().0); + previous = page; + } +} + +/// A legend's, colorbar's, table's or chart's ink colours its text and lines (#2257). Without +/// one, they draw in dark grey as before, a table on its white cells; with one, a table has no +/// white cells, only its header and stripes in a tint of the ink. +#[test] +fn an_ink_colours_legends_colorbars_tables_and_charts() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; + let red = Rgba::rgb(0xE0, 0x10, 0x10); + let reddish = |c: &Canvas| c.pixmap().pixels().iter().any(|p| p.alpha() > 200 && p.red() > 150 && p.green() < 90 && p.blue() < 90); + let draw = |f: &dyn Fn(&mut Canvas)| { + let mut c = Canvas::new(200, 120).unwrap(); + f(&mut c); + c + }; + let r = Rect::from_xywh(0.0, 0.0, 200.0, 120.0).unwrap(); + let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new("name", FieldType::Text), Field::new("n", FieldType::Double)]); + for (name, n) in [("a", 3.0), ("b", 1.0)] { + ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text(name.into()), Value::Float(n)]); + } + let map = Map::new("m"); + let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + let grey = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(0, 0, 0), Rgba::rgb(255, 255, 255)] }; + let bar = |ink| Bar { + title: "Height", + orientation: Orientation::Horizontal, + ticks: 3, + side: TickSide::End, + reverse: false, + comma: false, + ink, + }; + for (ink, expected) in [(INK, false), (red, true)] { + let legend = draw(&|c| { + legend_missing(c, r, &map, ("Key", 1), None, opts, ink, 1.0); + }); + assert_eq!(reddish(&legend), expected, "legend {ink:?}"); + assert_eq!(reddish(&draw(&|c| colorbar(c, r, &grey, &bar(ink), 1.0))), expected, "colorbar {ink:?}"); + // Its bars keep their blue. + let data = chart_kind(serde_json::json!({"field": "n", "label": "name"})).chart_data(&ds).unwrap(); + assert_eq!(reddish(&draw(&|c| chart(c, r, &data, &ChartLook::default(), ink, 1.0, false))), expected, "chart {ink:?}"); + } + // Two columns 90 px wide, a header and two rows 17 px high: (175, 25) is in the first + // row's empty right end, (175, 8) in the header's. + let plain = draw(&|c| table(c, r, &ds, 5, None, 1.0)); + let inked = draw(&|c| table(c, r, &ds, 5, Some(red), 1.0)); + assert!(!reddish(&plain) && reddish(&inked)); + let at = |c: &Canvas, x, y| c.pixmap().pixel(x, y).unwrap(); + assert_eq!((at(&plain, 175, 25).red(), at(&plain, 175, 25).alpha()), (255, 255), "white cells without an ink"); + assert_eq!(at(&inked, 175, 25).alpha(), 0, "none with one"); + let header = at(&inked, 175, 8); + assert!(header.alpha() > 0 && header.alpha() < 100 && header.green() < header.red(), "a tint of the ink: {header:?}"); +} + +/// No-data rows reuse the map's fallback symbol, respect filters, and never appear by +/// default. All-classes mode can key the symbol even when the current frame doesn't use it. +#[test] +fn layout_no_data_legend_follows_the_frame() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; + let mut map = Map::new("m"); + let mut ds = Dataset::new("tracts", GeometryType::Point, vec![Field::new("percent", FieldType::Double)]); + for v in [Value::Float(10.0), Value::Float(50.0), Value::Null] { + ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![v]); + } + let id = map.add_dataset(ds); + let l = map.layer_mut(id).unwrap(); + l.renderer = rustgis_map::Renderer::graduated( + &l.dataset, + &[], + "percent", + 2, + rustgis_map::ClassMethod::EqualInterval, + rustgis_map::Ramp::Ember, + rustgis_map::Symbol::default_for(GeometryType::Point, 0), + ) + .unwrap(); + let fallback = l.renderer.symbol_for(&l.dataset, 2); + let listed = |map: &mut Map, all: bool, show: bool| { + let drawn = (!all).then(|| complete_shown_legends(map, 1e6, show, &mut None, &Env::default()).unwrap()); + let opts = LegendOptions { show_no_data: show, hide_other: true, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + legend_rows(map, drawn.as_deref(), &opts) + .into_iter() + .filter_map(|r| match r { + LegendRow::Class(_, e) if e.label == "No data" => Some(e.symbol), + _ => None, + }) + .collect::>() + }; + assert!(listed(&mut map, false, false).is_empty()); + assert_eq!(listed(&mut map, false, true), vec![fallback]); + map.layer_mut(id).unwrap().definition_query = Some("percent IS NOT NULL".into()); + assert!(listed(&mut map, false, true).is_empty()); + assert_eq!(listed(&mut map, true, true), vec![fallback]); + let sizes = |map: &mut Map, show| { + legend_sizes_with_no_data_mm(map, 1e6, true, true, (show, rustgis_map::layout::LEGEND_TEXT_PT), (&[], &NO_LABELS)).unwrap()[0] + }; + assert!(sizes(&mut map, true).1 > sizes(&mut map, false).1); +} + +/// Page clipping is tested after alignment and rotation; box width alone is not clipping. +/// A legend's long title is text too, and invisible elements must not generate notices. +#[test] +fn layout_text_clipping_uses_ink_and_visibility() { + let mut l = Layout::new("Page", 120.0, 90.0); + let id = l.add("Title", (10.0, 10.0, 5.0, 12.0), ElementKind::text("Long line", 14.0, Rgba::rgb(0, 0, 0), false)); + let info = PageInfo::default(); + assert!(clipped_text(&l, &[], 96.0, &info).is_empty(), "outside the box but on the page"); + l.element_mut(id).unwrap().x = 117.0; + assert_eq!(clipped_text(&l, &[], 96.0, &info), vec![(id, "Title".into())]); + l.element_mut(id).unwrap().visible = false; + assert!(clipped_text(&l, &[], 96.0, &info).is_empty()); + let e = l.element_mut(id).unwrap(); + e.visible = true; + (e.x, e.y, e.w) = (0.0, 40.0, 60.0); + if let ElementKind::Text { align, rotation, letter_spacing, .. } = &mut e.kind { + *align = TextAlign::Right; + *letter_spacing = 2.0; + *rotation = 90.0; + } + assert!(clipped_text(&l, &[], 96.0, &info).is_empty(), "turned ink fits"); + l.element_mut(id).unwrap().y = 85.0; + assert_eq!(clipped_text(&l, &[], 96.0, &info).len(), 1, "turned ink is off-page"); + l.element_mut(id).unwrap().visible = false; + let frame = l.add( + "Frame", + (10.0, 10.0, 60.0, 70.0), + serde_json::from_value(serde_json::json!({"MapFrame":{"map":"m", "center":{"x":0,"y":0}, "scale":1000000}})).unwrap(), + ); + let legend = l.add( + "Legend", + (115.0, 10.0, 5.0, 40.0), + ElementKind::Legend { + frame, + title: "Long legend title".into(), + all_classes: false, + hide_other: false, + show_no_data: false, + exclude: vec![], + columns: 1, + labels: BTreeMap::new(), + color: None, + text_size: rustgis_map::layout::LEGEND_TEXT_PT, + }, + ); + assert_eq!(clipped_text(&l, &[Map::new("m")], 96.0, &info), vec![(legend, "Legend".into())]); + // Its title is measured at the size it is drawn at (#2581): one that fits on the page at + // 9 points runs past its edge at 36. + l.element_mut(legend).unwrap().x = 60.0; + assert!(clipped_text(&l, &[Map::new("m")], 96.0, &info).is_empty(), "fits at 9 points"); + if let ElementKind::Legend { text_size, .. } = &mut l.element_mut(legend).unwrap().kind { + *text_size = 36.0; + } + assert_eq!(clipped_text(&l, &[Map::new("m")], 96.0, &info), vec![(legend, "Legend".into())]); +} + +/// Shortens the legend wait on this thread until dropped, then puts back what was there (a test +/// run on one thread, `--test-threads=1`, shares it with the tests after). +struct ShortLegendWait(Option); + +fn short_legend_wait(wait: web_time::Duration) -> ShortLegendWait { + ShortLegendWait(TEST_LEGEND_WAIT.replace(Some(wait))) +} + +impl Drop for ShortLegendWait { + fn drop(&mut self) { + TEST_LEGEND_WAIT.set(self.0); + } +} + +/// No layer labelled: every layer under its name. +static NO_LABELS: BTreeMap = BTreeMap::new(); + +fn legend_page(url: &str) -> (Layout, Vec) { + let (mut page, mut maps) = vector_page(); + // Only the legend is painted; its hidden frame still provides the map and scale. + page.elements[0].visible = false; + page.add( + "Legend", + (10.0, 20.0, 100.0, 60.0), + ElementKind::Legend { + frame: page.elements[0].id, + title: String::new(), + all_classes: true, + hide_other: false, + show_no_data: false, + exclude: Vec::new(), + columns: 1, + labels: BTreeMap::new(), + color: None, + text_size: rustgis_map::layout::LEGEND_TEXT_PT, + }, + ); + let mut tile = rustgis_map::TileLayer::new("Walls", rustgis_map::TileKind::Raster, "https://tiles.test/red/{z}/{x}/{y}.png"); + tile.legends = vec![rustgis_data::ogc::Legend { url: url.into(), ..Default::default() }]; + maps[0].tiles.push(tile); + (page, maps) +} + +fn red_picture() -> Vec { + let mut image = Pixmap::new(24, 24).unwrap(); + image.fill(tiny_skia::Color::from_rgba8(220, 20, 20, 255)); + image.encode_png().unwrap() +} + +#[test] +fn an_interactive_page_does_not_wait_for_legend_pictures() { + use std::sync::mpsc; + let url = "https://tiles.test/waits/interactive-legend.png"; + let fetch = crate::tiles::tests::hold_fetch(url); + let (page, mut maps) = legend_page(url); + let (tx, rx) = mpsc::channel(); + let worker = std::thread::spawn(move || { + let result = render_pending(&page, &mut maps, 72.0, &PageInfo::default()); + tx.send((page, maps, result)).unwrap(); + }); + let done = fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); + // test-wait: an interactive render must finish while the legend fetch is deliberately held. + let result = rx.recv_timeout(std::time::Duration::from_secs(2)); + // Always release the fetch, even if the responsiveness assertion below fails. + done(Ok(red_picture())); + let (page, mut maps, short) = result.expect("the UI must not wait for the legend fetch"); + assert!(short.unwrap().1.legends, "the incomplete page stays pending"); + worker.join().unwrap(); + wait_for_tile_legends(&maps[0], 1e6, &[], web_time::Instant::now() + LEGEND_WAIT).unwrap(); + let (whole, pending) = render_pending(&page, &mut maps, 72.0, &PageInfo::default()).unwrap(); + assert_eq!(pending, PagePending::default(), "ready content does not keep the page pending"); + assert!(whole.pixels().iter().any(|p| p.red() > 200 && p.green() < 60), "the completed picture is painted"); + let exported = render(&page, &mut maps, 72.0, &PageInfo::default()).unwrap(); + assert_eq!(whole.data(), exported.data(), "ready interactive and complete rendering agree"); +} + +#[test] +fn a_page_waits_for_its_legends_only_until_its_deadline() { + let url = "https://tiles.test/waits/deadline-legend.png"; + let fetch = crate::tiles::tests::hold_fetch(url); + let (_, maps) = legend_page(url); + // A deadline already passed ends the wait at once, with the picture still on its way. + assert_eq!(wait_for_tile_legends(&maps[0], 1e6, &[], web_time::Instant::now()), Some(())); + assert!(tile_legends_pending(&maps[0], 1e6, &[])); + fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap()(Ok(red_picture())); +} + +#[test] +fn an_export_shares_one_legend_deadline_across_its_calls() { + assert!(LEGEND_BUDGET.get().is_none()); + { + let _export = legend_budget(); + let first = legend_deadline(); + { + let _inner = legend_budget(); + assert_eq!(legend_deadline(), first, "a call inside the export keeps its deadline"); + } + assert_eq!(legend_deadline(), first, "the inner call didn't end the export's budget"); + } + assert!(LEGEND_BUDGET.get().is_none(), "the budget ends with the export"); + let _next = legend_budget(); + assert!(LEGEND_BUDGET.get() == Some(None), "the next export starts afresh"); +} + +#[test] +fn a_legend_whose_picture_is_ready_does_not_start_the_exports_legend_clock() { + let url = "https://tiles.test/waits/ready-legend.png"; + let fetch = crate::tiles::tests::hold_fetch(url); + let (page, mut maps) = legend_page(url); + assert!(tile_legends_pending(&maps[0], 1e6, &[]), "the picture is asked for"); + fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap()(Ok(red_picture())); + wait_for_tile_legends(&maps[0], 1e6, &[], web_time::Instant::now() + LEGEND_WAIT).unwrap(); + assert!(!tile_legends_pending(&maps[0], 1e6, &[]), "the picture has landed"); + let _export = legend_budget(); + render_drawing_inner(&page, &mut maps, 72.0, &PageInfo::default(), &mut None).unwrap(); + assert!(LEGEND_BUDGET.get() == Some(None), "a legend with nothing to wait for leaves the clock unstarted"); + assert!(finish_legends().is_ok()); + // A later legend whose picture is first asked for now still gets the whole wait. + let before = web_time::Instant::now(); + assert!(legend_deadline() >= before + LEGEND_WAIT); +} + +#[test] +fn an_svg_export_gives_up_on_held_legends_at_one_deadline() { + let url = "https://tiles.test/waits/svg-deadline-legend.png"; + let fetch = crate::tiles::tests::hold_fetch(url); + let (mut page, mut maps) = legend_page(url); + let frame = page.elements[0].id; + page.add( + "Second legend", + (10.0, 5.0, 100.0, 10.0), + ElementKind::Legend { + frame, + title: String::new(), + all_classes: true, + hide_other: false, + show_no_data: false, + exclude: Vec::new(), + columns: 1, + labels: BTreeMap::new(), + color: None, + text_size: rustgis_map::layout::LEGEND_TEXT_PT, + }, + ); + // The thread-local budget and the shortened wait belong to this worker alone. + let worker = std::thread::spawn(move || { + TEST_LEGEND_WAIT.set(Some(web_time::Duration::from_millis(50))); + crate::svg::layout_svg(&page, &mut maps, 72.0, &PageInfo::default()).map(|_| ()) + }); + let done = fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); + let result = worker.join().unwrap(); + done(Err("test fetch released".into())); + assert!(result.unwrap_err().contains("still on their way"), "no successful SVG without its legend"); +} + +#[test] +fn an_export_drawn_without_a_legend_picture_stays_refused_when_the_picture_lands_later() { + let url = "https://tiles.test/waits/late-legend.png"; + let fetch = crate::tiles::tests::hold_fetch(url); + let (page, mut maps) = legend_page(url); + // A wait that has ended before it begins: the legend is drawn with its picture missing. + let _short = short_legend_wait(web_time::Duration::ZERO); + let _export = legend_budget(); + render_drawing_inner(&page, &mut maps, 72.0, &PageInfo::default(), &mut None).unwrap(); + fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap()(Ok(red_picture())); + wait_for_tile_legends(&maps[0], 1e6, &[], web_time::Instant::now() + LEGEND_WAIT).unwrap(); + assert!(!tile_legends_pending(&maps[0], 1e6, &[]), "the picture has landed"); + // What was drawn still lacks it: landing later doesn't make the export complete. + assert!(finish_legends().unwrap_err().contains("still on their way")); +} + +#[test] +fn an_off_page_legend_does_not_hold_any_export_up() { + let url = "https://tiles.test/waits/off-page-legend.png"; + let _held = crate::tiles::tests::hold_fetch(url); + let (mut page, mut maps) = legend_page(url); + let legend = page.elements.last().map(|e| e.id).unwrap(); + page.element_mut(legend).unwrap().x = 1000.0; + // No wait at all: were the legend's picture waited for or counted missing, each fails. + let _short = short_legend_wait(web_time::Duration::ZERO); + let info = PageInfo::default(); + // Drawn nowhere, its picture is neither waited for nor missing from the file. + render(&page, &mut maps, 72.0, &info).unwrap(); + render_drawing(&page, &mut maps, 72.0, &info).unwrap(); + crate::svg::layout_svg(&page, &mut maps, 72.0, &info).unwrap(); +} + +#[test] +fn a_legend_says_from_the_lookup_that_draws_it_whether_a_picture_is_missing() { + let url = "https://tiles.test/waits/lookup-legend.png"; + let fetch = crate::tiles::tests::hold_fetch(url); + let (_, maps) = legend_page(url); + let opts = || LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + let mut canvas = Canvas::new(200, 200).unwrap(); + let draw = |canvas: &mut Canvas| { + legend_missing(canvas, Rect::from_xywh(0.0, 0.0, 200.0, 200.0).unwrap(), &maps[0], ("", 1), None, opts(), INK, 1.0) + }; + assert!(draw(&mut canvas), "drawn while its picture is on its way"); + fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap()(Ok(red_picture())); + wait_for_tile_legends(&maps[0], 1e6, &[], web_time::Instant::now() + LEGEND_WAIT).unwrap(); + assert!(!draw(&mut canvas), "drawn with it"); +} + +#[test] +fn only_an_on_page_legend_is_waited_for_by_the_redraw() { + let url = "https://tiles.test/waits/redraw-legend.png"; + let fetch = crate::tiles::tests::hold_fetch(url); + let (mut page, maps) = legend_page(url); + let legend = page.elements.last().map(|e| e.id).unwrap(); + page.element_mut(legend).unwrap().x = 1000.0; + assert!(!legends_pending(&page, &maps), "off the page: not waited for"); + assert!(fetch.try_recv().is_err(), "nor is its picture asked for"); + page.element_mut(legend).unwrap().x = 10.0; + assert!(legends_pending(&page, &maps), "on the page, its picture is on its way"); + fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap()(Ok(red_picture())); +} + +#[test] +fn the_drawing_and_the_redraw_gate_agree_on_a_legend_at_the_pages_edge() { + // The page is 120 mm wide: 0.01 mm of the legend on it counts; none does not, at whatever + // resolution the page is drawn (a sub-pixel sliver must not make them disagree). + for (x, on_page) in [(119.99, true), (120.0, false)] { + let url = format!("https://tiles.test/waits/edge-legend-{x}.png"); + let fetch = crate::tiles::tests::hold_fetch(&url); + let (mut page, mut maps) = legend_page(&url); + let legend = page.elements.last().map(|e| e.id).unwrap(); + page.element_mut(legend).unwrap().x = x; + assert_eq!(legends_pending(&page, &maps), on_page, "the redraw gate at x = {x}"); + let _short = short_legend_wait(web_time::Duration::ZERO); + let _export = legend_budget(); + render_drawing_inner(&page, &mut maps, 72.0, &PageInfo::default(), &mut None).unwrap(); + assert_eq!(finish_legends().is_err(), on_page, "the page's drawing at x = {x}"); + if on_page { + fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap()(Ok(red_picture())); + } + } +} + +#[test] +fn an_export_includes_a_legend_that_arrives_while_it_waits() { + let url = "https://tiles.test/waits/export-legend.png"; + let fetch = crate::tiles::tests::hold_fetch(url); + let (page, mut maps) = legend_page(url); + let worker = std::thread::spawn(move || render(&page, &mut maps, 72.0, &PageInfo::default())); + let done = fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); + assert!(!worker.is_finished(), "a complete export waits for the held picture"); + done(Ok(red_picture())); + let image = worker.join().unwrap().unwrap(); + assert!(image.pixels().iter().any(|p| p.red() > 200 && p.green() < 60), "not a successful page without its picture"); +} + +#[test] +fn cancelled_legend_waits_return_no_export() { + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + mpsc, + }; + struct Probe { + flag: Arc, + waiting: mpsc::SyncSender<()>, + } + impl rustgis_data::progress::Probe for Probe { + fn cancelled(&self) -> bool { + let _ = self.waiting.try_send(()); + self.flag.load(Ordering::Relaxed) + } + fn begin(&self, _: u64) {} + fn advance(&self, _: u64) {} + } + for kind in 0..4 { + let url = format!("https://tiles.test/waits/cancelled-legend-{kind}.png"); + let fetch = crate::tiles::tests::hold_fetch(&url); + let (page, mut maps) = legend_page(&url); + let flag = Arc::new(AtomicBool::new(false)); + let cancel = flag.clone(); + let (waiting, observed) = mpsc::sync_channel(1); + let (tx, rx) = mpsc::channel(); + let worker = std::thread::spawn(move || { + let probe_flag = if kind == 3 { Arc::new(AtomicBool::new(false)) } else { flag.clone() }; + let _probe = rustgis_data::progress::install(Some(Arc::new(Probe { flag: probe_flag, waiting }))); + let _frame = (kind == 3).then(|| crate::cancel::install(flag)); + let info = PageInfo::default(); + let result = match kind { + 0 | 3 => render(&page, &mut maps, 72.0, &info).map(|_| ()), + 1 => render_drawing(&page, &mut maps, 72.0, &info).map(|_| ()), + _ => crate::svg::layout_svg(&page, &mut maps, 72.0, &info).map(|_| ()), + }; + tx.send(result).unwrap(); + }); + let done = fetch.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); + observed.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); + cancel.store(true, Ordering::Relaxed); + // test-wait: cancellation must finish before the deliberately pending fetch is released. + let result = rx.recv_timeout(std::time::Duration::from_secs(2)); + done(Err("test fetch released".into())); + assert_eq!(result.unwrap(), Err(rustgis_data::DataError::Cancelled.to_string()), "format {kind}"); + worker.join().unwrap(); + } +} + +/// A frame drawn over another takes its rectangle out of the other's: the bands above and below +/// it and the strips beside it are left, a strip too narrow to point into is dropped, and one +/// that covers it all leaves nothing (#1191). +#[test] +fn a_frame_drawn_over_another_leaves_the_rest_of_it() { + let r = [0.0, 0.0, 100.0, 50.0]; + assert_eq!(uncovered(r, [200.0, 0.0, 10.0, 10.0]), [r], "apart"); + assert_eq!( + uncovered(r, [10.0, 10.0, 20.0, 20.0]), + [[0.0, 0.0, 100.0, 10.0], [0.0, 30.0, 100.0, 20.0], [0.0, 10.0, 10.0, 20.0], [30.0, 10.0, 70.0, 20.0]] + ); + // Over its top-left corner, and past it. + assert_eq!(uncovered(r, [-5.0, -5.0, 15.0, 15.0]), [[0.0, 10.0, 100.0, 40.0], [10.0, 0.0, 90.0, 10.0]]); + assert_eq!(uncovered(r, [0.0, 0.0, 100.0, 49.995]), Vec::<[f64; 4]>::new(), "a 0.005 mm strip is dropped"); + assert!(uncovered(r, [-1.0, -1.0, 102.0, 52.0]).is_empty()); +} + +/// Each element is a layer of the page's recording, named after it and identified by its id +/// (#1815): two elements named alike are told apart by id, not by which comes first, so an +/// element that draws nothing on one page of a series doesn't hand its layer to the other. +#[test] +fn each_element_is_a_layer_with_its_id() { + use crate::vector::Item; + let mut layout = Layout::new("Layers", 120.0, 90.0); + let text = |t: &str| ElementKind::text(t, 12.0, Rgba::rgb(0, 0, 0), false); + let (a, b) = (layout.add("Texto", (10.0, 10.0, 60.0, 10.0), text("Um")), layout.add("Texto", (10.0, 30.0, 60.0, 10.0), text("Dois"))); + let layers = |layout: &Layout| { + let (drawing, _) = render_drawing(layout, &mut [], 96.0, &PageInfo::default()).unwrap(); + let (_, _, items) = drawing.finish(); + items.into_iter().filter_map(|i| if let Item::Group(g) = i { Some((g.layer?, g.layer_id?)) } else { None }).collect::>() + }; + assert_eq!(layers(&layout), [("Texto".to_string(), u64::from(a)), ("Texto".to_string(), u64::from(b))]); + // The first draws nothing: the second keeps its own layer. + if let Some(ElementKind::Text { text, .. }) = layout.elements.iter_mut().find(|e| e.id == a).map(|e| &mut e.kind) { + text.clear(); + } + assert_eq!(layers(&layout), [("Texto".to_string(), u64::from(b))]); +} + +/// The page's colour (#2855) is the first thing the PDF's drawing fills, over the whole page; +/// a white page is filled white as before. +#[test] +fn a_pages_colour_is_filled_first_in_the_pdfs_drawing() { + use crate::vector::{Brush, Item}; + let mut layout = Layout::new("Paper", 120.0, 90.0); + let first = |layout: &Layout| { + let (drawing, _) = render_drawing(layout, &mut [], 72.0, &PageInfo::default()).unwrap(); + let (w, h, items) = drawing.finish(); + match items.into_iter().next() { + Some(Item::Fill { path, brush: Brush::Solid(c), .. }) => { + let b = path.bounds(); + assert!(b.left() <= 0.0 && b.top() <= 0.0 && b.right() >= w - 0.5 && b.bottom() >= h - 0.5, "{b:?}"); + c.to_color_u8() + } + _ => panic!("the page is not filled first"), + } + }; + let c = first(&layout); + assert_eq!((c.red(), c.green(), c.blue(), c.alpha()), (255, 255, 255, 255)); + layout.paper = Some(Rgba::rgb(0x0B, 0x1B, 0x2B)); + let c = first(&layout); + assert_eq!((c.red(), c.green(), c.blue(), c.alpha()), (0x0B, 0x1B, 0x2B, 255)); +} + +/// A page with a frame of the built-in world and a title. +fn vector_page() -> (Layout, Vec) { + let mut layout = Layout::new("Vectors", 120.0, 90.0); + let kind = serde_json::from_value(serde_json::json!({"MapFrame": { + "map": "Map", "center": {"x": 0, "y": 0}, "scale": 150000000 + }})) + .unwrap(); + layout.add("World", (10.0, 20.0, 100.0, 60.0), kind); + let title = ElementKind::text("Shelby County", 18.0, Rgba::rgb(20, 20, 20), true); + layout.add("Title", (10.0, 4.0, 100.0, 12.0), title); + (layout, vec![Map::new("Map")]) +} + +#[test] +fn a_recorded_page_keeps_its_text_and_frame_as_vectors() { + use crate::vector::Item; + let (layout, mut maps) = vector_page(); + let (drawing, pictured) = render_drawing(&layout, &mut maps, 150.0, &PageInfo::default()).unwrap(); + assert!(pictured.is_empty() && !drawing.overflowed()); + let (_, _, items) = drawing.finish(); + let items = crate::vector::without_layers(items); + let text: String = items + .iter() + .filter_map(|i| if let Item::Glyphs(r) = i { Some(r) } else { None }) + .flat_map(|r| r.glyphs.iter().map(|g| g.ch)) + .collect(); + assert_eq!(text, "Shelby County", "the title, its space kept for copying"); + // The frame: a group cut to its box, its land as paths, not a picture of it. + let frame = items.iter().find_map(|i| if let Item::Group(g) = i { Some(g) } else { None }).expect("the frame's group"); + assert!(frame.clip.is_some()); + assert!(frame.items.iter().filter(|i| matches!(i, Item::Fill { .. })).count() > 50); + assert!(!frame.items.iter().any(|i| matches!(i, Item::Image(_)))); +} + +#[test] +fn a_recorded_page_draws_what_the_picture_of_it_shows() { + let (layout, mut maps) = vector_page(); + let info = PageInfo::default(); + let png = render(&layout, &mut maps, 96.0, &info).unwrap(); + let (drawing, _) = render_drawing(&layout, &mut maps, 96.0, &info).unwrap(); + let (_, _, items) = drawing.finish(); + let mut replayed = Pixmap::new(png.width(), png.height()).unwrap(); + crate::vector::replay(&items, &mut replayed, Transform::identity()); + // The same paths through the same rasteriser: only glyph edges (coverage against filled + // outlines) may differ. + let differ = png.pixels().iter().zip(replayed.pixels()).filter(|(a, b)| { + let (a, b) = (a.demultiply(), b.demultiply()); + a.red().abs_diff(b.red()).max(a.green().abs_diff(b.green())).max(a.blue().abs_diff(b.blue())) > 48 + }); + let share = differ.count() as f64 / png.pixels().len() as f64; + assert!(share < 0.005, "{:.3}% of pixels differ", share * 100.0); +} + +#[test] +fn a_huge_page_records_within_its_bounds() { + let mut layout = Layout::new("Huge", 5000.0, 5000.0); + layout.add("Title", (10.0, 10.0, 4000.0, 400.0), ElementKind::text("Shelby County", 300.0, Rgba::rgb(0, 0, 0), true)); + let (drawing, _) = render_drawing(&layout, &mut [], 600.0, &PageInfo::default()).unwrap(); + // Held to the page budget's size, as the picture of it is. + assert!(drawing.width as f64 <= MAX_SIDE && drawing.height as f64 <= MAX_SIDE); + assert!(!drawing.overflowed()); +} + +#[test] +fn a_turned_frame_stays_vectors() { + use crate::vector::Item; + let (mut layout, mut maps) = vector_page(); + if let Some(ElementKind::MapFrame { bearing, .. }) = layout.elements.first_mut().map(|e| &mut e.kind) { + *bearing = 30.0; + } + let (drawing, _) = render_drawing(&layout, &mut maps, 96.0, &PageInfo::default()).unwrap(); + let (_, _, items) = drawing.finish(); + let items = crate::vector::without_layers(items); + let frame = items.iter().find_map(|i| if let Item::Group(g) = i { Some(g) } else { None }).expect("the frame's group"); + // The turned view holds the north-up frame, turned. + let Some(Item::Group(north)) = frame.items.first() else { panic!("the north-up frame inside") }; + assert!(north.transform.ky.abs() > 0.3, "turned: {:?}", north.transform); + assert!(north.items.iter().filter(|i| matches!(i, Item::Fill { .. })).count() > 50); +} + +#[test] +fn a_frame_too_large_for_vectors_is_drawn_as_a_picture_and_named() { + use crate::vector::{Item, TEST_MAX_COST}; + let (layout, mut maps) = vector_page(); + TEST_MAX_COST.with(|l| l.set(Some(20_000))); + let result = render_drawing(&layout, &mut maps, 72.0, &PageInfo::default()); + TEST_MAX_COST.with(|l| l.set(None)); + let (drawing, pictured) = result.unwrap(); + assert_eq!(pictured.iter().map(|p| p.1.as_str()).collect::>(), ["World"]); + let (_, _, items) = drawing.finish(); + let items = crate::vector::without_layers(items); + assert!(items.iter().any(|i| matches!(i, Item::Image(_))), "the frame as a picture"); +} + +/// Every token the Format pane offers a layout's text is one the page expands (#516). +#[test] +fn the_tokens_offered_are_the_ones_expanded() { + let layout = Layout::new("Atlas", 100.0, 100.0); + let info = PageInfo { page: 2, pages: 5, page_name: "North".into() }; + let tokens = rustgis_map::layout::PAGE_TOKENS.iter().chain(rustgis_map::graphics::TOKENS); + for (token, _) in tokens { + assert!(!expand(token, &layout, &info, None).contains('{'), "{token}"); + } + assert_eq!(expand("{page} of {pages}, {pageName} · {layout}", &layout, &info, None), "2 of 5, North · Atlas"); +} + +/// A WMS or WMTS layer's legend is its service's picture under its name, as the Layers pane +/// shows it, narrowed to fit across and sized for; left out by name, hidden, or with none at +/// the frame's scale, it isn't listed. +#[test] +fn a_web_layers_legend_is_its_services_picture() { + crate::tiles::tests::serve(); + let mut map = Map::new("m"); + let mut t = rustgis_map::TileLayer::new("Walls", rustgis_map::TileKind::Raster, "https://tiles.test/red/{z}/{x}/{y}.png"); + t.legends = vec![rustgis_data::ogc::Legend { url: "https://tiles.test/red/legend.png".into(), ..Default::default() }]; + map.tiles.push(t); + // The red drawn (the picture is red; the name is dark) and how far right, in pixels. + let red = |map: &Map, width: f32, exclude: &[String], scale: f64| { + let mut pm = Pixmap::new(300, 400).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let opts = LegendOptions { show_no_data: false, hide_other: false, exclude, labels: &NO_LABELS, scale, size: 1.0 }; + crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, width, 400.0).unwrap(), map, ("", 1), None, opts, 1.0)); + let hits: Vec = (0..pm.height()) + .flat_map(|y| (0..pm.width()).map(move |x| (x, y))) + .filter(|&(x, y)| pm.pixel(x, y).is_some_and(|p| p.red() > 200 && p.green() < 60)) + .map(|(x, _)| x) + .collect(); + (hits.len(), hits.iter().max().copied().unwrap_or(0)) + }; + wait_for_tile_legends(&map, 1e6, &[], web_time::Instant::now() + LEGEND_WAIT).unwrap(); + let (ink, right) = red(&map, 300.0, &[], 1e6); + assert!(ink > 200 * 200, "the picture is drawn: {ink} px"); + assert!(right < 6 + 256, "a pixel a point: {right}"); + // Its name's row and the picture, 256 points down and 6 + 256 across. + let (w, h) = legend_sizes_mm(&mut map, 1e6, false, false, (&[], &NO_LABELS)).unwrap()[0]; + let mm = 25.4 / 96.0; + assert!((w - 262.0 * mm).abs() < 1e-6 && (h - (f64::from(LEGEND_ROW) + 256.0) * mm).abs() < 1e-6, "{w} × {h} mm"); + let (_, right) = red(&map, 100.0, &[], 1e6); + assert!(right < 100, "narrowed to fit: {right}"); + assert_eq!(red(&map, 300.0, &["WALLS".into()], 1e6).0, 0, "left out by name"); + map.tiles[0].legends[0].max_scale = Some(1e5); + assert_eq!(red(&map, 300.0, &[], 1e6).0, 0, "none at this scale"); + map.tiles[0].legends[0].max_scale = None; + // Narrowed, a picture takes only the height it's drawn at: a second layer's fits under it + // (a 70-point legend: 64 points across, so 64 down), and the drawing order is the map's. + let mut second = map.tiles[0].clone(); + second.name = "Floors".into(); + map.tiles.push(second); + let mut pm = Pixmap::new(70, 200).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 70.0, 200.0).unwrap(), &map, ("", 1), None, opts, 1.0)); + let red_rows = + (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| pm.pixel(x, y).is_some_and(|p| p.red() > 200 && p.green() < 60))).count(); + assert!(red_rows >= 2 * 63, "both pictures, {red_rows} rows"); + let names: Vec<&str> = legend_rows(&map, None, &opts) + .iter() + .filter_map(|r| match r { + LegendRow::Head(n) => Some(*n), + _ => None, + }) + .collect(); + assert_eq!(names, ["Walls", "Floors"]); + // Among the map's layers where the map draws them: a web layer placed over a feature + // layer is listed just above it, under the feature layers above. + let lower = map.add_dataset(rustgis_data::Dataset::new("Lower", GeometryType::Point, vec![])); + map.add_dataset(rustgis_data::Dataset::new("Upper", GeometryType::Point, vec![])); + map.tiles[1].over = Some(lower); + let listed: Vec<&str> = legend_rows(&map, None, &opts) + .iter() + .filter_map(|r| match r { + LegendRow::Head(n) => Some(*n), + LegendRow::Plain(_, name) => Some(*name), + _ => None, + }) + .collect(); + let feature_order: Vec<&str> = map.layers.iter().map(|l| l.name.as_str()).collect(); + let expected: Vec<&str> = + feature_order.iter().flat_map(|n| if *n == "Lower" { vec!["Floors", "Lower"] } else { vec![*n] }).chain(["Walls"]).collect(); + assert_eq!(listed, expected, "layers top first: {feature_order:?}"); + // A heading with no room for any of its picture under it isn't drawn: a legend one row + // tall stays blank (the map's layers set aside, whose rows would fit). + map.layers.clear(); + let mut pm = Pixmap::new(300, 15).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(0.0, 0.0, 300.0, LEGEND_ROW).unwrap(), &map, ("", 1), None, opts, 1.0) + }); + assert!(pm.pixels().iter().all(|p| p.red() > 200 && p.green() > 200), "no heading alone"); + map.tiles.truncate(1); + map.tiles[0].visible = false; + 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"); + // A paper colour (#2532) is the background too, and coverage still finds only the data. + let white = frame_coverage(&mut map, Coord::new(0.0, 0.0), 1_000_000.0, 100.0, 100.0, 64); + map.paper = Some(Rgba::rgb(0xF1, 0xEA, 0xDF)); + assert!(plain(&mut map, (2.0, 70.0, 25.0, 25.0)), "a corner is the coloured paper"); + assert_eq!(frame_coverage(&mut map, Coord::new(0.0, 0.0), 1_000_000.0, 100.0, 100.0, 64), white); + assert_eq!(map.paper, Some(Rgba::rgb(0xF1, 0xEA, 0xDF)), "put back after coverage"); + map.paper = None; + 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"); +} + +#[test] +fn plain_dark_basemaps_keep_the_legend_paper_while_light_ones_clear_it() { + for body in ["earth", "mars"] { + for basemap in [rustgis_map::Basemap::Midnight, rustgis_map::Basemap::Paper, rustgis_map::Basemap::Ocean] { + let mut map = Map::new("plain"); + (map.body, map.basemap, map.graticule) = (body.into(), basemap, false); + // The Earth frame is open Gulf of Guinea water; on Mars it is the palette's grey. + let plain = frame_plain_under(&mut map, Coord::new(0.0, 0.0), 1_000_000.0, (100.0, 100.0), (40.0, 40.0, 20.0, 20.0), 128); + assert_eq!(plain, basemap != rustgis_map::Basemap::Midnight, "{body}: {basemap:?}"); + } + } +} + +/// 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] +fn frame_coverage_leaves_out_layers_that_only_outline() { + use rustgis_data::{Dataset, Geometry}; + let count = |map: &mut Map| { + let (.., cells) = frame_coverage(map, Coord::new(0.0, 0.0), 1_000_000.0, 100.0, 100.0, 64).unwrap(); + cells.iter().filter(|c| **c).count() + }; + let point = || { + let mut d = Dataset::new("far", GeometryType::Point, Vec::new()); + d.push(Some(Geometry::Point(Coord::new(-0.3, -0.3))), Vec::new()); + d + }; + let mut map = Map::new("m"); + let mut square = Dataset::new("border", GeometryType::Polygon, Vec::new()); + square.push( + Some(Geometry::Polygon(vec![vec![ + [(-0.2, -0.2), (0.2, -0.2), (0.2, 0.2), (-0.2, 0.2), (-0.2, -0.2)].map(|(x, y)| Coord::new(x, y)).to_vec(), + ]])), + Vec::new(), + ); + let border = map.add_dataset(square); + 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!(count(&mut map) > 0, "alone, it is what the map shows"); + map.add_dataset(point()); + let beside = count(&mut map); + assert!(map.layer(border).is_some_and(|l| l.visible), "shown again"); + let mut alone = Map::new("m"); + alone.add_dataset(point()); + assert_eq!(beside, count(&mut alone), "only the point counts"); + let l = map.layers.iter_mut().find(|l| l.id == border).unwrap(); + assert!(only_outlines(l)); + l.labels.enabled = true; + assert!(!only_outlines(l), "labels make it more than an outline"); + l.labels.enabled = false; + l.fill_layers = vec![rustgis_map::fills::FillLayer::default()]; + assert!(!only_outlines(l), "a stacked fill draws inside it"); + l.no_fill = Some(rustgis_map::NoFill::Symbols); + assert!(!only_outlines(l), "No Fill's symbols leave a stacked fill drawn"); + l.no_fill = Some(rustgis_map::NoFill::Override); + assert!(only_outlines(l), "No Fill's override is the fill that hides the rest"); + l.no_fill = None; + l.fill_layers.clear(); + l.symbol_by.fill = Some("'#ff0000'".into()); + assert!(!only_outlines(l), "a fill by expression draws inside it"); + l.symbol_by.fill = None; + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol::default_for(GeometryType::Polygon, 0)); + assert!(!only_outlines(l), "a filled symbol"); + l.no_fill = Some(rustgis_map::NoFill::Symbols); + assert!(only_outlines(l), "No Fill counts as no fill"); + let symbol = rustgis_map::Symbol::default_for(GeometryType::Polygon, 0); + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("a".into(), symbol)], + other: symbol, + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: [("a".to_string(), vec![rustgis_map::fills::FillLayer::default()])].into(), + other_fills: Vec::new(), + expression: None, + }; + assert!(!only_outlines(l), "No Fill's symbols leave a class's stacked fill drawn"); + l.no_fill = Some(rustgis_map::NoFill::Override); + assert!(only_outlines(l), "the override hides that too"); + l.no_fill = None; + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { + fill: Rgba::new(0, 0, 0, 0), + ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) + }); + + // A layer out of scale at the frame's scale draws nothing there: the outline is all it shows. + let drawn_alone = { + let far = map.layers.iter().find(|l| l.id != border).map(|l| l.id).unwrap(); + map.layers.iter_mut().find(|l| l.id == far).unwrap().min_scale = Some(1.0); + let shown = count(&mut map); + map.layers.iter_mut().find(|l| l.id == far).unwrap().min_scale = None; + shown + }; + assert!(drawn_alone > beside, "{drawn_alone} of {beside}"); + let l = map.layers.iter_mut().find(|l| l.id == border).unwrap(); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol::default_for(GeometryType::Polygon, 0)); + assert!(plain_fill(l), "one colour"); + l.labels.enabled = true; + assert!(!plain_fill(l), "labels make it more than context"); +} + +/// A polygon layer in one colour running on past the frame is context beside a layer drawn by +/// classes; one inside the frame, such as a study area, is what the map shows. +#[test] +fn frame_coverage_leaves_out_one_colour_fills_beside_classes() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; + let count = |map: &mut Map| { + let (.., cells) = frame_coverage(map, Coord::new(0.0, 0.0), 1_000_000.0, 100.0, 100.0, 64).unwrap(); + cells.iter().filter(|c| **c).count() + }; + let mut map = Map::new("m"); + let square = |name: &str, r: f64| { + let mut d = Dataset::new(name, GeometryType::Polygon, Vec::new()); + d.push( + Some(Geometry::Polygon(vec![vec![[(-r, -r), (r, -r), (r, r), (-r, r), (-r, -r)].map(|(x, y)| Coord::new(x, y)).to_vec()]])), + Vec::new(), + ); + d + }; + // About 0.9° across the frame: the states run on past it. + let states = map.add_dataset(square("states", 2.0)); + let mut d = Dataset::new("far", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); + d.push(Some(Geometry::Point(Coord::new(-0.3, -0.3))), vec![Value::Text("c".into())]); + let far = map.add_dataset(d); + let with_states = count(&mut map); + let s = |c| rustgis_map::Symbol::default_for(GeometryType::Point, c); + if let Some(l) = map.layers.iter_mut().find(|l| l.id == far) { + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("c".to_string(), s(0))], + other: s(1), + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + } + let beside_classes = count(&mut map); + assert!(beside_classes > 0 && beside_classes < with_states, "{beside_classes} of {with_states}"); + assert!(map.layer(states).is_some_and(|l| l.visible), "shown again"); + map.add_dataset(square("study area", 0.1)); + let with_study_area = count(&mut map); + assert!(with_study_area > beside_classes, "a one-colour layer inside the frame counts: {with_study_area} of {beside_classes}"); + + // A drawing three times the frame's width, judged on the frame: a layer running past the + // frame but not past the drawing is context in both, and one inside the frame is counted. + let mut map = Map::new("m"); + let neighbour = map.add_dataset(square("neighbour", 0.6)); + let far = { + let mut d = Dataset::new("far", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); + d.push(Some(Geometry::Point(Coord::new(-0.3, -0.3))), vec![Value::Text("c".into())]); + map.add_dataset(d) + }; + if let Some(l) = map.layers.iter_mut().find(|l| l.id == far) { + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("c".to_string(), s(0))], + other: s(1), + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + } + let drawn = |map: &mut Map, judged: (f64, f64)| { + let (.., cells) = frame_coverage_judged_on(map, Coord::new(0.0, 0.0), 1_000_000.0, (300.0, 300.0), judged, 192).unwrap(); + cells.iter().filter(|c| **c).count() + }; + let on_the_drawing = drawn(&mut map, (300.0, 300.0)); + let on_the_frame = drawn(&mut map, (100.0, 100.0)); + assert!(on_the_frame < on_the_drawing / 4, "the neighbour is context on the frame: {on_the_frame} of {on_the_drawing}"); + assert!(map.layer(neighbour).is_some_and(|l| l.visible), "shown again"); +} + +/// A legend's rows go into columns: as even as they go, a layer's name with the row under it, +/// and in a box too short each filled in turn; one column draws as it always has. +#[test] +fn a_legends_rows_go_into_columns() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; + let mut map = Map::new("m"); + let mut d = Dataset::new("pts", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); + d.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text("c0".into())]); + let pts = map.add_dataset(d); + let s = |c| rustgis_map::Symbol::default_for(GeometryType::Point, c); + if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) { + // The layer's name, 30 classes and the other values: 32 rows. + let classes = (0u32..30).map(|i| (format!("c{i}"), s(i))).collect(); + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes, + other: s(31), + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + } + let opts = || LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + let rows = legend_rows(&map, None, &opts()); + assert_eq!(rows.len(), 32); + assert_eq!(balanced(&rows, 1, (1e6, 1.0)), (vec![0], 32.0 * LEGEND_ROW)); + assert_eq!(balanced(&rows, 2, (1e6, 1.0)), (vec![0, 16], 16.0 * LEGEND_ROW)); + assert_eq!(balanced(&rows, 3, (1e6, 1.0)).1, 11.0 * LEGEND_ROW); + assert_eq!(balanced(&[], 3, (1e6, 1.0)), (vec![0], 0.0)); + // Too short for them all: each filled in turn, and the last holds what fits of the rest. + let (starts, fits) = flow(&rows, 3, 5.0 * LEGEND_ROW, (1e6, 1.0)); + assert_eq!((starts, fits), (vec![0, 5, 10], false)); + // A layer's name isn't left at the foot of a column; the last, with none under it, can be. + let heads = [LegendRow::Head("a"), LegendRow::Head("b"), LegendRow::Head("c"), LegendRow::Head("d"), LegendRow::Head("e")]; + assert_eq!(flow(&heads, 3, 3.0 * LEGEND_ROW, (1e6, 1.0)), (vec![0, 2], true)); + + let sizes = legend_sizes_mm(&mut map, 1e6, true, false, (&[], &NO_LABELS)).unwrap(); + let row = f64::from(LEGEND_ROW) * 25.4 / 96.0; + for (size, rows) in sizes.iter().zip([32.0, 16.0, 11.0]) { + assert!((size.1 - rows * row).abs() < 1e-6, "{size:?} for {rows} rows"); + } + assert!(sizes[0].0 < sizes[1].0 && sizes[1].0 < sizes[2].0, "{sizes:?}"); + + // How far right and down the legend draws in a box, and how many pixels. + let ink = |columns: usize, w: f32, h: f32| { + let mut pm = Pixmap::new(500, 500).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(0.0, 0.0, w, h).unwrap(), &map, ("", columns), None, opts(), 1.0); + }); + let dark = |x, y| pm.pixel(x, y).is_some_and(|p| p.red() < 200 || p.green() < 200 || p.blue() < 200); + let right = (0..500).filter(|&x| (0..500).any(|y| dark(x, y))).max().unwrap_or(0); + let down = (0..500).filter(|&y| (0..500).any(|x| dark(x, y))).max().unwrap_or(0); + (right, down) + }; + let mm_pt = 96.0 / 25.4; + let (right1, down1) = ink(1, 500.0, 500.0); + let (right2, down2) = ink(2, 500.0, 500.0); + let (right3, down3) = ink(3, 500.0, 500.0); + assert!(f64::from(down1) > 31.0 * sizes[0].1 / 32.0 * mm_pt, "{down1}"); + assert!(f64::from(down2) <= sizes[1].1 * mm_pt && down2 > down3, "{down2} then {down3}"); + assert!(right1 < right2 && right2 < right3, "{right1}, {right2}, {right3}"); + assert!(f64::from(right3) <= sizes[2].0 * mm_pt + 1.0, "{right3} across {:?}", sizes[2]); + // A value out of range, from a file edited by hand, draws what the nearest would. + assert_eq!(ink(0, 500.0, 500.0), (right1, down1)); + assert_eq!(ink(9, 500.0, 500.0), (right3, down3)); + // A box too narrow for the columns closes them up: the last still starts inside it, past + // where the first two end in a box of their own. + let narrow = f64::from(right3) as f32 * 0.8; + let (right_narrow, down_narrow) = ink(3, narrow, 500.0); + assert!(f64::from(right_narrow) < f64::from(right3) && right_narrow > right1, "{right_narrow} of {right3}"); + // Moved sideways, the letters' lowest edge can land a pixel higher; a lost row would be 15. + assert!(down_narrow.abs_diff(down3) < LEGEND_ROW as u32 / 2, "no row left out: {down_narrow} of {down3}"); +} + +/// The widest class label of `rows`, in points. +fn widest_label(rows: &[LegendRow]) -> f32 { + rows.iter().map(|row| row.width(0.0, 1.0) - 12.0).fold(0.0, f32::max) +} + +/// A point layer in Unique Values, for a legend's rows. +fn classed_point_map(classes: Vec<(String, rustgis_map::Symbol)>, small: rustgis_map::Symbol) -> Map { + point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes, + other: small, + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + }) +} + +/// A box one row tall: in one column a layer's name is drawn alone, as it always was; in more, +/// it waits for room for the class under it, and the first column stays blank. +#[test] +fn a_layers_name_stays_with_its_class_only_in_columns() { + let small = rustgis_map::Symbol::default_for(GeometryType::Point, 0); + let classes = (0u32..4).map(|i| (format!("c{i}"), small)).collect(); + let map = classed_point_map(classes, small); + let opts = || LegendOptions { show_no_data: false, hide_other: true, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + let rows = legend_rows(&map, None, &opts()); + let (starts, _) = flow(&rows, 2, LEGEND_ROW, (1e6, 1.0)); + assert_eq!(starts, vec![0, 2]); + let first = widest(column_parts(&rows, &starts).next().unwrap(), (1e6, 1.0)); + let drawn_in_first = |columns: usize| { + let mut pm = Pixmap::new(300, 15).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(0.0, 0.0, 300.0, LEGEND_ROW).unwrap(), &map, ("", columns), None, opts(), 1.0); + }); + (0..first as u32).any(|x| (0..15).any(|y| pm.pixel(x, y).is_some_and(|p| p.red() < 200))) + }; + assert!(drawn_in_first(1), "one column draws the name alone"); + assert!(!drawn_in_first(2), "two columns keep it with its class"); +} + +/// A large point symbol makes its row taller and widens its column's symbols only: the columns +/// balance what the rows take, and the other column stays as narrow as its labels let it. +#[test] +fn a_legends_columns_hold_large_point_symbols() { + let small = rustgis_map::Symbol { size: 4.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + let classes = (0u32..10).map(|i| (format!("c{i}"), rustgis_map::Symbol { size: if i < 2 { 40.0 } else { 4.0 }, ..small })).collect(); + let map = classed_point_map(classes, small); + let opts = LegendOptions { show_no_data: false, hide_other: true, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + let rows = legend_rows(&map, None, &opts); + let tall = rows[1].height(1e6, 1.0); + assert!(tall > 2.0 * LEGEND_ROW, "{tall}"); + // The name and the two large symbols, then the eight small ones: counted row by row, these + // would be split at the middle. + let (starts, height) = balanced(&rows, 2, (1e6, 1.0)); + assert_eq!(starts, vec![0, 3], "{height}"); + assert_eq!(height, 8.0 * LEGEND_ROW); + let parts: Vec<_> = column_parts(&rows, &starts).collect(); + assert!( + widest(parts[1], (1e6, 1.0)) < widest(parts[0], (1e6, 1.0)) - 20.0, + "{} and {}", + widest(parts[0], (1e6, 1.0)), + widest(parts[1], (1e6, 1.0)) + ); + // In one column, the small rows' labels line up with the large symbols' as before. + assert_eq!( + widest(&rows, (1e6, 1.0)), + widest(parts[0], (1e6, 1.0)).max(swatch_column(&rows, (1e6, 1.0)) + 12.0 + widest_label(parts[1])) + ); +} + +/// A legend shows a layer under the label it gives it, by the layer's name in any case (#1654): +/// a plain layer's row and a classed layer's heading; it measures and draws the label, so its +/// size follows it. A layer it gives no label, or a blank one, shows its name. +#[test] +fn a_legend_shows_a_layers_label() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; + let mut map = Map::new("m"); + let long = "BrasilData: Setores censitários 2022 (MG)"; + map.add_dataset(Dataset::new(long, GeometryType::Point, vec![])); + let mut d = Dataset::new("pts", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); + d.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text("a".into())]); + let pts = map.add_dataset(d); + if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) { + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("a".into(), rustgis_map::Symbol::default_for(GeometryType::Point, 0))], + other: rustgis_map::Symbol::default_for(GeometryType::Point, 1), + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + } + let labels = + |pairs: &[(&str, &str)]| -> BTreeMap { pairs.iter().map(|(n, l)| (n.to_string(), l.to_string())).collect() }; + let names = |labels: &BTreeMap| -> Vec { + let opts = LegendOptions { show_no_data: false, hide_other: true, exclude: &[], labels, scale: 1e6, size: 1.0 }; + legend_rows(&map, None, &opts) + .iter() + .filter_map(|r| match r { + LegendRow::Head(n) | LegendRow::Plain(_, n) => Some(n.to_string()), + _ => None, + }) + .collect() + }; + // Top first: pts over the long-named layer. + assert_eq!(names(&NO_LABELS), ["pts", long]); + let short = labels(&[("brasildata: Setores censitários 2022 (mg)", "Setores"), ("PTS", "Pontos")]); + assert_eq!(names(&short), ["Pontos", "Setores"], "by name, any case"); + assert_eq!(names(&labels(&[("pts", " ")])), ["pts", long], "a blank label shows the name"); + assert_eq!(names(&labels(&[("Atlantis", "x")])), ["pts", long], "a label for no layer of the map changes nothing"); + // Its size: narrower with the short label, wider with a long one; as tall either way. + let size = |labels: &BTreeMap| legend_sizes_mm(&mut map.clone(), 1e6, true, true, (&[], labels)).unwrap()[0]; + let (named, labelled) = (size(&NO_LABELS), size(&short)); + let wide = size(&labels(&[(long, "Setores censitários do Censo Demográfico de 2022 em Minas Gerais")])); + assert!(labelled.0 < named.0 - 20.0 && wide.0 > named.0 + 20.0, "{labelled:?} {named:?} {wide:?}"); + assert!((labelled.1 - named.1).abs() < 1e-9 && (wide.1 - named.1).abs() < 1e-9); + // Drawn: the label, which ends within the width measured for it. + let reach = |labels: &BTreeMap| { + let mut pm = Pixmap::new(400, 200).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let opts = LegendOptions { show_no_data: false, hide_other: true, exclude: &[], labels, scale: 1e6, size: 1.0 }; + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(0.0, 0.0, 400.0, 200.0).unwrap(), &map, ("", 1), None, opts, 1.0) + }); + let right = (0..pm.width()).filter(|&x| (0..pm.height()).any(|y| pm.pixel(x, y).is_some_and(|p| p.red() < 200))).max(); + f64::from(right.unwrap_or(0)) * 25.4 / 96.0 + }; + for (labels, (w, _)) in [(&NO_LABELS, named), (&short, labelled)] { + let right = reach(labels); + assert!(right <= w + 0.3 && right > w - 1.5, "{right} mm drawn across {w} mm"); + } +} + +#[test] +fn legends_leave_out_what_the_frame_does_not_draw() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; + // A layer with one feature, of class "a", classed a, b and c; and an empty layer. + let mut map = Map::new("m"); + let mut d = Dataset::new("pts", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); + d.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text("a".into())]); + let pts = map.add_dataset(d); + map.add_dataset(Dataset::new("empty", GeometryType::Point, vec![])); + let s = |c| rustgis_map::Symbol::default_for(GeometryType::Point, c); + if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) { + let classes = ["a", "b", "c"].iter().zip(0u32..).map(|(k, i)| (k.to_string(), s(i))).collect(); + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes, + other: s(3), + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + } + // How far down the legend draws, in pixels. + let depth_without = |map: &Map, drawn: Option<&[(u32, Vec)]>, hide_other: bool, exclude: &[String]| { + let mut pm = Pixmap::new(300, 400).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let opts = LegendOptions { show_no_data: false, hide_other, exclude, labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(0.0, 0.0, 300.0, 400.0).unwrap(), map, ("", 1), drawn, opts, 1.0) + }); + (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| pm.pixel(x, y).is_some_and(|p| p.red() < 200))).max().unwrap_or(0) + }; + let depth = |map: &Map, drawn: Option<&[(u32, Vec)]>, hide_other: bool| depth_without(map, drawn, hide_other, &[]); + let drawn = shown_legends(&map, 1e6, false, &Env::default()); + assert_eq!(drawn.len(), 1, "the empty layer draws nothing: {drawn:?}"); + let (shown, all) = (depth(&map, Some(&drawn), false), depth(&map, None, false)); + // The drawn legend is two rows (the layer's heading and "a"); every class makes it six + // (b, c, and the empty layer's row too). Compared with each other, so + // the font and antialiasing don't matter. + assert!(shown > 0, "the drawn class is listed"); + assert!(all >= 2 * shown, "{shown} px of {all}"); + // The size a legend takes holds what it draws, to within a row: two rows drawn, six with + // every class. + let row = f64::from(LEGEND_ROW) * 25.4 / 96.0; + // How far right the legend draws, in pixels (points at this scale), as `depth` goes down. + let reach = |map: &Map, drawn: Option<&[(u32, Vec)]>| { + let mut pm = Pixmap::new(300, 400).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::canvas::with_canvas(&mut pm, |c| { + legend( + c, + Rect::from_xywh(0.0, 0.0, 300.0, 400.0).unwrap(), + map, + ("", 1), + drawn, + LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }, + 1.0, + ) + }); + (0..pm.width()).filter(|&x| (0..pm.height()).any(|y| pm.pixel(x, y).is_some_and(|p| p.red() < 200))).max().unwrap_or(0) + }; + for (all_classes, ink, right) in [(false, shown, reach(&map, Some(&drawn))), (true, all, reach(&map, None))] { + let (w, h) = legend_sizes_mm(&mut map, 1e6, all_classes, false, (&[], &NO_LABELS)).unwrap()[0]; + let (ink, right) = (f64::from(ink) * 25.4 / 96.0, f64::from(right) * 25.4 / 96.0); + assert!(w > 0.0 && ink <= h && h - ink < row, "{ink} mm drawn in {h} mm"); + // The widths in the same units as the drawing: the ink ends within the width measured, + // short of it by no more than a glyph's side bearing. + assert!(right <= w + 0.3 && right > w - 1.5, "{right} mm drawn across {w} mm"); + } + assert!((legend_sizes_mm(&mut map, 1e6, false, false, (&[], &NO_LABELS)).unwrap()[0].1 - 2.0 * row).abs() < 1e-9); + // A layer the legend leaves out (by name, any case) isn't listed, drawn or not. + let name = map.layer(pts).unwrap().name.to_uppercase(); + assert_eq!(depth_without(&map, Some(&drawn), false, std::slice::from_ref(&name)), 0, "its only drawn layer left out"); + let rest = depth_without(&map, None, false, &[name]); + assert!(rest > 0 && rest < all, "the other layer is still listed: {rest} px of {all}"); + // Hiding takes one row off the full legend, and nothing off the drawn + // one, which has none. + assert!(depth(&map, None, true) < all); + assert_eq!(depth(&map, Some(&drawn), true), shown); + // A layer whose drawn features all fall in , hidden, is left out rather + // than drawn as a plain swatch. + if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) + && let rustgis_map::Renderer::Unique { classes, .. } = &mut l.renderer + { + classes.retain(|(k, _)| k != "a"); + } + let drawn = shown_legends(&map, 1e6, false, &Env::default()); + assert!(depth(&map, Some(&drawn), false) > 0, " alone is listed"); + assert_eq!(depth(&map, Some(&drawn), true), 0, "and hidden, the layer is left out"); + // So is one whose drawn features all fall in a fully transparent , + // rather than drawn as a plain swatch of its first feature. + let set_other_alpha = |map: &mut Map, a: u8| { + if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) + && let rustgis_map::Renderer::Unique { other, .. } = &mut l.renderer + { + other.fill = other.fill.with_alpha(a); + other.stroke = other.stroke.with_alpha(a); + } + }; + set_other_alpha(&mut map, 0); + let drawn = shown_legends(&map, 1e6, false, &Env::default()); + assert_eq!(depth(&map, Some(&drawn), false), 0, "the invisible fallback stands for nothing"); + set_other_alpha(&mut map, 255); + // A class that bears the fallback's name is a class: hiding the fallback keeps it. + if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) + && let rustgis_map::Renderer::Unique { classes, .. } = &mut l.renderer + { + classes.push(("a".into(), s(0))); + classes.iter_mut().for_each(|(k, _)| { + if k == "a" { + *k = rustgis_map::symbology::OTHER_VALUES.into(); + } + }); + } + if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) { + l.dataset.features.iter_mut().for_each(|f| f.attrs = vec![Value::Text(rustgis_map::symbology::OTHER_VALUES.into())]); + } + let drawn = shown_legends(&map, 1e6, false, &Env::default()); + assert!(depth(&map, Some(&drawn), true) > 0, "the class named like the fallback is still listed"); + // A Graduated layer with no classes still shows its plain swatch, as before #207. + if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) { + l.renderer = rustgis_map::Renderer::Graduated { + field: "g".into(), + breaks: Vec::new(), + symbols: Vec::new(), + ramp: rustgis_map::Ramp::Ember, + method: rustgis_map::ClassMethod::NaturalBreaks, + min: 0.0, + classes: 0, + class_labels: Default::default(), + class_strokes: Default::default(), + class_fills: Default::default(), + }; + } + map.layers.retain(|l| l.id == pts); + assert!(depth(&map, None, false) > 0, "the empty Graduated layer is listed"); +} + +/// A layout with one map frame on `map` and a colorbar of its first raster, by name (one drawn by +/// classes isn't a colorbar's by default, #1679), at 10–90 × 10–30 mm (a vertical one at 10–30 × +/// 10–90 mm), drawn at 96 dpi. +fn colorbar_page(map: &Map, orientation: Orientation, reverse: bool, title: &str) -> Pixmap { + let mut l = Layout::new("Layout", 100.0, 100.0); + let frame = l.add( + "Map", + (95.0, 95.0, 4.0, 4.0), + ElementKind::MapFrame { + map: map.name.clone(), + center: Coord::new(0.0, 0.0), + scale: 1e8, + shape: FrameShape::Rectangle, + grid: None, + extent_of: None, + extent_color: rustgis_map::layout::INDICATOR_COLOR, + extent_width: rustgis_map::layout::INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }, + ); + let rect = if orientation == Orientation::Vertical { (10.0, 10.0, 20.0, 80.0) } else { (10.0, 10.0, 80.0, 20.0) }; + let layer = map.layers.iter().find(|l| l.is_raster()).map(|l| l.name.clone()); + let kind = + ElementKind::Colorbar { frame, layer, title: title.into(), orientation, ticks: 5, tick_side: TickSide::End, reverse, color: None }; + l.add("Colorbar", rect, kind); + render(&l, &mut [map.clone()], 96.0, &PageInfo::default()).unwrap() +} + +/// A page whose frame draws a layer without its cast shadows says why, named by the layer; one +/// with them, or without any asked for, says nothing. +#[test] +fn a_page_says_why_a_frame_drew_no_cast_shadows() { + let relief = |shadow| rustgis_map::raster::RasterRenderer::ShadedRelief { + band: 0, + ramp: None, + azimuth: 315.0, + altitude: 30.0, + z_factor: 1.0, + shadow, + sky: 0.0, + fill: 0.0, + rock: None, + ambient: None, + balanced: false, + }; + for shadow in [0.0, 1.0] { + let map = ramp_map(relief(shadow), rustgis_map::raster::Stretch::MinMax); + let (_, said) = crate::shadows_said(|| colorbar_page(&map, Orientation::Horizontal, false, "")); + assert!(said.notices.is_empty() && !said.to_come, "shadow {shadow}: {said:?}"); + } + // Read in place with only its overview held: no whole grid to trace. + let mut map = ramp_map(relief(1.0), rustgis_map::raster::Stretch::MinMax); + let rl = map.layers.iter_mut().find_map(|l| l.raster.as_mut()).unwrap(); + rl.in_place = true; + let mut r = (**rl.data.as_ref().unwrap()).clone(); + r.overview = Some((1000, 10)); + rl.data = Some(std::sync::Arc::new(r)); + let (_, said) = crate::shadows_said(|| colorbar_page(&map, Orientation::Horizontal, false, "")); + let said = said.notices; + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("dem: ") && said[0].contains("read in place"), "{said:?}"); + // What the map view's frame said is not a page's: a clean page drawn after it says nothing. + let camera = rustgis_map::Camera { center: rustgis_geom::lonlat_to_merc(Coord::new(0.5, 0.5)), res: 2000.0, bearing: 0.0, pitch: 0.0 }; + crate::render(&mut map, &crate::View { width: 64.0, height: 64.0, pixels_per_point: 1.0, camera, sky: false }); + let clean = ramp_map(relief(0.0), rustgis_map::raster::Stretch::MinMax); + let (_, said) = crate::shadows_said(|| colorbar_page(&clean, Orientation::Horizontal, false, "")); + assert!(said.notices.is_empty(), "{said:?}"); +} + +/// A page with maps showing copies of one relief (each layer the first of its map, so with the +/// same id), each under its own sun, drawn again until it has no shadows to come, as the +/// Layout view draws it while they land. Panics if it never settles. +fn page_settles_with_suns(suns: &[f64]) { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let n = 300usize; + let heights: Vec = (0..n * n).map(|i| (((i % n) as f32 / 9.0).sin() + ((i / n) as f32 / 7.0).cos()) * 400.0).collect(); + let gt = GeoTransform { origin_x: -1.0, origin_y: 1.0, pixel_width: 2.0 / n as f64, pixel_height: -2.0 / n as f64 }; + let dem = Raster::new("dem", n as u32, n as u32, vec![heights], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let rl = rustgis_map::raster::RasterLayer::from_path(dem, "dem.tif"); + let mut maps = Vec::new(); + let mut l = Layout::new("Layout", 100.0, 100.0); + for (i, azimuth) in suns.iter().enumerate() { + let name = format!("m{i}"); + let mut copy = rl.clone(); + copy.style.renderer = rustgis_map::raster::RasterRenderer::ShadedRelief { + band: 0, + ramp: None, + azimuth: *azimuth, + altitude: 10.0, + z_factor: 1.0, + shadow: 1.0, + sky: 0.0, + fill: 0.0, + rock: None, + ambient: None, + balanced: false, + }; + let mut m = Map::new(name.clone()); + assert_eq!(m.add_raster("dem", copy), 1); + maps.push(m); + let frame = ElementKind::MapFrame { + map: name.clone(), + center: Coord::new(0.0, 0.0), + scale: 1e7, + shape: FrameShape::Rectangle, + grid: None, + extent_of: None, + extent_color: rustgis_map::layout::INDICATOR_COLOR, + extent_width: rustgis_map::layout::INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }; + l.add(&name, (5.0 + 20.0 * i as f64, 5.0, 18.0, 18.0), frame); + } + let start = std::time::Instant::now(); + loop { + let (drawn, said) = crate::shadows_said(|| render_pending(&l, &mut maps, 48.0, &PageInfo::default())); + drawn.unwrap(); + assert!(said.notices.is_empty(), "{said:?}"); + if !said.to_come { + break; + } + assert!(start.elapsed() < std::time::Duration::from_secs(60), "the page never got its shadows"); + std::thread::yield_now(); + } +} + +/// Two maps lit otherwise on a page: neither map's grid stops the other's. +#[test] +fn two_maps_lit_otherwise_on_a_page_keep_their_own_shadows() { + page_settles_with_suns(&[315.0, 135.0]); +} + +/// More maps lit otherwise than the grids kept for going back: none is let go while it is drawn. +#[test] +fn many_maps_lit_otherwise_on_a_page_all_get_their_shadows() { + page_settles_with_suns(&[315.0, 135.0, 45.0, 225.0, 0.0]); +} + +/// A map with one 100 × 1 raster valued 0–99 by column, styled by `renderer`. +fn ramp_map(renderer: rustgis_map::raster::RasterRenderer, stretch: rustgis_map::raster::Stretch) -> Map { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 0.01, pixel_height: -0.01 }; + let data: Vec = (0..100).map(|i| i as f32).collect(); + let r = Raster::new("dem", 100, 1, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let mut rl = rustgis_map::raster::RasterLayer::from_path(r, "dem.tif"); + rl.style.renderer = renderer; + rl.style.stretch = stretch; + let mut map = Map::new("m"); + map.add_raster("dem", rl); + map +} + +/// A map with a land cover raster of `n` classes (values 1 to `n`, one cell each) drawn by its +/// colour table, the first named "Forest". +fn classes_map(n: u8) -> Map { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 0.01, pixel_height: -0.01 }; + let mut palette = vec![[0, 0, 0, 0]; 256]; + for v in 1..=n { + palette[usize::from(v)] = [v, 255 - v, 128, 255]; + } + let data: Vec = (1..=n).map(f32::from).collect(); + let mut r = Raster::new("lc", u32::from(n), 1, vec![data], gt, Crs::LonLat, None, ColorHint::Palette(palette), "UInt8").unwrap(); + r.bands[0].classes = vec![String::new(), "Forest".into()]; + let mut rl = rustgis_map::raster::RasterLayer::from_path(r, "lc.tif"); + rl.style.renderer = rustgis_map::raster::RasterRenderer::Colormap; + let mut map = Map::new("m"); + map.add_raster("Land cover", rl); + map +} + +/// A classified raster's legend: its name over its classes, as the Layers pane lists them, by +/// what the frame shows and with every class alike (a colour table lists the values it holds); +/// left out by name; a raster on a ramp isn't listed (#1679). +#[test] +fn a_legend_lists_a_classified_rasters_classes() { + let mut map = classes_map(5); + let opts = LegendOptions { show_no_data: false, hide_other: true, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + let labels = |rows: &[LegendRow]| -> Vec { + rows.iter() + .map(|r| match r { + LegendRow::Head(name) => format!("[{name}]"), + LegendRow::Class(_, en) => en.label.clone(), + LegendRow::Plain(_, name) => format!("plain {name}"), + LegendRow::Picture(_) => "picture".into(), + }) + .collect() + }; + let want = ["[Land cover]", "Forest", "2", "3", "4", "5"]; + assert_eq!(labels(&legend_rows(&map, None, &opts)), want); + let drawn = shown_legends(&map, 1e6, false, &Env::default()); + assert_eq!(labels(&legend_rows(&map, Some(&drawn), &opts)), want); + // Its swatches are the pane's colours. + let pane: Vec = map.layers[0] + .raster + .as_ref() + .unwrap() + .legend() + .into_iter() + .filter_map(|e| match e { + rustgis_map::raster::RasterLegend::Class { color, .. } => Some(color), + _ => None, + }) + .collect(); + let swatches: Vec = legend_rows(&map, None, &opts) + .iter() + .filter_map(|r| if let LegendRow::Class(_, en) = r { Some(en.symbol.fill) } else { None }) + .collect(); + assert_eq!(swatches, pane); + // Sized by its rows: its name and five classes. + let mm = 25.4 / 96.0; + let [(_, h), ..] = legend_sizes_mm(&mut map, 1e6, false, false, (&[], &NO_LABELS)).unwrap(); + assert!((h - 6.0 * f64::from(LEGEND_ROW) * mm).abs() < 1e-6, "{h} mm"); + let labelled = BTreeMap::from([("Land cover".to_string(), "Classes do MapBiomas".to_string())]); + let opts_labelled = LegendOptions { labels: &labelled, ..opts }; + assert_eq!(labels(&legend_rows(&map, None, &opts_labelled))[0], "[Classes do MapBiomas]"); + // Left out by name, or when hidden. + let exclude = ["land cover".to_string()]; + assert!(legend_rows(&map, None, &LegendOptions { exclude: &exclude, ..opts }).is_empty()); + map.layers[0].visible = false; + assert!(shown_legends(&map, 1e6, false, &Env::default()).is_empty()); + assert!(legend_rows(&map, None, &opts).is_empty()); + // A raster on a ramp: a colorbar keys it, the legend doesn't list it. + let ramp = ramp_map( + rustgis_map::raster::RasterRenderer::Stretch { band: 0, ramp: rustgis_map::Ramp::Harbour, invert: false }, + rustgis_map::raster::Stretch::MinMax, + ); + assert!(legend_rows(&ramp, None, &opts).is_empty() && shown_legends(&ramp, 1e6, false, &Env::default()).is_empty()); +} + +/// A drawn legend fills each class's swatch with its colour, under the raster's name. +#[test] +fn a_drawn_legend_fills_a_raster_class_with_its_colour() { + let map = classes_map(5); + let pm = point_legend(&map); + for v in 1..=5u8 { + let c = (v, 255 - v, 128); + let found = pm.pixels().iter().any(|p| (p.red(), p.green(), p.blue()) == c); + assert!(found, "class {v}'s colour {c:?}"); + } +} + +/// A page with a main frame and an inset (5–55 mm) that outlines it in `color` at `width`. +fn indicator_page(color: Rgba, width: f64) -> Pixmap { + let map = Map::new("m"); + let frame = |center, scale, extent_of| ElementKind::MapFrame { + map: "m".into(), + center, + scale, + shape: FrameShape::Rectangle, + grid: None, + extent_of, + extent_color: color, + extent_width: width, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }; + let mut l = Layout::new("Layout", 100.0, 100.0); + let main = l.add("Main", (60.0, 60.0, 30.0, 30.0), frame(Coord::new(20.0, 10.0), 5e7, None)); + l.add("Inset", (5.0, 5.0, 50.0, 50.0), frame(Coord::new(0.0, 0.0), 2e8, Some(main))); + render(&l, &mut [map], 96.0, &PageInfo::default()).unwrap() +} + +/// Pixels inside the inset (5–55 mm) close to `c`. +fn inset_pixels(pm: &Pixmap, c: Rgba) -> usize { + let k = PT_PER_MM; + let near = |p: (u8, u8, u8)| p.0.abs_diff(c.r()) < 40 && p.1.abs_diff(c.g()) < 40 && p.2.abs_diff(c.b()) < 40; + ((5.0 * k) as u32..(55.0 * k) as u32) + .flat_map(|y| ((5.0 * k) as u32..(55.0 * k) as u32).map(move |x| (x, y))) + .filter(|&(x, y)| near(rgb(pm, x, y))) + .count() +} + +/// One line of black text drawn in a white 400 × 60 px box with `style`. +fn styled_line(style: TextStyle) -> Pixmap { + let mut pm = Pixmap::new(400, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 0.0, 400.0, 60.0).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| text_block(c, r, "Oceano Atlântico", 20.0, Rgba::rgb(0, 0, 0), style, 1.0)); + pm +} + +/// The leftmost and rightmost inked columns, and the inked column nearest the left at the +/// top and at the bottom of the letters. +fn text_ink(pm: &Pixmap) -> (u32, u32, u32, u32) { + let dark = |x: u32, y: u32| rgb(pm, x, y).0 < 128; + let rows: Vec = (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| dark(x, y))).collect(); + let (top, bottom) = (rows[0], rows[rows.len() - 1]); + let cols: Vec = (0..pm.width()).filter(|&x| (0..pm.height()).any(|y| dark(x, y))).collect(); + let first = |y: u32| (0..pm.width()).find(|&x| dark(x, y)).unwrap_or(0); + (cols[0], cols[cols.len() - 1], first(top + 1), first(bottom - 1)) +} + +/// The height of the inked rows. +fn text_height(pm: &Pixmap) -> u32 { + let rows: Vec = (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| rgb(pm, x, y).0 < 128)).collect(); + rows[rows.len() - 1] - rows[0] +} + +/// A page with `kind` in (10, 10, 80, 30) mm on white. +fn shape_page(kind: ElementKind) -> Layout { + let mut l = Layout::new("L", 100.0, 50.0); + l.add("Shape", (10.0, 10.0, 80.0, 30.0), kind); + l +} + +/// The runs of inked and blank pixels along a row (or a column) from `from` to `to`: how many +/// times it goes from ink to blank. +fn gaps(pm: &Pixmap, along: impl Iterator) -> usize { + let ink: Vec = along.map(|(x, y)| rgb(pm, x, y).0 < 128).collect(); + ink.windows(2).filter(|w| w[0] && !w[1]).count() +} + +/// A dashed line has gaps where its pattern says, its arrowhead solid; a dashed rectangle's +/// outline has gaps on all four sides; solid, both draw as before (#1763). +#[test] +fn dashed_lines_and_outlines_have_gaps() { + use rustgis_map::layout::LineDir; + let black = Rgba::rgb(0, 0, 0); + let dash = rustgis_map::symbology::Dash::new(&[6.0, 6.0]); + let png = |kind: ElementKind| render(&shape_page(kind), &mut [], 96.0, &PageInfo::default()).unwrap(); + // 96 dpi: 1 mm is 3.78 px. The line runs along y = 25 mm from x = 10 to 90 mm. + let px = |mm: f64| (mm * 96.0 / 25.4).round() as u32; + let line = |dash, head| ElementKind::Line { color: black, width: 2.0, dir: LineDir::Horizontal, head, dash }; + let along = |pm: &Pixmap| gaps(pm, (px(11.0)..px(80.0)).map(|x| (x, px(25.0)))); + assert_eq!(along(&png(line(None, LineHead::None))), 0, "solid"); + // 69 mm is about 261 points (PT_PER_MM): a 12-point round each, so some 22 gaps. + let dashed = png(line(dash, LineHead::End)); + assert!((20..=24).contains(&along(&dashed)), "{} gaps", along(&dashed)); + // The head (the last 6 + 2.5 × 2 = 11 points, 2.9 mm) is filled: no gap across it. + assert_eq!(gaps(&dashed, (px(87.5)..px(89.8)).map(|x| (x, px(25.0)))), 0, "the arrowhead stays solid"); + let rect = |dash| ElementKind::Rectangle { fill: Rgba::new(0, 0, 0, 0), outline: black, width: 2.0, radius: 0.0, dash }; + let sides = |pm: &Pixmap| { + let (x0, x1, y0, y1) = (px(10.0), px(90.0), px(10.0), px(40.0)); + [ + gaps(pm, (x0 + 4..x1 - 4).map(|x| (x, y0))), + gaps(pm, (x0 + 4..x1 - 4).map(|x| (x, y1))), + gaps(pm, (y0 + 4..y1 - 4).map(|y| (x0, y))), + gaps(pm, (y0 + 4..y1 - 4).map(|y| (x1, y))), + ] + }; + assert_eq!(sides(&png(rect(None))), [0; 4], "solid"); + let dashed = sides(&png(rect(dash))); + assert!(dashed.iter().all(|g| *g >= 3), "gaps on every side: {dashed:?}"); + let oval = |dash| ElementKind::Ellipse { fill: Rgba::new(0, 0, 0, 0), outline: black, width: 2.0, dash }; + // Round its outline: the ellipse fills (10, 10, 80, 30) mm. + let round = |pm: &Pixmap| { + let px = |mm: f64| mm * 96.0 / 25.4; + // Inked where any pixel within one of the curve's point is: the 2-point stroke is about + // 2 pixels wide. + let near = |(x, y): (f64, f64)| { + (-1..=1).any(|dx| (-1..=1).any(|dy| rgb(pm, (x.round() as i32 + dx) as u32, (y.round() as i32 + dy) as u32).0 < 128)) + }; + let ink: Vec = (0..2000) + .map(|i| f64::from(i) / 2000.0 * std::f64::consts::TAU) + .map(|t| near((px(50.0 + 40.0 * t.cos()), px(25.0 + 15.0 * t.sin())))) + .collect(); + ink.windows(2).filter(|w| w[0] && !w[1]).count() + }; + assert_eq!(round(&png(oval(None))), 0, "solid"); + assert!(round(&png(oval(dash))) >= 20, "{}", round(&png(oval(dash)))); +} + +/// A dashed box round a turned text, on one page (#1763): the picture has the box's gaps and +/// the text running down the page inside it; the recorded page (the PDF's) keeps the dashes as +/// pieces and the text as glyphs; the SVG writes the dash array and the turn. +#[test] +fn a_dashed_box_and_a_turned_text_share_a_page() { + use crate::vector::Item; + // The text's box (10, 45, 80, 10) mm turned 90° about (50, 50): 45..55 across, 10..90 down. + let mut layout = turned_text_page(90.0); + let dash = rustgis_map::symbology::Dash::new(&[6.0, 6.0]); + let outline = Rgba::rgb(0, 0, 0); + layout.add( + "Box", + (5.0, 5.0, 90.0, 90.0), + ElementKind::Rectangle { fill: Rgba::new(0, 0, 0, 0), outline, width: 2.0, radius: 0.0, dash }, + ); + let info = PageInfo::default(); + let png = render(&layout, &mut [], 96.0, &info).unwrap(); + let px = |mm: f64| (mm * 96.0 / 25.4).round() as u32; + assert!(gaps(&png, (px(10.0)..px(90.0)).map(|x| (x, px(5.0)))) >= 3, "the box's top is dashed"); + // Inside the box: the text, tall and narrow about x = 50 mm. + let inside: Vec<(u32, u32)> = + (px(8.0)..px(92.0)).flat_map(|y| (px(8.0)..px(92.0)).map(move |x| (x, y))).filter(|&(x, y)| rgb(&png, x, y).0 < 128).collect(); + let (l, r) = (inside.iter().map(|p| p.0).min().unwrap(), inside.iter().map(|p| p.0).max().unwrap()); + let (t, b) = (inside.iter().map(|p| p.1).min().unwrap(), inside.iter().map(|p| p.1).max().unwrap()); + assert!(b - t > 4 * (r - l) && l > px(44.0) && r < px(56.0), "the text runs down the page: {l},{t} to {r},{b}"); + let (drawing, _) = render_drawing(&layout, &mut [], 96.0, &info).unwrap(); + let (_, _, items) = drawing.finish(); + let items = crate::vector::without_layers(items); + let pieces: usize = items + .iter() + .filter_map(|i| if let Item::Stroke { path, .. } = i { Some(path) } else { None }) + .map(|p| p.segments().filter(|s| matches!(s, tiny_skia::PathSegment::MoveTo(_))).count()) + .sum(); + let text: String = items + .iter() + .filter_map(|i| if let Item::Glyphs(r) = i { Some(r) } else { None }) + .flat_map(|r| r.glyphs.iter().map(|g| g.ch)) + .collect(); + assert!(pieces > 20 && text == "Fonte: IBGE, 2022", "{pieces} dashes, text {text:?}"); + let svg = crate::svg::layout_svg(&layout, &mut [], 96.0, &info).unwrap().0; + assert!(svg.contains("stroke-dasharray") && svg.contains(r#"transform="rotate(90 50 50)""#), "{svg}"); +} + +/// A dashed outline is kept as vectors, its dashes as the pieces of the path (as a dashed line +/// layer's are), which draw what its picture shows (#1763). +#[test] +fn a_dashed_outline_is_kept_as_its_dashes() { + use crate::vector::Item; + let dash = rustgis_map::symbology::Dash::new(&[6.0, 6.0]); + let kind = ElementKind::Rectangle { fill: Rgba::new(0, 0, 0, 0), outline: Rgba::rgb(0, 0, 0), width: 2.0, radius: 0.0, dash }; + let layout = shape_page(kind); + let info = PageInfo::default(); + let png = render(&layout, &mut [], 96.0, &info).unwrap(); + let (drawing, _) = render_drawing(&layout, &mut [], 96.0, &info).unwrap(); + let (_, _, items) = drawing.finish(); + let items = crate::vector::without_layers(items); + let pieces: usize = items + .iter() + .filter_map(|i| if let Item::Stroke { path, .. } = i { Some(path) } else { None }) + .map(|p| p.segments().filter(|s| matches!(s, tiny_skia::PathSegment::MoveTo(_))).count()) + .sum(); + assert!(pieces > 20, "{pieces} dashes kept"); + let mut replayed = Pixmap::new(png.width(), png.height()).unwrap(); + replayed.fill(tiny_skia::Color::WHITE); + crate::vector::replay(&items, &mut replayed, Transform::identity()); + let differ = png.pixels().iter().zip(replayed.pixels()).filter(|(a, b)| a.red().abs_diff(b.red()) > 48).count(); + assert!(differ < 50, "{differ} pixels differ"); +} + +/// A page with one text element in (10, 45, 80, 10) mm, turned `turn` degrees. +fn turned_text_page(turn: f64) -> Layout { + let mut l = Layout::new("L", 100.0, 100.0); + let mut kind = ElementKind::text("Fonte: IBGE, 2022", 14.0, Rgba::rgb(0, 0, 0), false); + if let ElementKind::Text { rotation, .. } = &mut kind { + *rotation = turn; + } + l.add("Source", (10.0, 45.0, 80.0, 10.0), kind); + l +} + +/// The dark pixels' bounds: left, top, right, bottom. +fn ink_bounds(pm: &Pixmap) -> (u32, u32, u32, u32) { + let dark: Vec<(u32, u32)> = + (0..pm.height()).flat_map(|y| (0..pm.width()).map(move |x| (x, y))).filter(|&(x, y)| rgb(pm, x, y).0 < 128).collect(); + let xs = dark.iter().map(|p| p.0); + let ys = dark.iter().map(|p| p.1); + (xs.clone().min().unwrap(), ys.clone().min().unwrap(), xs.max().unwrap(), ys.max().unwrap()) +} + +/// A page with `text` at 12 pt in (10, 10, 40, 60) mm, wrapped to its box or not (#2346), +/// aligned `align` and turned `turn` degrees. +fn note_page(text: &str, wrap: bool, align: TextAlign, turn: f64) -> Layout { + let mut l = Layout::new("L", 100.0, 100.0); + let mut kind = ElementKind::text(text, 12.0, Rgba::rgb(0, 0, 0), false); + if let ElementKind::Text { wrap: w, align: a, rotation, .. } = &mut kind { + (*w, *a, *rotation) = (wrap, align, turn); + } + l.add("Note", (10.0, 10.0, 40.0, 60.0), kind); + l +} + +const NOTE: &str = "Population counts from the 2020 census; boundaries simplified for print"; + +/// A wrapped text breaks at spaces into lines that stay within its box's width, whichever +/// its alignment; unwrapped, the same sentence runs past the box as it always has (#2346). +#[test] +fn a_wrapped_text_breaks_into_lines_that_fit_its_box() { + let mm = 96.0 / 25.4; + let (left, right) = (10.0 * mm, 50.0 * mm); + let ink = |l: &Layout| ink_bounds(&render(l, &mut [], 96.0, &PageInfo::default()).unwrap()); + let (_, t, r, b) = ink(¬e_page(NOTE, false, TextAlign::Left, 0.0)); + assert!(f64::from(r) > right + 40.0, "unwrapped, it runs past the box: {r}"); + let line = b - t; + for align in TextAlign::ALL { + let (l, t, r, b) = ink(¬e_page(NOTE, true, align, 0.0)); + assert!(f64::from(l) >= left - 2.0 && f64::from(r) <= right + 2.0, "{align:?}: inked {l}..{r} in {left}..{right}"); + assert!(b - t > 3 * line, "{align:?}: in several lines, {t}..{b}"); + } + // A word wider than the box (an address) is broken across lines, kept within it. + let url = "https://example.org/data/population/census-2020/boundaries-simplified.zip"; + let (l, t, r, b) = ink(¬e_page(url, true, TextAlign::Left, 0.0)); + assert!(f64::from(l) >= left - 2.0 && f64::from(r) <= right + 2.0 && b - t > 2 * line, "{l},{t} to {r},{b}"); + // Its own line breaks are kept: a blank line between two short ones stays. + let (_, t, _, b) = ink(¬e_page("Source\n\nIBGE", true, TextAlign::Left, 0.0)); + let (_, t2, _, b2) = ink(¬e_page("Source\nIBGE", true, TextAlign::Left, 0.0)); + assert!(b - t > b2 - t2 + line / 2, "{t}..{b} against {t2}..{b2}"); +} + +/// A turned wrapped text wraps to its unturned box's width: turned 90°, its lines run down the +/// page within the box's 40 mm about its centre (#2346). +#[test] +fn a_turned_wrapped_text_wraps_to_its_unturned_width() { + let mm = 96.0 / 25.4; + let (l, t, r, b) = ink_bounds(&render(¬e_page(NOTE, true, TextAlign::Left, 90.0), &mut [], 96.0, &PageInfo::default()).unwrap()); + // The box's centre is at (30, 40) mm: 40 mm wide, turned, it spans 20 to 60 mm down the page. + assert!(f64::from(t) >= 20.0 * mm - 2.0 && f64::from(b) <= 60.0 * mm + 2.0, "{t}..{b}"); + assert!(r - l > 40, "its lines side by side: {l}..{r}"); +} + +/// A wrapped text whose lines reach past its box's bottom is reported as cut, as a text with +/// too many line breaks is; one whose lines fit isn't (#2346). +#[test] +fn a_wrapped_text_past_its_box_is_reported_cut() { + let info = PageInfo::default(); + let mut l = note_page(NOTE, true, TextAlign::Left, 0.0); + assert!(clipped_text(&l, &[], 96.0, &info).is_empty()); + let id = l.elements[0].id; + l.element_mut(id).unwrap().h = 4.0; + assert_eq!(clipped_text(&l, &[], 96.0, &info), vec![(id, "Note".into())]); +} + +/// A wrapped text past the 200 lines a text draws is reported cut, even when its 201st line is +/// blank and the text goes on after it (#2346); one followed only by blank lines loses nothing +/// and isn't. +#[test] +fn a_wrapped_text_past_its_last_drawn_line_is_reported_cut() { + let info = PageInfo::default(); + let page = |tail: &str| { + let mut l = Layout::new("L", 100.0, 1500.0); + let mut kind = ElementKind::text(format!("{}{tail}", vec!["a"; 200].join("\n")), 12.0, Rgba::rgb(0, 0, 0), false); + if let ElementKind::Text { wrap, .. } = &mut kind { + *wrap = true; + } + let id = l.add("Note", (10.0, 10.0, 40.0, 1400.0), kind); + (l, id) + }; + let (l, id) = page("\n\u{a0}\nZ"); + assert_eq!(clipped_text(&l, &[], 96.0, &info), vec![(id, "Note".into())]); + let (l, _) = page("\n\n\n"); + assert!(clipped_text(&l, &[], 96.0, &info).is_empty(), "only blank lines past it"); + // Counted as more than the one line seen: the wrapped text was broken no further. + let (l, id) = page("\nZ"); + let loss = text_losses(&l, &[], 96.0, &info); + assert_eq!( + loss, + vec![TextLoss { + id, + name: "Note".into(), + left_out: 1, + at_least: true, + below_box: false, + past_limit: true, + off_page: false, + unit_label: None + }] + ); + let said = lines_left_out_notice(&loss[0]).unwrap(); + assert!(said.starts_with("1 or more lines of the text \"Note\""), "{said}"); + assert!(said.ends_with("aren't drawn: a text draws at most 200 lines; split it into more than one text"), "{said}"); +} + +/// The lines of a text left out below its box are counted, blank ones not, and said in the +/// singular or the plural; a text whose lines all fit says nothing (#2346). +#[test] +fn a_text_counts_the_lines_left_out_of_its_box() { + let info = PageInfo::default(); + let mut l = note_page("one\ntwo\n\nfour\nfive", false, TextAlign::Left, 0.0); + let id = l.elements[0].id; + let losses = |l: &Layout| text_losses(l, &[], 96.0, &info); + assert!(losses(&l).is_empty(), "all fit"); + l.element_mut(id).unwrap().h = 2.0; + let loss = losses(&l); + assert_eq!( + loss, + vec![TextLoss { + id, + name: "Note".into(), + left_out: 3, + at_least: false, + below_box: true, + past_limit: false, + off_page: false, + unit_label: None + }] + ); + // The element alone is measured the same, and another id finds nothing. + assert_eq!(text_loss(&l, &[], 96.0, &info, id).as_ref(), loss.first()); + assert_eq!(text_loss(&l, &[], 96.0, &info, id + 1), None); + let said = lines_left_out_notice(&loss[0]).unwrap(); + assert!(said.starts_with(&format!("3 lines of the text \"Note\" ({id}) don't fit its box and aren't drawn")), "{said}"); + if let ElementKind::Text { text, .. } = &mut l.element_mut(id).unwrap().kind { + *text = "one\ntwo".into(); + } + let said = lines_left_out_notice(&losses(&l)[0]).unwrap(); + assert!(said.starts_with(&format!("1 line of the text \"Note\" ({id}) doesn't fit its box and isn't drawn")), "{said}"); + // Off the page but all drawn: cut, with no line left out to count. + let e = l.element_mut(id).unwrap(); + (e.h, e.x) = (60.0, 99.0); + let loss = losses(&l); + assert_eq!(loss.len(), 1); + assert_eq!(lines_left_out_notice(&loss[0]), None); +} + +/// A text whose ink crosses the page's edge is told apart from its lines left out, with the +/// advice that fixes an edge: moved past each side it is, back inside or turned within the +/// page it isn't, and one cut below its box and past the edge has both (#2703). +#[test] +fn a_text_past_the_pages_edge_is_told_with_its_advice() { + let info = PageInfo::default(); + let mut l = note_page("Note", false, TextAlign::Left, 0.0); + let id = l.elements[0].id; + let put = |l: &mut Layout, (x, y): (f64, f64)| { + if let Some(e) = l.element_mut(id) { + (e.x, e.y) = (x, y); + } + }; + let turn = |l: &mut Layout, degrees: f64| { + if let Some(ElementKind::Text { rotation, .. }) = l.element_mut(id).map(|e| &mut e.kind) { + *rotation = degrees; + } + }; + let told = |l: &Layout| text_loss(l, &[], 96.0, &info, id).and_then(|loss| off_page_notice(&loss)); + let said = format!( + "The text \"Note\" ({id}) runs off the page, so part of it isn't drawn; move it inside the page, resize it or reduce its size" + ); + assert_eq!(told(&l), None, "inside the page"); + // Past each edge. + for at in [(98.0, 10.0), (10.0, 99.0), (-30.0, 10.0), (10.0, -5.0)] { + put(&mut l, at); + let loss = text_loss(&l, &[], 96.0, &info, id).unwrap_or_else(|| panic!("{at:?} is past an edge")); + assert!(loss.off_page && loss.left_out == 0 && !loss.below_box, "{at:?} {loss:?}"); + assert_eq!(off_page_notice(&loss), Some(said.clone()), "{at:?}"); + assert_eq!(lines_left_out_notice(&loss), None, "{at:?}: no line is left out"); + put(&mut l, (10.0, 10.0)); + assert_eq!(told(&l), None, "{at:?} moved back inside"); + } + // A text that doesn't cross says nothing, whatever else is lost. + let inside = TextLoss { + id, + name: "Note".into(), + left_out: 1, + at_least: false, + below_box: true, + past_limit: false, + off_page: false, + unit_label: None, + }; + assert_eq!(off_page_notice(&inside), None); + // Turned within the page: nothing. Turned about its box's centre past the edge: told. + put(&mut l, (30.0, 10.0)); + turn(&mut l, 90.0); + assert_eq!(told(&l), None, "turned within the page"); + turn(&mut l, 180.0); + assert_eq!(told(&l), None, "turned within the page"); + put(&mut l, (80.0, 10.0)); + turn(&mut l, 0.0); + assert_eq!(told(&l), None, "unturned, it is inside"); + turn(&mut l, 180.0); + assert_eq!(told(&l), Some(said.clone()), "turned about its box's centre, past the edge"); + // Cut below its box and past the edge: each is told, apart. + let mut l = note_page("one\ntwo\nthree", false, TextAlign::Left, 0.0); + let id = l.elements[0].id; + if let Some(e) = l.element_mut(id) { + (e.x, e.h) = (98.0, 2.0); + } + let loss = text_loss(&l, &[], 96.0, &info, id).unwrap_or_else(|| panic!("cut")); + assert!(loss.below_box && loss.off_page && loss.left_out == 2, "{loss:?}"); + let (lines, edge) = (lines_left_out_notice(&loss).unwrap_or_default(), off_page_notice(&loss).unwrap_or_default()); + assert!(lines.contains("don't fit its box") && !lines.contains("page"), "{lines}"); + assert!(edge.contains("runs off the page") && !edge.contains("lines"), "{edge}"); + // No ink, nothing to cut: an empty or blank text, past the edge. + for blank in ["", " \n "] { + let mut l = note_page(blank, false, TextAlign::Left, 0.0); + let id = l.elements[0].id; + if let Some(e) = l.element_mut(id) { + e.x = 98.0; + } + assert_eq!(text_loss(&l, &[], 96.0, &info, id), None, "{blank:?} has no ink"); + } + // A file can hold any place and size: measured without a panic, and told at most once. + for (x, y, size) in + [(1e300, -1e300, 12.0), (f64::NAN, f64::INFINITY, 12.0), (10.0, 10.0, f64::NAN), (10.0, 10.0, 1e300), (98.0, 10.0, 1e300)] + { + let mut l = note_page("Note", false, TextAlign::Left, 0.0); + let id = l.elements[0].id; + if let Some(e) = l.element_mut(id) { + (e.x, e.y) = (x, y); + if let ElementKind::Text { size: s, .. } = &mut e.kind { + *s = size; + } + } + let losses = text_losses(&l, &[], 96.0, &info); + assert!(losses.len() <= 1 && losses.iter().all(|loss| off_page_notice(loss).iter().count() <= 1), "{x} {y} {size}"); + } +} + +/// A long text counts every line left out below its box, each only looked at for a letter +/// past the box: none is shaped there (#2346). +#[test] +fn a_long_text_counts_every_line_left_out() { + let info = PageInfo::default(); + let mut l = note_page(&vec!["x"; 3000].join("\n"), false, TextAlign::Left, 0.0); + let id = l.elements[0].id; + l.element_mut(id).unwrap().h = 2.0; + let loss = text_losses(&l, &[], 96.0, &info); + assert_eq!( + loss, + vec![TextLoss { + id, + name: "Note".into(), + left_out: 2999, + at_least: false, + below_box: true, + past_limit: true, + off_page: false, + unit_label: None + }] + ); + let said = lines_left_out_notice(&loss[0]).unwrap(); + assert!(said.ends_with("make the box taller or the text smaller, and split it, as a text draws at most 200 lines"), "{said}"); + // A box tall enough for 200 lines: the rest are past the limit, which no box draws (#2346). + let mut tall = note_page(&vec!["x"; 250].join("\n"), false, TextAlign::Left, 0.0); + tall.height = 2000.0; + tall.element_mut(id).unwrap().h = 1900.0; + let loss = text_losses(&tall, &[], 96.0, &info); + assert_eq!( + loss, + vec![TextLoss { + id, + name: "Note".into(), + left_out: 50, + at_least: false, + below_box: false, + past_limit: true, + off_page: false, + unit_label: None + }] + ); + let said = lines_left_out_notice(&loss[0]).unwrap(); + assert_eq!( + said, + format!("50 lines of the text \"Note\" ({id}) aren't drawn: a text draws at most 200 lines; split it into more than one text") + ); + // Blank lines below the box and then one letter: that one line is left out. + let mut l = note_page(&format!("x{}\nZ", "\n".repeat(2000)), false, TextAlign::Left, 0.0); + l.element_mut(id).unwrap().h = 2.0; + assert_eq!( + text_losses(&l, &[], 96.0, &info), + vec![TextLoss { + id, + name: "Note".into(), + left_out: 1, + at_least: false, + below_box: false, + past_limit: true, + off_page: false, + unit_label: None + }] + ); +} + +/// The cut-off notice suggests breaking lines or wrapping them for a text not wrapped, and +/// only the box or the size when every text it names is wrapped already (#2346). +#[test] +fn the_cut_off_notice_suggests_wrapping_a_text_not_wrapped() { + let info = PageInfo::default(); + for wrap in [false, true] { + let mut l = note_page(NOTE, wrap, TextAlign::Left, 0.0); + let id = l.elements[0].id; + l.element_mut(id).unwrap().h = 2.0; + let note = clipped_text_notice(&l, &clipped_text(&l, &[], 96.0, &info)).unwrap(); + assert!(note.starts_with(&format!("Text is cut off in 1 layout element(s): Note ({id}); ")), "{note}"); + assert_eq!(note.contains("Wrap to the box"), !wrap, "{note}"); + assert_eq!(note.contains("add line breaks"), !wrap, "{note}"); + assert!(note.contains("reduce its size"), "{note}"); + } + // A legend's title, or an element gone since, has no wrap to turn on: line breaks, as before. + let l = note_page(NOTE, true, TextAlign::Left, 0.0); + let note = clipped_text_notice(&l, &[(999, "Gone".into())]).unwrap(); + assert!(note.ends_with("resize or move the text, reduce its size, or add line breaks"), "{note}"); + let both = clipped_text_notice(&l, &[(l.elements[0].id, "Note".into()), (999, "Gone".into())]).unwrap(); + assert!(!both.contains("Wrap to the box") && both.contains("add line breaks"), "{both}"); + assert_eq!(clipped_text_notice(&Layout::new("L", 10.0, 10.0), &[]), None); +} + +/// The same lines at every resolution: they are measured at one (#2346), so the layout view, +/// an image export and a print break a text alike. +#[test] +fn a_wrapped_text_breaks_alike_at_every_resolution() { + let style = TextStyle { face: text::Face::default(), align: TextAlign::Left, spacing: 0.0, valign: TextVAlign::Top, line_spacing: 1.0 }; + let lines = wrapped(NOTE, 40.0, 12.0, style); + assert!(lines.lines().count() > 3, "{lines}"); + assert!(lines.lines().all(|l| !l.starts_with(' ') && !l.ends_with(' ')), "{lines:?}"); + assert_eq!(lines.replace('\n', " "), NOTE, "broken only at its spaces"); + let tall = |dpi: f64| { + let pm = render(¬e_page(NOTE, true, TextAlign::Left, 0.0), &mut [], dpi, &PageInfo::default()).unwrap(); + let (_, t, _, b) = ink_bounds(&pm); + f64::from(b - t) / dpi + }; + assert!((tall(96.0) - tall(300.0)).abs() < 0.03, "{} against {} inches", tall(96.0), tall(300.0)); +} + +/// A text turned 90° runs down the page from the top of its turned box, -90° up it from the +/// bottom, about the centre of its box (#1763); upright, it runs across as before. +#[test] +fn a_turned_text_runs_down_or_up_the_page() { + // 100 mm at 96 dpi; the box's centre at 50 mm. + let centre = 50.0 * 96.0 / 25.4; + let ink = |turn: f64| ink_bounds(&render(&turned_text_page(turn), &mut [], 96.0, &PageInfo::default()).unwrap()); + let (l, t, r, b) = ink(0.0); + assert!(r - l > 4 * (b - t), "upright runs across: {l},{t} to {r},{b}"); + for turn in [90.0, -90.0] { + let (l, t, r, b) = ink(turn); + assert!(b - t > 4 * (r - l), "{turn}° runs along the page: {l},{t} to {r},{b}"); + // Across: within the turned box, 10 mm wide about the centre. + assert!((f64::from(l + r) / 2.0 - centre).abs() < 10.0 * 96.0 / 25.4 / 2.0, "{turn}°: {l}..{r}"); + // Along: a left-aligned line starts at the box's left edge, which a turn of 90° takes to + // the top and one of -90° to the bottom. + let middle = f64::from(t + b) / 2.0; + assert!(if turn > 0.0 { middle < centre } else { middle > centre }, "{turn}°: {t}..{b} about {centre}"); + } +} + +/// A quarter-turned text keeps as sharp as an upright one: its picture is put on whole pixels, +/// not filtered between them, so its edges have no more part-covered pixels (#1763). At 300 dpi +/// the box's corner falls between pixels (10 mm is 118.1 of them). +#[test] +fn a_quarter_turned_text_is_as_sharp_as_upright() { + // Solid pixels (darker than 80 %) and part-covered ones (20 to 80 %). + let edges = |turn: f64| { + let pm = render(&turned_text_page(turn), &mut [], 300.0, &PageInfo::default()).unwrap(); + let dark = (0..pm.height()).flat_map(|y| (0..pm.width()).map(move |x| (x, y))).map(|(x, y)| 255 - u32::from(rgb(&pm, x, y).0)); + dark.fold((0u32, 0u32), |(solid, part), d| (solid + u32::from(d > 204), part + u32::from(d > 51 && d <= 204))) + }; + let (solid, part) = edges(0.0); + let upright = f64::from(part) / f64::from(solid); + for turn in [90.0, -90.0, 180.0] { + let (s, p) = edges(turn); + let turned = f64::from(p) / f64::from(s); + assert!(turned < upright * 1.2, "{turn}°: {p} part-covered to {s} solid, upright {part} to {solid}"); + assert!(s.abs_diff(solid) * 10 < solid, "{turn}°: as much ink, {s} solid to {solid}"); + } +} + +/// A turned text's picture covers the lines it draws, not its whole box: a short line in a +/// large box takes a small picture, where its alignment puts the line (#1763). +#[test] +fn a_turned_texts_picture_covers_its_lines() { + let r = Rect::from_xywh(0.0, 0.0, 2000.0, 1000.0).unwrap(); + let plain = TextStyle { face: text::Face::default(), align: TextAlign::Left, spacing: 0.0, valign: TextVAlign::Top, line_spacing: 1.0 }; + let px = 14.0 * 1.33; + let area = |align| text_area(r, "Fonte: IBGE", 14.0, TextStyle { align, ..plain }, 1.0).unwrap(); + let left = area(TextAlign::Left); + assert!(left.width() < 200.0 && left.height() < 4.0 * px, "{left:?}"); + assert!(left.left() < 0.0 && left.top() < 0.0, "a line's height of room: {left:?}"); + let right = area(TextAlign::Right); + assert!((right.right() - (2000.0 + px)).abs() < 1.0 && (right.width() - left.width()).abs() < 1.0, "{right:?}"); + let centre = area(TextAlign::Center); + assert!(((centre.left() + centre.right()) / 2.0 - 1000.0).abs() < 1.0, "{centre:?}"); + // Two lines, twice the pitch; nothing when there is no line. + let two = text_area( + r, + "Fonte: IBGE +Elaboração: RustGIS", + 14.0, + plain, + 1.0, + ) + .unwrap(); + assert!((two.height() - left.height() - px * 1.25).abs() < 0.01); + assert!(text_area(r, "", 14.0, plain, 1.0).is_none()); +} + +/// A turned box past the page's budget is still drawn turned, at a lower resolution, not +/// left out or left upright (#1763). +#[test] +fn a_huge_turned_box_is_drawn_at_a_lower_resolution() { + let mut pm = Canvas::new(200, 200).unwrap(); + // 20,000 px long (past MAX_SIDE), 20 high, about the canvas's centre. + let r = Rect::from_xywh(-9_900.0, 90.0, 20_000.0, 20.0).unwrap(); + let mut scale = 0.0; + let area = Rect::from_xywh(0.0, 0.0, r.width(), r.height()).unwrap(); + draw_turned_box(&mut pm, r, 90.0, area, |c, inner, k| { + scale = k; + c.fill_rect(inner, &paint(Rgba::rgb(0, 0, 0), 1.0), Transform::identity(), None); + }); + assert!(scale < 1.0 && scale > 0.0, "{scale}"); + // Turned upright: a bar down the middle, top to bottom; nothing beside it. + let dark = |x: u32, y: u32| pm.pixmap().pixel(x, y).is_some_and(|p| p.alpha() > 128); + assert!(dark(100, 2) && dark(100, 197) && dark(95, 100), "the bar runs down the page"); + assert!(!dark(70, 100) && !dark(130, 100)); +} + +/// A turned text is kept as turned glyphs, which draw what its picture shows (#1763). +#[test] +fn a_turned_text_is_kept_turned_as_vectors() { + use crate::vector::Item; + let layout = turned_text_page(90.0); + let info = PageInfo::default(); + let png = render(&layout, &mut [], 96.0, &info).unwrap(); + let (drawing, _) = render_drawing(&layout, &mut [], 96.0, &info).unwrap(); + let (_, _, items) = drawing.finish(); + let items = crate::vector::without_layers(items); + let text: String = items + .iter() + .filter_map(|i| if let Item::Glyphs(r) = i { Some(r) } else { None }) + .flat_map(|r| r.glyphs.iter().map(|g| g.ch)) + .collect(); + assert_eq!(text, "Fonte: IBGE, 2022", "kept as text, not a picture"); + let mut replayed = Pixmap::new(png.width(), png.height()).unwrap(); + replayed.fill(tiny_skia::Color::WHITE); + crate::vector::replay(&items, &mut replayed, Transform::identity()); + let (pl, pt, pr, pb) = ink_bounds(&png); + let (vl, vt, vr, vb) = ink_bounds(&replayed); + assert!( + pl.abs_diff(vl) <= 2 && pt.abs_diff(vt) <= 2 && pr.abs_diff(vr) <= 2 && pb.abs_diff(vb) <= 2, + "{pl},{pt},{pr},{pb} vs {vl},{vt},{vr},{vb}" + ); +} + +/// Text elements take italic, alignment and letter spacing (#213, point c); plain, they draw +/// as before. +#[test] +fn text_takes_italic_alignment_and_letter_spacing() { + let plain = TextStyle { face: text::Face::default(), align: TextAlign::Left, spacing: 0.0, valign: TextVAlign::Top, line_spacing: 1.0 }; + let base = styled_line(plain); + let (l, r, ..) = text_ink(&base); + assert!(l < 4, "left-aligned starts at the left: {l}"); + // Plain is what the old upright, left-aligned drawing gave. + let mut old = Pixmap::new(400, 60).unwrap(); + old.fill(tiny_skia::Color::WHITE); + let px = 20.0 * 1.33; + crate::canvas::with_canvas(&mut old, |c| { + text::text_at(c, "Oceano Atlântico", 0.0, px * 0.6, px, Rgba::rgb(0, 0, 0), false, text::Align::Left, false) + }); + assert_eq!(text_ink(&old).0.abs_diff(l), 0); + assert_eq!(text_ink(&old).1.abs_diff(r), 0); + // Right and centre: the same width, moved. + let (rl, rr, ..) = text_ink(&styled_line(TextStyle { align: TextAlign::Right, ..plain })); + assert!((397..=399).contains(&rr) && (rr - rl).abs_diff(r - l) <= 1, "right-aligned ends at the right: {rl}..{rr}"); + let (cl, cr, ..) = text_ink(&styled_line(TextStyle { align: TextAlign::Center, ..plain })); + assert!(cl.abs_diff(400 - cr) <= 2, "centred: {cl}..{cr}"); + // Spacing: 15 gaps of 3 pt widen the line by about 15 × 3 × 1.33 px. + let (sl, sr, ..) = text_ink(&styled_line(TextStyle { spacing: 3.0, ..plain })); + let grown = (sr - sl) as f32 - (r - l) as f32; + assert!((grown - 15.0 * 3.0 * 1.33).abs() < 3.0, "{grown}"); + // Italic: a straight stem (an `l`) leans right, its top about tan 12° of its height + // right of its foot; upright, it stands straight. + let stem = |italic: bool| { + let mut pm = Pixmap::new(120, 120).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(40.0, 0.0, 80.0, 120.0).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| { + text_block(c, r, "l", 60.0, Rgba::rgb(0, 0, 0), TextStyle { face: text::Face { italic, ..plain.face }, ..plain }, 1.0) + }); + let (.., top, bottom) = text_ink(&pm); + (top as i32 - bottom as i32, text_height(&pm)) + }; + let ((upright, _), (lean, height)) = (stem(false), stem(true)); + assert!(upright.abs() <= 1, "upright stem: {upright}"); + assert!((lean as f32 - 0.2126 * height as f32).abs() <= 3.0, "lean {lean} over {height} px"); + // Right-aligned, slanted or tightened past the letters' width, the ink stays in the box. + for style in [ + TextStyle { align: TextAlign::Right, face: text::Face { italic: true, ..plain.face }, ..plain }, + TextStyle { align: TextAlign::Right, spacing: -5.0, ..plain }, + ] { + let mut pm = Pixmap::new(400, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 0.0, 300.0, 60.0).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| text_block(c, r, "Oceano Atlântico", 20.0, Rgba::rgb(0, 0, 0), style, 1.0)); + let (l, r, ..) = text_ink(&pm); + assert!((296..=300).contains(&r) && l < r, "inked {l}..{r} in a 300 px box"); + } + // 2 pt letters at -5 pt run backwards: still drawn, inside the box. + let mut pm = Pixmap::new(400, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 0.0, 300.0, 60.0).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| { + text_block(c, r, "MMMM", 2.0, Rgba::rgb(0, 0, 0), TextStyle { align: TextAlign::Right, spacing: -5.0, ..plain }, 4.0) + }); + let (l, r, ..) = text_ink(&pm); + assert!(r <= 300 && l < r, "inked {l}..{r}"); +} + +/// A 100 × 100 mm page with `text` at 12 pt in black in (10, 10, 40, `h`) mm, its kind changed +/// by `f`. +fn block_page(text: &str, h: f64, f: &dyn Fn(&mut ElementKind)) -> Layout { + let mut l = Layout::new("L", 100.0, 100.0); + let mut kind = ElementKind::text(text, 12.0, Rgba::rgb(0, 0, 0), false); + f(&mut kind); + l.add("Block", (10.0, 10.0, 40.0, h), kind); + l +} + +/// Sets a text's block alignment, line spacing and case. +fn set_block(k: &mut ElementKind, v: TextVAlign, ls: f64, c: TextCase) { + if let ElementKind::Text { valign, line_spacing, case, .. } = k { + (*valign, *line_spacing, *case) = (v, ls, c); + } +} + +/// The rows with a dark pixel, from the top. +fn ink_rows(pm: &Pixmap) -> Vec { + (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| rgb(pm, x, y).0 < 128)).collect() +} + +/// How many separate runs of columns with a dark pixel there are, from the left. +fn ink_column_runs(pm: &Pixmap) -> usize { + let inked: Vec = (0..pm.width()).map(|x| (0..pm.height()).any(|y| rgb(pm, x, y).0 < 128)).collect(); + inked.windows(2).filter(|w| !w[0] && w[1]).count() + usize::from(inked.first() == Some(&true)) +} + +/// A text's block sits at the top of its box, as texts always have, in its middle, or with its +/// last line on its bottom edge; the block itself is the same, moved. +#[test] +fn a_text_block_sits_at_the_top_middle_or_bottom_of_its_box() { + let draw = |v: TextVAlign| { + render(&block_page("one\ntwo\nthree", 60.0, &|k| set_block(k, v, 1.0, TextCase::None)), &mut [], 96.0, &PageInfo::default()) + .unwrap() + }; + let (top, mid, bottom) = (ink_rows(&draw(TextVAlign::Top)), ink_rows(&draw(TextVAlign::Middle)), ink_rows(&draw(TextVAlign::Bottom))); + let plain = ink_rows(&render(&block_page("one\ntwo\nthree", 60.0, &|_| {}), &mut [], 96.0, &PageInfo::default()).unwrap()); + assert_eq!(top, plain, "top is today's drawing"); + let span = |r: &[u32]| r[r.len() - 1] - r[0]; + // Moved by part of a pixel, its edge rows may shade past the threshold one row more or less. + for moved in [&mid, &bottom] { + assert!(span(moved).abs_diff(span(&top)) <= 1, "the same block, moved: {} and {}", span(moved), span(&top)); + } + let (box_top, box_bottom) = ((10.0 * 96.0 / 25.4) as u32, (70.0 * 96.0 / 25.4) as u32); + assert!(box_bottom - bottom[bottom.len() - 1] <= 12, "bottom: last ink row {} of the box's {box_bottom}", bottom[bottom.len() - 1]); + let (above, below) = (mid[0] - box_top, box_bottom - mid[mid.len() - 1]); + assert!(above.abs_diff(below) <= 8, "middle: {above} above, {below} below"); +} + +/// Line spacing multiplies the distance between lines: twice as far apart at 2, half at 0.5. +#[test] +fn line_spacing_spreads_the_lines_by_its_multiple() { + let span = |ls: f64| { + let pm = render( + &block_page("one\ntwo\nthree", 60.0, &|k| set_block(k, TextVAlign::Top, ls, TextCase::None)), + &mut [], + 96.0, + &PageInfo::default(), + ) + .unwrap(); + let r = ink_rows(&pm); + (r[r.len() - 1] - r[0]) as f64 + }; + // The usual pitch in pixels at 96 dpi, a layout point a pixel there. + let pitch = 12.0 * 1.33 * 1.25; + assert!(((span(2.0) - span(1.0)) - 2.0 * pitch).abs() <= 2.0, "{} {}", span(2.0), span(1.0)); + assert!(((span(1.0) - span(0.5)) - pitch).abs() <= 2.0, "{} {}", span(1.0), span(0.5)); +} + +/// A block taller than its box is drawn from the top whatever its alignment: its first lines +/// are kept, the same lines left out and said, and none is drawn above the box. +#[test] +fn a_block_taller_than_its_box_keeps_its_first_lines_whatever_its_valign() { + let info = PageInfo::default(); + let page = |v| block_page("one\ntwo\nthree\nfour\nfive", 7.0, &|k| set_block(k, v, 1.0, TextCase::None)); + let top = page(TextVAlign::Top); + let loss = text_losses(&top, &[], 96.0, &info); + assert_eq!(loss.iter().map(|l| l.left_out).collect::>(), [3]); + for v in [TextVAlign::Middle, TextVAlign::Bottom] { + let l = page(v); + assert_eq!(render(&l, &mut [], 96.0, &info).unwrap().data(), render(&top, &mut [], 96.0, &info).unwrap().data(), "{v:?}"); + assert_eq!(text_losses(&l, &[], 96.0, &info), loss, "{v:?}"); + assert_eq!(lines_left_out_notice(&text_losses(&l, &[], 96.0, &info)[0]), lines_left_out_notice(&loss[0])); + } +} + +/// A text of more lines than a text draws is cut at them, so it is drawn from the top whatever +/// its alignment, though the lines kept would fit its box; one of exactly that many, all +/// drawn, is still aligned. +#[test] +fn a_text_cut_at_the_most_lines_it_draws_starts_at_the_top() { + let info = PageInfo::default(); + // 2 pt lines are 0.88 mm apart: 200 of them fill 176 mm of a 200 mm box. + let page = |lines: usize, v| { + let text = (0..lines).map(|i| format!("line {i}")).collect::>().join( + " +", + ); + let mut l = Layout::new("L", 100.0, 300.0); + let mut kind = ElementKind::text(&text, 2.0, Rgba::rgb(0, 0, 0), false); + set_block(&mut kind, v, 1.0, TextCase::None); + l.add("Block", (10.0, 10.0, 40.0, 200.0), kind); + l + }; + let drawn = |l: &Layout| render(l, &mut [], 96.0, &info).unwrap(); + let top = page(300, TextVAlign::Top); + for v in [TextVAlign::Middle, TextVAlign::Bottom] { + let l = page(300, v); + assert_eq!(drawn(&l).data(), drawn(&top).data(), "{v:?}"); + assert_eq!(text_losses(&l, &[], 96.0, &info), text_losses(&top, &[], 96.0, &info), "{v:?}"); + let svg = |l: &Layout| crate::svg::layout_svg(l, &mut [], 96.0, &info).unwrap().0; + assert_eq!(svg(&l), svg(&top), "{v:?}"); + assert_ne!(drawn(&page(200, v)).data(), drawn(&page(200, TextVAlign::Top)).data(), "{v:?}: all drawn, aligned"); + } + let text = |n: usize| { + vec!["x"; n].join( + " +", + ) + }; + assert_eq!(text_shift(TextVAlign::Bottom, 5000.0, 10.0, &text(201), 1.0), 0.0); + assert_eq!(text_shift(TextVAlign::Bottom, 5000.0, 10.0, &text(200), 1.0), block_shift(TextVAlign::Bottom, 5000.0, 10.0, 200, 1.0)); + assert!(text_shift(TextVAlign::Bottom, 5000.0, 10.0, &text(200), 1.0) > 0.0); +} + +/// The cut-off check steps by the spaced pitch, as the page draws: a wider spacing leaves lines +/// out of a box that held them, a tighter one draws lines a box cut. +#[test] +fn line_spacing_changes_the_lines_left_out() { + let info = PageInfo::default(); + let left_out = |h: f64, ls: f64| { + let l = block_page("one\ntwo\nthree\nfour\nfive", h, &|k| set_block(k, TextVAlign::Top, ls, TextCase::None)); + text_losses(&l, &[], 96.0, &info).first().map_or(0, |l| l.left_out) + }; + assert_eq!((left_out(25.0, 1.0), left_out(25.0, 2.0)), (0, 2)); + assert_eq!((left_out(12.0, 1.0), left_out(12.0, 0.5)), (2, 0)); +} + +/// Case applies once the tokens are filled in, and before the wrap, which breaks the wider +/// words. +#[test] +fn case_applies_after_the_tokens_and_before_the_wrap() { + let info = PageInfo { page: 2, pages: 3, page_name: String::new() }; + let draw = |t: &str, c| render(&block_page(t, 20.0, &|k| set_block(k, TextVAlign::Top, 1.0, c)), &mut [], 96.0, &info).unwrap(); + assert_eq!(draw("Page {page} of {pages}", TextCase::Upper).data(), draw("PAGE 2 OF 3", TextCase::None).data()); + assert_eq!(draw("PAGE {page} OF {pages}", TextCase::Lower).data(), draw("page 2 of 3", TextCase::None).data()); + let style = text_style(false, false, rustgis_map::layout::FontFamily::Sans, None, TextAlign::Left, 0.0); + let s = "boundaries simplified for print from the census".to_string(); + let lines = |c| drawn_text(s.clone(), c, true, 40.0, 12.0, style).lines().count(); + assert!(lines(TextCase::Upper) > lines(TextCase::Lower), "{} {}", lines(TextCase::Upper), lines(TextCase::Lower)); + assert_eq!(drawn_text(s.clone(), TextCase::None, false, 40.0, 12.0, style), s, "unwrapped and as typed: unchanged"); +} + +/// A turned text's picture covers its lines where its block alignment and spacing put them. +#[test] +fn a_turned_bottom_aligned_text_is_drawn_whole() { + let info = PageInfo::default(); + let ink = |v, ls| { + let pm = render( + &block_page("one\ntwo\nthree", 60.0, &|k| { + set_block(k, v, ls, TextCase::None); + if let ElementKind::Text { rotation, .. } = k { + *rotation = 90.0; + } + }), + &mut [], + 96.0, + &info, + ) + .unwrap(); + (ink_bounds(&pm), ink_column_runs(&pm)) + }; + // Spaced alike, so only the alignment differs. Turned a quarter clockwise, the box's + // down runs leftwards across the page: its lines are runs of inked columns. + let ((tl, tt, tr, tb), top_runs) = ink(TextVAlign::Top, 1.5); + let ((bl, bt, br, bb), bottom_runs) = ink(TextVAlign::Bottom, 1.5); + assert_eq!((top_runs, bottom_runs), (3, 3), "a run of columns a line, all three drawn"); + assert!((tr - tl).abs_diff(br - bl) <= 2, "the same block across: {tl}..{tr} and {bl}..{br}"); + assert!((tb - tt).abs_diff(bb - bt) <= 2, "the same lines along: {tt}..{tb} and {bt}..{bb}"); + // Moved left by the room the block leaves: the box's 60 mm less three lines at 1.5, + // 12 pt × 1.33 × 1.25 × (1 + 2 × 1.5) = 79.8 px, of 226.8 px: 147.0 px. + let free = 60.0 * 96.0 / 25.4 - 12.0 * 1.33 * 1.25 * (1.0 + 2.0 * 1.5); + for (t, b) in [(tl, bl), (tr, br)] { + assert!((f64::from(t) - f64::from(b) - free).abs() <= 2.0, "moved {} px of {free:.1}", f64::from(t) - f64::from(b)); + } +} + +/// Where a text's block and case put its ink decides whether it runs off the page: a box +/// hanging past the page's bottom, its one line at the box's top, middle or bottom; and a line +/// near the page's right edge in upper case, its letters wider. +#[test] +fn a_text_block_and_case_are_said_off_the_page_where_they_put_the_ink() { + let info = PageInfo::default(); + // The 100 mm page is 378.0 px tall at 96 dpi; the box (10, 80, 40, 30) mm runs from 302.4 + // to 415.7 px. Its one line of 12 pt (15.96 px a line, a pitch of 19.95) has its middle + // 9.6 px under where the block starts, the block 19.95 px tall in a box of 113.4: at the + // top at 312.0 px, in the middle 46.7 px lower at 358.7, at the bottom 93.4 px lower at + // 405.4, below the page's 378.0 whatever the font's letters (some 8 px each way). + let hanging = |v| { + let mut l = Layout::new("L", 100.0, 100.0); + let mut kind = ElementKind::text("one", 12.0, Rgba::rgb(0, 0, 0), false); + set_block(&mut kind, v, 1.0, TextCase::None); + l.add("Hanging", (10.0, 80.0, 40.0, 30.0), kind); + text_losses(&l, &[], 96.0, &info) + }; + assert_eq!(hanging(TextVAlign::Top), [], "at the top, on the page"); + assert_eq!(hanging(TextVAlign::Middle), [], "in the middle, still on the page"); + let bottom = hanging(TextVAlign::Bottom); + assert!(bottom.len() == 1 && bottom[0].off_page && bottom[0].left_out == 0, "{bottom:?}"); + assert!(off_page_notice(&bottom[0]).is_some()); + // The page is 378.0 px wide; the box starts at 83 mm, 313.7 px, 64.3 px from its edge. + // Ten letters `lflflflflf` of 12 pt (an em of 15.96 px) take some 0.25 em each as typed, + // about 40 px, and some 0.58 em in upper case (`LFLFLFLFLF`), about 93 px: on the page as + // typed with room for 1.6 times as wide letters, past its edge in upper case at 0.69 times + // as wide ones. + let near_edge = |c| { + let mut l = Layout::new("L", 100.0, 100.0); + let mut kind = ElementKind::text("lflflflflf", 12.0, Rgba::rgb(0, 0, 0), false); + set_block(&mut kind, TextVAlign::Top, 1.0, c); + l.add("Edge", (83.0, 50.0, 10.0, 10.0), kind); + text_losses(&l, &[], 96.0, &info) + }; + assert_eq!(near_edge(TextCase::None), [], "as typed, on the page"); + let upper = near_edge(TextCase::Upper); + assert!(upper.len() == 1 && upper[0].off_page && upper[0].left_out == 0, "{upper:?}"); + assert!(off_page_notice(&upper[0]).is_some()); +} + +/// A block alignment or line spacing that reaches the page unrepaired is clamped where it is +/// used: an unknown alignment draws at the top, a spacing not a finite number (an infinity too) +/// at the usual one, one out of range at the nearer limit; none moves a line to a place not a +/// number. +#[test] +fn hostile_text_block_settings_draw_clamped() { + let style = text_style(false, false, rustgis_map::layout::FontFamily::Sans, None, TextAlign::Left, 0.0); + let kept = |v, ls: f64| { + let s = style.with_block(v, ls); + (s.valign, s.line_spacing) + }; + assert_eq!(kept(TextVAlign::Invalid, f64::NAN), (TextVAlign::Top, 1.0)); + assert_eq!(kept(TextVAlign::Bottom, 9.0), (TextVAlign::Bottom, 3.0)); + assert_eq!(kept(TextVAlign::Middle, f64::INFINITY), (TextVAlign::Middle, 1.0)); + assert_eq!(kept(TextVAlign::Middle, f64::NEG_INFINITY), (TextVAlign::Middle, 1.0)); + assert_eq!(kept(TextVAlign::Top, 0.1), (TextVAlign::Top, 0.5)); + for (v, box_h, px, ls) in [ + (TextVAlign::Bottom, f64::NAN, 10.0, 1.0), + (TextVAlign::Middle, 100.0, f64::NAN, 1.0), + (TextVAlign::Bottom, 100.0, 10.0, f64::NAN), + (TextVAlign::Bottom, f64::INFINITY, 10.0, 1.0), + (TextVAlign::Invalid, 100.0, 10.0, 1.0), + ] { + assert_eq!(block_shift(v, box_h, px, 3, ls), 0.0, "{v:?} {box_h} {px} {ls}"); + } + assert_eq!(block_shift(TextVAlign::Bottom, 100.0, 10.0, 0, 1.0), 0.0, "no line"); + let info = PageInfo::default(); + let draw = |v, ls| render(&block_page("one\ntwo", 60.0, &|k| set_block(k, v, ls, TextCase::Invalid)), &mut [], 96.0, &info).unwrap(); + assert_eq!(draw(TextVAlign::Invalid, f64::NAN).data(), draw(TextVAlign::Top, 1.0).data()); + assert_eq!(draw(TextVAlign::Bottom, 1e300).data(), draw(TextVAlign::Bottom, 3.0).data()); + let l = block_page("one\ntwo", 60.0, &|k| set_block(k, TextVAlign::Bottom, f64::NAN, TextCase::Invalid)); + assert!(text_losses(&l, &[], 96.0, &info).is_empty()); +} + +/// The extent indicator is drawn in its own colour and width (#213): red and 2 pt until set. +#[test] +fn extent_indicators_take_their_colour_and_width() { + use rustgis_map::layout::{INDICATOR_COLOR, INDICATOR_WIDTH}; + let blue = Rgba::rgb(0x1F, 0x4E, 0x9A); + let default = indicator_page(INDICATOR_COLOR, INDICATOR_WIDTH); + assert!(inset_pixels(&default, INDICATOR_COLOR) > 0, "red by default"); + let thin = indicator_page(blue, 1.0); + let thick = indicator_page(blue, 6.0); + assert_eq!(inset_pixels(&thin, INDICATOR_COLOR), 0, "no red once restyled"); + let (t, w) = (inset_pixels(&thin, blue), inset_pixels(&thick, blue)); + assert!(t > 0 && w > 3 * t, "a wider outline covers more: {t} at 1 pt, {w} at 6 pt"); +} + +/// A map frame's border (#2557): dark grey and 0.8 pt by default, in its own colour and width +/// once set, none at a width of 0, and along the frame's shape, a round frame's leaving the +/// corners of its box clear. +#[test] +fn a_map_frame_border_takes_its_colour_and_width_or_none() { + use rustgis_map::layout::{FRAME_BORDER_COLOR, FRAME_BORDER_WIDTH, INDICATOR_COLOR, INDICATOR_WIDTH}; + let page = |shape: FrameShape, border_color: Rgba, border_width: f64| { + let mut map = Map::new("m"); + (map.basemap, map.graticule) = (rustgis_map::Basemap::Blank, false); + let mut l = Layout::new("Layout", 100.0, 100.0); + l.add( + "Frame", + (20.0, 20.0, 60.0, 60.0), + ElementKind::MapFrame { + map: "m".into(), + center: Coord::new(0.0, 0.0), + scale: 1e7, + shape, + grid: None, + extent_of: None, + extent_color: INDICATOR_COLOR, + extent_width: INDICATOR_WIDTH, + border_color, + border_width, + bearing: 0.0, + pitch: 0.0, + }, + ); + render(&l, &mut [map], 96.0, &PageInfo::default()).unwrap() + }; + // Pixels of a tone (a line this thin is blended with the white page), over the whole page + // or in the frame box's top-left corner. + let count = |pm: &Pixmap, tone: fn(u8, u8, u8) -> bool, corner: bool| { + let edge = (20.0 * PT_PER_MM + 6.0) as u32; + let (w, h) = if corner { (edge, edge) } else { (pm.width(), pm.height()) }; + (0..h) + .flat_map(|y| (0..w).map(move |x| (x, y))) + .filter(|&(x, y)| { + let (r, g, b) = rgb(pm, x, y); + tone(r, g, b) + }) + .count() + }; + let grey: fn(u8, u8, u8) -> bool = |r, g, b| r.max(g).max(b) - r.min(g).min(b) < 12 && r < 240; + let bluish: fn(u8, u8, u8) -> bool = |r, _, b| i32::from(b) - i32::from(r) > 30; + let inked: fn(u8, u8, u8) -> bool = |r, g, b| r.min(g).min(b) < 240; + let blue = Rgba::rgb(0x1F, 0x4E, 0x9A); + let default = page(FrameShape::Rectangle, FRAME_BORDER_COLOR, FRAME_BORDER_WIDTH); + assert!(count(&default, grey, false) > 0, "dark grey by default"); + assert_eq!(count(&default, bluish, false), 0); + let thin = page(FrameShape::Rectangle, blue, 1.0); + let thick = page(FrameShape::Rectangle, blue, 6.0); + assert_eq!(count(&thin, grey, false), 0, "no grey once recoloured"); + let (t, w) = (count(&thin, bluish, false), count(&thick, bluish, false)); + assert!(t > 0 && w > 3 * t, "a wider border covers more: {t} at 1 pt, {w} at 6 pt"); + let none = page(FrameShape::Rectangle, blue, 0.0); + assert_eq!(count(&none, inked, false), 0, "no border at 0"); + let clear = page(FrameShape::Rectangle, Rgba::new(0x1F, 0x4E, 0x9A, 0), 3.0); + assert_eq!(count(&clear, inked, false), 0, "none in a clear colour"); + let round = page(FrameShape::Circle, blue, 3.0); + assert!(count(&round, bluish, false) > 0, "a round frame has its border too"); + assert_eq!(count(&round, bluish, true), 0, "along the circle, not the box's corner"); + assert!(count(&thick, bluish, true) > 0, "a rectangle's border reaches its corner"); +} + +/// On a globe, the extent indicator is drawn where the globe shows the area, also away from +/// the disc's centre (#2348): through the flat camera, Svalbard 18° north of the centre came out +/// half as far again up, nearly 5 mm off on a 50 mm locator. +#[test] +fn an_extent_indicator_on_a_globe_lands_on_the_area() { + use rustgis_map::layout::{INDICATOR_COLOR, INDICATOR_WIDTH, frame_camera}; + let (area, at, scale) = (Coord::new(20.0, 78.0), Coord::new(20.0, 60.0), 2e8); + let mut globe = Map::new("g"); + globe.set_projection(rustgis_map::Projection::Globe); + let maps = || [Map::new("m"), globe.clone()]; + let frame = |map: &str, center, scale, extent_of| ElementKind::MapFrame { + map: map.into(), + center, + scale, + shape: FrameShape::Rectangle, + grid: None, + extent_of, + extent_color: INDICATOR_COLOR, + extent_width: INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }; + let mut l = Layout::new("Layout", 100.0, 100.0); + let main = l.add("Main", (60.0, 60.0, 30.0, 30.0), frame("m", area, 2e7, None)); + l.add("Locator", (5.0, 5.0, 50.0, 50.0), frame("g", at, scale, Some(main))); + let pm = render(&l, &mut maps(), 96.0, &PageInfo::default()).unwrap(); + // Where the globe draws the area, in pixels on the page. + let side = 50.0 * PT_PER_MM; + let g = rustgis_map::globe::Globe::new(&frame_camera(&globe, at, scale, 0.0, 0.0), side, side); + let (x, y) = g.forward(area).unwrap(); + // At 96 dpi a layout point is a pixel. + let expected = (5.0 * PT_PER_MM + x, 5.0 * PT_PER_MM + y); + // The red pixels' middle, inside the locator. + let px_mm = PT_PER_MM; + let red: Vec<(f64, f64)> = ((5.0 * px_mm) as u32..(55.0 * px_mm) as u32) + .flat_map(|y| ((5.0 * px_mm) as u32..(55.0 * px_mm) as u32).map(move |x| (x, y))) + .filter(|&(x, y)| { + let (r, g, b) = rgb(&pm, x, y); + r > 180 && g < 90 && b < 90 + }) + .map(|(x, y)| (f64::from(x), f64::from(y))) + .collect(); + assert!(!red.is_empty(), "no extent indicator on the globe"); + let n = red.len() as f64; + let mid = (red.iter().map(|p| p.0).sum::() / n, red.iter().map(|p| p.1).sum::() / n); + let off = ((mid.0 - expected.0).powi(2) + (mid.1 - expected.1).powi(2)).sqrt() / px_mm; + assert!(off < 1.5, "the indicator's middle {mid:?} is {off:.1} mm from the area at {expected:?}"); +} + +/// A frame on the globe is outlined by what it shows of the globe (#2348): zoomed in on Iceland, +/// around Iceland on a globe locator; seen whole, with no edge on the disc, not at all (through +/// the flat camera its edges were read as a flat world, a line drawn across the locator). +#[test] +fn a_frame_on_the_globe_is_outlined_by_what_it_shows() { + use rustgis_map::layout::{INDICATOR_COLOR, INDICATOR_WIDTH, frame_camera}; + let mut globe = Map::new("g"); + globe.set_projection(rustgis_map::Projection::Globe); + let frame = |center, scale, extent_of| ElementKind::MapFrame { + map: "g".into(), + center, + scale, + shape: FrameShape::Rectangle, + grid: None, + extent_of, + extent_color: INDICATOR_COLOR, + extent_width: INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }; + let (at, scale) = (Coord::new(-20.0, 55.0), 2e8); + // The red pixels inside the locator (5–55 mm), with the source frame on `center` at 1:`main`. + let red = |center: Coord, main: f64| { + let mut l = Layout::new("Layout", 100.0, 100.0); + // 40 mm across: near the equator, wider than the smallest globe the camera draws there. + let source = l.add("Main", (58.0, 58.0, 40.0, 40.0), frame(center, main, None)); + l.add("Locator", (5.0, 5.0, 50.0, 50.0), frame(at, scale, Some(source))); + let pm = render(&l, &mut [globe.clone()], 96.0, &PageInfo::default()).unwrap(); + let k = PT_PER_MM; + ((5.0 * k) as u32..(55.0 * k) as u32) + .flat_map(|y| ((5.0 * k) as u32..(55.0 * k) as u32).map(move |x| (x, y))) + .filter(|&(x, y)| { + let (r, g, b) = rgb(&pm, x, y); + r > 180 && g < 90 && b < 90 + }) + .map(|(x, y)| (f64::from(x), f64::from(y))) + .collect::>() + }; + let iceland = red(Coord::new(-19.0, 65.0), 2e7); + assert!(!iceland.is_empty(), "no outline of the zoomed-in frame"); + let n = iceland.len() as f64; + let mid = (iceland.iter().map(|p| p.0).sum::() / n, iceland.iter().map(|p| p.1).sum::() / n); + let side = 50.0 * PT_PER_MM; + let g = rustgis_map::globe::Globe::new(&frame_camera(&globe, at, scale, 0.0, 0.0), side, side); + let (x, y) = g.forward(Coord::new(-19.0, 65.0)).unwrap(); + let expected = (5.0 * PT_PER_MM + x, 5.0 * PT_PER_MM + y); + let off = ((mid.0 - expected.0).powi(2) + (mid.1 - expected.1).powi(2)).sqrt() / PT_PER_MM; + assert!(off < 1.5, "the outline's middle {mid:?} is {off:.1} mm from Iceland at {expected:?}"); + let whole = red(Coord::new(-20.0, 10.0), 4e8); + assert!(whole.is_empty(), "the globe seen whole outlined by {} red pixels", whole.len()); +} + +/// A frame on the globe whose sides run off the disc is outlined by its top and bottom edges +/// only, broken where they leave the disc, not joined by a line across the globe (#2348), and +/// running up to the disc's rim (#2369). +#[test] +fn a_frame_partly_off_the_globe_is_outlined_without_a_chord() { + use rustgis_map::layout::{INDICATOR_COLOR, INDICATOR_WIDTH, frame_camera}; + let mut globe = Map::new("g"); + globe.set_projection(rustgis_map::Projection::Globe); + let frame = |center, scale, extent_of| ElementKind::MapFrame { + map: "g".into(), + center, + scale, + shape: FrameShape::Rectangle, + grid: None, + extent_of, + extent_color: INDICATOR_COLOR, + extent_width: INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }; + let center = Coord::new(-20.0, 0.0); + // The source frame, 40 × 20 mm: a scale whose disc is taller than the frame, its sides in + // the sky beside the disc, and its corners too. + let (sw, sh) = (40.0, 20.0); + let disc = |scale: f64| { + let cam = frame_camera(&globe, center, scale, 0.0, 0.0); + rustgis_map::globe::Globe::new(&cam, sw * PT_PER_MM, sh * PT_PER_MM).disc_radius() / PT_PER_MM + }; + let source_scale = (1..400).map(|i| f64::from(i) * 1e6).find(|&s| disc(s) < 0.5 * sw - 3.0).unwrap(); + assert!(disc(source_scale) > 0.5 * sh + 2.0, "a disc {:.1} mm across", 2.0 * disc(source_scale)); + let (at, scale) = (center, 2.0 * source_scale); + let mut l = Layout::new("Layout", 100.0, 100.0); + let source = l.add("Main", (55.0, 70.0, sw, sh), frame(center, source_scale, None)); + l.add("Locator", (5.0, 5.0, 50.0, 50.0), frame(at, scale, Some(source))); + let pm = render(&l, &mut [globe.clone()], 96.0, &PageInfo::default()).unwrap(); + let red = |x: u32, y: u32| { + let (r, g, b) = rgb(&pm, x, y); + r > 180 && g < 90 && b < 90 + }; + let k = PT_PER_MM; + let (x0, x1) = ((5.0 * k) as u32, (55.0 * k) as u32); + let inked = (x0..x1).flat_map(|y| (x0..x1).map(move |x| (x, y))).filter(|&(x, y)| red(x, y)).count(); + assert!(inked > 0, "no outline of the frame"); + // The row through the source frame's centre, between its top and bottom edges: crossed only + // by a chord. + let side = 50.0 * k; + let g = rustgis_map::globe::Globe::new(&frame_camera(&globe, at, scale, 0.0, 0.0), side, side); + let (_, cy) = g.forward(center).unwrap(); + let row = (5.0 * k + cy).round() as u32; + let crossed: Vec = (row - 2..=row + 2).flat_map(|y| (x0..x1).filter(move |&x| red(x, y))).collect(); + assert!(crossed.is_empty(), "the outline crosses the middle of the globe at {crossed:?}"); + // The top and bottom edges are outlined up to the rim, where they leave the disc, not up + // to the last of their samples on it (#2369). + let s = rustgis_map::globe::Globe::new(&frame_camera(&globe, center, source_scale, 0.0, 0.0), sw * k, sh * k); + let (r, (sx0, sy0)) = (s.disc_radius(), s.forward(center).unwrap()); + let half = (r * r - sy0 * sy0).sqrt() - 1e-3; + for (sx, sy) in [(sx0 - half, 0.0), (sx0 + half, 0.0), (sx0 - half, sh * k), (sx0 + half, sh * k)] { + let on_rim = s.inverse(sx, sy).expect("a point just inside the rim is on the globe"); + let (x, y) = g.forward(on_rim).expect("the rim seen on the locator"); + let (x, y) = (5.0 * k + x, 5.0 * k + y); + let gap = (x0..x1) + .flat_map(|py| (x0..x1).map(move |px| (px, py))) + .filter(|&(px, py)| red(px, py)) + .map(|(px, py)| (f64::from(px) - x).hypot(f64::from(py) - y)) + .fold(f64::INFINITY, f64::min) + / k; + assert!(gap < 0.3, "the outline ends {gap:.2} mm short of the rim at ({sx:.0}, {sy:.0}) on the frame"); + } +} + +/// A frame on the globe across the antimeridian, outlined on a flat frame, stays one small box +/// near the flat frame's centre (#2348): its edge's longitudes kept continuous, not jumping from +/// 179.5° to -179.5° and drawing a line across the flat map, and brought to the flat frame's side +/// of ±180° when they start on the other. +#[test] +fn a_globe_frame_across_the_antimeridian_is_outlined_in_one_piece() { + use rustgis_map::layout::{INDICATOR_COLOR, INDICATOR_WIDTH}; + let mut globe = Map::new("g"); + globe.set_projection(rustgis_map::Projection::Globe); + let frame = |map: &str, center, scale, extent_of| ElementKind::MapFrame { + map: map.into(), + center, + scale, + shape: FrameShape::Rectangle, + grid: None, + extent_of, + extent_color: INDICATOR_COLOR, + extent_width: INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }; + // The globe frame's centre and the flat locator's: on 180°, and a frame on -179° whose + // first point (its top-left corner) is on the +180° side, on a locator on -175°. + for (source_at, locator_at) in [(180.0, 180.0), (-179.0, -175.0)] { + let mut l = Layout::new("Layout", 100.0, 100.0); + // 40 mm at 1:20M, about 800 km across: 4 mm on the locator at 1:200M. + let source = l.add("Main", (58.0, 58.0, 40.0, 40.0), frame("g", Coord::new(source_at, 0.0), 2e7, None)); + l.add("Locator", (5.0, 5.0, 50.0, 50.0), frame("m", Coord::new(locator_at, 0.0), 2e8, Some(source))); + let pm = render(&l, &mut [globe.clone(), Map::new("m")], 96.0, &PageInfo::default()).unwrap(); + let k = PT_PER_MM; + let (x0, x1) = ((5.0 * k) as u32, (55.0 * k) as u32); + let red: Vec<(u32, u32)> = (x0..x1) + .flat_map(|y| (x0..x1).map(move |x| (x, y))) + .filter(|&(x, y)| { + let (r, g, b) = rgb(&pm, x, y); + r > 180 && g < 90 && b < 90 + }) + .collect(); + assert!(!red.is_empty(), "{source_at}° on {locator_at}°: no outline of the frame"); + let middle = 30.0 * k; + let far = red.iter().filter(|&&(x, y)| (f64::from(x) - middle).abs() > 6.0 * k || (f64::from(y) - middle).abs() > 6.0 * k).count(); + assert_eq!(far, 0, "{source_at}° on {locator_at}°: {far} of {} red pixels more than 6 mm from the middle", red.len()); + } +} + +/// A frame of the map `map`, named "s", at `source` (centre, scale, width and height in mm) +/// outlined on a locator 90 × 80 mm of the map `locator`, named "m", at `view` (centre and +/// scale), on a page 200 × 120 mm: the outline's red pixels, in millimetres from the locator's +/// centre (x east, y south). +fn outline_on(map: Map, source: (Coord, f64, f64, f64), locator: Map, view: (Coord, f64)) -> Vec<(f64, f64)> { + use rustgis_map::layout::{INDICATOR_COLOR, INDICATOR_WIDTH}; + let frame = |map: &str, center, scale, extent_of| ElementKind::MapFrame { + map: map.into(), + center, + scale, + shape: FrameShape::Rectangle, + grid: None, + extent_of, + extent_color: INDICATOR_COLOR, + extent_width: INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }; + let (at, scale, w, h) = source; + let mut l = Layout::new("Layout", 200.0, 120.0); + let main = l.add("Main", (5.0, 5.0, w, h), frame("s", at, scale, None)); + l.add("Locator", (100.0, 5.0, 90.0, 80.0), frame("m", view.0, view.1, Some(main))); + let pm = render(&l, &mut [map, locator], 96.0, &PageInfo::default()).unwrap(); + let k = PT_PER_MM; + let (x0, x1, y0, y1) = ((100.0 * k) as u32, (190.0 * k) as u32, (5.0 * k) as u32, (85.0 * k) as u32); + (y0..y1) + .flat_map(|y| (x0..x1).map(move |x| (x, y))) + .filter(|&(x, y)| { + let (r, g, b) = rgb(&pm, x, y); + r > 180 && g < 90 && b < 90 + }) + .map(|(x, y)| (f64::from(x) / k - 145.0, f64::from(y) / k - 45.0)) + .collect() +} + +/// [`outline_on`] a flat world map at 1:600M centred on (0°, 0°). +fn outline_on_flat_world(map: Map, source: (Coord, f64, f64, f64)) -> Vec<(f64, f64)> { + outline_on(map, source, Map::new("m"), (Coord::new(0.0, 0.0), 6e8)) +} + +/// A flat frame wider than what its locator's projection can show (UTM zone 31, 30° either +/// side of 3°E) is outlined there in pieces, broken where its edges leave what the locator +/// shows, not joined by a line across the locator (#2369). +#[test] +fn a_frame_wider_than_its_locators_projection_is_outlined_without_a_chord() { + let mut utm = Map::new("m"); + utm.set_projection(rustgis_map::Projection::Custom("EPSG:32631".into())); + // 80 × 20 mm at 1:175M on the equator, centred on 3°E: about 60°W to 66°E and 16°S to 16°N, + // its sides outside the zone, its top and bottom edges crossing it. + let red = outline_on(Map::new("s"), (Coord::new(3.0, 0.0), 1.75e8, 80.0, 20.0), utm, (Coord::new(3.0, 0.0), 1.5e8)); + assert!(!red.is_empty(), "no outline of the frame"); + // The equator's row is crossed only by a line joining the top edge to the bottom one. + let across: Vec<_> = red.iter().filter(|p| p.1.abs() < 1.0).collect(); + assert!(across.is_empty(), "the outline crosses the equator at {across:?}"); +} + +#[test] +fn an_extent_indicator_reaches_its_locators_projection_boundary() { + let source = Map::new("s"); + let mut locator = Map::new("m"); + locator.set_projection(rustgis_map::Projection::Custom("EPSG:32631".into())); + let center = Coord::new(3.0, 0.0); + let camera = rustgis_map::layout::frame_camera(&source, center, 1.75e8, 0.0, 0.0); + let top = source.to_lonlat(camera.to_map(40.0 * PT_PER_MM, 0.0, 80.0 * PT_PER_MM, 20.0 * PT_PER_MM)).unwrap().y; + let red = outline_on(source, (center, 1.75e8, 80.0, 20.0), locator.clone(), (center, 1.5e8)); + // UTM's forward transform accepts 30 degrees on either side of its central meridian. + // All four ends reach that boundary, whether entering or leaving the visible area. + for lon in [-27.0 + 1e-7, 33.0 - 1e-7] { + for lat in [-top, top] { + let edge = locator.to_map(Coord::new(lon, lat)).unwrap(); + let middle = locator.to_map(center).unwrap(); + let expected = ((edge.x - middle.x) / 150_000.0, (middle.y - edge.y) / 150_000.0); + let distance = red.iter().map(|p| (p.0 - expected.0).hypot(p.1 - expected.1)).fold(f64::INFINITY, f64::min); + assert!(distance < 0.6, "the outline stops {distance:.2} mm short of ({lon}, {lat})"); + } + } +} + +/// A boundary search on either side of the date line follows the short arc, in either +/// direction, rather than drawing a chord across the UTM overview (#2433). +#[test] +fn an_overviews_boundary_search_crosses_the_date_line_on_the_short_arc() { + for (code, center, inside, outside, edge) in + [("EPSG:32655", 147.0, 176.0, -179.0, 177.0 - 1e-7), ("EPSG:32606", -147.0, -176.0, 179.0, -177.0 + 1e-7)] + { + let mut map = Map::new("overview"); + map.set_projection(rustgis_map::Projection::Custom(code.into())); + let camera = rustgis_map::layout::frame_camera(&map, Coord::new(center, 0.0), 1e8, 0.0, 0.0); + let view = View { width: 600.0, height: 400.0, pixels_per_point: 1.0, camera, sky: false }; + let screen = |lon| { + let p = map.to_map(Coord::new(lon, 10.0)).unwrap(); + camera.try_to_screen(p, view.width, view.height).unwrap() + }; + let start = screen(inside); + let end = screen(edge); + for reverse in [false, true] { + let mut ring = [Some(Coord::new(inside, 10.0)), Some(Coord::new(outside, 10.0))]; + if reverse { + ring.reverse(); + } + let mut canvas = Canvas::new(600, 400).unwrap(); + outline_lonlat(&mut canvas, &map, &view, &ring, false, Rgba::rgb(255, 0, 0), 2.0); + let pm = canvas.into_pixmap(); + let red: Vec<_> = (0..400) + .flat_map(|y| (0..600).map(move |x| (x, y))) + .filter(|&(x, y)| { + let (r, g, b) = rgb(&pm, x, y); + r > 180 && g < 90 && b < 90 + }) + .map(|(x, y)| (f64::from(x), f64::from(y))) + .collect(); + assert!(!red.is_empty(), "{code}, reverse {reverse}: no outline"); + assert!( + red.iter().all(|p| p.0 >= start.0.min(end.0) - 2.0 && p.0 <= start.0.max(end.0) + 2.0), + "{code}, reverse {reverse}: a chord across the overview" + ); + assert!( + red.iter().any(|p| (p.0 - end.0).hypot(p.1 - end.1) < 2.0), + "{code}, reverse {reverse}: the outline does not reach the boundary" + ); + } + } +} + +/// A flat frame on a custom projection whose edges run off its world (Mollweide, zoomed out +/// past its ellipse) is outlined by its top and bottom edges, broken where they leave the +/// world and reaching it there, not joined by lines across the map (#2369). +#[test] +fn a_flat_frame_off_its_projections_world_is_outlined_without_a_chord() { + let mut moll = Map::new("s"); + moll.set_projection(rustgis_map::Projection::from_code("mollweide").unwrap()); + // 80 × 20 mm at 1:600M: Mollweide's world is 60 × 30 mm, so the frame's sides are off it + // and its top and bottom edges leave it about 22 mm either side of the centre. + let red = outline_on_flat_world(moll, (Coord::new(0.0, 0.0), 6e8, 80.0, 20.0)); + assert!(!red.is_empty(), "no outline of the frame"); + // The equator's row is crossed only by a line joining the top edge to the bottom one. + let across: Vec<_> = red.iter().filter(|p| p.1.abs() < 1.0).collect(); + assert!(across.is_empty(), "the outline crosses the equator at {across:?}"); + // The edges run to the world's sides, ±180° (33.4 mm from the centre at 1:600M), and no + // further: without bisecting, they stopped at the last sample on the world, at about 160°. + let reach = red.iter().fold(0.0_f64, |m, p| m.max(p.0.abs())); + assert!((reach - 33.4).abs() < 0.6, "the outline reaches {reach:.1} mm from the centre, not ±180°"); + for side in [-1.0, 1.0] { + assert!(red.iter().any(|p| (p.0 * side - 33.4).abs() < 0.6), "no outline at the world's {side} side"); + } +} + +/// A frame on the globe around the North Pole, outlined on a flat world map, is split at ±180° +/// and drawn across the whole world, not as one piece a stretch of which is off the world, past +/// ±180° (#2369). +#[test] +fn a_globe_frame_around_a_pole_is_outlined_across_a_flat_world() { + let mut globe = Map::new("s"); + globe.set_projection(rustgis_map::Projection::Globe); + // 40 mm at 1:40M, about 1600 km across, centred 5° (550 km) from the pole: the pole inside + // it. (A frame's centre is kept in Web Mercator, up to 85.05°.) + let (at, scale) = (Coord::new(30.0, 85.0), 4e7); + let cam = rustgis_map::layout::frame_camera(&globe, at, scale, 0.0, 0.0); + let side = 40.0 * PT_PER_MM; + let (px, py) = rustgis_map::globe::Globe::new(&cam, side, side).forward(Coord::new(0.0, 90.0)).expect("the pole on the disc"); + assert!((0.0..side).contains(&px) && (0.0..side).contains(&py), "the pole at ({px:.0}, {py:.0}), off the frame"); + let red = outline_on_flat_world(globe, (at, scale, 40.0, 40.0)); + assert!(!red.is_empty(), "no outline of the frame"); + // On both of the world's sides, ±180° (33.4 mm from the centre), and not past them. + for dir in [-1.0, 1.0] { + assert!(red.iter().any(|p| (p.0 * dir - 33.4).abs() < 1.0), "no outline at the world's {dir} side"); + } + let past: Vec<_> = red.iter().filter(|p| p.0.abs() > 34.2).collect(); + assert!(past.is_empty(), "{} red pixels past ±180°, as far as {:?}", past.len(), past.iter().map(|p| p.0).fold(0.0_f64, f64::max)); +} + +/// A ring placed on Robinson centred on 150°E, whose edge is at -30°, is cut there, each piece +/// on its side of the map, not joined across it (#2369): a flat frame's ring across the edge, +/// and a globe frame's around a pole, a whole turn of longitude. +#[test] +fn a_ring_is_cut_at_its_maps_own_edge() { + let mut robinson = Map::new("m"); + robinson.set_projection(rustgis_map::Projection::Custom("robinson +lon_0=150".into())); + let mid = Some(Coord::new(150.0, 0.0)); + let flat = [(-40.0, 10.0), (-20.0, 10.0), (-20.0, 20.0), (-40.0, 20.0), (-40.0, 10.0)].map(|(x, y)| Some(Coord::new(x, y))); + // From 20°E all the way round, 85°N, as a pole's ring runs, its longitudes continuous. + let pole: Vec> = (0..=36).map(|i| Some(Coord::new(20.0 + 10.0 * f64::from(i), 85.0))).collect(); + for (name, ring, from_globe) in [("flat", &flat[..], false), ("pole", &pole[..], true)] { + let placed = ring_on_flat(&robinson, mid, ring, from_globe); + let points: Vec = placed.iter().flatten().copied().collect(); + assert!(!points.is_empty(), "{name}: nothing placed"); + // Every point in the map's world, -30° to 330°, so it projects onto its own side. + let out: Vec<_> = points.iter().filter(|c| !(-30.0..=330.0).contains(&c.x)).collect(); + assert!(out.is_empty(), "{name}: points outside the map's world: {out:?}"); + // On both sides of the edge, the pieces broken apart. + assert!(points.iter().any(|c| c.x < -29.0) && points.iter().any(|c| c.x > 329.0), "{name}: not on both sides: {points:?}"); + let jumps: Vec<_> = placed.windows(2).filter_map(|w| Some((w[0]?, w[1]?))).filter(|(a, b)| (a.x - b.x).abs() > 180.0).collect(); + assert!(jumps.is_empty(), "{name}: joined across the edge: {jumps:?}"); + } + // On Web Mercator, which doesn't wrap, a flat frame's ring is placed where it is. + assert_eq!(ring_on_flat(&Map::new("m"), Some(Coord::new(0.0, 0.0)), &flat, false), flat.to_vec()); +} + +/// A flat frame wider than the world, outlined on another flat frame, is drawn where it is +/// (#2348): its first point past -180° doesn't move it a turn east, so both its sides show. +#[test] +fn a_flat_frame_wider_than_the_world_is_outlined_where_it_is() { + use rustgis_map::layout::{INDICATOR_COLOR, INDICATOR_WIDTH}; + let frame = |center, scale, extent_of| ElementKind::MapFrame { + map: "m".into(), + center, + scale, + shape: FrameShape::Rectangle, + grid: None, + extent_of, + extent_color: INDICATOR_COLOR, + extent_width: INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }; + let at = Coord::new(0.0, 0.0); + let mut l = Layout::new("Layout", 200.0, 120.0); + // 80 mm at 1:529M on the equator: about 380° of longitude, -190° to 190°. + let source = l.add("Main", (5.0, 5.0, 80.0, 20.0), frame(at, 5.29e8, None)); + // 90 mm at 1:593M: about 480°, so both of the source's sides are in it. + l.add("Locator", (100.0, 5.0, 90.0, 60.0), frame(at, 5.93e8, Some(source))); + let pm = render(&l, &mut [Map::new("m")], 96.0, &PageInfo::default()).unwrap(); + let k = PT_PER_MM; + let red = |x: u32, y: u32| { + let (r, g, b) = rgb(&pm, x, y); + r > 180 && g < 90 && b < 90 + }; + let (top, bottom) = ((5.0 * k) as u32, (65.0 * k) as u32); + let middle = 145.0 * k; + let side = |xs: std::ops::Range| xs.flat_map(|x| (top..bottom).map(move |y| (x, y))).filter(|&(x, y)| red(x, y)).count(); + let (west, east) = (side((100.0 * k) as u32..(middle - 10.0 * k) as u32), side((middle + 10.0 * k) as u32..(190.0 * k) as u32)); + assert!(west > 0 && east > 0, "the outline's sides: {west} red pixels west of the middle, {east} east"); +} + +fn rgb(pm: &Pixmap, x: u32, y: u32) -> (u8, u8, u8) { + pm.pixel(x, y).map(|p| (p.red(), p.green(), p.blue())).unwrap_or((255, 255, 255)) +} + +/// A colorbar's title longer than the element is wide wraps inside it (#2493), every word kept; +/// the bar goes under its lines. +#[test] +fn a_colorbars_long_title_wraps_inside_it() { + let scale = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(200, 200, 200), Rgba::rgb(230, 230, 230)] }; + let title = "Precipitação média mensal JAXA GSMaP (mm/mês), jan–mar 2025"; + let bar = Bar { title, orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; + // A canvas wider than the element, so ink past its right edge shows. + let mut c = Canvas::new(600, 200).unwrap(); + let r = Rect::from_xywh(10.0, 10.0, 200.0, 150.0).unwrap(); + colorbar(&mut c, r, &scale, &bar, 1.0); + let dark = |x: u32, y: u32| c.pixmap().pixel(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120); + let past = (r.right().ceil() as u32 + 1..600).find(|x| (0..200).any(|y| dark(*x, y))); + assert_eq!(past, None, "the title's ink past the element's right edge"); + let lines = colorbar_title_lines(title, 200.0 / PT_PER_MM); + assert!(lines.len() >= 2, "{lines:?}"); + assert_eq!(lines.concat().replace(' ', ""), title.replace(' ', ""), "every word is kept"); + // The second line is inked, under the first. + let pitch = (COLORBAR_TITLE_PT * 1.33 * 1.25) as u32; + let line = |y0: u32| (y0..y0 + 8).any(|y| (10..210).any(|x| dark(x, y))); + assert!(line(10 + pitch + 3), "a second line of title"); +} + +/// A colorbar's title stops short of the bar's own room, so a long title never leaves the bar +/// without its tick labels: the bar ends above them, its labels under it (#2638). Before, the +/// title's second line took the room, and the bar filled the element's bottom with no labels. +#[test] +fn a_colorbars_long_title_leaves_its_bar_room_for_labels() { + // A red-to-blue bar, so its pixels are told apart from the grey text. + let scale = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(220, 30, 30), Rgba::rgb(30, 30, 220)] }; + let title = "Precipitação média mensal JAXA GSMaP (mm/mês), jan–mar 2025"; + let bar = Bar { title, orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; + // 100 × 40 px: room for two lines of title, but then only 8 px of bar, with no labels. + let mut c = Canvas::new(300, 200).unwrap(); + colorbar(&mut c, Rect::from_xywh(10.0, 10.0, 100.0, 40.0).unwrap(), &scale, &bar, 1.0); + let px = |x: u32, y: u32| c.pixmap().pixel(x, y); + let coloured = + |y: u32| (10..110).any(|x| px(x, y).is_some_and(|p| p.alpha() > 200 && p.green() < 90 && p.red().abs_diff(p.blue()) > 60)); + let dark = |y: u32| (10..110).any(|x| px(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120 && p.blue() < 120)); + assert!((26..36).any(coloured), "the bar under the title"); + assert!(!(44..50).any(coloured), "the bar ends above its labels, not at the element's bottom"); + assert!((40..50).any(dark), "its labels under it"); +} + +/// A vertical colorbar's end labels are centred on its bar's ends, so its title leaves the bar +/// two labels' height (#2638): a vertical colorbar 25 px high (6.6 mm at 96 dpi) holds its +/// one-line title back and says so, its bar keeping both end labels, and one 12 mm high draws +/// the title and says nothing. A vertical colorbar too short for its end labels, or too narrow +/// for its labels beside the bar, says so even with no title, and a horizontal one too short +/// for its labels under its bar, too. +#[test] +fn a_colorbars_labels_left_out_are_said() { + let map = ramp_map( + rustgis_map::raster::RasterRenderer::Stretch { band: 0, ramp: rustgis_map::Ramp::Thermal, invert: false }, + rustgis_map::raster::Stretch::MinMax, + ); + let info = PageInfo::default(); + let mm = 25.4 / 96.0; + // (orientation, title, width and height in mm, a loss said, title lines left out) + for (orientation, title, w, h, said, left_out) in [ + (Orientation::Vertical, "Elevation (m)", 25.0, 25.0 * mm, true, 1), + (Orientation::Vertical, "Elevation (m)", 25.0, 12.0, false, 0), + (Orientation::Vertical, "", 25.0, 12.0 * mm, true, 0), + (Orientation::Vertical, "", 25.0, 25.0 * mm, false, 0), + // Too narrow for its labels beside the bar: they're left out, and said. + (Orientation::Vertical, "", 2.0, 25.0, true, 0), + (Orientation::Horizontal, "", 25.0, 15.0 * mm, true, 0), + (Orientation::Horizontal, "", 25.0, 25.0 * mm, false, 0), + ] { + let mut l = Layout::new("Page", 120.0, 90.0); + let frame = l.add( + "Frame", + (60.0, 60.0, 50.0, 25.0), + serde_json::from_value(serde_json::json!({"MapFrame":{"map":"m", "center":{"x":0,"y":0}, "scale":1000000}})).unwrap(), + ); + let kind = ElementKind::Colorbar { + frame, + layer: None, + title: title.into(), + orientation, + ticks: 5, + tick_side: TickSide::End, + reverse: false, + color: None, + }; + l.add("Colorbar", (5.0, 5.0, w, h), kind); + let losses = text_losses(&l, std::slice::from_ref(&map), 96.0, &info); + let case = format!("{orientation:?} {title:?} {w:.1} × {h:.1} mm: {losses:?}"); + assert_eq!(losses.len() == 1, said, "{case}"); + if let Some(loss) = losses.first() { + assert!(loss.below_box && loss.left_out == left_out, "{case}"); + // Its own advice, not a text's line breaks. + let note = clipped_text_notice(&l, &[(loss.id, loss.name.clone())]).unwrap_or_default(); + assert!(note.contains("make the colorbar larger"), "{case}: {note}"); + } + } + // As drawn: 25 px high, the title held back, both end labels inside the element. + let scale = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(220, 30, 30), Rgba::rgb(30, 30, 220)] }; + let bar = Bar { + title: "Elevation (m)", + orientation: Orientation::Vertical, + ticks: 2, + side: TickSide::End, + reverse: false, + comma: false, + ink: INK, + }; + let mut c = Canvas::new(200, 100).unwrap(); + colorbar(&mut c, Rect::from_xywh(10.0, 10.0, 100.0, 25.0).unwrap(), &scale, &bar, 1.0); + let dark = |x: u32, y: u32| c.pixmap().pixel(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120 && p.blue() < 120); + // The labels stand to the bar's right, past its ticks: ink near its top end and its bottom. + let label_ink = |ys: std::ops::Range| ys.into_iter().any(|y| (60..110).any(|x| dark(x, y))); + assert!(label_ink(10..20), "the top end's label"); + assert!(label_ink(26..36), "the bottom end's label"); +} + +/// A label left out for spilling out of a colorbar takes no room, so it doesn't thin the next +/// one away unsaid (#2638): on a bar 40 px wide, the end label 1000 spills past its left +/// side and is counted, and the middle label 1500, inside, is still drawn. +#[test] +fn a_colorbars_spilled_label_doesnt_thin_the_next() { + let scale = ColorScale::Ramp { lo: 1000.0, hi: 2000.0, colors: vec![Rgba::rgb(220, 30, 30), Rgba::rgb(30, 30, 220)] }; + let bar = + Bar { title: "", orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; + let plan = colorbar_plan(Rect::from_xywh(0.0, 0.0, 40.0, 40.0).unwrap(), &scale, &bar, 1.0); + let drawn: Vec<&str> = plan.labels.iter().map(|l| l.0.as_str()).collect(); + assert!(plan.spilled >= 1, "the end label spills: {drawn:?}"); + assert!(drawn.contains(&"1500"), "the middle label is drawn: {drawn:?}"); +} + +/// A colorbar too short for a line of title over its bar holds the title back, and the bar +/// then starts at the element's top, keeping its labels: a title not drawn takes no room +/// (#2638). Before, the bar was pushed down by the room of a line never drawn, and lost them. +#[test] +fn a_colorbar_whose_title_is_held_back_keeps_its_labels() { + let scale = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(220, 30, 30), Rgba::rgb(30, 30, 220)] }; + let title = "Precipitação média mensal JAXA GSMaP (mm/mês), jan–mar 2025"; + let bar = Bar { title, orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; + // 100 × 30 px, from y = 10 to 40: a line of title (16.8 px) and the bar's own room + // (19.8) don't both fit, so no line is drawn. + assert_eq!(colorbar_title_drawn(4, 10.0, 40.0 - colorbar_bar_room(1.0, Orientation::Horizontal), COLORBAR_TITLE_PT as f32 * 1.33), 0); + let mut c = Canvas::new(300, 200).unwrap(); + colorbar(&mut c, Rect::from_xywh(10.0, 10.0, 100.0, 30.0).unwrap(), &scale, &bar, 1.0); + let px = |x: u32, y: u32| c.pixmap().pixel(x, y); + let coloured = + |y: u32| (10..110).any(|x| px(x, y).is_some_and(|p| p.alpha() > 200 && p.green() < 90 && p.red().abs_diff(p.blue()) > 60)); + let dark = |y: u32| (10..110).any(|x| px(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120 && p.blue() < 120)); + assert!((11..15).any(coloured), "the bar at the element's top"); + assert!(!(35..40).any(coloured), "the bar ends above its labels"); + assert!((30..40).any(dark), "its labels under it"); +} + +/// A colorbar's title lines are drawn only where the bar keeps its own room under them, the +/// first too, with no slack: the bar never loses its labels to them (#2638). At 12 px a line, +/// the first needs 16.8 px and each further one 15 more, over the bar's 19.8. +#[test] +fn a_colorbars_title_lines_leave_the_bar_its_room() { + let (px, room) = (COLORBAR_TITLE_PT as f32 * 1.33, colorbar_bar_room(1.0, Orientation::Horizontal)); + for (height, lines) in [(20.0, 0), (36.0, 0), (37.0, 1), (51.2, 1), (52.0, 2), (200.0, 5)] { + assert_eq!(colorbar_title_drawn(5, 0.0, height - room, px), lines, "{height} px"); + } + // Whatever the height, the lines drawn leave the bar its room. + for h in 0..300 { + let h = h as f32 * 0.5; + let n = colorbar_title_drawn(5, 0.0, h - room, px); + assert!(n == 0 || px * (1.4 + 1.25 * (n - 1) as f32) + room <= h, "{h} px: {n} lines"); + } +} + +/// A colorbar too short for its title's lines draws those that fit inside it, not lines past +/// its bottom, and the page's cut-off check says the rest are left out; one tall enough says +/// nothing (#2493). +#[test] +fn a_colorbars_title_lines_past_its_bottom_are_left_out_and_said() { + let scale = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(200, 200, 200), Rgba::rgb(230, 230, 230)] }; + let title = "Precipitação média mensal JAXA GSMaP (mm/mês), jan–mar 2025"; + let bar = Bar { title, orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; + // 100 px wide, four lines or more; 20 px high, no line: the first's room would end at + // 10 + 12 × 1.4 = 26.8, leaving the bar less than its own 19.8 (a second would be centred + // at 32, within a line of the bottom at 30, as a text element's line may be). + assert!(colorbar_title_lines(title, 100.0 / PT_PER_MM).len() >= 4); + let mut c = Canvas::new(300, 200).unwrap(); + colorbar(&mut c, Rect::from_xywh(10.0, 10.0, 100.0, 20.0).unwrap(), &scale, &bar, 1.0); + let dark = |x: u32, y: u32| c.pixmap().pixel(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120); + let lowest = (0..200).rev().find(|y| (0..300).any(|x| dark(x, *y))); + assert!(lowest.is_some_and(|y| y <= 30), "ink down to {lowest:?}, past the colorbar's bottom at 30"); + // On a page, in a frame whose map has a raster on a ramp. + let map = ramp_map( + rustgis_map::raster::RasterRenderer::Stretch { band: 0, ramp: rustgis_map::Ramp::Thermal, invert: false }, + rustgis_map::raster::Stretch::MinMax, + ); + let mut l = Layout::new("Page", 120.0, 90.0); + let frame = l.add( + "Frame", + (60.0, 60.0, 50.0, 25.0), + serde_json::from_value(serde_json::json!({"MapFrame":{"map":"m", "center":{"x":0,"y":0}, "scale":1000000}})).unwrap(), + ); + let kind = ElementKind::Colorbar { + frame, + layer: None, + title: title.into(), + orientation: Orientation::Horizontal, + ticks: 5, + tick_side: TickSide::End, + reverse: false, + color: None, + }; + let id = l.add("Colorbar", (5.0, 5.0, 25.0, 6.0), kind); + let info = PageInfo::default(); + let losses = text_losses(&l, std::slice::from_ref(&map), 96.0, &info); + assert_eq!(losses.len(), 1, "the short colorbar's title is cut"); + // 6 mm high: no room for a line of title over the bar's own: every line said. + let lines = colorbar_title_lines(title, 25.0).len(); + assert!(lines >= 3 && losses[0].id == id && losses[0].below_box, "{lines} lines"); + assert_eq!(losses[0].left_out, lines); + l.element_mut(id).unwrap().h = 40.0; + assert!(text_losses(&l, std::slice::from_ref(&map), 96.0, &info).is_empty(), "tall enough for every line"); +} + +#[test] +fn colorbars_draw_the_raster_colour_scale() { + use rustgis_map::raster::{RasterRenderer, Stretch}; + let ramp = rustgis_map::Ramp::Thermal; + let map = ramp_map(RasterRenderer::Stretch { band: 0, ramp: ramp.clone(), invert: false }, Stretch::MinMax); + let k = PT_PER_MM; + // A row through the bar, near its top edge (the labels are below it). + let y = (12.0 * k) as u32; + let pm = colorbar_page(&map, Orientation::Horizontal, false, ""); + let (left, right) = (rgb(&pm, (16.0 * k) as u32, y), rgb(&pm, (84.0 * k) as u32, y)); + let close = |a: (u8, u8, u8), b: Rgba| a.0.abs_diff(b.r()) < 40 && a.1.abs_diff(b.g()) < 40 && a.2.abs_diff(b.b()) < 40; + assert!(close(left, ramp.at(0.0)), "the low end is the ramp's start: {left:?} vs {:?}", ramp.at(0.0)); + assert!(close(right, ramp.at(1.0)), "the high end is the ramp's end: {right:?} vs {:?}", ramp.at(1.0)); + // Labelled below the bar: dark text under it, between the bar and the element's bottom. + let inked = |pm: &Pixmap, y0: f64, y1: f64| { + ((y0 * k) as u32..(y1 * k) as u32).any(|y| (0..pm.width()).any(|x| rgb(pm, x, y).0 < 80 && rgb(pm, x, y).2 < 80)) + }; + assert!(inked(&pm, 26.0, 30.0), "tick labels below the bar"); + // Reversed, the ends swap. + let rev = colorbar_page(&map, Orientation::Horizontal, true, ""); + assert!(close(rgb(&rev, (16.0 * k) as u32, y), ramp.at(1.0))); + assert!(close(rgb(&rev, (84.0 * k) as u32, y), ramp.at(0.0))); + // Vertical, low values sit at the bottom. + let v = colorbar_page(&map, Orientation::Vertical, false, ""); + let x = (11.0 * k) as u32; + assert!(close(rgb(&v, x, (85.0 * k) as u32), ramp.at(0.0)), "{:?}", rgb(&v, x, (85.0 * k) as u32)); + assert!(close(rgb(&v, x, (15.0 * k) as u32), ramp.at(1.0)), "{:?}", rgb(&v, x, (15.0 * k) as u32)); + // A title pushes the bar down under it. + let t = colorbar_page(&map, Orientation::Horizontal, false, "Elevation (m)"); + assert!(inked(&t, 10.0, 13.0), "the title is drawn at the top"); + + // Classes draw as steps, one colour each. + let breaks = vec![24.0, 49.0, 74.0, 99.0]; + let classify = + RasterRenderer::Classify { band: 0, method: rustgis_map::ClassMethod::EqualInterval, ramp: ramp.clone(), breaks, classes: 4 }; + let classes = ramp_map(classify, Stretch::MinMax); + // Named: a colorbar with no layer leaves a raster drawn by classes to the legend (#1679). + assert!(rustgis_map::layout::colorbar_layer(&classes, None).is_none()); + assert!(rustgis_map::layout::colorbar_layer(&map, None).is_some(), "a stretch is the default's"); + // A stretched raster in a hidden group isn't the default's: the one the map shows is. + let mut hidden = map.clone(); + let top = hidden.layers[0].clone(); + let id = hidden.add_raster("hidden", top.raster.clone().unwrap()); + let mut group = rustgis_map::LayerGroup::new("off"); + group.visible = false; + group.children.push(id); + hidden.add_group(group); + assert_eq!(rustgis_map::layout::colorbar_layer(&hidden, None).map(|l| l.name.as_str()), Some("dem")); + let pm = colorbar_page(&classes, Orientation::Horizontal, false, ""); + let mut colours: Vec<(u8, u8, u8)> = ((16.0 * k) as u32..(84.0 * k) as u32).map(|x| rgb(&pm, x, y)).collect(); + colours.dedup(); + assert!((4..=7).contains(&colours.len()), "four steps (and their seams): {colours:?}"); + + // In an element too short for its labels, they are left out rather than drawn under it. + let mut l = Layout::new("Layout", 100.0, 100.0); + let frame = l.add( + "Map", + (95.0, 95.0, 4.0, 4.0), + ElementKind::MapFrame { + map: "m".into(), + center: Coord::new(0.0, 0.0), + scale: 1e8, + shape: FrameShape::Rectangle, + grid: None, + extent_of: None, + extent_color: rustgis_map::layout::INDICATOR_COLOR, + extent_width: rustgis_map::layout::INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }, + ); + let kind = ElementKind::Colorbar { + frame, + layer: None, + title: String::new(), + orientation: Orientation::Horizontal, + ticks: 5, + tick_side: TickSide::End, + reverse: false, + color: None, + }; + l.add("Colorbar", (10.0, 10.0, 80.0, 3.0), kind); + let short = render(&l, &mut [map.clone()], 96.0, &PageInfo::default()).unwrap(); + assert!(!inked(&short, 13.5, 20.0), "nothing spills below the element"); + assert!(close(rgb(&short, (16.0 * k) as u32, (11.0 * k) as u32), ramp.at(0.0)), "the bar is still drawn"); + + // RGB has no colour scale: a placeholder, not a bar. + let pm = + colorbar_page(&ramp_map(RasterRenderer::Rgb { red: 0, green: 0, blue: 0 }, Stretch::MinMax), Orientation::Horizontal, false, ""); + assert_eq!(rgb(&pm, (16.0 * k) as u32, y), (0xF0, 0xF1, 0xF3)); +} + +#[test] +fn colorbar_tick_labels_are_even_and_tidy() { + let labels = |lo, hi, n| tick_labels(lo, hi, n).into_iter().map(|(_, s)| s).collect::>(); + assert_eq!(labels(0.0, 100.0, 5), ["0", "25", "50", "75", "100"]); + assert_eq!(labels(0.0, 1.0, 5), ["0.00", "0.25", "0.50", "0.75", "1.00"]); + assert_eq!(labels(0.0, 1.0, 3), ["0.0", "0.5", "1.0"]); + assert_eq!(labels(-1.0, 1.0, 2), ["-1", "1"]); + // Odd bounds keep only the decimals the step needs. + assert_eq!(labels(12.345, 87.9, 2), ["12", "88"]); + assert_eq!(labels(-0.004, 1.0, 2), ["0", "1"], "no -0"); + // One value: one label. Out of range counts are clamped. + assert_eq!(labels(5.0, 5.0, 5), ["5"]); + assert_eq!(tick_labels(0.0, 1.0, 0).len(), 2); + assert_eq!(tick_labels(0.0, 1.0, 1000).len(), rustgis_map::layout::MAX_COLORBAR_TICKS); + assert!(tick_labels(f64::NAN, 1.0, 5).is_empty()); + assert_eq!(labels(0.0, 4e6, 2), ["0", "4.0M"]); +} + +#[test] +fn hairline_rectangles_draw_thin() { + // A filled 0.15 mm rule at 300 dpi is under two pixels tall, not a 1 mm bar (#211). + let mut l = Layout::new("Layout", 50.0, 20.0); + l.add( + "Rule", + (5.0, 10.0, 40.0, 0.15), + ElementKind::Rectangle { fill: Rgba::rgb(0, 0, 0), outline: Rgba::rgb(0, 0, 0), width: 0.0, radius: 0.0, dash: None }, + ); + let pm = render(&l, &mut [], 300.0, &PageInfo::default()).unwrap(); + let x = pm.width() / 2; + let inked = (0..pm.height()).filter(|&y| pm.pixel(x, y).is_some_and(|p| p.red() < 250)).count(); + assert!((1..=3).contains(&inked), "{inked} rows inked"); +} + +#[test] +fn arrowheads_are_drawn_at_the_ends_they_point_to() { + use rustgis_map::layout::LineDir; + // 100 × 20 mm at 254 dpi (ten pixels a millimetre); a level arrow from 10 to 90 mm. + let mut l = Layout::new("Layout", 100.0, 20.0); + let blue = Rgba::rgb(0, 0, 255); + l.add( + "Arrow", + (10.0, 7.0, 80.0, 6.0), + ElementKind::Line { color: blue, width: 1.0, dir: LineDir::Horizontal, head: LineHead::End, dash: None }, + ); + let pm = render(&l, &mut [], 254.0, &PageInfo::default()).unwrap(); + let inked = |x: u32, y: u32| pm.pixel(x, y).is_some_and(|p| p.red() < 128 && p.blue() > 128); + // At 254 dpi (2.65 pixels a point) the shaft is about 2.6 px wide and the head about 22 px + // long and 10 px either side of the line: 5 px off the line, 15 px back from the tip, is + // inside the head, but clear of the shaft at the tail. + assert!(inked(500, 100), "the shaft"); + assert!(inked(885, 105) && inked(885, 95), "the head, either side of the line"); + assert!(!inked(115, 105) && !inked(115, 95), "no head at the tail"); + assert!(!inked(905, 100), "nothing past the tip"); +} + +#[test] +fn ellipses_and_lines_draw_inside_their_boxes() { + use rustgis_map::layout::LineDir; + // 100 × 50 mm at 254 dpi: ten pixels a millimetre. + let mut l = Layout::new("Layout", 100.0, 50.0); + let red = Rgba::rgb(255, 0, 0); + l.add("Circle", (10.0, 10.0, 30.0, 30.0), ElementKind::Ellipse { fill: red, outline: red, width: 0.0, dash: None }); + l.add( + "Line", + (50.0, 10.0, 40.0, 30.0), + ElementKind::Line { color: Rgba::rgb(0, 0, 255), width: 2.0, dir: LineDir::Rising, head: LineHead::None, dash: None }, + ); + let pm = render(&l, &mut [], 254.0, &PageInfo::default()).unwrap(); + let is = |x: u32, y: u32, want: (u8, u8, u8)| pm.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == want); + let (white, red, blue) = ((255, 255, 255), (255, 0, 0), (0, 0, 255)); + // The circle's middle is filled; its box's corner, outside the circle, isn't. + assert!(is(250, 250, red), "circle centre"); + assert!(is(110, 110, white), "outside the circle, in its box's corner"); + // The rising line runs from the box's bottom-left to its top-right, through the middle. + assert!(is(700, 250, blue), "the line's middle"); + assert!(is(550, 150, white) && is(850, 350, white), "the other diagonal stays blank"); +} + +/// A 100 × 100 mm page with one map frame filling 10–90 mm, showing the world at 1:200M with +/// `grid` over it, drawn at 96 dpi. +fn grid_page(grid: rustgis_map::layout::Grid) -> Pixmap { + let mut maps = vec![Map::new("m")]; + let mut l = Layout::new("Layout", 100.0, 100.0); + l.add( + "Map", + (10.0, 10.0, 80.0, 80.0), + ElementKind::MapFrame { + map: "m".into(), + center: Coord::new(0.0, 0.0), + scale: 2e8, + shape: FrameShape::Rectangle, + grid: Some(grid), + extent_of: None, + extent_color: rustgis_map::layout::INDICATOR_COLOR, + extent_width: rustgis_map::layout::INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }, + ); + render(&l, &mut maps, 96.0, &PageInfo::default()).unwrap() +} + +/// Pixels in the box (page millimetres) that `hit` picks. +fn count(pm: &Pixmap, (x0, y0, x1, y1): (f64, f64, f64, f64), hit: impl Fn(tiny_skia::PremultipliedColorU8) -> bool) -> usize { + let px = |mm: f64| (mm * PT_PER_MM) as u32; + (px(y0)..px(y1)).flat_map(|y| (px(x0)..px(x1)).map(move |x| (x, y))).filter(|&(x, y)| pm.pixel(x, y).is_some_and(&hit)).count() +} + +fn red(p: tiny_skia::PremultipliedColorU8) -> bool { + p.red() > 180 && p.green() < 90 && p.blue() < 90 +} + +fn ink(p: tiny_skia::PremultipliedColorU8) -> bool { + p.red() < 90 && p.green() < 90 && p.blue() < 90 +} + +/// A page whose 80 mm frame shows Winterthur at 1:25,000 (2 km across) on a map in `projection`. +fn winterthur_page(grid: rustgis_map::layout::Grid, projection: rustgis_map::Projection) -> Pixmap { + let mut m = Map::new("m"); + m.projection = projection; + let mut maps = vec![m]; + let mut l = Layout::new("Layout", 100.0, 100.0); + l.add( + "Map", + (10.0, 10.0, 80.0, 80.0), + ElementKind::MapFrame { + map: "m".into(), + center: Coord::new(8.73, 47.5), + scale: 25_000.0, + shape: FrameShape::Rectangle, + grid: Some(grid), + extent_of: None, + extent_color: rustgis_map::layout::INDICATOR_COLOR, + extent_width: rustgis_map::layout::INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }, + ); + render(&l, &mut maps, 96.0, &PageInfo::default()).unwrap() +} + +/// Where red runs cross a row of the page (page millimetres): the middle of each run. +fn red_runs(pm: &Pixmap, y_mm: f64) -> Vec { + let y = (y_mm * PT_PER_MM) as u32; + let mut out = Vec::new(); + let mut start = None; + for x in 0..pm.width() { + match (pm.pixel(x, y).is_some_and(red), start) { + (true, None) => start = Some(x), + (false, Some(s)) => { + out.push(f64::from(s + x - 1) / 2.0 / PT_PER_MM); + start = None; + } + _ => {} + } + } + out +} + +/// A measured grid: eastings and northings its step apart in its coordinate system (1 km is +/// 40 mm at 1:25,000), bent onto the map's projection, straight on a map in that system; the +/// map's own system, else the frame's UTM zone, when it names none; nothing for a system it +/// can't draw. +#[test] +fn measured_grids_draw_eastings_and_northings() { + use rustgis_map::layout::{Grid, GridKind}; + let utm = Grid { + kind: GridKind::Measured, + crs: Some("EPSG:25832".into()), + step: 1000.0, + color: Rgba::rgb(0xFF, 0, 0), + labels: false, + width: 1.5, + ..Grid::default() + }; + let gaps = |xs: &[f64]| xs.windows(2).map(|w| w[1] - w[0]).collect::>(); + // On Web Mercator: 1 km is 40 mm on paper, give or take Mercator's scale at 47.5°N. + let pm = winterthur_page(utm.clone(), rustgis_map::Projection::WebMercator); + let xs = red_runs(&pm, 50.0); + assert!(xs.len() >= 2, "{xs:?}"); + assert!(gaps(&xs).iter().all(|g| (g - 40.0).abs() < 1.5), "{xs:?}"); + // On a map in EPSG:25832 itself: exactly 40 mm, and straight (the same at the top and bottom). + let own = rustgis_map::Projection::Custom("EPSG:25832".into()); + let pm = winterthur_page(utm.clone(), own.clone()); + let (top, bottom) = (red_runs(&pm, 20.0), red_runs(&pm, 80.0)); + assert!(gaps(&top).iter().all(|g| (g - 40.0).abs() < 0.3), "{top:?}"); + assert_eq!(top.len(), bottom.len()); + assert!(top.iter().zip(&bottom).all(|(a, b)| (a - b).abs() < 0.3), "{top:?} {bottom:?}"); + // Naming none: the map's own system draws the same grid; on Web Mercator, UTM 32N's + // (EPSG:32632, the same eastings as 25832 to a metre) does. + let unnamed = Grid { crs: None, ..utm.clone() }; + assert!(red_runs(&winterthur_page(unnamed.clone(), own), 20.0).iter().zip(&top).all(|(a, b)| (a - b).abs() < 0.3)); + let mercator = red_runs(&winterthur_page(utm.clone(), rustgis_map::Projection::WebMercator), 20.0); + let zone = red_runs(&winterthur_page(unnamed, rustgis_map::Projection::WebMercator), 20.0); + assert_eq!(mercator.len(), zone.len()); + assert!(mercator.iter().zip(&zone).all(|(a, b)| (a - b).abs() < 0.3), "{mercator:?} {zone:?}"); + // A map in an ESRI system (or a preset): its own, by its PROJ definition, straight on it. + let esri = rustgis_map::Projection::Custom("ESRI:102031".into()); + let pm = winterthur_page(Grid { crs: None, ..utm.clone() }, esri); + let (top, bottom) = (red_runs(&pm, 20.0), red_runs(&pm, 80.0)); + assert!(top.len() >= 2 && top.len() == bottom.len(), "{top:?} {bottom:?}"); + assert!(top.iter().zip(&bottom).all(|(a, b)| (a - b).abs() < 0.3), "the map's own system: straight {top:?} {bottom:?}"); + // A system it can't draw (geographic, unknown): nothing. + for crs in ["EPSG:4326", "EPSG:1", "not a system"] { + let pm = winterthur_page(Grid { crs: Some(crs.into()), ..utm.clone() }, rustgis_map::Projection::WebMercator); + assert_eq!(count(&pm, (10.0, 10.0, 90.0, 90.0), red), 0, "{crs}"); + } + // A step too fine for the frame is widened rather than drawn as a blur. + let fine = winterthur_page(Grid { step: 1.0, ..utm.clone() }, rustgis_map::Projection::WebMercator); + // (About 2 km across: 50 m apart, some 40 lines across the frame.) + let across = red_runs(&fine, 50.0).len(); + assert!((20..=55).contains(&across), "{across} lines across: not a red blur"); + // Its labels: eastings and northings, whole or short, a step apart. + let tr = rustgis_data::raster::Crs::parse("EPSG:25832").unwrap().transformer().unwrap(); + let frame: Vec = [(8.71, 47.49), (8.75, 47.49), (8.75, 47.51), (8.71, 47.51)].iter().map(|&(x, y)| Coord::new(x, y)).collect(); + let mut lines = Vec::new(); + measured_lines(&utm, &tr, &frame, false, &mut lines); + let eastings: Vec<&str> = lines.iter().filter(|l| l.2).map(|l| l.1.as_str()).collect(); + assert!(eastings.contains(&"479000") && eastings.contains(&"480000"), "{eastings:?}"); + assert!(lines.iter().filter(|l| !l.2).any(|l| l.1 == "5261000"), "{lines:?}"); + let mut short = Vec::new(); + measured_lines(&Grid { short: true, ..utm.clone() }, &tr, &frame, false, &mut short); + assert!(short.iter().any(|l| l.2 && l.1 == "79") && short.iter().any(|l| !l.2 && l.1 == "61")); + // MGRS labels: an interval picked for the frame is at most 100 km, a square's side. + let country: Vec = [(3.0, 43.0), (15.0, 43.0), (15.0, 52.0), (3.0, 52.0)].iter().map(|&(x, y)| Coord::new(x, y)).collect(); + let tr32 = rustgis_data::raster::Crs::from_epsg(32632).unwrap().transformer().unwrap(); + let step_of = |g: &Grid| { + let mut l = Vec::new(); + measured_lines(g, &tr32, &country, false, &mut l); + let mut xs: Vec = l.iter().filter(|l| l.2).filter_map(|l| l.1.parse::().ok()).collect(); + xs.sort_by(f64::total_cmp); + xs.windows(2).map(|w| w[1] - w[0]).fold(f64::INFINITY, f64::min) + }; + let plain = Grid { step: 0.0, ..utm.clone() }; + assert_eq!(step_of(&plain), 200_000.0); + assert_eq!(step_of(&Grid { mgrs: true, ..plain }), 100_000.0); + // A frame of no extent draws none. + let mut none = Vec::new(); + measured_lines(&utm, &tr, &[], false, &mut none); + assert!(none.is_empty()); + assert_eq!((nice_step(2000.0, 1.0), nice_step(7000.0, 1.0), nice_step(1.0, 1.0)), (500.0, 1000.0, 1.0)); +} + +/// A measured grid labelled as MGRS names each 100 km square that shows, by its grid zone +/// designation and letters, where the label fits in it: one square over Winterthur at +/// 1:25,000, several at 1:2,000,000, each label in the square it names; in zone 32 only on a +/// frame across its edge with zone 33; both bands across the Equator; none on a frame too small +/// for a label. The grid is in UTM 32N for MGRS on a map in it, and in the frame's MGRS zone +/// (Norway's and Svalbard's exceptions kept) over LV95 or Web Mercator. +#[test] +fn mgrs_labels_name_the_100_km_squares() { + use rustgis_map::layout::{Grid, GridKind}; + let map = Map::new("m"); + let tr = rustgis_data::raster::Crs::from_epsg(32632).unwrap().transformer().unwrap(); + // (A label's size fixed, not measured: the fonts installed differ between machines.) + let size = |_: &str| (40.0_f32, 16.0_f32); + let view = |center: Coord, scale: f64, mm: f64| View { + width: mm * PT_PER_MM, + height: mm * PT_PER_MM, + pixels_per_point: 1.0, + camera: frame_camera(&map, center, scale, 0.0, 0.0), + sky: false, + }; + let at = |v: &View, x: f32, y: f32| map.to_lonlat(v.camera.to_map(f64::from(x), f64::from(y), v.width, v.height)).unwrap(); + let near = view(Coord::new(8.73, 47.5), 25_000.0, 80.0); + let one = mgrs_squares(&map, &near, None, 32, &tr, size); + assert_eq!(one.len(), 1, "{one:?}"); + assert_eq!(one[0].0, "32T MT"); + assert!((f64::from(one[0].1) - near.width / 2.0).abs() < 2.0 && (f64::from(one[0].2) - near.height / 2.0).abs() < 2.0); + let wide = view(Coord::new(8.73, 47.5), 2_000_000.0, 80.0); + let many = mgrs_squares(&map, &wide, None, 32, &tr, size); + assert!(many.len() >= 2, "{many:?}"); + for (text, x, y) in &many { + let named = rustgis_geom::to_mgrs(at(&wide, *x, *y), 0).unwrap().to_string(); + assert_eq!(&named, text); + } + // Across the edge with zone 33 at 12° E: only zone 32's squares, west of it. + let edge = view(Coord::new(11.0, 47.5), 2_000_000.0, 80.0); + let west = mgrs_squares(&map, &edge, None, 32, &tr, size); + assert!(!west.is_empty() && west.iter().all(|(t, x, y)| t.starts_with("32") && at(&edge, *x, *y).x < 12.0), "{west:?}"); + assert!(mgrs_squares(&map, &view(Coord::new(8.73, 47.5), 25_000.0, 15.0), None, 32, &tr, size).is_empty()); + // Across the Equator, a northern zone's grid names the southern squares too, as MGRS does. + let equator = view(Coord::new(9.0, 0.0), 2_000_000.0, 80.0); + let both = mgrs_squares(&map, &equator, None, 32, &tr, size); + for band in ["32N ", "32M "] { + assert!(both.iter().any(|(t, ..)| t.starts_with(band)), "{band}: {both:?}"); + } + for (text, x, y) in &both { + assert_eq!(&rustgis_geom::to_mgrs(at(&equator, *x, *y), 0).unwrap().to_string(), text); + } + // Its system: UTM 32N on a map in it or over LV95 (the frame's zone), the one named. + let g = Grid { kind: GridKind::Measured, mgrs: true, ..Grid::default() }; + let c = Coord::new(8.73, 47.5); + let on = |code: &str| { + let mut m = Map::new("m"); + m.projection = rustgis_map::Projection::Custom(code.into()); + m + }; + assert_eq!(measured_crs(&g, &on("EPSG:32632"), Coord::new(14.0, 47.5)).map(|c| c.epsg()), Some(32632)); + assert_eq!(measured_crs(&g, &on("EPSG:2056"), c).map(|c| c.epsg()), Some(32632)); + assert_eq!(measured_crs(&g, &map, c).map(|c| c.epsg()), Some(32632)); + // MGRS's zone at the centre: Bergen's 32V, Svalbard's 33X; a plain measured grid's 6° one. + assert_eq!(measured_crs(&g, &map, Coord::new(5.3, 60.4)).map(|c| c.epsg()), Some(32632)); + assert_eq!(measured_crs(&g, &map, Coord::new(10.0, 78.0)).map(|c| c.epsg()), Some(32633)); + assert_eq!(measured_crs(&g, &map, Coord::new(9.0, -1.0)).map(|c| c.epsg()), Some(32732)); + let plain = Grid { mgrs: false, ..g.clone() }; + assert_eq!(measured_crs(&plain, &map, Coord::new(5.3, 60.4)).map(|c| c.epsg()), Some(32631)); + let named = Grid { crs: Some("EPSG:32733".into()), ..g.clone() }; + assert_eq!(measured_crs(&named, &map, c).map(|c| c.epsg()), Some(32733)); + assert_eq!(measured_crs(&Grid { crs: Some("EPSG:2056".into()), ..g }, &map, c), None); +} + +#[test] +fn mgrs_labels_on_the_globe_name_the_squares_it_draws() { + // #2337: on a globe, a label names the square the globe draws under it, not the one the + // flat map would show at that place in the frame. + let mut map = Map::new("m"); + map.set_projection(rustgis_map::Projection::Globe); + let tr = rustgis_data::raster::Crs::from_epsg(32632).unwrap().transformer().unwrap(); + // Small labels at 1:20,000,000, where the globe's curve parts it from the flat map: the + // two agree at the middle of the frame and drift apart away from it. + let size = |_: &str| (6.0_f32, 4.0_f32); + let view = View { + width: 120.0 * PT_PER_MM, + height: 120.0 * PT_PER_MM, + pixels_per_point: 1.0, + camera: frame_camera(&map, Coord::new(9.0, 47.5), 20_000_000.0, 0.0, 0.0), + sky: false, + }; + let globe = rustgis_map::globe::Globe::new(&view.camera, view.width, view.height); + // The square the globe draws at a label's place, if any. + let under = |x: f32, y: f32| globe.inverse(f64::from(x), f64::from(y)).and_then(|c| rustgis_geom::to_mgrs(c, 0)).map(|m| m.to_string()); + let squares = mgrs_squares(&map, &view, Some(&globe), 32, &tr, size); + assert!(squares.len() >= 2, "{squares:?}"); + for (text, x, y) in &squares { + assert_eq!(under(*x, *y).as_ref(), Some(text)); + } + // Through the flat camera, as before, some labels sit on another square of the globe. + let flat = mgrs_squares(&map, &view, None, 32, &tr, size); + assert!(flat.iter().any(|(text, x, y)| under(*x, *y).as_ref() != Some(text)), "{flat:?}"); +} + +#[test] +fn the_space_around_a_globe_is_free_in_its_coverage() { + // #2337: the light space a globe is drawn on leaves room for a layout's surrounds, as the + // blank basemap's white paper does (its ocean too, as open sea on a flat map); the + // atmosphere's glow at the globe's rim doesn't. Before, every cell was taken. + let mut map = Map::new("m"); + map.set_projection(rustgis_map::Projection::Globe); + // A globe about 64 mm across in a frame 100 mm square. + let (gw, gh, cells) = frame_coverage(&mut map, Coord::new(0.0, 0.0), 2e8, 100.0, 100.0, 50).unwrap(); + let cell = |x: u32, y: u32| cells[(y * gw + x) as usize]; + assert!(cells.iter().any(|c| *c), "the glow at the rim is drawn"); + for (x, y) in [(1, 1), (gw - 2, 1), (1, gh - 2), (gw - 2, gh - 2)] { + assert!(!cell(x, y), "the space at the corner ({x}, {y}) is free"); + } +} + +#[test] +fn a_measured_grid_on_the_globe_seen_whole_is_drawn() { + // #2337: with the whole globe inside the frame, no edge of it lands on the globe; the + // measured grid takes its bounds from the globe in the frame instead of drawing nothing. + use rustgis_map::layout::{Grid, GridKind}; + let mut m = Map::new("m"); + m.set_projection(rustgis_map::Projection::Globe); + let mut maps = vec![m]; + let mut l = Layout::new("Layout", 100.0, 100.0); + let grid = Grid { + kind: GridKind::Measured, + crs: Some("EPSG:32632".into()), + step: 0.0, + color: Rgba::rgb(0xFF, 0, 0), + labels: false, + width: 1.0, + ..Grid::default() + }; + l.add( + "Map", + (10.0, 10.0, 80.0, 80.0), + ElementKind::MapFrame { + map: "m".into(), + center: Coord::new(9.0, 45.0), + scale: 2e8, + shape: FrameShape::Rectangle, + grid: Some(grid), + extent_of: None, + extent_color: rustgis_map::layout::INDICATOR_COLOR, + extent_width: rustgis_map::layout::INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }, + ); + let pm = render(&l, &mut maps, 96.0, &PageInfo::default()).unwrap(); + assert!(count(&pm, (30.0, 30.0, 70.0, 70.0), red) > 20, "the measured grid's lines on the globe"); + assert_eq!(count(&pm, (11.0, 11.0, 20.0, 20.0), red), 0, "none past the rim"); +} + +#[test] +fn a_grid_on_the_globe_is_drawn_on_it() { + // #2337: a frame of a map on the globe draws its graticule through the globe, not as a + // flat world around it: none of it beyond the globe's rim, in the frame's corners. + use rustgis_map::layout::Grid; + let mut m = Map::new("m"); + m.set_projection(rustgis_map::Projection::Globe); + let mut maps = vec![m]; + let mut l = Layout::new("Layout", 100.0, 100.0); + let grid = Grid { step: 30.0, color: Rgba::rgb(0xFF, 0, 0), labels: true, width: 1.0, ..Grid::default() }; + l.add( + "Map", + (10.0, 10.0, 80.0, 80.0), + ElementKind::MapFrame { + map: "m".into(), + center: Coord::new(0.0, 0.0), + // A globe about 64 mm across, in the middle of the 80 mm frame. + scale: 2e8, + shape: FrameShape::Rectangle, + grid: Some(grid), + extent_of: None, + extent_color: rustgis_map::layout::INDICATOR_COLOR, + extent_width: rustgis_map::layout::INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }, + ); + let pm = render(&l, &mut maps, 96.0, &PageInfo::default()).unwrap(); + assert!(count(&pm, (40.0, 40.0, 60.0, 60.0), red) > 50, "lines on the globe"); + // Neither lines nor labels (dark) past the rim: in the corners and along the edges. + let ink = |p: tiny_skia::PremultipliedColorU8| red(p) || (p.alpha() > 0 && p.red() < 120 && p.green() < 120 && p.blue() < 120); + let corners = [(11.0, 11.0, 20.0, 20.0), (80.0, 11.0, 89.0, 20.0), (11.0, 80.0, 20.0, 89.0), (80.0, 80.0, 89.0, 89.0)]; + let edges = [(25.0, 11.0, 75.0, 15.0), (25.0, 85.0, 75.0, 89.0), (11.0, 25.0, 15.0, 75.0), (85.0, 25.0, 89.0, 75.0)]; + for r in corners.into_iter().chain(edges) { + assert_eq!(count(&pm, r, ink), 0, "nothing past the rim at {r:?}"); + } +} + +#[test] +fn grids_draw_lines_ticks_or_both() { + use rustgis_map::layout::{Grid, GridStyle}; + let g = + |style| Grid { step: 30.0, color: Rgba::rgb(0xFF, 0, 0), labels: false, style, tick_length: 4.0, width: 1.0, ..Grid::default() }; + let inner = (25.0, 25.0, 75.0, 75.0); + let rim = (10.0, 10.0, 90.0, 13.0); + let lines = grid_page(g(GridStyle::Lines)); + let ticks = grid_page(g(GridStyle::Ticks)); + let both = grid_page(g(GridStyle::LinesAndTicks)); + // Ticks only: nothing across the middle of the frame, but marks along its edge. + assert!(count(&lines, inner, red) > 100, "lines cross the frame"); + assert_eq!(count(&ticks, inner, red), 0, "ticks stay at the edges"); + assert!(count(&ticks, rim, red) > 10, "ticks along the top edge"); + // Lines and ticks: the lines, with the ticks' extra width along the edge. + assert!(count(&both, inner, red) > 100); + assert!(count(&both, rim, red) > count(&lines, rim, red), "ticks thicken the lines at the edge"); + // The line width is the grid's. + let thick = grid_page(Grid { width: 3.0, ..g(GridStyle::Lines) }); + assert!(count(&thick, inner, red) > 2 * count(&lines, inner, red)); +} + +#[test] +fn grid_labels_go_on_the_edges_picked() { + use rustgis_map::layout::{Grid, GridEdges}; + let g = |edges, label_orientation| Grid { step: 30.0, color: Rgba::new(0, 0, 0, 0), edges, label_orientation, ..Grid::default() }; + let (top, bottom) = ((20.0, 10.0, 80.0, 16.0), (20.0, 84.0, 80.0, 90.0)); + let (left, right) = ((10.0, 20.0, 18.0, 80.0), (82.0, 20.0, 90.0, 80.0)); + let default = grid_page(g(GridEdges::default(), Orientation::Horizontal)); + assert!(count(&default, bottom, ink) > 0 && count(&default, left, ink) > 0, "bottom and left by default"); + assert_eq!(count(&default, top, ink) + count(&default, right, ink), 0); + let flipped = grid_page(g(GridEdges { top: true, bottom: false, left: false, right: true }, Orientation::Horizontal)); + assert!(count(&flipped, top, ink) > 0 && count(&flipped, right, ink) > 0, "top and right when picked"); + assert_eq!(count(&flipped, bottom, ink) + count(&flipped, left, ink), 0); + // Vertical side labels run along the edge: narrower across it than horizontal ones. + // Columns with any text in them, inside the frame's left edge; antialiased text counts + // too, as a thin system font (Windows) may leave no pixel of a stem fully dark. + let across = |pm: &Pixmap| { + let px = |mm: f64| (mm * PT_PER_MM) as u32; + let shaded = |p: tiny_skia::PremultipliedColorU8| p.red() < 200 && p.green() < 200 && p.blue() < 200; + (px(11.0)..px(30.0)).filter(|&x| (px(20.0)..px(80.0)).any(|y| pm.pixel(x, y).is_some_and(shaded))).count() + }; + let horizontal = grid_page(g(GridEdges { top: false, bottom: false, left: true, right: false }, Orientation::Horizontal)); + let vertical = grid_page(g(GridEdges { top: false, bottom: false, left: true, right: false }, Orientation::Vertical)); + assert!(count(&vertical, left, ink) > 0); + assert!(across(&vertical) < across(&horizontal), "{} columns, against {}", across(&vertical), across(&horizontal)); +} + +/// A grid's labels at its label size (#2581): at 16 points each is twice as tall as at the +/// default 8 and sits twice as far in from the edge past the ticks; at 8 they are where they +/// always were; out of range they are drawn in range. +#[test] +fn a_grids_labels_take_its_label_size() { + use rustgis_map::layout::Grid; + let (fw, fh, ppp) = (80.0 * PT_PER_MM, 80.0 * PT_PER_MM, 2.0); + let map = Map::new("m"); + let view = + View { width: fw, height: fh, pixels_per_point: ppp, camera: frame_camera(&map, Coord::new(0.0, 0.0), 2e8, 0.0, 0.0), sky: false }; + let labels = |label_size: f64| { + let mut pm = Canvas::from_pixmap(Pixmap::new((fw * ppp) as u32, (fh * ppp) as u32).unwrap()); + let g = Grid { step: 30.0, tick_length: 0.0, label_size, ..Grid::default() }; + draw_grid(&mut pm, &map, &view, &g, false) + }; + let (small, big) = (labels(GRID_LABEL_PT), labels(16.0)); + let bottom = |drawn: &[(Edge, [f32; 4])]| drawn.iter().find(|(e, _)| *e == Edge::Bottom).map(|(_, r)| *r).unwrap(); + let (s, b) = (bottom(&small), bottom(&big)); + assert!(((b[3] - b[1]) - 2.0 * (s[3] - s[1])).abs() < 1e-3, "{b:?} against {s:?}"); + let gap = |r: [f32; 4]| fh as f32 - r[3]; + assert!(gap(b) > gap(s), "farther in from the edge: {} against {}", gap(b), gap(s)); + // The default: 8 points, 1.33 pixels a point, 3 points past the ticks, its halo 1.2 lines. + assert!(((s[3] - s[1]) - 8.0 * 1.33 * 1.2).abs() < 1e-3, "{s:?}"); + assert_eq!(labels(1e9), labels(100.0)); + assert_eq!(labels(f64::NAN), small); +} + +/// A tile layer's credit on a frame with a labelled grid (#1767): in the bottom-right corner, +/// where it was drawn, it runs over the bottom labels; the frame moves it clear of every label, +/// whichever edges carry them and however the side ones run, and leaves the labels as the grid +/// drew them. +#[test] +fn a_frames_attribution_keeps_clear_of_its_grid_labels() { + use rustgis_map::layout::{Grid, GridEdges}; + let (fw, fh, ppp) = (80.0 * PT_PER_MM, 80.0 * PT_PER_MM, 2.0); + let map = Map::new("m"); + let view = + View { width: fw, height: fh, pixels_per_point: ppp, camera: frame_camera(&map, Coord::new(0.0, 0.0), 2e8, 0.0, 0.0), sky: false }; + let credit = vec!["© OpenStreetMap contributors".to_string()]; + let white = || { + let mut pm = Pixmap::new((fw * ppp) as u32, (fh * ppp) as u32).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + pm + }; + // Whether each pixel is darkened by text, antialiased edges included. + let shaded = |pm: &Pixmap| pm.pixels().iter().map(|p| p.red() < 200 && p.green() < 200 && p.blue() < 200).collect::>(); + let grid = |edges, label_orientation| Grid { step: 30.0, color: Rgba::new(0, 0, 0, 0), edges, label_orientation, ..Grid::default() }; + // The grid's labels and the credit, each on its own frame (the credit `inset` from the + // corner, else where the frame puts it); the pixels both darken. + let overlap = |g: &Grid, credit: &[String], inset: Option<(f32, f32)>| { + let mut labels_pm = Canvas::from_pixmap(white()); + let labels = draw_grid(&mut labels_pm, &map, &view, g, false); + assert!(!labels.is_empty()); + let (w, h) = (fw as f32, fh as f32); + let tw = crate::attribution_text(credit).unwrap().1; + let inset = inset.unwrap_or_else(|| attribution_inset((w, h), tw, &labels)); + let mut credit_pm = Canvas::from_pixmap(white()); + crate::draw_attribution(&mut credit_pm, credit, ppp as f32, inset); + shaded(labels_pm.pixmap()).iter().zip(shaded(credit_pm.pixmap())).filter(|(a, b)| **a && *b).count() + }; + let default = grid(GridEdges::default(), Orientation::Horizontal); + assert!(overlap(&default, &credit, Some((0.0, 0.0))) > 20, "in the corner, the credit runs over the bottom labels"); + for (bottom, right) in [(true, false), (true, true), (false, true)] { + for orientation in [Orientation::Horizontal, Orientation::Vertical] { + let g = grid(GridEdges { top: true, bottom, left: true, right }, orientation); + assert_eq!(overlap(&g, &credit, None), 0, "bottom {bottom}, right {right}, {orientation:?}"); + } + } + // A credit wider than the frame (several layers' credits, a narrow frame) runs past both + // edges; it keeps clear of the bottom and right labels all the same. + let long = vec![ + "© OpenStreetMap contributors".to_string(), + "MapBiomas, sistemas de irrigação (CC BY 4.0)".to_string(), + "Instituto Brasileiro de Geografia e Estatística".to_string(), + ]; + assert!(crate::attribution_text(&long).unwrap().1 > fw as f32); + for (bottom, right) in [(true, true), (false, true)] { + for orientation in [Orientation::Horizontal, Orientation::Vertical] { + let g = grid(GridEdges { top: false, bottom, left: false, right }, orientation); + assert_eq!(overlap(&g, &long, None), 0, "long credit: bottom {bottom}, right {right}, {orientation:?}"); + } + } + // Drawn with the frame's map: the labels' pixels are the grid's alone. + let mut labels_pm = Canvas::from_pixmap(white()); + let all = grid(GridEdges { top: false, bottom: true, left: false, right: true }, Orientation::Horizontal); + let labels = draw_grid(&mut labels_pm, &map, &view, &all, false); + let img = crate::Rendered { + pixmap: white(), + labels: Vec::new(), + unplaced: Vec::new(), + attribution: credit.clone(), + tiles_pending: false, + data_pending: false, + tile_errors: Vec::new(), + partial: Vec::new(), + pending_in_place: Vec::new(), + recorded: None, + label_layers: Vec::new(), + }; + let framed = finish_frame(img, ppp, Some((&map, &view, &all, false))); + let (a, b) = (labels_pm.pixmap(), framed.pixmap()); + assert_ne!(a.data(), b.data(), "the credit is drawn"); + for (_, [x0, y0, x1, y1]) in &labels { + let px = |v: f32| (v * ppp as f32) as u32; + for (x, y) in (px(*y0)..px(*y1)).flat_map(|y| (px(*x0)..px(*x1)).map(move |x| (x, y))) { + assert_eq!(a.pixel(x, y), b.pixel(x, y), "({x}, {y})"); + } + } +} + +/// The credit stays in the corner with nothing under it, goes up above a bottom label and left +/// of a right one (above it, when going left would take it out of the frame), and pays no heed +/// to the top and left labels. +#[test] +fn attribution_inset_steps_round_the_labels_in_its_way() { + let (size, tw) = ((200.0, 100.0), 60.0); + assert_eq!(attribution_inset(size, tw, &[]), (0.0, 0.0)); + // A bottom label under the credit, another left of it. + let under = [(Edge::Bottom, [150.0, 88.0, 170.0, 98.0]), (Edge::Bottom, [40.0, 88.0, 60.0, 98.0])]; + let (bottom, right) = attribution_inset(size, tw, &under); + assert_eq!(right, 0.0); + // The credit's foot (its centre plus half its height) sits 2 points over the label's top. + assert!((100.0 - bottom - crate::ATTRIBUTION_SIZE * 0.9 + crate::ATTRIBUTION_SIZE * 0.8 - 86.0).abs() < 1e-3, "{bottom}"); + // A right label beside it once it is up: it moves left of it too. + let both = [under[0], (Edge::Right, [180.0, 70.0, 197.0, 82.0])]; + let (b2, r2) = attribution_inset(size, tw, &both); + assert_eq!(b2, bottom); + assert!((200.0 - r2 - 4.0 - 178.0).abs() < 1e-3, "{r2}"); + // Labels on the other edges are not in its way. + let others = [(Edge::Left, [130.0, 88.0, 196.0, 98.0]), (Edge::Top, [130.0, 88.0, 196.0, 98.0])]; + assert_eq!(attribution_inset(size, tw, &others), (0.0, 0.0)); + // Left of a right label it would leave the frame (180 points from x = 16, a label at + // x = 163, it would start at x = -19): it goes above the label instead, still in the + // corner's column. + let side = [(Edge::Right, [163.0, 85.0, 197.0, 97.0])]; + let (b3, r3) = attribution_inset(size, 180.0, &side); + assert_eq!(r3, 0.0); + assert!((100.0 - b3 - crate::ATTRIBUTION_SIZE * 0.9 + crate::ATTRIBUTION_SIZE * 0.8 - 83.0).abs() < 1e-3, "{b3}"); + // No room above it either (a frame 20 points tall): as far left as the frame holds it, + // starting at its left edge. + let low = [(Edge::Right, [163.0, 3.0, 197.0, 15.0])]; + let (b4, r4) = attribution_inset((200.0, 20.0), 180.0, &low); + assert_eq!(b4, 0.0); + assert!((crate::attribution_center(200.0, 180.0, r4) - 90.0).abs() < 1e-3, "{r4}"); + // Wider than the frame: never left (it can't fit), above the label when there is room. + let (b5, r5) = attribution_inset(size, 300.0, &side); + assert_eq!((b5, r5), (b3, 0.0)); + let (b6, r6) = attribution_inset((200.0, 20.0), 300.0, &low); + assert_eq!((b6, r6), (0.0, 0.0), "it stays where it was drawn"); +} + +#[test] +fn north_arrow_styles_differ_and_take_their_colours() { + let draw = |style, fill| { + let mut pm = Pixmap::new(80, 120).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::canvas::with_canvas(&mut pm, |c| { + north_arrow(c, Rect::from_xywh(0.0, 0.0, 80.0, 120.0).unwrap(), style, fill, Rgba::rgb(0x22, 0x22, 0x22), 1.0, 0.0) + }); + pm + }; + let red_fill = Rgba::rgb(0xFF, 0, 0); + let all: Vec = ArrowStyle::ALL.iter().map(|&s| draw(s, red_fill)).collect(); + for (i, a) in all.iter().enumerate() { + let filled = (0..120).flat_map(|y| (0..80).map(move |x| (x, y))).filter(|&(x, y)| a.pixel(x, y).is_some_and(red)).count(); + assert!(filled > 50, "{:?} uses the fill colour", ArrowStyle::ALL[i]); + for b in &all[i + 1..] { + assert_ne!(a.data(), b.data(), "each style draws differently"); + } + } +} + +#[test] +fn a_north_arrow_turns_with_its_frame() { + // The mean position of the red arrowhead (its N and outline are dark), as an offset from + // the middle of an 80 × 120 arrow. + let lean = |bearing| { + let mut pm = Pixmap::new(80, 120).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 0.0, 80.0, 120.0).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| { + north_arrow(c, r, ArrowStyle::Triangle, Rgba::rgb(0xFF, 0, 0), Rgba::rgb(0x22, 0x22, 0x22), 1.0, bearing) + }); + let pts: Vec<(f64, f64)> = (0..120) + .flat_map(|y| (0..80).map(move |x| (x, y))) + .filter(|&(x, y)| pm.pixel(x, y).is_some_and(red)) + .map(|(x, y)| (f64::from(x), f64::from(y))) + .collect(); + let n = pts.len().max(1) as f64; + (pts.iter().map(|p| p.0).sum::() / n - 40.0, pts.iter().map(|p| p.1).sum::() / n - 60.0) + }; + // North up: the arrowhead's bulk (its base) lies below the middle, its tip above. + let (x, y) = lean(0.0); + assert!(x.abs() < 1.0 && y > 3.0, "{x}, {y}"); + // East up (the map turned 90°): north points left, so the base lies right of the middle. + let (x, y) = lean(90.0); + assert!(x > 3.0 && y.abs() < 1.0, "{x}, {y}"); + let (x, _) = lean(-90.0); + assert!(x < -3.0, "{x}"); +} + +/// A scale bar's default colour and fill. +const DEFAULT_COLORS: (Rgba, Rgba) = (Rgba::rgb(0x22, 0x22, 0x22), Rgba::rgb(0xFF, 0xFF, 0xFF)); + +/// A white `width` x 60 pixmap with `bar` drawn on it at 100 m of ground a point, a pixel a +/// point, with a decimal point, in the default colours. +fn draw_bar(bar: &BarOptions<'_>, width: u32) -> Pixmap { + let mut pm = Pixmap::new(width, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 0.0, width as f32, 60.0).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, bar, DEFAULT_COLORS, 1.0, false)); + pm +} + +/// Dark runs along row `y`. +fn dark_runs(pm: &Pixmap, y: u32) -> usize { + let dark: Vec = (0..pm.width()).map(|x| pm.pixel(x, y).is_some_and(ink)).collect(); + dark.windows(2).filter(|w| !w[0] && w[1]).count() + usize::from(dark.first() == Some(&true)) +} + +/// The first and last columns with anything but white on row `y`. +fn marked_span(pm: &Pixmap, y: u32) -> Option<(u32, u32)> { + let marked = |x: &u32| pm.pixel(*x, y).is_some_and(|p| p.red() < 200 || p.green() < 200 || p.blue() < 200); + let first = (0..pm.width()).find(marked)?; + let last = (0..pm.width()).rev().find(marked)?; + Some((first, last)) +} + +/// The rows holding ink. +fn bar_ink_rows(pm: &Pixmap) -> Vec { + (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| pm.pixel(x, y).is_some_and(ink))).collect() +} + +/// How much darker than white the pixels in rows `from..=to` are, summed. +fn darkness(pm: &Pixmap, from: u32, to: u32) -> u32 { + (from..=to) + .flat_map(|y| (0..pm.width()).map(move |x| (x, y))) + .filter_map(|(x, y)| pm.pixel(x, y)) + .map(|p| 255 - u32::from(p.red())) + .sum() +} + +/// 64-bit FNV-1a over the pixmaps' bytes. +#[cfg(not(target_arch = "wasm32"))] +fn fnv(pms: &[Pixmap]) -> u64 { + pms.iter().flat_map(|p| p.data().iter()).fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) +} + +/// 64-bit FNV-1a over one byte slice. +#[cfg(not(target_arch = "wasm32"))] +fn fnv_bytes(b: &[u8]) -> u64 { + b.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) +} + +/// A plain scale bar on a white `w` x 60 pixmap, in the default colours. +#[cfg(not(target_arch = "wasm32"))] +fn draw_default(style: ScaleBarStyle, units: ScaleUnits, divisions: usize, ground: f64, w: u32, ppp: f64, comma: bool) -> Pixmap { + let mut pm = Pixmap::new(w, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 0.0, w as f32, 60.0).unwrap(); + let bar = BarOptions { units, divisions, style, ..BarOptions::default() }; + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, ground, &bar, DEFAULT_COLORS, ppp, comma)); + pm +} + +/// How [`plain_texts_draw_as_before`]'s pages drew, and what their cut-off check found, before +/// texts had a block alignment, line spacing or case; in the built-in face. +#[cfg(not(target_arch = "wasm32"))] +const PINNED_TEXT_PIXELS: u64 = 0x0556_a0ef_54c0_2e87; +#[cfg(not(target_arch = "wasm32"))] +const PINNED_TEXT_LOSSES: u64 = 0x26af_01ce_67e5_7cfd; + +/// A text with none of the block settings draws, and is measured for lines that don't fit and ink +/// off the page, exactly as main did: every page at 96 dpi, and the first eight (left-aligned, +/// unwrapped, upright and turned a quarter) at 300 dpi too, which is enough to hold the scaling +/// of the line pitch. In a process of its own, told to use the built-in face before any text. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn plain_texts_draw_as_before() { + if std::env::var_os("RUSTGIS_TEXT_PIN_CHILD").is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "layout::tests::plain_texts_draw_as_before", "--nocapture"]) + .env("RUSTGIS_TEXT_PIN_CHILD", "1") + .env("RUSTGIS_BUILTIN_FONTS", "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"), "the test didn't run in the child process"); + return; + } + let info = PageInfo { page: 2, pages: 3, page_name: String::new() }; + let (mut drawn, mut measured) = (Vec::new(), String::new()); + for (i, l) in crate::layout::plain_text_pages().iter().enumerate() { + for dpi in if i < 8 { &[96.0, 300.0][..] } else { &[96.0][..] } { + drawn.push(render(l, &mut [], *dpi, &info).unwrap()); + measured.push_str(&format!("{:?}\n", text_losses(l, &[], *dpi, &info))); + } + } + // The pages exercise both checks. + assert!(measured.contains("below_box: true") && measured.contains("off_page: true"), "{measured}"); + let losses = fnv_bytes(measured.as_bytes()); + assert_eq!((fnv(&drawn), losses), (PINNED_TEXT_PIXELS, PINNED_TEXT_LOSSES), "{:#x} {:#x}", fnv(&drawn), losses); +} + +/// How [`scale_bars_without_details_draw_as_before`]'s bars drew before scale bars had details, +/// their labels in the built-in face. +#[cfg(not(target_arch = "wasm32"))] +const PINNED: u64 = 0x3975_8d68_da45_882b; + +/// A bar with none of the details draws exactly as main drew it: every style, unit, division +/// count, ground resolution, density and decimal mark. Its labels are drawn in the built-in +/// face, whatever fonts the machine has: in a process of its own, told so before any text. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn scale_bars_without_details_draw_as_before() { + if std::env::var_os("RUSTGIS_SCALE_BAR_PIN_CHILD").is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "layout::tests::scale_bars_without_details_draw_as_before", "--nocapture"]) + .env("RUSTGIS_SCALE_BAR_PIN_CHILD", "1") + .env("RUSTGIS_BUILTIN_FONTS", "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"), "the test didn't run in the child process"); + return; + } + let mut drawn = Vec::new(); + for style in ScaleBarStyle::ALL { + for units in [ScaleUnits::Auto, ScaleUnits::Miles, ScaleUnits::Feet, ScaleUnits::Meters] { + for divisions in [1, 4, 10] { + for ground in [0.37, 100.0, 7.84] { + for (w, ppp) in [(93u32, 1.0), (300, 1.0), (300, 300.0 / 72.0)] { + for comma in [false, true] { + drawn.push(draw_default(style, units, divisions, ground, w, ppp, comma)); + } + } + } + } + } + } + assert_eq!(fnv(&drawn), PINNED, "{:#x}", fnv(&drawn)); +} + +#[test] +fn scale_bars_count_in_their_units_and_divisions() { + // 100 m of ground per point: about 25 km across the bar. + let draw = |(units, divisions, style)| draw_bar(&BarOptions { units, divisions, style, ..BarOptions::default() }, 300); + // Dark runs along the bar's middle row: one per dark division of an alternating bar. + let runs = |pm: &Pixmap| { + let y = (60.0 * 0.62) as u32; + let dark: Vec = (0..pm.width()).map(|x| pm.pixel(x, y).is_some_and(ink)).collect(); + dark.windows(2).filter(|w| !w[0] && w[1]).count() + usize::from(dark.first() == Some(&true)) + }; + let four = draw((ScaleUnits::Auto, 4, ScaleBarStyle::Alternating)); + let five = draw((ScaleUnits::Auto, 5, ScaleBarStyle::Alternating)); + assert_eq!(runs(&four), 2, "two dark divisions"); + assert_eq!(runs(&five), 3, "three dark divisions, the last at the end"); + // Miles and kilometres give bars of different lengths and labels. + assert_ne!(draw((ScaleUnits::Miles, 4, ScaleBarStyle::Alternating)).data(), four.data()); + // A line or a stepped line fills no division. + for style in [ScaleBarStyle::Line, ScaleBarStyle::Stepped] { + let pm = draw((ScaleUnits::Auto, 4, style)); + let dark = (0..300).filter(|&x| pm.pixel(x, 37).is_some_and(ink)).count(); + assert!(dark < 20, "{style:?}: {dark} dark pixels across the bar"); + assert_ne!(pm.data(), four.data()); + } + let with = |f: &dyn Fn(&mut BarOptions<'static>)| { + let mut b = BarOptions::default(); + f(&mut b); + draw_bar(&b, 300) + }; + let runs = |pm: &Pixmap| dark_runs(pm, 37); + assert_eq!(runs(&with(&|_| {})), 2); + // The first division cut in four alternating parts from zero, the first dark, and the + // divisions after going on from them: parts 0 and 2, then divisions 1 and 3. + assert_eq!(runs(&with(&|b| b.subdivisions = 4)), 4); + assert_eq!(with(&|b| b.subdivisions = 1).data(), with(&|_| {}).data(), "one part is the division whole"); + // A stepped bar's upper steps are the alternating bar's dark divisions, after the cut one too: + // its thin line, drawn soft, marks the bar's top row. + let cut4 = |style| { + let bar = BarOptions { style, subdivisions: 4, ..BarOptions::default() }; + let placed = bar_layout(Rect::from_xywh(0.0, 0.0, 300.0, 60.0).unwrap(), 100.0, &bar, 1.0, false).unwrap(); + (draw_bar(&bar, 300), placed) + }; + let (alternating, placed) = cut4(ScaleBarStyle::Alternating); + let (stepped, _) = cut4(ScaleBarStyle::Stepped); + let seg = placed.len / placed.divs as f32; + let top = placed.y0.round() as u32; + let mid = |j: usize| (placed.x0 + seg * (j as f32 + 0.5)) as u32; + let dark: Vec = (placed.before + 1..placed.divs).map(|j| alternating.pixel(mid(j), 37).is_some_and(ink)).collect(); + let upper: Vec = (placed.before + 1..placed.divs) + .map(|j| (top - 1..=top + 1).any(|y| stepped.pixel(mid(j), y).is_some_and(|p| p.red() < 200))) + .collect(); + assert_eq!(dark, [true, false, true], "divisions 1 and 3 dark"); + assert_eq!(upper, dark, "the stepped bar's upper steps"); + // Two whole divisions before zero: six divisions, three dark. + assert_eq!(runs(&with(&|b| b.divisions_before_zero = 2)), 3); + assert_eq!(bar_ink_rows(&with(&|b| b.divisions_before_zero = 2)), bar_ink_rows(&with(&|_| {})), "the same rows, bar and labels"); + // Across zero the light division before it meets a dark part: the bar's first ink is at + // zero, as on the same bar uncut, with the light division left of it. + let first_ink = |pm: &Pixmap| (0..pm.width()).find(|&x| pm.pixel(x, 37).is_some_and(ink)); + let uncut = with(&|b| b.divisions_before_zero = 1); + let cut = with(&|b| { + b.divisions_before_zero = 1; + b.subdivisions = 4; + }); + let zero = first_ink(&uncut).unwrap(); + assert!(zero > 20, "a division before zero: {zero}"); + assert_eq!(first_ink(&cut), Some(zero), "dark right of zero"); + assert!(cut.pixel(zero + 1, 37).is_some_and(ink) && !cut.pixel(zero - 2, 37).is_some_and(ink), "dark right of zero, light left"); + // A single or stepped line gets short ticks inside its first division. + for style in [ScaleBarStyle::Line, ScaleBarStyle::Stepped] { + let plain = with(&|b| b.style = style); + let cut = with(&|b| { + b.style = style; + b.subdivisions = 3; + }); + assert!(darkness(&cut, 35, 39) > darkness(&plain, 35, 39) + 100, "{style:?}"); + } +} + +/// A bar whose first negative label leaves it no room still draws: the label takes at most +/// half the bar's room, reaching left of the box past that. +#[test] +fn a_scale_bar_before_zero_draws_where_its_first_label_leaves_no_room() { + let bar = BarOptions { text_size: 24.0, divisions_before_zero: 2, divisions: 10, ..BarOptions::default() }; + let mut pm = Pixmap::new(40, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 0.0, 40.0, 60.0).unwrap(); + // Filled in its colour throughout, so along its middle the bar is one solid run. + let solid = (DEFAULT_COLORS.0, DEFAULT_COLORS.0); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, &bar, solid, 1.0, false)); + // Moved down so its big labels reach no higher than the box's top, the bar is drawn under + // them: along its middle row, one solid run, half the bar's room at least (34 px, the 1 km + // that fits in 17), not a sliver. + let placed = bar_layout(r, 100.0, &bar, 1.0, false).unwrap(); + let middle = (placed.y0 + placed.bar_h / 2.0) as u32; + assert!(placed.y0 > 30.0, "moved down: {}", placed.y0); + assert!(dark_runs(&pm, middle) > 0, "the bar is drawn"); + let (a, b) = marked_span(&pm, middle).unwrap(); + assert!(b - a >= 8, "the bar keeps half its room: {a}..{b}"); +} + +#[test] +fn scale_bars_fit_their_box_by_the_strategy() { + // 79 px to use at 100 m a point: 7.9 km of ground, in kilometres. + let width = |fit| { + let bar = BarOptions { units: ScaleUnits::Kilometers, fit, ..BarOptions::default() }; + let (a, b) = marked_span(&draw_bar(&bar, 93), 37).unwrap(); + b - a + }; + assert!((width(ScaleBarFit::AdjustDivisionValue) as i32 - 50).abs() <= 2, "a round 5 km in four 1.25 km divisions"); + assert!((width(ScaleBarFit::AdjustDivision) as i32 - 70).abs() <= 2, "seven round 1 km divisions"); + assert!((width(ScaleBarFit::AdjustWidth) as i32 - 40).abs() <= 2, "four 1 km divisions, narrower than the box"); + // Ten asked: fifteen 0.5 km divisions would fit, so the division steps up to 1 km, seven. + let bar = BarOptions { units: ScaleUnits::Kilometers, fit: ScaleBarFit::AdjustDivision, divisions: 10, ..BarOptions::default() }; + let (a, b) = marked_span(&draw_bar(&bar, 93), 37).unwrap(); + assert!(((b - a) as i32 - 70).abs() <= 2, "seven 1 km divisions, not ten of 0.5 km: {}", b - a); + // Extreme grounds, every fit, divisions before zero: never past the box, never empty. + for ground in [1e-4, 0.37, 100.0, 1e5, 1e7] { + for fit in ScaleBarFit::ALL { + for before in [0, 2] { + let bar = BarOptions { fit, divisions_before_zero: before, divisions: 10, ..BarOptions::default() }; + let mut pm = Pixmap::new(120, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(10.0, 0.0, 100.0, 60.0).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, ground, &bar, DEFAULT_COLORS, 1.0, false)); + let (a, b) = marked_span(&pm, 37).unwrap_or((0, 0)); + assert!(b > a && b < 110, "{ground} {fit:?} {before}: {a}..{b}"); + } + } + } + // Two divisions before zero count toward the ten: in a wide room, ten in all, never twelve. + let bar = + BarOptions { units: ScaleUnits::Kilometers, fit: ScaleBarFit::AdjustDivision, divisions_before_zero: 2, ..BarOptions::default() }; + let mut most = 0; + for w in (300..1400).step_by(23) { + let b = bar_layout(Rect::from_xywh(0.0, 0.0, w as f32, 60.0).unwrap(), 100.0, &bar, 1.0, false).unwrap(); + assert!(b.divs <= rustgis_map::layout::MAX_SCALE_DIVISIONS && b.before == 2, "{w} px: {} divisions", b.divs); + let pm = draw_bar(&bar, w); + let middle = (b.y0 + b.bar_h / 2.0) as u32; + // An alternating bar's dark divisions: half of them, the first before zero dark. + assert_eq!(dark_runs(&pm, middle), b.divs.div_ceil(2), "{w} px"); + let (a, z) = marked_span(&pm, middle).unwrap(); + assert!(((z - a) as f32 - b.len).abs() <= 2.0, "{w} px: {a}..{z} for {}", b.len); + most = most.max(b.divs); + } + assert_eq!(most, rustgis_map::layout::MAX_SCALE_DIVISIONS, "a wide room reaches ten"); + // Ten asked and two before zero: ten in all under every fit, not twelve. + for fit in ScaleBarFit::ALL { + let bar = BarOptions { fit, divisions: 10, divisions_before_zero: 2, ..BarOptions::default() }; + let b = bar_layout(Rect::from_xywh(0.0, 0.0, 300.0, 60.0).unwrap(), 100.0, &bar, 1.0, false).unwrap(); + assert!(b.divs <= rustgis_map::layout::MAX_SCALE_DIVISIONS, "{fit:?}: {} divisions", b.divs); + let middle = (b.y0 + b.bar_h / 2.0) as u32; + assert!(dark_runs(&draw_bar(&bar, 300), middle) <= 5, "{fit:?}: at most five dark of ten"); + } +} + +/// The narrowest element keeps its bar where an export rebuilds it from an f32 rectangle: near +/// an A2 sheet's right edge, at 300 and 600 dpi (#1379). +#[test] +fn a_scale_bar_keeps_its_bar_near_the_right_edge_at_print_density() { + // As an export places an element: page mm at `k` pixels a mm, `ppp` pixels a point. + let pt_per_mm = rustgis_map::layout::PT_PER_MM; + for i in 0..400 { + let ground = 10f64.powf(-1.0 + 4.0 * f64::from(i) / 400.0); + for widest_mm in [25.0, 63.0, 126.0] { + let w_pt = scale_bar_width_pt(ground, widest_mm * pt_per_mm, (ScaleUnits::Auto, 4, SCALE_BAR_TEXT_PT), false, 4.0).unwrap(); + let plan = bar_plan(ground, w_pt, ScaleUnits::Auto); + for (x_mm, dpi) in [(380.0, 300.0), (560.0, 300.0), (380.0, 600.0), (560.0, 600.0)] { + let k = dpi / 25.4; + let ppp = k / pt_per_mm; + let r = Rect::from_xywh((x_mm * k) as f32, 0.0, (w_pt / pt_per_mm * k) as f32, 10.0).unwrap(); + let drawn = bar_plan(ground, f64::from(r.width()) / ppp, ScaleUnits::Auto); + assert_eq!(drawn, plan, "{ground} m a point, {widest_mm} mm at most, x {x_mm} mm, {dpi} dpi"); + } + } + } +} + +/// The narrowest element for a scale bar draws the very bar a wider one does, labels and all, +/// within itself (#1379). +#[test] +fn a_scale_bar_draws_the_same_in_its_narrowest_element() { + let draw = |ground: f64, width: f32| { + let mut pm = Pixmap::new(320, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 0.0, width, 60.0).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, ground, &BarOptions::default(), DEFAULT_COLORS, 1.0, true)); + pm + }; + // 20 km on a bar of 300 points takes two thirds of it; 10 km at 37.2 m a point, a third. + for (ground, narrower_than) in [(100.0, 260.0), (37.2, 190.0), (78.4, 300.0)] { + let w = scale_bar_width_pt(ground, 300.0, (ScaleUnits::Auto, 4, SCALE_BAR_TEXT_PT), true, 4.0).unwrap(); + assert!(w < narrower_than, "{ground} m a point: {w} points"); + let (wide, narrow) = (draw(ground, 300.0), draw(ground, w as f32)); + assert_eq!(wide.data(), narrow.data(), "{ground} m a point: the same bar in {w} points"); + let past = (w.ceil() as u32..320).flat_map(|x| (0..60).map(move |y| (x, y))).filter(|&(x, y)| narrow.pixel(x, y).is_some_and(ink)); + assert_eq!(past.count(), 0, "{ground} m a point: nothing drawn past {w} points"); + } + assert_eq!(scale_bar_width_pt(0.0, 300.0, (ScaleUnits::Auto, 4, SCALE_BAR_TEXT_PT), false, 4.0), None); + // Miles count in other lengths: the box still draws the same bar. + let w = scale_bar_width_pt(100.0, 300.0, (ScaleUnits::Miles, 4, SCALE_BAR_TEXT_PT), false, 4.0).unwrap(); + assert!(w <= 300.0 && bar_plan(100.0, w, ScaleUnits::Miles) == bar_plan(100.0, 300.0, ScaleUnits::Miles)); +} + +#[test] +fn scale_bars_draw_in_their_colours() { + let mut pm = Pixmap::new(300, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + type Px = tiny_skia::PremultipliedColorU8; + // A red colour and a blue fill. + let colors = (Rgba::rgb(0xD0, 0x10, 0x10), Rgba::rgb(0x10, 0x10, 0xD0)); + let r = Rect::from_xywh(0.0, 0.0, 300.0, 60.0).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, &BarOptions::default(), colors, 1.0, false)); + let count = |hit: fn(Px) -> bool, y: u32| (0..300).filter(|&x| pm.pixel(x, y).is_some_and(hit)).count(); + let y = (60.0 * 0.62) as u32; + // Along the bar: the dark divisions in the colour, the light ones in the fill, nothing in + // the old ink. + assert!(count(red, y) > 40, "red divisions"); + assert!(count(|p| p.blue() > 180 && p.red() < 90 && p.green() < 90, y) > 40, "blue divisions"); + assert_eq!(count(ink, y), 0, "no default ink left"); + // The labels above the bar are in the colour too. + let labels = (0..y.saturating_sub(8)).map(|row| count(|p| p.red() > 120 && p.green() < 90 && p.blue() < 90, row)).sum::(); + assert!(labels > 0, "red labels"); + assert_eq!((0..y.saturating_sub(8)).map(|row| count(ink, row)).sum::(), 0, "no ink labels"); +} + +/// A detailed scale bar's box (#1379) is the narrowest that draws the same bar with all it +/// has: its unit after the bar written in full, its label before zero, and nothing past the +/// box's side but its padding. A plain bar's is the one it always had. +#[test] +fn a_detailed_scale_bars_box_holds_all_it_draws() { + let mut bar = ElementKind::scale_bar(0); + if let ElementKind::ScaleBar { unit_label, unit_label_position, divisions_before_zero, .. } = &mut bar { + (*unit_label, *unit_label_position, *divisions_before_zero) = (Some("Kilometres".into()), UnitLabelPosition::AfterBar, 1); + } + let options = BarOptions::of(&bar).unwrap(); + let w = scale_bar_box_width_pt(100.0, 300.0, &bar, false, 4.0).unwrap(); + assert!(w < 300.0, "{w}"); + let at = |w: f64| bar_layout(Rect::from_xywh(0.0, 0.0, w as f32, 60.0).unwrap(), 100.0, &options, 1.0, false).unwrap(); + let (wide, narrow) = (at(300.0), at(w)); + assert_eq!((narrow.total, narrow.divs, narrow.len), (wide.total, wide.divs, wide.len), "the same bar"); + assert_eq!(narrow.unit.as_ref().map(|u| u.text.as_str()), Some("Kilometres"), "its unit in full"); + assert!(f64::from(narrow.right) + 4.0 <= w + 1e-6, "{} in {w}", narrow.right); + // A little narrower, it would draw another bar or cut what it writes. + let less = at(w * 0.98); + let cut = less.total != wide.total || less.unit.as_ref().map(|u| u.text.as_str()) != Some("Kilometres"); + assert!(cut || f64::from(less.right) + 4.0 > w * 0.98, "the narrowest"); + let plain = ElementKind::scale_bar(0); + assert_eq!( + scale_bar_box_width_pt(100.0, 300.0, &plain, false, 4.0), + scale_bar_width_pt(100.0, 300.0, (ScaleUnits::Auto, 4, SCALE_BAR_TEXT_PT), false, 4.0) + ); + assert_eq!(scale_bar_box_width_pt(0.0, 300.0, &bar, false, 4.0), None); +} + +/// A scale bar's labels at their text size (#2581): at 16 points their room over the bar and +/// between them is twice the default's and the bar keeps its length and height; 8 points draws +/// as the bar always did; the width a box needs counts its last label at that size. +#[test] +fn a_scale_bars_labels_take_its_text_size() { + let plain = |divisions: usize, text_size: f64| BarOptions { divisions, text_size, ..BarOptions::default() }; + let r = Rect::from_xywh(0.0, 0.0, 400.0, 80.0).unwrap(); + let at = |pt: f64| bar_layout(r, 100.0, &plain(4, pt), 1.0, false).unwrap(); + let (small, big) = (at(SCALE_BAR_TEXT_PT), at(16.0)); + assert_eq!((small.len, small.bar_h, small.y0), (big.len, big.bar_h, big.y0), "the bar keeps its size"); + assert!((big.px - 2.0 * small.px).abs() < 1e-3, "{} against {}", big.px, small.px); + // Its inset follows, and more: its first label reaches no further left than at 8 points, + // where its "0" pokes a little past the box's side. + let reach = |b: &BarLayout| b.x0 - text::measure(&b.labels[0].1, b.px / 1.33, false) / 2.0; + assert!(reach(&small) < 0.0, "{}", reach(&small)); + assert!(big.x0 >= 2.0 * BAR_INSET - 1e-3 && (reach(&big) - reach(&small)).abs() < 1e-3, "{} {}", big.x0, reach(&big)); + let over = |b: &BarLayout| b.y0 - b.label_y; + assert!((over(&big) - 2.0 * over(&small)).abs() < 1e-3, "its room over the bar follows"); + // The default draws the bar as before: an 8-point label 1.33 pixels a point, 2 pixels in. + assert_eq!((small.px, small.x0), (8.0 * 1.33, BAR_INSET)); + // Out of range or non-finite, as a program may hand it, it is drawn in range. + assert_eq!(at(1e9).px, at(100.0).px); + assert_eq!(at(f64::NAN).px, small.px); + // Labels that would touch at the larger size are left out, never the ends. + let crowded = bar_layout(Rect::from_xywh(0.0, 0.0, 120.0, 80.0).unwrap(), 100.0, &plain(10, 40.0), 1.0, false).unwrap(); + assert!(crowded.labels.len() < 11, "{} labels", crowded.labels.len()); + assert_eq!(crowded.labels.first().map(|l| l.1.as_str()), Some("0")); + // In a box 34 pixels tall (9 mm at a point a pixel), the default leaves room over its + // labels; at 14 points the bar moves down so they reach no higher than the box's top, and + // at 40 the box is too short for them and the bar, which is drawn below it. + let in_box = |h: f32, pt: f64| bar_layout(Rect::from_xywh(0.0, 0.0, 400.0, h).unwrap(), 100.0, &plain(4, pt), 1.0, false).unwrap(); + let rise = |b: &BarLayout| b.label_y - b.px * BAR_LABEL_RISE; + let (eight, fourteen, forty) = (in_box(34.0, 8.0), in_box(34.0, 14.0), in_box(34.0, 40.0)); + assert!((eight.y0 - (34.0 * 0.62 - eight.bar_h / 2.0)).abs() < 1e-4 && rise(&eight) > 0.0, "the default where it was"); + assert!(fourteen.y0 > eight.y0 && rise(&fourteen).abs() < 1e-3 && !fourteen.cramped, "moved down: {}", fourteen.y0); + assert!(forty.cramped && rise(&forty).abs() < 1e-3, "too short: the bar at {}", forty.y0); + assert!(!eight.cramped && !fourteen.cramped); + // Sideways, its last label at 40 points past a narrow box's right side, its bar the same + // length: too narrow, its box tall enough. At 8 points the same box holds it. + let narrow = |pt: f64| bar_layout(Rect::from_xywh(0.0, 0.0, 90.0, 400.0).unwrap(), 100.0, &plain(4, pt), 1.0, false).unwrap(); + let (n8, n40) = (narrow(8.0), narrow(40.0)); + assert!(!n8.cramped && n40.cramped && n40.y0 + n40.bar_h < 400.0 && n40.len == n8.len, "{} {}", n40.y0, n40.len); + // Its end label, always drawn as its first is, running into the first above the default + // size reaches past the box's side too: the box is too small, and said. + for pt in [9.0, 12.0, 20.0, 40.0, 100.0] { + for w in (20..400).step_by(7) { + let Some(b) = bar_layout(Rect::from_xywh(0.0, 0.0, w as f32, 400.0).unwrap(), 100.0, &plain(4, pt), 1.0, false) else { + continue; + }; + let half = |s: &str| text::measure(s, b.px / 1.33, false) / 2.0; + let ((fx, fs), (ex, es)) = (&b.labels[0], &b.labels[b.labels.len() - 1]); + let clash = b.labels.len() > 1 && ex - half(es) < fx + half(fs); + assert!(!clash || b.cramped, "{pt} pt in {w} px: its end label over its first, not said"); + } + } + // A publication's short box (17 pixels): the default reaches over it, as it always did, + // and a larger size reaches no higher. + let (short8, short12) = (in_box(17.0, 8.0), in_box(17.0, 12.0)); + assert!((short8.y0 - (17.0 * 0.62 - short8.bar_h / 2.0)).abs() < 1e-4 && rise(&short8) < 0.0); + assert!((rise(&short12) - rise(&short8)).abs() < 1e-3, "{} against {}", rise(&short12), rise(&short8)); + let width = |pt| scale_bar_width_pt(100.0, 300.0, (ScaleUnits::Auto, 4, pt), false, 4.0).unwrap(); + assert!(width(40.0) > width(SCALE_BAR_TEXT_PT), "{} against {}", width(40.0), width(SCALE_BAR_TEXT_PT)); +} + +/// A scale bar's labels that don't fit are reported as a text is, measured where they are +/// drawn (#2581): at 40 points a box too short for them and its bar, and a label past the +/// page's right edge. +#[test] +fn a_scale_bars_labels_off_the_page_are_reported() { + let maps = vec![Map::new("m")]; + let mut l = Layout::new("Page", 120.0, 90.0); + let frame = l.add( + "Frame", + (10.0, 30.0, 100.0, 50.0), + serde_json::from_value(serde_json::json!({"MapFrame":{"map":"m", "center":{"x":0,"y":0}, "scale":1000000}})).unwrap(), + ); + let bar = l.add("Scale Bar", (10.0, 0.0, 100.0, 12.0), ElementKind::scale_bar(frame)); + let info = PageInfo::default(); + assert!(clipped_text(&l, &maps, 96.0, &info).is_empty(), "8 points fit"); + if let Some(ElementKind::ScaleBar { text_size, .. }) = l.element_mut(bar).map(|e| &mut e.kind) { + *text_size = 40.0; + } + assert_eq!(clipped_text(&l, &maps, 96.0, &info), vec![(bar, "Scale Bar".into())]); + let note = clipped_text_notice(&l, &clipped_text(&l, &maps, 96.0, &info)).unwrap(); + assert!(note.ends_with("move it inside the page or make its box larger, or reduce its text size"), "{note}"); + let loss = text_loss(&l, &maps, 96.0, &info, bar).unwrap(); + assert!(loss.below_box && scale_bar_fit_notices(std::slice::from_ref(&loss))[0].contains("its box is too small"), "{loss:?}"); + // A tall box holds them at 20 points; off the page's right edge, its last label is cut. + l.element_mut(bar).unwrap().h = 60.0; + if let Some(ElementKind::ScaleBar { text_size, .. }) = l.element_mut(bar).map(|e| &mut e.kind) { + *text_size = 20.0; + } + assert!(clipped_text(&l, &maps, 96.0, &info).is_empty(), "a tall box holds them"); + l.element_mut(bar).unwrap().x = 60.0; + let loss = text_loss(&l, &maps, 96.0, &info, bar).unwrap(); + assert!( + !loss.below_box && loss.off_page && scale_bar_fit_notices(std::slice::from_ref(&loss))[0].contains("runs off the page"), + "{loss:?}" + ); + // Too small and off the page both: each said. + l.element_mut(bar).unwrap().h = 12.0; + if let Some(ElementKind::ScaleBar { text_size, .. }) = l.element_mut(bar).map(|e| &mut e.kind) { + *text_size = 40.0; + } + let both = text_loss(&l, &maps, 96.0, &info, bar).unwrap(); + let said = scale_bar_fit_notices(std::slice::from_ref(&both)); + assert!(both.below_box && both.off_page && said.len() == 2 && said[1].contains("runs off the page"), "{both:?} {said:?}"); + // Several bars are told in one notice a kind, their count and names. + let small = TextLoss { below_box: true, off_page: false, ..loss.clone() }; + let two = scale_bar_fit_notices(&[small.clone(), TextLoss { name: "B".into(), ..small.clone() }]); + assert!(two.len() == 1 && two[0].starts_with("2 scale bars (\"Scale Bar\", \"B\"): their boxes are too small"), "{two:?}"); + assert_eq!(scale_bar_fit_notices(&[small, loss]).len(), 2, "a notice a kind"); + // Drawn without ink, its labels show nothing and aren't measured, as a text's. + if let Some(ElementKind::ScaleBar { color, .. }) = l.element_mut(bar).map(|e| &mut e.kind) { + *color = Rgba::new(0, 0, 0, 0); + } + assert!(text_loss(&l, &maps, 96.0, &info, bar).is_none(), "a bar without ink"); + l.element_mut(bar).unwrap().visible = false; + assert!(clipped_text(&l, &maps, 96.0, &info).is_empty(), "a hidden bar draws nothing"); +} + +/// A 100 x 60 mm page with a 90 x 20 mm frame at its foot showing a map at 1:10,000,000: the +/// map, the page and the frame's id. +fn colour_test_page() -> (Vec, Layout, u32) { + let maps = vec![Map::new("m")]; + let mut l = Layout::new("Layout", 100.0, 60.0); + let frame = l.add( + "Map", + (5.0, 35.0, 90.0, 20.0), + ElementKind::MapFrame { + map: "m".into(), + center: Coord::new(0.0, 0.0), + scale: 10_000_000.0, + shape: FrameShape::Rectangle, + grid: None, + extent_of: None, + extent_color: rustgis_map::layout::INDICATOR_COLOR, + extent_width: rustgis_map::layout::INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }, + ); + (maps, l, frame) +} + +/// A page draws a scale bar in its own colour and fill: the element's, through `draw_page`. +#[test] +fn a_page_draws_its_scale_bar_in_its_colours() { + let (mut maps, mut l, frame) = colour_test_page(); + let (crimson, navy) = (Rgba::rgb(0xD0, 0x10, 0x10), Rgba::rgb(0x10, 0x10, 0xD0)); + let mut bar = ElementKind::scale_bar(frame); + if let ElementKind::ScaleBar { color, fill, .. } = &mut bar { + (*color, *fill) = (crimson, navy); + } + l.add("Scale Bar", (5.0, 5.0, 90.0, 20.0), bar); + let pm = render(&l, &mut maps, 96.0, &PageInfo::default()).unwrap(); + // Above the frame (30 mm of the page's 60): the bar's divisions in its colour and fill, and + // nothing in the default ink. + let above = pm.height() / 2; + let count = |hit: fn(tiny_skia::PremultipliedColorU8) -> bool| { + (0..above).flat_map(|y| (0..pm.width()).map(move |x| (x, y))).filter(|&(x, y)| pm.pixel(x, y).is_some_and(hit)).count() + }; + assert!(count(red) > 100, "red divisions and labels"); + assert!(count(|p| p.blue() > 180 && p.red() < 90 && p.green() < 90) > 100, "blue divisions"); + assert_eq!(count(ink), 0, "no default ink"); +} + +#[test] +fn scale_numbers_have_decimals_and_thousands() { + // Auto: as each label needs, with no separators, exactly as before. + assert_eq!(bar_number(5000.0, 1000.0, None, false), "5000"); + assert_eq!(bar_number(0.0125, 0.0125, None, false), "0.0125"); + assert_eq!(bar_number(-500.0, 500.0, None, false), "-500"); + assert_eq!(bar_number(2.5, 1.25, None, true), "2,5"); + // Fixed decimals with their thousands apart, the marks swapped under a decimal comma. + assert_eq!(bar_number(5000.0, 1000.0, Some(0), false), "5,000"); + assert_eq!(bar_number(5000.0, 1000.0, Some(0), true), "5.000"); + assert_eq!(bar_number(3.75, 1.25, Some(0), false), "4", "fixed at none, rounded"); + assert_eq!(bar_number(1250.0, 250.0, Some(2), false), "1,250.00"); + assert_eq!(bar_number(1250.0, 250.0, Some(2), true), "1.250,00"); + assert_eq!(bar_number(12500.0, 2500.0, Some(3), true), "12.500,000"); + assert_eq!(bar_number(-1500.0, 500.0, Some(1), true), "-1.500,0"); + assert_eq!(bar_number(0.0, 5.0, Some(2), false), "0.00"); + assert_eq!(bar_number(-0.001, 5.0, Some(1), false), "0.0", "no sign on a zero"); + assert_eq!(bar_number(f64::NAN, 1.0, Some(2), false), "0.00", "never a panic"); + assert_eq!(bar_number(1250.0, 250.0, Some(9), false), "1,250.000", "at most 3"); +} + +#[test] +fn scale_bars_draw_subdivisions_and_place_labels_above_or_below() { + let with = |f: &dyn Fn(&mut BarOptions<'static>)| { + let mut b = BarOptions::default(); + f(&mut b); + draw_bar(&b, 300) + }; + let above = with(&|_| {}); + let rows = bar_ink_rows(&above); + assert!(rows.iter().any(|&y| y < 32) && rows.iter().all(|&y| y < 42), "labels over the bar: {rows:?}"); + let below = with(&|b| b.label_position = ScaleLabelPosition::Below); + let rows = bar_ink_rows(&below); + assert!(rows.iter().all(|&y| y >= 18) && rows.iter().any(|&y| y > 28), "labels under it: {rows:?}"); + // Subdivisions aren't labelled: the first ink row stays where the labels put it. + let cut = with(&|b| b.subdivisions = 3); + assert_eq!(bar_ink_rows(&cut).first(), bar_ink_rows(&above).first()); + // A bigger label is taller; decimals change the labels. + assert!(bar_ink_rows(&with(&|b| b.text_size = 16.0)).len() > rows.len() + 4); + assert_ne!(with(&|b| b.decimals = Some(2)).data(), above.data()); + assert_ne!(with(&|b| b.divisions_before_zero = 1).data(), above.data()); +} + +#[test] +fn unit_labels_sit_after_the_bar_when_asked() { + let draw = |text: Option<&'static str>, at| { + draw_bar(&BarOptions { unit_label: text, unit_label_position: at, units: ScaleUnits::Kilometers, ..BarOptions::default() }, 300) + }; + let right_of = |pm: &Pixmap| (0..pm.height()).filter_map(|y| (0..pm.width()).rev().find(|&x| pm.pixel(x, y).is_some_and(ink))).max(); + let none = draw(Some(""), UnitLabelPosition::AfterBar); + let feet = draw(Some("Feet"), UnitLabelPosition::AfterBar); + let (_, bare_end) = marked_span(&none, 37).unwrap(); + let (_, word_end) = marked_span(&feet, 37).unwrap(); + assert!(word_end > bare_end + 15, "level with the bar, after it: {word_end} against {bare_end}"); + // Left out, the abbreviation follows the last label; "" prints none. + let default = draw(None, UnitLabelPosition::AfterLabels); + let blank = draw(Some(""), UnitLabelPosition::AfterLabels); + assert!(right_of(&default) > right_of(&blank)); + // Above or below, on a line of its own. + let top = |pm: &Pixmap| bar_ink_rows(pm).first().copied().unwrap_or(0); + let bottom = |pm: &Pixmap| bar_ink_rows(pm).last().copied().unwrap_or(0); + assert!(top(&draw(Some("Feet"), UnitLabelPosition::Above)) < top(&blank)); + assert!(bottom(&draw(Some("Feet"), UnitLabelPosition::Below)) > bottom(&blank)); + assert_ne!(draw(Some("FEET"), UnitLabelPosition::AfterBar).data(), feet.data(), "verbatim"); + // Other scripts and emoji draw without a panic. + for text in ["距離 km", "مسافة", "🚶"] { + for at in UnitLabelPosition::ALL { + let _ = draw(Some(text), at); + } + } + // A label of spaces prints nothing and takes no room: after the bar or on a line of its own. + assert_eq!(draw(Some(" "), UnitLabelPosition::AfterBar).data(), none.data()); + assert_eq!(draw(Some(" "), UnitLabelPosition::Above).data(), draw(Some(""), UnitLabelPosition::Above).data()); + // A 100-character unit stays inside a 93 px element wherever it is placed. + let long: String = "Kilometres ".repeat(10).chars().take(100).collect(); + let narrow = |text: &str, at| { + draw_bar( + &BarOptions { unit_label: Some(text), unit_label_position: at, units: ScaleUnits::Kilometers, ..BarOptions::default() }, + 93, + ) + }; + let marked = |p: tiny_skia::PremultipliedColorU8| p.red() < 200 || p.green() < 200 || p.blue() < 200; + for at in UnitLabelPosition::ALL { + let pm = narrow(&long, at); + let past: Vec<(u32, u32)> = (0..pm.height()) + .flat_map(|y| (92..pm.width()).map(move |x| (x, y))) + .filter(|&(x, y)| pm.pixel(x, y).is_some_and(marked)) + .collect(); + assert!(past.is_empty(), "{at:?}: ink past the element at {past:?}"); + assert_ne!(pm.data(), narrow("", at).data(), "{at:?}: the unit is drawn, shortened"); + } + // After the labels, the unit is shortened and the last label's number kept whole: the ink + // columns of the number drawn alone are all there, moved left with the label. + let columns = |pm: &Pixmap| -> Vec { (0..pm.width()).map(|x| (0..33).any(|y| pm.pixel(x, y).is_some_and(ink))).collect() }; + let bare = columns(&narrow("", UnitLabelPosition::AfterLabels)); + let long_cols = columns(&narrow(&long, UnitLabelPosition::AfterLabels)); + let end = bare.iter().rposition(|&c| c).unwrap(); + // The last number: back from its right edge to a 3 px gap. + let start = (0..end).rev().find(|&x| x >= 2 && !bare[x] && !bare[x - 1] && !bare[x - 2]).map_or(0, |x| x + 1); + let number = &bare[start..=end]; + let found = (0..=start).any(|d| long_cols[start - d..=end - d] == *number); + assert!(found, "the last number {start}..={end} is drawn whole: {long_cols:?}"); +} + +/// A long unit after the labels of a short bar, centred on its end, stays inside both edges of +/// the element, the last number drawn whole. +#[test] +fn a_unit_after_the_labels_of_a_short_bar_stays_inside_both_edges() { + let long = "k".repeat(100); + // 79 px to use at 250 m a point, 19.8 km: four 2 km divisions, a 32 px bar ending nearer + // the left edge than the right. + let draw = |unit: &str| { + let bar = + BarOptions { units: ScaleUnits::Kilometers, fit: ScaleBarFit::AdjustWidth, unit_label: Some(unit), ..BarOptions::default() }; + let mut pm = Pixmap::new(93, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 0.0, 93.0, 60.0).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 250.0, &bar, DEFAULT_COLORS, 1.0, false)); + pm + }; + let (pm, bare) = (draw(&long), draw("")); + // The first label, "0", reaches the left edge as on every bar: the long unit adds nothing + // there, nor anything at the right edge. + let at = |pm: &Pixmap, x: u32| (0..pm.height()).map(|y| pm.pixel(x, y).is_some_and(ink)).collect::>(); + assert_eq!(at(&pm, 0), at(&bare, 0), "nothing more at the left edge"); + assert!(at(&pm, 92).iter().all(|d| !d), "nothing at the right edge"); + // The last number: its ink columns (rows above the bar) drawn alone are all there. + let columns = |pm: &Pixmap| -> Vec { (0..pm.width()).map(|x| (0..33).any(|y| pm.pixel(x, y).is_some_and(ink))).collect() }; + let (bare, long_cols) = (columns(&bare), columns(&pm)); + let end = bare.iter().rposition(|&c| c).unwrap(); + let start = (0..end).rev().find(|&x| x >= 2 && !bare[x] && !bare[x - 1] && !bare[x - 2]).map_or(0, |x| x + 1); + let number = &bare[start..=end]; + let found = (0..=start).any(|d| long_cols[start - d..=end - d] == *number); + assert!(found, "the last number {start}..={end} is drawn whole: {long_cols:?}"); +} + +#[test] +fn a_wide_unit_label_after_the_bar_keeps_the_bar() { + let long = "Kilometres of ground distance, as measured on the map ".repeat(2); + for width in [12u32, 40, 93, 300] { + for height in [8u32, 60] { + let bar = BarOptions { + unit_label: Some(long.as_str()), + unit_label_position: UnitLabelPosition::AfterBar, + units: ScaleUnits::Kilometers, + ..BarOptions::default() + }; + let mut pm = Pixmap::new(width, height).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 0.0, width as f32, height as f32).unwrap(); + // Filled in its colour throughout, so along its middle the bar is one solid run. + let solid = (DEFAULT_COLORS.0, DEFAULT_COLORS.0); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, &bar, solid, 1.0, false)); + if width >= 40 && height == 60 { + let marked = |x: u32| pm.pixel(x, 37).is_some_and(|p| p.red() < 200 || p.green() < 200 || p.blue() < 200); + let a = (0..width).find(|&x| marked(x)).unwrap_or(width); + // The bar ends where the 3 px gap before its unit begins; the unit follows. + let gap = (a..width).find(|&x| (x..x + 3).all(|x| !marked(x))).unwrap_or(width); + let end = gap.saturating_sub(1); + let unit = (gap..width).find(|&x| marked(x)); + // Half the 85 % room is the bar's; its round length is at least 40 % of that. + let room = width as f32 * 0.85 * 0.5; + let (least, most) = ((room * 0.4) as u32 - 2, (room + 2.0) as u32); + assert!(end >= a + least && end <= a + most, "width {width}: the bar keeps half its room, {a}..{end}"); + // Shortened to the room kept for it, the unit stays inside the bar's room and + // the element; at 40 px it may not fit at all and is left out. + if width > 40 { + assert!(unit.is_some_and(|x| x >= end + 3), "width {width}: the unit after the bar, from {unit:?}"); + } + let inside = (BAR_INSET + width as f32 * 0.85 + 1.0).min(width as f32 - 1.0) as u32; + let past = (inside..width).find(|&x| marked(x)); + assert!(past.is_none(), "width {width}: the unit stays in the bar's room, ink at {past:?}"); + } + } + } +} + +#[test] +fn a_unit_label_after_the_bar_is_shortened_to_its_room() { + let measure = |s: &str| s.chars().count() as f32 * 10.0; + assert_eq!(shortened("Feet", 40.0, measure).as_deref(), Some("Feet")); + assert_eq!(shortened("Kilometres", 40.0, measure).as_deref(), Some("Kil…")); + assert_eq!(shortened("Kilo metres", 60.0, measure).as_deref(), Some("Kilo…"), "no space before the ellipsis"); + assert_eq!(shortened("Kilometres", 20.0, measure).as_deref(), Some("K…")); + assert_eq!(shortened("Kilometres", 19.0, measure), None, "nothing when not even a letter fits"); + assert_eq!(shortened("", -1.0, measure), None); + // A long unit takes a handful of measurements, not one a character. + let calls = std::cell::Cell::new(0); + let counted = |s: &str| { + calls.set(calls.get() + 1); + measure(s) + }; + let long = "k".repeat(100); + assert_eq!(shortened(&long, 105.0, counted).as_deref(), Some("kkkkkkkkk…")); + assert!(calls.get() <= 9, "{} measurements", calls.get()); + // After the last label, only the unit is shortened, never the number. + assert_eq!(last_label("25", "Kilometres", 130.0, measure), ("25 Kilometres".into(), None)); + assert_eq!(last_label("25", "Kilometres", 80.0, measure), ("25 Kilo…".into(), Some(UnitLabelCut::Shortened))); + assert_eq!( + last_label("25", "Kilometres", 40.0, measure), + ("25".into(), Some(UnitLabelCut::LeftOut)), + "the number alone when not a letter fits" + ); + assert_eq!(last_label("1,250", "km", 10.0, measure), ("1,250".into(), Some(UnitLabelCut::LeftOut)), "the number is never cut"); +} + +/// A unit label shortened with an ellipsis, or left out with no room for it, is said, as a cut +/// text is, wherever it is placed; one drawn whole, or a plain bar's abbreviation, is not. +#[test] +fn a_shortened_or_left_out_unit_label_is_said() { + let long = "Kilometres ".repeat(9); + let cut = |w: f32, unit: Option<&str>, unit_label_position| { + let bar = BarOptions { unit_label: unit, unit_label_position, units: ScaleUnits::Kilometers, ..BarOptions::default() }; + bar_layout(Rect::from_xywh(0.0, 0.0, w, 60.0).unwrap(), 100.0, &bar, 1.0, false).unwrap().unit_cut + }; + for at in UnitLabelPosition::ALL { + assert_eq!(cut(200.0, Some(&long), at), Some(UnitLabelCut::Shortened), "{at:?}"); + assert_eq!(cut(400.0, Some("Km"), at), None, "{at:?}: drawn whole"); + assert_eq!(cut(200.0, None, at), None, "{at:?}: the abbreviation"); + } + // Not even a letter of it fits after the bar's last label in a box this narrow. + assert_eq!(cut(20.0, Some(&long), UnitLabelPosition::AfterLabels), Some(UnitLabelCut::LeftOut)); + let loss = |name: &str, unit_label| TextLoss { + id: 1, + name: name.into(), + left_out: 0, + at_least: false, + below_box: false, + past_limit: false, + off_page: false, + unit_label, + }; + let said = scale_bar_fit_notices(&[loss("A", Some(UnitLabelCut::Shortened))]); + assert_eq!(said.len(), 1); + assert!(said[0].starts_with("Scale bar \"A\": its unit label is shortened to fit"), "{said:?}"); + let said = scale_bar_fit_notices(&[loss("A", Some(UnitLabelCut::LeftOut)), loss("B", Some(UnitLabelCut::LeftOut))]); + assert!(said.len() == 1 && said[0].starts_with("2 scale bars (\"A\", \"B\"): their unit labels are left out"), "{said:?}"); + assert!(scale_bar_fit_notices(&[loss("A", None)]).is_empty()); +} + +/// A bar whose lines just fit its box, so none is written smaller, still draws them all inside it. +#[test] +fn a_scale_bar_rows_stay_inside_a_box_they_just_fit() { + let bar = BarOptions { + unit_label: Some("Kilometres"), + unit_label_position: UnitLabelPosition::Above, + label_position: ScaleLabelPosition::Above, + text_size: 24.0, + units: ScaleUnits::Kilometers, + ..BarOptions::default() + }; + // The 93 x 88 box in the middle of a taller page, so ink outside it would show. + let mut pm = Pixmap::new(93, 128).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 20.0, 93.0, 88.0).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, &bar, DEFAULT_COLORS, 1.0, false)); + let marked = |p: tiny_skia::PremultipliedColorU8| p.red() < 200 || p.green() < 200 || p.blue() < 200; + let rows: Vec = (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| pm.pixel(x, y).is_some_and(marked))).collect(); + assert!(!rows.is_empty() && rows.iter().all(|&y| (20..108).contains(&y)), "every line inside the box: {rows:?}"); +} + +/// A bar in a box too short for its lines draws them at their size and is said, as a bar too +/// short for its labels at their text size is (#2581): its labels below and its unit above +/// count, where a plain bar's labels alone fit. A box tall enough draws them all inside it. +#[test] +fn a_scale_bar_unit_label_row_in_a_short_box_is_said() { + let bar = BarOptions { + unit_label: Some("Kilometres"), + unit_label_position: UnitLabelPosition::Above, + label_position: ScaleLabelPosition::Below, + units: ScaleUnits::Kilometers, + ..BarOptions::default() + }; + let short = Rect::from_xywh(0.0, 20.0, 300.0, 20.0).unwrap(); + let placed = bar_layout(short, 100.0, &bar, 1.0, false).unwrap(); + assert!(placed.cramped, "too short for its lines"); + assert_eq!(placed.px, SCALE_BAR_TEXT_PT as f32 * 1.33, "drawn at its size, not smaller"); + assert!(!bar_layout(short, 100.0, &BarOptions::default(), 1.0, false).unwrap().cramped, "a plain bar fits"); + // In a box tall enough, every line inside it: the unit above and the labels under the bar. + let mut pm = Pixmap::new(300, 80).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 20.0, 300.0, 40.0).unwrap(); + assert!(!bar_layout(r, 100.0, &bar, 1.0, false).unwrap().cramped); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, &bar, DEFAULT_COLORS, 1.0, false)); + let marked = |x: u32, y: u32| pm.pixel(x, y).is_some_and(|p| p.red() < 250 || p.green() < 250 || p.blue() < 250); + let rows: Vec = (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| marked(x, y))).collect(); + assert!(!rows.is_empty() && rows.iter().all(|y| (20..60).contains(y)), "inside the box: {rows:?}"); + // On a page, the short box is told as the text size's is: too small for its labels. + let maps = vec![Map::new("m")]; + let mut l = Layout::new("Page", 120.0, 90.0); + let frame = l.add( + "Frame", + (10.0, 30.0, 100.0, 50.0), + serde_json::from_value(serde_json::json!({"MapFrame":{"map":"m", "center":{"x":0,"y":0}, "scale":1000000}})).unwrap(), + ); + let id = l.add("Scale Bar", (10.0, 0.0, 100.0, 12.0), ElementKind::scale_bar(frame)); + let info = PageInfo::default(); + let set = |l: &mut Layout, size: f64, rows: bool| { + if let Some(ElementKind::ScaleBar { text_size, label_position, unit_label_position, .. }) = l.element_mut(id).map(|e| &mut e.kind) { + *text_size = size; + (*label_position, *unit_label_position) = if rows { + (ScaleLabelPosition::Below, UnitLabelPosition::Above) + } else { + (ScaleLabelPosition::Above, UnitLabelPosition::AfterLabels) + }; + } + }; + set(&mut l, 20.0, false); + assert!(text_loss(&l, &maps, 96.0, &info, id).is_none(), "a plain bar's labels at 20 points fit"); + set(&mut l, 20.0, true); + let loss = text_loss(&l, &maps, 96.0, &info, id).unwrap(); + assert!(loss.below_box && scale_bar_fit_notices(std::slice::from_ref(&loss))[0].contains("its box is too small"), "{loss:?}"); + set(&mut l, SCALE_BAR_TEXT_PT, true); + assert!(text_loss(&l, &maps, 96.0, &info, id).is_none(), "its rows at 8 points fit"); +} + +/// A page draws its scale bar's details through `draw_page`: the unit label in the bar's colour. +#[test] +fn a_page_draws_a_scale_bar_with_its_details() { + let (mut maps, mut l, frame) = colour_test_page(); + let mut bar = ElementKind::scale_bar(frame); + if let ElementKind::ScaleBar { color, label_position, unit_label, unit_label_position, subdivisions, divisions_before_zero, .. } = + &mut bar + { + *color = Rgba::rgb(0xD0, 0x10, 0x10); + (*label_position, *unit_label, *unit_label_position) = + (ScaleLabelPosition::Below, Some("Kilometres".into()), UnitLabelPosition::Above); + (*subdivisions, *divisions_before_zero) = (4, 1); + } + l.add("Scale Bar", (5.0, 5.0, 90.0, 20.0), bar.clone()); + let pm = render(&l, &mut maps, 96.0, &PageInfo::default()).unwrap(); + let rows = |from: u32, to: u32, hit: fn(tiny_skia::PremultipliedColorU8) -> bool| { + (from..to).flat_map(|y| (0..pm.width()).map(move |x| (x, y))).filter(|&(x, y)| pm.pixel(x, y).is_some_and(hit)).count() + }; + // The strip of the bar's 20 mm box over the bar (its middle at 15 mm, its top 4 px above) + // holds the unit label, in the bar's colour. + let mm = pm.height() as f32 / 60.0; + assert!(rows((5.0 * mm) as u32, (13.5 * mm) as u32, red) > 30, "the unit label over the bar, crimson"); + assert_eq!(rows(0, pm.height() / 2, ink), 0, "no default ink"); + // The same bar without its details draws differently on the same page. + let (mut maps2, mut plain, frame2) = colour_test_page(); + let mut same = ElementKind::scale_bar(frame2); + if let ElementKind::ScaleBar { color, .. } = &mut same { + *color = Rgba::rgb(0xD0, 0x10, 0x10); + } + plain.add("Scale Bar", (5.0, 5.0, 90.0, 20.0), same); + assert_ne!(pm.data(), render(&plain, &mut maps2, 96.0, &PageInfo::default()).unwrap().data()); +} + +#[test] +fn scale_numbers_are_short() { + assert_eq!(scale_number(5.0, 1.25), "5"); + assert_eq!(scale_number(2.5, 1.25), "2.5"); + assert_eq!(scale_number(1.25, 1.25), "1.25"); + assert_eq!(scale_number(0.0, 1.25), "0"); + assert_eq!(scale_number(100.0, 50.0), "100"); + // Small totals keep their precision: 0.05 km in four divisions. + assert_eq!(scale_number(0.0125, 0.0125), "0.0125"); + assert_eq!(scale_number(0.0375, 0.0125), "0.0375"); + assert_eq!(scale_number(0.125, 0.125), "0.125"); + // A step that never comes out even keeps two significant digits of it. + assert_eq!(scale_number(1.0 / 3.0, 1.0 / 3.0), "0.33"); + assert_eq!(scale_number(2.0 / 3.0, 1.0 / 3.0), "0.67"); + assert_eq!(scale_number(1.0, 1.0 / 3.0), "1"); + assert_eq!(scale_number(20.0 / 3.0, 10.0 / 3.0), "6.7"); + assert_eq!(scale_number(200.0 / 3.0, 100.0 / 3.0), "67"); + assert_eq!(scale_number(0.01 / 3.0, 0.01 / 3.0), "0.0033"); +} + +/// Graticule labels: meridians along the top and bottom and parallels along the sides come +/// first; a slanting meridian leaving through a side is labelled there only clear of the +/// parallels' labels, and none lands by a corner. +#[test] +fn graticule_labels_keep_clear_of_each_other() { + let along = |_: Edge, s: &str| s.len() as f32 * 5.0; + let label = |edge, at: f32, s: &str, lon| (edge, at, s.to_string(), lon); + let labels = vec![ + // A meridian leaving through the right edge just by a parallel's label (put first, so + // only the order fixes it), and another well clear of any. + label(Edge::Right, 205.0, "36°W", true), + label(Edge::Right, 200.0, "6°S", false), + label(Edge::Right, 400.0, "34°W", true), + label(Edge::Top, 150.0, "42°W", true), + // A parallel curving out through the top near a meridian's label: clear of it, but + // too close to read as its own. + label(Edge::Top, 185.0, "2°S", false), + // By a corner: left out, and a side's label within two label heights of the top. + label(Edge::Top, 4.0, "44°W", true), + label(Edge::Right, 15.0, "2°S", false), + ]; + let kept: Vec = + kept_labels(labels.clone(), (600.0, 500.0), (along, |_: Edge, _: &str| 20.0), 10.0, 1.0).into_iter().map(|(.., s)| s).collect(); + assert_eq!(kept, ["6°S", "42°W", "34°W"]); + // Labels reaching further in than a short frame is across are left out, not cut by it: + // on a frame 30 pixels tall, the top's; the sides', 600 wide, keep theirs. + let kept: Vec = kept_labels(labels, (600.0, 30.0), (along, |_: Edge, _: &str| 40.0), 10.0, 1.0) + .into_iter() + .filter(|(edge, ..)| *edge == Edge::Top) + .map(|(.., s)| s) + .collect(); + assert!(kept.is_empty(), "{kept:?}"); + // And on a frame 15 pixels wide, the sides' labels, whose flat labels reach their width in. + let across = |edge: Edge, s: &str| if matches!(edge, Edge::Left | Edge::Right) { s.len() as f32 * 5.0 + 6.0 } else { 6.0 }; + let side = vec![label(Edge::Right, 200.0, "6°S", false), label(Edge::Left, 250.0, "8°S", false)]; + assert_eq!(kept_labels(side.clone(), (600.0, 500.0), (along, across), 10.0, 1.0).len(), 2, "a wide frame keeps them"); + assert!(kept_labels(side, (15.0, 500.0), (along, across), 10.0, 1.0).is_empty(), "a narrow one leaves them out"); +} + +/// A text's layer statistics (#2853) fill in from the frame's map, written as a chart's values +/// with the layout's decimal mark, beside `{scale}`; a token with no figure, or with no frame, +/// is drawn as written. What each such token is missing is said, once. +#[test] +fn a_text_shows_its_layers_statistics() { + use rustgis_data::{Dataset, Field, FieldType, GeometryType, Value}; + let mut ds = Dataset::new("Plants", GeometryType::None, vec![Field::new("mw", FieldType::Double), Field::new("name", FieldType::Text)]); + for mw in [12_000.5, 11_553.25] { + ds.push(None, vec![Value::Float(mw), Value::Text("x".into())]); + } + let mut map = Map::new("m"); + map.add_dataset(ds); + let cam = frame_camera(&map, Coord::new(0.0, 0.0), 6_300_000.0, 0.0, 0.0); + let info = PageInfo { page: 1, pages: 1, page_name: String::new() }; + let mut layout = Layout::new("L", 100.0, 100.0); + let text = "{count:Plants} plants, {sum:Plants:mw} MW, mean {mean:Plants:mw}; {sum:Plants:name} {count:Nowhere}"; + assert_eq!( + expand(text, &layout, &info, Some((&map, cam))), + "2 plants, 23,553.75 MW, mean 11,776.88; {sum:Plants:name} {count:Nowhere}" + ); + layout.decimal_comma = true; + assert_eq!( + expand(text, &layout, &info, Some((&map, cam))), + "2 plants, 23.553,75 MW, mean 11.776,88; {sum:Plants:name} {count:Nowhere}" + ); + // Without a frame, every token as written, and said so; a text without tokens says nothing. + assert_eq!(expand("{count:Plants} plants", &layout, &info, None), "{count:Plants} plants"); + let maps = [map]; + assert_eq!( + statistic_notices(&layout, &maps, "{count:Plants} and {count:Plants}"), + vec!["{count:Plants} shows as written: the layout has no map frame whose map it would read".to_string()] + ); + assert_eq!(statistic_notices(&layout, &maps, "Plants at {scale}"), Vec::::new()); + let kind = serde_json::from_value(serde_json::json!({"MapFrame": {"map": "m", "center": {"x": 0, "y": 0}, "scale": 6300000}})).unwrap(); + layout.add("Frame", (0.0, 0.0, 50.0, 50.0), kind); + let said = statistic_notices(&layout, &maps, "{sum:Plants:name} {sum:Plants:name} {count:Nowhere} {min:Plants:nosuch} {count:Plants}"); + assert_eq!( + said, + vec![ + "{sum:Plants:name} shows as written: 'name' of 'Plants' holds no numbers".to_string(), + "{count:Nowhere} shows as written: the map of the layout's first frame has no layer named 'Nowhere'".to_string(), + "{min:Plants:nosuch} shows as written: 'Plants' has no field named 'nosuch'".to_string(), + ] + ); +} + +/// A layer read in place holds only the features loaded, so a figure over it is partial: said +/// when the text is set (#2853), as is a layer that holds everything not. +#[test] +fn a_streamed_layers_statistic_says_it_covers_what_is_loaded() { + use rustgis_data::{Dataset, Field, FieldType, GeometryType, Value}; + let layer = |name: &str| { + let fields = vec![Field::new("mw", FieldType::Double), Field::new("blank", FieldType::Double)]; + let mut ds = Dataset::new(name, GeometryType::None, fields); + ds.push(None, vec![Value::Float(1.0), Value::Null]); + ds + }; + let mut map = Map::new("m"); + map.add_dataset(layer("Held")); + map.add_dataset(layer("Streamed")); + map.layers.iter_mut().find(|l| l.name == "Streamed").unwrap().source = Some(Default::default()); + let mut layout = Layout::new("L", 100.0, 100.0); + let kind = serde_json::from_value(serde_json::json!({"MapFrame": {"map": "m", "center": {"x": 0, "y": 0}, "scale": 6300000}})).unwrap(); + layout.add("Frame", (0.0, 0.0, 50.0, 50.0), kind); + let maps = [map]; + assert_eq!( + statistic_notices(&layout, &maps, "{count:Held} {count:Streamed} {count:Streamed} {sum:Streamed:mw} {sum:Streamed:no} {max:Streamed:blank}"), + vec![ + "{count:Streamed} covers only the features of 'Streamed' that are loaded: it is read in place".to_string(), + "{sum:Streamed:mw} covers only the features of 'Streamed' that are loaded: it is read in place".to_string(), + "{sum:Streamed:no} shows as written: 'Streamed' has no field named 'no'".to_string(), + // No number loaded yet, but a later load may bring some: the scope is said as well. + "{max:Streamed:blank} covers only the features of 'Streamed' that are loaded: it is read in place".to_string(), + "{max:Streamed:blank} shows as written: no feature of 'Streamed' its definition query keeps has a number in 'blank', or the figure is past a number's range".to_string(), + ] + ); +} + +/// A raster layer has no features, so a figure over it has none to give: drawn as written and +/// said (#2853), never a 0 that reads like a count. +#[test] +fn a_raster_layers_statistic_is_drawn_as_written() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1.0, pixel_height: -1.0 }; + let r = Raster::new("e", 1, 1, vec![vec![1.0]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let mut map = Map::new("m"); + map.add_raster("Elevation", rustgis_map::RasterLayer::from_path(r, "e.tif")); + let cam = frame_camera(&map, Coord::new(0.0, 0.0), 6_300_000.0, 0.0, 0.0); + let info = PageInfo { page: 1, pages: 1, page_name: String::new() }; + let mut layout = Layout::new("L", 100.0, 100.0); + assert_eq!(expand("{count:Elevation}", &layout, &info, Some((&map, cam))), "{count:Elevation}"); + let kind = serde_json::from_value(serde_json::json!({"MapFrame": {"map": "m", "center": {"x": 0, "y": 0}, "scale": 6300000}})).unwrap(); + layout.add("Frame", (0.0, 0.0, 50.0, 50.0), kind); + let maps = [map]; + assert_eq!( + statistic_notices(&layout, &maps, "{count:Elevation}"), + vec!["{count:Elevation} shows as written: 'Elevation' is a raster layer, which has no features".to_string()] + ); + // The same figures over a map given directly, as a presentation map page's title is. + assert_eq!( + map_statistic_notices(&maps[0], "the page's map", "{count:Elevation}"), + vec!["{count:Elevation} shows as written: 'Elevation' is a raster layer, which has no features".to_string()] + ); +} + +/// A frame whose map the project doesn't hold is told apart from a layout with no frame (#2853). +#[test] +fn a_statistic_names_a_frame_whose_map_is_missing() { + let mut layout = Layout::new("L", 100.0, 100.0); + let said = |layout: &Layout| statistic_notices(layout, &[Map::new("m")], "{count:Cities}"); + assert_eq!(said(&layout), vec!["{count:Cities} shows as written: the layout has no map frame whose map it would read".to_string()]); + let kind = + serde_json::from_value(serde_json::json!({"MapFrame": {"map": "gone", "center": {"x": 0, "y": 0}, "scale": 6300000}})).unwrap(); + layout.add("Frame", (0.0, 0.0, 50.0, 50.0), kind); + assert_eq!( + said(&layout), + vec!["{count:Cities} shows as written: the map of the layout's first frame is not in the project".to_string()] + ); +} + +/// A figure written without its field (`{sum:Plants}`) is drawn as written, which is no token for +/// the page, and is said (#2853), as one with a field the layer lacks is. +#[test] +fn a_statistic_without_its_field_is_said() { + use rustgis_data::{Dataset, Field, FieldType, GeometryType}; + let mut map = Map::new("m"); + map.add_dataset(Dataset::new("Plants", GeometryType::None, vec![Field::new("mw", FieldType::Double)])); + let mut layout = Layout::new("L", 100.0, 100.0); + let kind = serde_json::from_value(serde_json::json!({"MapFrame": {"map": "m", "center": {"x": 0, "y": 0}, "scale": 6300000}})).unwrap(); + layout.add("Frame", (0.0, 0.0, 50.0, 50.0), kind); + let maps = [map]; + assert_eq!( + statistic_notices(&layout, &maps, "{sum:Plants} {count:Plants} {max:Nowhere} {mean:Plants:mw}"), + vec![ + "{sum:Plants} shows as written: a sum takes a field: write {sum:Plants:field}".to_string(), + "{max:Nowhere} shows as written: the map of the layout's first frame has no layer named 'Nowhere'".to_string(), + "{mean:Plants:mw} shows as written: no feature of 'Plants' its definition query keeps has a number in 'mw', or the figure is past a number's range".to_string(), + ] + ); +} + +/// A layout with a decimal comma swaps the marks of the numbers it prints, `{scale}` included, +/// and leaves other text alone. +#[test] +fn a_decimal_comma_swaps_the_marks() { + assert_eq!(decimal("0.05".into(), true), "0,05"); + assert_eq!(decimal("6,300,000".into(), true), "6.300.000"); + assert_eq!(decimal("0.05".into(), false), "0.05"); + let map = Map::new("m"); + let cam = frame_camera(&map, Coord::new(0.0, 0.0), 6_300_000.0, 0.0, 0.0); + let info = PageInfo { page: 1, pages: 1, page_name: String::new() }; + let mut layout = Layout::new("L", 100.0, 100.0); + let point = expand("Scale {scale}, page {page}.", &layout, &info, Some((&map, cam))); + layout.decimal_comma = true; + let comma = expand("Scale {scale}, page {page}.", &layout, &info, Some((&map, cam))); + // "Scale 1:6,300,000, page 1." and "Scale 1:6.300.000, page 1.": the scale's marks swap, the + // text's comma stays. + let scale = point.strip_prefix("Scale ").and_then(|t| t.strip_suffix(", page 1.")).unwrap_or_else(|| panic!("{point}")); + assert!(scale.starts_with("1:") && scale.contains(','), "{point}"); + assert_eq!(comma, format!("Scale {}, page 1.", scale.replace(',', "."))); +} + +/// A map of one point layer, one point, set by `edit`. +fn point_legend_map(edit: impl FnOnce(&mut rustgis_map::Layer)) -> Map { + use rustgis_data::{Dataset, Geometry}; + let mut map = Map::new("m"); + let mut d = Dataset::new("pts", GeometryType::Point, vec![]); + d.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![]); + map.add_dataset(d); + if let Some(l) = map.layers.last_mut() { + edit(l); + } + map +} + +/// The legend of `map` at 1:1e6, every class, on white. +fn point_legend(map: &Map) -> Pixmap { + let mut pm = Pixmap::new(200, 200).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 200.0, 200.0).unwrap(), map, ("", 1), None, opts, 1.0)); + pm +} + +/// The legend of `map` at 1:1e6 recorded for a vector export, on a page of `side` pixels, drawn +/// back on white. +fn recorded_legend(map: &Map, side: u32) -> Pixmap { + let mut c = Canvas::recording(side, side).unwrap(); + let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + legend(&mut c, Rect::from_xywh(0.0, 0.0, side as f32, side as f32).unwrap(), map, ("", 1), None, opts, 1.0); + let (_, _, items) = c.into_drawing().unwrap().finish(); + let mut pm = Pixmap::new(side, side).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::vector::replay(&items, &mut pm, Transform::identity()); + pm +} + +/// What the map's code draws for a point at (`x`, `y`) on white. +fn drawn_point(s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke], (x, y): (f32, f32), ppp: f32) -> Pixmap { + let mut pm = Pixmap::new(200, 200).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::canvas::with_canvas(&mut pm, |c| { + if strokes.is_empty() { + crate::draw_marker(c, x, y, s, 1.0, None, ppp); + } else { + point_marks::draw(c, x, y, s, strokes, 0.0, None, ppp); + } + }); + pm +} + +/// What the map's code draws for a point at (`x`, `y`), composited as one at `opacity`, on +/// white. +fn drawn_see_through(s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke], (x, y): (f32, f32), ppp: f32, opacity: f32) -> Pixmap { + let mut own = Pixmap::new(200, 200).unwrap(); + crate::canvas::with_canvas(&mut own, |c| draw_point(c, (x, y), s, strokes, ppp)); + let mut pm = Pixmap::new(200, 200).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + pm.draw_pixmap(0, 0, own.as_ref(), &PixmapPaint { opacity, ..PixmapPaint::default() }, Transform::identity(), None); + pm +} + +/// Whether two pictures differ by no more than a rounding over `w` × `h` from the top left +/// corner. +fn near_corner(a: &Pixmap, b: &Pixmap, w: u32, h: u32) -> bool { + (0..h).all(|y| { + (0..w).all(|x| match (a.pixel(x, y), b.pixel(x, y)) { + (Some(p), Some(q)) => p.red().abs_diff(q.red()).max(p.green().abs_diff(q.green())).max(p.blue().abs_diff(q.blue())) <= 2, + _ => false, + }) + }) +} + +/// Whether two pictures are the same over `w` × `h` from the top left corner. +fn same_corner(a: &Pixmap, b: &Pixmap, w: u32, h: u32) -> bool { + (0..h).all(|y| (0..w).all(|x| a.pixel(x, y) == b.pixel(x, y))) +} + +/// A stacked stroke: a square of `size` points in `color`, with no outline. +fn square_mark(color: Rgba, size: f32) -> rustgis_map::LineStroke { + let markers = rustgis_map::LineMarkers { + mark: rustgis_map::LineMark::Marker(rustgis_map::Marker::Square), + size, + ..rustgis_map::LineMarkers::default() + }; + rustgis_map::LineStroke { color: Some(color), width: Some(0.0), markers: Some(markers), ..rustgis_map::LineStroke::default() } +} + +/// Every marker, tiny and ordinary, with an outline and without, at the pixels the map's code +/// gives it. +#[test] +fn a_legend_draws_a_point_as_the_map_does() { + let red = Rgba::rgb(255, 0, 0); + let base = rustgis_map::Symbol { fill: red, stroke: Rgba::rgb(0, 0, 255), ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + // Every shape, tiny and ordinary, with no outline and with one. + for marker in rustgis_map::Marker::ALL { + for (size, stroke_width) in [(2.0, 0.0), (10.0, 0.0), (10.0, 1.0)] { + let s = rustgis_map::Symbol { marker, size, stroke_width, ..base }; + let map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s)); + // The first row, 15 points tall, its swatch 16 wide. + let want = drawn_point(&s, &[], (8.0, 7.5), 1.0); + assert!(same_corner(&point_legend(&map), &want, 16, 15), "{marker:?} of {size} pt, outline {stroke_width} pt"); + } + } + // A class's symbol too, indented under its layer's name. + let s = rustgis_map::Symbol { marker: rustgis_map::Marker::Triangle, size: 10.0, stroke_width: 0.0, ..base }; + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("a".to_string(), s)], + other: s, + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + }); + let got = point_legend(&map); + let want = drawn_point(&s, &[], (6.0 + 8.0, 15.0 + 7.5), 1.0); + assert!((15..30).all(|y| (6..22).all(|x| got.pixel(x, y) == want.pixel(x, y))), "the class's triangle"); +} + +/// An outline under half a pixel is as thin in a legend as on the map. +#[test] +fn a_legend_draws_a_hairline_outline_as_the_map_does() { + // Thinner than half a pixel: the map's marker strokes it at its width, with no minimum. + let s = rustgis_map::Symbol { + size: 10.0, + stroke: Rgba::rgb(0, 0, 255), + stroke_width: 0.1, + ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) + }; + let map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s)); + assert!(same_corner(&point_legend(&map), &drawn_point(&s, &[], (8.0, 7.5), 1.0), 16, 15)); +} + +/// A layer's stacked marks replace its marker, in a row that holds them. +#[test] +fn a_legend_draws_a_points_stacked_marks() { + let strokes = vec![square_mark(Rgba::rgb(255, 0, 0), 12.0), square_mark(Rgba::rgb(0, 0, 0), 4.0)]; + let s = rustgis_map::Symbol::default_for(GeometryType::Point, 0); + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.line_strokes = strokes.clone(); + }); + // 12 pt squares reach 7.2 pt: the row is 15 points tall still. + assert!(same_corner(&point_legend(&map), &drawn_point(&s, &strokes, (8.0, 7.5), 1.0), 16, 15)); +} + +/// Stacked marks at the opacity of a layer and its groups, on pixels and in a recording. +#[test] +fn a_see_through_point_is_composited_as_one_with_its_groups() { + let s = rustgis_map::Symbol { size: 10.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + let strokes = vec![square_mark(Rgba::rgb(255, 0, 0), 12.0), square_mark(Rgba::rgb(0, 0, 0), 12.0)]; + let mut map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.line_strokes = strokes.clone(); + l.transparency = 50.0; + }); + let middle = |map: &Map| point_legend(map).pixel(8, 7).map(|p| (p.red(), p.green(), p.blue())).unwrap(); + // Black at half over white: grey, with none of the red under it showing. + let (r, g, b) = middle(&map); + assert!((120..=135).contains(&r) && r == g && g == b, "{r} {g} {b}"); + // Its group's transparency applies too: half of half. + let id = map.layers[0].id; + let mut group = rustgis_map::LayerGroup::new("g"); + group.transparency = 50.0; + group.children.push(id); + map.add_group(group); + let (r, g, b) = middle(&map); + assert!((185..=197).contains(&r) && r == g && g == b, "{r} {g} {b}"); + // Recorded for a vector export, it is half of half too. + let p = recorded_legend(&map, 200).pixel(8, 7).unwrap(); + let (r, g, b) = (p.red(), p.green(), p.blue()); + assert!((185..=197).contains(&r) && r == g && g == b, "recorded: {r} {g} {b}"); +} + +/// A square turned by its own angle reaches past 0.6 of its size: its row holds its corners, +/// which the picture of a see-through symbol would cut. +#[test] +fn a_see_through_mark_with_its_own_angle_keeps_its_corners() { + let s = rustgis_map::Symbol { size: 10.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + let mut mark = square_mark(Rgba::rgb(0, 0, 255), 40.0); + if let Some(m) = &mut mark.markers { + m.angle = 45.0; + } + let strokes = vec![mark]; + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.line_strokes = strokes.clone(); + l.transparency = 50.0; + }); + let side = 2.0 * point_marks::reach(&s, &strokes); + assert!(side > 50.0, "{side}"); + let drawn = drawn_see_through(&s, &strokes, (side / 2.0, side / 2.0), 1.0, 0.5); + assert!(near_corner(&point_legend(&map), &drawn, side.ceil() as u32, side.ceil() as u32)); +} + +/// A plain point at half its opacity, its outline over its fill: composited as one, so the fill +/// doesn't show through the outline. +#[test] +fn a_see_through_plain_point_is_composited_as_the_map_composites_a_layer() { + let s = rustgis_map::Symbol { + fill: Rgba::rgb(255, 0, 0), + stroke: Rgba::rgb(0, 0, 255), + stroke_width: 1.0, + size: 8.0, + marker: rustgis_map::Marker::Square, + }; + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.transparency = 50.0; + }); + assert!(near_corner(&point_legend(&map), &drawn_see_through(&s, &[], (8.0, 7.5), 1.0, 0.5), 16, 15)); +} + +/// A large symbol takes a taller row and a wider column in a legend's size; an ordinary one +/// doesn't. +#[test] +fn a_legend_grows_to_hold_a_large_point() { + let mm = 25.4 / 96.0; + let s = |size| rustgis_map::Symbol { size, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + let label = f64::from(6.0 + text::measure("pts", 9.0, false)); + // An ordinary symbol keeps the row and the swatch's column. + let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(10.0))); + let [(w, h), ..] = legend_sizes_mm(&mut map, 1e6, true, false, (&[], &NO_LABELS)).unwrap(); + assert!((h - f64::from(LEGEND_ROW) * mm).abs() < 1e-6, "{h} mm"); + // Its width within a rounding: it is summed in f32, past a name as wide as its font makes it. + assert!((w - (f64::from(LEGEND_SWATCH) + label) * mm).abs() < 1e-4, "{w} mm"); + // One of 40 pt reaches 24 pt from its point: 48 pt each way. + let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(40.0))); + let [(w, h), ..] = legend_sizes_mm(&mut map, 1e6, true, false, (&[], &NO_LABELS)).unwrap(); + assert!((h - 48.0 * mm).abs() < 1e-6, "{h} mm"); + assert!((w - (48.0 + label) * mm).abs() < 1e-4, "{w} mm"); + assert!(same_corner(&point_legend(&map), &drawn_point(&s(40.0), &[], (24.0, 24.0), 1.0), 48, 48)); + // A frame too short for the row draws no part of it. + let mut pm = Pixmap::new(200, 200).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let blank = pm.clone(); + let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 200.0, 47.0).unwrap(), &map, ("", 1), None, opts, 1.0)); + assert!(pm.data() == blank.data()); + // A size no page could hold stays a size a legend can take. + let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(f32::MAX))); + let [(w, h), ..] = legend_sizes_mm(&mut map, 1e6, true, false, (&[], &NO_LABELS)).unwrap(); + assert!(w.is_finite() && h.is_finite(), "{w} × {h} mm"); +} + +/// A legend's text size (#2581) scales its text, rows, swatches and gaps, and its title's room, +/// from 9 points; a point symbol keeps the size the map draws it at, its row growing only as +/// far as it needs. +#[test] +fn a_legends_text_size_scales_its_rows_but_not_its_point_symbols() { + let mm = 25.4 / 96.0; + let s = |size| rustgis_map::Symbol { size, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + let sized = |map: &mut Map, pt: f64| legend_sizes_with_no_data_mm(map, 1e6, true, false, (false, pt), (&[], &NO_LABELS)).unwrap()[0]; + // An ordinary symbol at 18 points: the row, the swatch's column, the gap and the name twice + // their size at 9. + let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(10.0))); + let (w, h) = sized(&mut map, 18.0); + assert!((h - f64::from(2.0 * LEGEND_ROW) * mm).abs() < 1e-6, "{h} mm"); + let label = f64::from(12.0 + text::measure("pts", 18.0, false)); + assert!((w - (f64::from(2.0 * LEGEND_SWATCH) + label) * mm).abs() < 1e-4, "{w} mm"); + assert_eq!( + sized(&mut map, rustgis_map::layout::LEGEND_TEXT_PT), + legend_sizes_mm(&mut map, 1e6, true, false, (&[], &NO_LABELS)).unwrap()[0] + ); + // One of 40 points keeps its 48: the row (30 at 18 points) and the column grow to it. + let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(40.0))); + let (w, h) = sized(&mut map, 18.0); + assert!((h - 48.0 * mm).abs() < 1e-6, "{h} mm"); + assert!((w - (48.0 + label) * mm).abs() < 1e-4, "{w} mm"); + let mut pm = Pixmap::new(200, 200).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 2.0 }; + crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 200.0, 200.0).unwrap(), &map, ("", 1), None, opts, 1.0)); + assert!(same_corner(&pm, &drawn_point(&s(40.0), &[], (24.0, 24.0), 1.0), 48, 48), "the symbol as the map draws it"); + // A polygon's swatch is twice as wide, as its column is. + let red = Rgba::rgb(255, 0, 0); + let fill = rustgis_map::Symbol { fill: red, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) }; + let map = shape_legend_map(GeometryType::Polygon, |l| l.renderer = rustgis_map::Renderer::Single(fill)); + let across = |size: f32| { + let mut pm = Pixmap::new(200, 200).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let opts = LegendOptions { size, ..opts }; + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(0.0, 0.0, 200.0, 200.0).unwrap(), &map, ("", 1), None, opts, 1.0) + }); + (0..pm.width()).filter(|&x| (0..pm.height()).any(|y| pm.pixel(x, y).is_some_and(|p| (p.red(), p.green()) == (255, 0)))).count() + }; + // Its fill inside its outline's edge pixels: 16 points more across, at twice the size. + let (one, two) = (across(1.0), across(2.0)); + assert_eq!(two - one, 16, "{one} and {two} px"); + // A line wider than its row, at a small size, is cut to its row (#2518): nothing above the + // box. + let small = LegendOptions { size: 4.0 / 9.0, ..opts }; + let drawn = |map: &Map, at: (f32, f32), opts: LegendOptions| { + let mut pm = Pixmap::new(200, 200).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(at.0, at.1, 200.0 - at.0, 200.0 - at.1).unwrap(), map, ("", 1), None, opts, 1.0) + }); + pm + }; + // The first row and column `colour` takes. + let ink = |pm: &Pixmap, (r, g, b): (u8, u8, u8)| { + let at = |x: u32, y: u32| pm.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == (r, g, b)); + ((0..pm.height()).find(|&y| (0..pm.width()).any(|x| at(x, y))), (0..pm.width()).find(|&x| (0..pm.height()).any(|y| at(x, y)))) + }; + let wide = rustgis_map::Symbol { stroke: red, stroke_width: 20.0, ..rustgis_map::Symbol::default_for(GeometryType::Polyline, 0) }; + let map = shape_legend_map(GeometryType::Polyline, |l| l.renderer = rustgis_map::Renderer::Single(wide)); + let (top, _) = ink(&drawn(&map, (0.0, 50.0), small), (255, 0, 0)); + assert!(top.is_some_and(|y| y >= 50), "drawn, nothing above the legend's box: {top:?}"); + // A thin one stays within its row and keeps the plain swatch it always had. + let thin = rustgis_map::Symbol { stroke_width: 1.0, ..wide }; + let row = (0.0, 0.0, LEGEND_SWATCH, LEGEND_ROW); + let b = swatch_ink(row, GeometryType::Polyline, (&thin, &[], &[]), (LEGEND_SWATCH, 1.0)).unwrap(); + assert!(b.top() >= 0.0 && b.bottom() <= LEGEND_ROW, "{b:?}"); + // A polygon's wide outline is cut at its row's top and bottom, plain or stacked, and on the + // left at the legend's edge, where nothing lies before its column. + let blue = Rgba::rgb(0, 0, 255); + let outlined = + rustgis_map::Symbol { fill: red, stroke: blue, stroke_width: 12.0, ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) }; + let solid = rustgis_map::fills::FillLayer { color: Some(red), pattern: rustgis_map::fills::FillPattern::Solid }; + // (The stacked one at the default size: a stack is always composited, and cut, as #2518 set.) + for (fills, opts) in [(vec![], small), (vec![solid], LegendOptions { size: 1.0, ..opts })] { + let stacked = !fills.is_empty(); + let map = shape_legend_map(GeometryType::Polygon, |l| { + l.renderer = rustgis_map::Renderer::Single(outlined); + l.fill_layers = fills; + }); + let (top, left) = ink(&drawn(&map, (50.0, 50.0), opts), (0, 0, 255)); + assert!(top.is_some_and(|y| y >= 50), "stacked {stacked}: nothing above the legend's box: {top:?}"); + assert_eq!(left, Some(50), "stacked {stacked}: drawn to the legend's edge, not past it"); + } + // Left of a column that has room before it (a class's indent, the gap between columns as + // drawn), the outline reaches into that room and no further. + let map = shape_legend_map(GeometryType::Polygon, |l| l.renderer = rustgis_map::Renderer::Single(outlined)); + for lead in [6.0f32, 2.0] { + let mut pm = Pixmap::new(100, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::canvas::with_canvas(&mut pm, |c| { + swatch( + c, + (50.0, 20.0, LEGEND_SWATCH, LEGEND_ROW), + &map.layers[0], + (&outlined, &[], &[]), + 1.0, + 1e6, + (1.0, LEGEND_SWATCH, (lead, 6.0)), + ) + }); + let (_, left) = ink(&pm, (0, 0, 255)); + assert_eq!(left, Some(50 - lead as u32), "room {lead}: its outer half, 6 points, as far as its room"); + } + // The title's room follows; a size past the range, or none at all, is brought into it. + assert!((legend_title_mm(18.0) - 2.0 * legend_title_mm(9.0)).abs() < 1e-12); + assert_eq!(legend_size(1e9), 100.0 / 9.0); + assert_eq!((legend_size(f64::NAN), legend_size(9.0)), (1.0, 1.0)); +} + +/// A layer's reference scale sizes its symbol at the frame's scale. +#[test] +fn a_legend_scales_a_point_with_its_reference_scale() { + let s = rustgis_map::Symbol { size: 10.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + // Twice as large at 1:1e6: 10 pt reaches 12 pt from its point, in a row of 24. + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.reference_scale = Some(2e6); + }); + assert!(same_corner(&point_legend(&map), &drawn_point(&s, &[], (12.0, 12.0), 2.0), 24, 24)); +} + +/// A diagram's categories on a point layer with stacked marks: each row shows its own colour, +/// not the layer's marks. +#[test] +fn a_diagrams_rows_keep_their_own_mark_on_a_layer_with_stacked_marks() { + let (red, green) = (Rgba::rgb(255, 0, 0), Rgba::rgb(0, 255, 0)); + let category = |field: &str, colour| rustgis_map::DiagramCategory { field: field.into(), colour }; + let map = point_legend_map(|l| { + l.line_strokes = vec![square_mark(Rgba::rgb(0, 0, 0), 12.0)]; + l.diagram = Some(rustgis_map::DiagramSettings { + kind: rustgis_map::DiagramKind::Pie, + categories: vec![category("a", red), category("b", green)], + size: rustgis_map::DiagramSize::Fixed(12.0), + start_angle: 0.0, + background: None, + stroke: rustgis_map::DiagramSettings::default_stroke(), + stroke_width: 0.75, + labels: rustgis_map::DiagramLabel::None, + }); + }); + let pm = point_legend(&map); + let at = |x, y| pm.pixel(x, y).map(|p| (p.red(), p.green(), p.blue())); + // The layer's name, then a row each, the swatch 6 points in. + assert_eq!(at(14, 22), Some((255, 0, 0))); + assert_eq!(at(14, 37), Some((0, 255, 0))); +} + +/// A one-feature line or polygon layer, edited by `edit`. +fn shape_legend_map(gt: GeometryType, edit: impl FnOnce(&mut rustgis_map::Layer)) -> Map { + use rustgis_data::{Dataset, Geometry}; + let mut map = Map::new("m"); + let mut d = Dataset::new("shapes", gt, vec![]); + let (a, b, c) = (Coord::new(0.0, 0.0), Coord::new(1.0, 0.0), Coord::new(1.0, 1.0)); + let g = match gt { + GeometryType::Polyline => Geometry::Line(vec![vec![a, c]]), + _ => Geometry::Polygon(vec![vec![vec![a, b, c, a]]]), + }; + d.push(Some(g), vec![]); + map.add_dataset(d); + if let Some(l) = map.layers.last_mut() { + edit(l); + } + map +} + +/// How many pixels in `xs` × `ys` are within 40 of `c` in every channel. +fn inked(pm: &Pixmap, xs: std::ops::Range, ys: std::ops::Range, c: Rgba) -> usize { + let near = |a: u8, b: u8| a.abs_diff(b) <= 40; + ys.flat_map(|y| xs.clone().map(move |x| (x, y))) + .filter(|(x, y)| pm.pixel(*x, *y).is_some_and(|p| near(p.red(), c.r()) && near(p.green(), c.g()) && near(p.blue(), c.b()))) + .count() +} + +/// A stacked stroke `width` points wide in `color`. +fn plain_stroke(color: Rgba, width: f32) -> rustgis_map::LineStroke { + rustgis_map::LineStroke { color: Some(color), width: Some(width), ..rustgis_map::LineStroke::default() } +} + +/// Hatch lines `spacing` points apart, a point wide, across. +fn hatch(color: Rgba, spacing: f32) -> rustgis_map::fills::FillLayer { + rustgis_map::fills::FillLayer { + color: Some(color), + pattern: rustgis_map::fills::FillPattern::Hatch { angle: 0.0, spacing, width: 1.0, offset: 0.0 }, + } +} + +/// A line or polygon layer with no stacked strokes or fills keeps the swatch it always had, +/// pixel for pixel (#2490): a line through three points, or a box with its outline. +#[test] +fn a_plain_line_or_polygon_keeps_its_swatch() { + let s = rustgis_map::Symbol { + fill: Rgba::rgb(255, 0, 0), + stroke: Rgba::rgb(0, 0, 255), + stroke_width: 2.0, + ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) + }; + for gt in [GeometryType::Polyline, GeometryType::Polygon] { + let map = shape_legend_map(gt, |l| l.renderer = rustgis_map::Renderer::Single(s)); + let mut want = Pixmap::new(200, 200).unwrap(); + want.fill(tiny_skia::Color::WHITE); + let stroke = Stroke { width: 2.0, ..Stroke::default() }; + crate::canvas::with_canvas(&mut want, |c| { + if gt == GeometryType::Polyline { + let mut pb = PathBuilder::new(); + pb.move_to(0.0, 10.5); + pb.line_to(6.4, 4.5); + pb.line_to(16.0, 9.0); + c.stroke_path(&pb.finish().unwrap(), &paint(s.stroke, 1.0), &stroke, Transform::identity(), None); + } else { + let b = Rect::from_xywh(0.0, 3.0, 16.0, 9.0).unwrap(); + c.fill_rect(b, &paint(s.fill, 1.0), Transform::identity(), None); + c.stroke_path(&PathBuilder::from_rect(b), &paint(s.stroke, 1.0), &stroke, Transform::identity(), None); + } + }); + assert!(same_corner(&point_legend(&map), &want, 16, 15), "{gt:?}"); + } +} + +/// A line's stacked strokes show in its swatch as on the map: a casing under its core, and +/// dashes (#2490). +#[test] +fn a_legend_draws_a_lines_casing_and_dashes() { + let (black, red) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0)); + let drawn = + |strokes: Vec| point_legend(&shape_legend_map(GeometryType::Polyline, |l| l.line_strokes = strokes)); + let cased = drawn(vec![plain_stroke(black, 8.0), plain_stroke(red, 2.0)]); + assert!(inked(&cased, 0..16, 0..15, black) > 20, "the casing"); + assert!(inked(&cased, 0..16, 0..15, red) > 5, "the core over it"); + let dashed = rustgis_map::LineStroke { + dash: rustgis_map::symbology::Dash::new(&[2.0, 4.0]), + cap: rustgis_map::LineCap::Butt, + ..plain_stroke(red, 2.0) + }; + let dashed = drawn(vec![plain_stroke(black, 8.0), dashed]); + assert!(inked(&dashed, 0..16, 0..15, red) * 3 < inked(&cased, 0..16, 0..15, red) * 2, "a dashed core shows less of it"); + // One plain stroke draws in its own colour alone. + assert_eq!(inked(&drawn(vec![plain_stroke(red, 2.0)]), 0..16, 0..15, black), 0); +} + +/// Markers along a line show in its swatch (#2490). +#[test] +fn a_legend_draws_markers_along_a_line() { + let blue = Rgba::rgb(0, 0, 255); + let map = shape_legend_map(GeometryType::Polyline, |l| { + l.line_strokes = vec![plain_stroke(Rgba::rgb(128, 128, 128), 1.0), square_mark(blue, 6.0)]; + }); + assert!(inked(&point_legend(&map), 0..16, 0..15, blue) > 10); +} + +/// With symbol levels on, a line's swatch draws its strokes level by level, as the map does. +#[test] +fn a_legend_draws_a_lines_strokes_by_level() { + let (black, red) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0)); + let drawn = |levels: bool| { + let map = shape_legend_map(GeometryType::Polyline, |l| { + l.line_strokes = vec![ + rustgis_map::LineStroke { level: Some(1), ..plain_stroke(red, 2.0) }, + rustgis_map::LineStroke { level: Some(0), ..plain_stroke(black, 8.0) }, + ]; + l.stroke_levels = levels; + }); + inked(&point_legend(&map), 0..16, 0..15, red) + }; + assert!(drawn(true) > 5, "the core's level is above the casing's"); + assert_eq!(drawn(false), 0, "in their order, the casing covers the core"); +} + +/// A stroke shifted past its row is cut at the swatch's box, not drawn over the next row. +#[test] +fn a_legend_cuts_a_shifted_stroke_at_its_box() { + let red = Rgba::rgb(255, 0, 0); + for (offset, shows) in [(4.0, true), (30.0, false)] { + let map = shape_legend_map(GeometryType::Polyline, |l| { + l.line_strokes = vec![rustgis_map::LineStroke { offset, ..plain_stroke(red, 3.0) }]; + }); + let pm = point_legend(&map); + assert_eq!(inked(&pm, 0..16, 0..15, red) > 0, shows, "offset {offset}"); + assert_eq!(inked(&pm, 0..200, 15..200, red), 0, "offset {offset}: nothing below its row"); + } + // One plain stroke wider than the row is cut at it too. + let map = shape_legend_map(GeometryType::Polyline, |l| l.line_strokes = vec![plain_stroke(red, 30.0)]); + let pm = point_legend(&map); + assert!(inked(&pm, 0..16, 0..15, red) > 50); + assert_eq!(inked(&pm, 0..200, 15..200, red), 0, "a wide stroke: nothing below its row"); + // Its round ends reach into the gap before the text, 6 points, and no further (#2581): a + // label beside it keeps its own pixels. The same for a plain polygon's wide outline. + assert!(inked(&pm, 16..22, 0..15, red) > 0, "into the gap"); + assert_eq!(inked(&pm, 22..200, 0..200, red), 0, "nothing where the text starts"); + let outline = rustgis_map::Symbol { stroke: red, stroke_width: 30.0, ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) }; + let map = shape_legend_map(GeometryType::Polygon, |l| l.renderer = rustgis_map::Renderer::Single(outline)); + let pm = point_legend(&map); + assert!(inked(&pm, 16..22, 0..15, red) > 0, "a plain outline into the gap"); + assert_eq!(inked(&pm, 22..200, 0..200, red), 0, "a plain outline: nothing where the text starts"); +} + +/// A polygon's stacked fills show in its swatch: a hatch over a fill, and a class's own fills +/// in its row, the other classes' plain (#2490). +#[test] +fn a_legend_draws_a_polygons_stacked_fills() { + let (black, red, white) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0), Rgba::rgb(255, 255, 255)); + let solid = rustgis_map::fills::FillLayer { color: Some(Rgba::rgb(0, 200, 0)), pattern: rustgis_map::fills::FillPattern::Solid }; + let map = shape_legend_map(GeometryType::Polygon, |l| l.fill_layers = vec![solid, hatch(black, 3.0)]); + let pm = point_legend(&map); + assert!(inked(&pm, 1..15, 4..11, black) > 5, "the hatch"); + assert!(inked(&pm, 1..15, 4..11, Rgba::rgb(0, 200, 0)) > 5, "the fill under it"); + // Classes: only the first has fills of its own, and the layer none. + let s = rustgis_map::Symbol { fill: red, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) }; + let map = shape_legend_map(GeometryType::Polygon, |l| { + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("a".to_string(), s), ("b".to_string(), s)], + other: s, + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: [("a".to_string(), vec![hatch(black, 3.0)])].into_iter().collect(), + other_fills: Vec::new(), + expression: None, + }; + }); + let pm = point_legend(&map); + // The layer's name, then a row a class, the swatch 6 points in. + assert!(inked(&pm, 7..21, 19..26, black) > 5, "class a's hatch"); + assert_eq!(inked(&pm, 7..21, 19..26, red), 0, "a hatch with no fill under it leaves the paper"); + assert!(inked(&pm, 7..21, 19..26, white) > 5); + assert_eq!(inked(&pm, 7..21, 34..41, black), 0, "class b has none"); + assert!(inked(&pm, 7..21, 34..41, red) > 50, "its symbol's fill"); +} + +/// A polygon's outline is drawn over its stacked fills, as on the map (#2490). +#[test] +fn a_legend_draws_a_polygons_outline_over_its_fills() { + let (blue, green) = (Rgba::rgb(0, 0, 255), Rgba::rgb(0, 200, 0)); + let s = rustgis_map::Symbol { stroke: blue, stroke_width: 2.0, ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) }; + let solid = rustgis_map::fills::FillLayer { color: Some(green), pattern: rustgis_map::fills::FillPattern::Solid }; + let map = shape_legend_map(GeometryType::Polygon, |l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.fill_layers = vec![solid]; + }); + let pm = point_legend(&map); + // The box's top edge, 3 points down, under the 2-point outline; its inside, the fill. + assert!(inked(&pm, 1..15, 3..4, blue) > 10, "the outline"); + assert_eq!(inked(&pm, 1..15, 3..4, green), 0, "no fill over it"); + assert!(inked(&pm, 2..14, 5..10, green) > 50, "the fill inside"); +} + +/// A diagram's categories keep their own colour on a layer with stacked strokes or fills. +#[test] +fn a_diagrams_rows_keep_their_colour_on_lines_and_polygons() { + let (black, red, green) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0), Rgba::rgb(0, 255, 0)); + let category = |field: &str, colour| rustgis_map::DiagramCategory { field: field.into(), colour }; + for gt in [GeometryType::Polyline, GeometryType::Polygon] { + let map = shape_legend_map(gt, |l| { + l.line_strokes = vec![plain_stroke(black, 8.0)]; + l.fill_layers = vec![hatch(black, 3.0)]; + l.diagram = Some(rustgis_map::DiagramSettings { + kind: rustgis_map::DiagramKind::Pie, + categories: vec![category("a", red), category("b", green)], + size: rustgis_map::DiagramSize::Fixed(12.0), + start_angle: 0.0, + background: None, + stroke: rustgis_map::DiagramSettings::default_stroke(), + stroke_width: 0.75, + labels: rustgis_map::DiagramLabel::None, + }); + }); + let pm = point_legend(&map); + assert_eq!(inked(&pm, 6..22, 15..45, black), 0, "{gt:?}: not the layer's stack"); + // A one-point line is mostly part-covered pixels: its hue tells it. + let tinted = |ys: std::ops::Range, hue: fn(tiny_skia::PremultipliedColorU8) -> bool| { + ys.flat_map(|y| (6..22).map(move |x| (x, y))).filter(|(x, y)| pm.pixel(*x, *y).is_some_and(hue)).count() + }; + assert!(tinted(15..30, |p| p.red() > p.green().saturating_add(60)) > 5, "{gt:?}: red"); + assert!(tinted(30..45, |p| p.green() > p.red().saturating_add(60)) > 5, "{gt:?}: green"); + } +} + +/// A see-through line or polygon layer's swatch is see-through too, as its points' are. +#[test] +fn a_legend_draws_a_see_through_polygon_see_through() { + let s = + rustgis_map::Symbol { fill: Rgba::rgb(255, 0, 0), stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) }; + let map = shape_legend_map(GeometryType::Polygon, |l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.transparency = 50.0; + }); + let p = point_legend(&map).pixel(8, 7).unwrap(); + assert_eq!(p.red(), 255); + assert!((100..160).contains(&p.green()), "{}", p.green()); +} + +/// A line grows with its layer's reference scale in the swatch, as on the map. +#[test] +fn a_legend_scales_a_line_with_its_reference_scale() { + let blue = Rgba::rgb(0, 0, 255); + let drawn = |reference: Option| { + let map = shape_legend_map(GeometryType::Polyline, |l| { + l.line_strokes = vec![plain_stroke(blue, 2.0)]; + l.reference_scale = reference; + }); + inked(&point_legend(&map), 0..16, 0..15, blue) + }; + // Drawn at 1:1e6: a reference of 1:2e6 makes it twice as wide. + assert!(drawn(Some(2e6)) * 2 > drawn(None) * 3, "{} against {}", drawn(Some(2e6)), drawn(None)); +} + +/// A vector export draws the stacked fills and strokes a raster one does. +#[test] +fn a_recorded_legend_draws_stacked_fills_and_strokes() { + let (black, red) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0)); + let map = shape_legend_map(GeometryType::Polygon, |l| l.fill_layers = vec![hatch(black, 3.0)]); + assert!(inked(&recorded_legend(&map, 200), 1..15, 4..11, black) > 5); + let map = shape_legend_map(GeometryType::Polyline, |l| l.line_strokes = vec![plain_stroke(black, 8.0), plain_stroke(red, 2.0)]); + let pm = recorded_legend(&map, 200); + assert!(inked(&pm, 0..16, 0..15, black) > 20 && inked(&pm, 0..16, 0..15, red) > 5); +} + +/// A box off the pixel grid: a recording cuts its symbol at the box, not at the whole pixels +/// round it, so the pixel its edge crosses is half covered. +#[test] +fn a_recorded_point_is_cut_at_its_box() { + let s = rustgis_map::Symbol { + fill: Rgba::rgb(0, 0, 255), + size: 3000.0, + stroke_width: 0.0, + marker: rustgis_map::Marker::Square, + ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) + }; + let map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s)); + let mut c = Canvas::recording(2100, 2100).unwrap(); + let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + legend(&mut c, Rect::from_xywh(0.5, 0.5, 2099.0, 2099.0).unwrap(), &map, ("", 1), None, opts, 1.0); + let (_, _, items) = c.into_drawing().unwrap().finish(); + let mut pm = Pixmap::new(2100, 2100).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::vector::replay(&items, &mut pm, Transform::identity()); + // The box runs from 0.5 to 2048.5. + let red = |x, y| pm.pixel(x, y).map_or(0, |p| p.red()); + assert_eq!(red(10, 10), 0); + assert!((60..200).contains(&red(2048, 10)), "{}", red(2048, 10)); + assert!((60..200).contains(&red(10, 2048)), "{}", red(10, 2048)); +} + +/// An upright square's and triangle's corners lie further than 0.6 of their size from their +/// centre, but along each axis, which is what the box holds, they stay inside it. +#[test] +fn an_upright_mark_stays_in_its_row() { + let s = rustgis_map::Symbol { size: 10.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + for marker in [rustgis_map::Marker::Square, rustgis_map::Marker::Triangle] { + let mut mark = square_mark(Rgba::rgb(0, 0, 255), 40.0); + if let Some(m) = &mut mark.markers { + m.mark = rustgis_map::LineMark::Marker(marker); + } + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.line_strokes = vec![mark]; + }); + let pm = point_legend(&map); + let white = |x, y| pm.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == (255, 255, 255)); + // A box of 48 points: its edges are clear, and the mark is in it. + assert!((0..48).all(|i| white(i, 0) && white(i, 47) && white(0, i) && white(47, i)), "{marker:?}"); + assert!(!white(24, 24), "{marker:?}"); + } +} + +/// A class's row draws the marks the map gives its features, else its layer's. +#[test] +fn a_legend_draws_a_class_with_its_own_marks() { + let s = rustgis_map::Symbol::default_for(GeometryType::Point, 0); + let (own, others, layers) = ( + vec![square_mark(Rgba::rgb(255, 0, 0), 12.0)], + vec![square_mark(Rgba::rgb(0, 255, 0), 12.0)], + vec![square_mark(Rgba::rgb(0, 0, 255), 12.0)], + ); + let map = point_legend_map(|l| { + l.line_strokes = layers.clone(); + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("a".to_string(), s), ("b".to_string(), s)], + other: s, + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: [("a".to_string(), own.clone())].into_iter().collect(), + other_strokes: others.clone(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + }); + let got = point_legend(&map); + // Under the layer's name, each row 15 points tall, its swatch 6 in: class a has its own, + // class b takes the layer's, and the fallback has its own. + for (row, strokes) in [(1u32, &own), (2, &layers), (3, &others)] { + let top = row * 15; + let want = drawn_point(&s, strokes, (14.0, top as f32 + 7.5), 1.0); + assert!((top..top + 15).all(|y| (6..22).all(|x| got.pixel(x, y) == want.pixel(x, y))), "row {row}"); + } +} + +/// A large point widens the column: a line or a box stays a swatch wide, and the names line up. +#[test] +fn a_wide_column_keeps_lines_and_boxes_a_swatch_wide_in_its_middle() { + use rustgis_data::Dataset; + let blue = Rgba::rgb(0, 0, 255); + let point = + rustgis_map::Symbol { fill: blue, size: 40.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + for gt in [GeometryType::Polyline, GeometryType::Polygon] { + // A point of 40 pt makes the column 48 wide: a swatch of 16 in its middle runs from 16 to 32. + let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(point)); + let id = map.add_dataset(Dataset::new("line", gt, vec![])); + let red = Rgba::rgb(255, 0, 0); + if let Some(l) = map.layer_mut(id) { + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { + fill: red, + stroke: red, + stroke_width: 2.0, + ..rustgis_map::Symbol::default_for(gt, 0) + }); + } + let pm = point_legend(&map); + let columns = |ink: &dyn Fn(u8, u8, u8) -> bool| -> Vec { + (0..pm.width()) + .filter(|&x| (0..pm.height()).any(|y| pm.pixel(x, y).is_some_and(|p| p.alpha() > 0 && ink(p.red(), p.green(), p.blue())))) + .collect() + }; + let swatch = columns(&|r, g, b| r > 200 && g < 60 && b < 60); + let (left, right) = (swatch.first().copied().unwrap_or(0), swatch.last().copied().unwrap_or(0)); + assert!((14..=17).contains(&left) && (31..=34).contains(&right), "{gt:?}: {left} to {right}"); + // Both names start past the column, where the blue point has no part in it. + let names = columns(&|r, g, b| r < 100 && g < 100 && b < 100); + assert!(names.first().is_some_and(|x| (53..60).contains(x)), "{gt:?}: {names:?}"); + } +} + +/// A symbol past the limit fills its box and stays in it, on pixels and in a recording. +#[test] +fn an_oversized_point_stays_in_its_row() { + let blue = Rgba::rgb(0, 0, 255); + let s = rustgis_map::Symbol { + fill: blue, + size: 3000.0, + stroke_width: 0.0, + marker: rustgis_map::Marker::Square, + ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) + }; + // Opaque and see-through: a row and a column of 2048 pt, which the square fills. + for transparency in [0.0, 50.0] { + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.transparency = transparency; + }); + let mut pm = Pixmap::new(2100, 2100).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(0.0, 0.0, 2100.0, 2100.0).unwrap(), &map, ("", 1), None, opts, 1.0) + }); + // Drawn, and recorded for a vector export, where only its clip cuts it. + for pm in [pm, recorded_legend(&map, 2100)] { + let white = |x, y| pm.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == (255, 255, 255)); + assert!(!white(10, 10) && !white(2040, 2040), "transparency {transparency}: it fills the box"); + assert!(white(10, 2060) && white(2060, 10), "transparency {transparency}: it stays in the box"); + } + } +} + +/// A legend starting off the canvas: a symbol larger than the canvas still covers all of it. +#[test] +fn a_see_through_point_larger_than_the_canvas_covers_it_from_off_its_edge() { + let s = rustgis_map::Symbol { + fill: Rgba::rgb(0, 0, 255), + size: 3000.0, + stroke_width: 0.0, + marker: rustgis_map::Marker::Square, + ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) + }; + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.transparency = 50.0; + }); + let mut pm = Pixmap::new(300, 300).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let opts = LegendOptions { show_no_data: false, hide_other: false, exclude: &[], labels: &NO_LABELS, scale: 1e6, size: 1.0 }; + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(-50.0, -50.0, 2100.0, 2100.0).unwrap(), &map, ("", 1), None, opts, 1.0) + }); + // Its box runs from -50 to 1998: every corner of the canvas is in it. + for (x, y) in [(5, 5), (295, 5), (5, 295), (295, 295)] { + let white = pm.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == (255, 255, 255)); + assert!(!white, "({x}, {y})"); + } +} + +/// A class's large symbol counts in a legend's size as a plain row's does. +#[test] +fn a_class_row_takes_the_wide_column_in_a_legends_size() { + let mm = 25.4 / 96.0; + let s = rustgis_map::Symbol { size: 40.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + let mut map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("a".to_string(), s)], + other: s, + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + }); + // The layer's name over the class: a row of 15 and one of 48, 6 + 48 + 6 before its label. + let [(w, h), ..] = legend_sizes_mm(&mut map, 1e6, true, true, (&[], &NO_LABELS)).unwrap(); + assert!((h - f64::from(LEGEND_ROW + 48.0) * mm).abs() < 1e-6, "{h} mm"); + assert!((w - f64::from(48.0 + 12.0 + text::measure("a", 8.5, false)) * mm).abs() < 1e-4, "{w} mm"); +} + +/// An element's background (#2257) is drawn under it on the page, grown by its padding and +/// turned with a turned text; drawn alone, as an SVG's picture of it, the element leaves it to +/// the SVG's own shape. +#[test] +fn a_background_is_drawn_under_its_element_and_turns_with_it() { + use rustgis_map::layout::Background; + let px = |mm: f64| (mm * 96.0 / 25.4).round() as u32; + let red = |pm: &Pixmap, x: f64, y: f64| rgb(pm, px(x), px(y)) == (255, 0, 0); + let page = |turn: f64, background: Option| { + let mut l = Layout::new("L", 100.0, 100.0); + let mut kind = ElementKind::text("", 12.0, Rgba::rgb(0, 0, 0), false); + if let ElementKind::Text { rotation, .. } = &mut kind { + *rotation = turn; + } + let id = l.add("T", (40.0, 40.0, 20.0, 10.0), kind); + l.element_mut(id).unwrap().background = background; + (l, id) + }; + let back = Background { padding: 5.0, ..Background::filled(Rgba::rgb(255, 0, 0)) }; + let (plain, _) = page(0.0, None); + assert!(!red(&render(&plain, &mut [], 96.0, &PageInfo::default()).unwrap(), 45.0, 45.0), "none by default"); + let (l, id) = page(0.0, Some(back)); + let pm = render(&l, &mut [], 96.0, &PageInfo::default()).unwrap(); + assert!(red(&pm, 45.0, 45.0), "inside the box"); + assert!(red(&pm, 37.0, 37.0), "in the padding"); + assert!(!red(&pm, 33.0, 45.0), "past the padding"); + // Turned 90°, the box (and so its background) stands upright about its centre (50, 45). + let (turned, _) = page(90.0, Some(Background::filled(Rgba::rgb(255, 0, 0)))); + let pm = render(&turned, &mut [], 96.0, &PageInfo::default()).unwrap(); + assert!(red(&pm, 50.0, 37.0), "above the unturned box, inside the turned one"); + assert!(!red(&pm, 42.0, 45.0), "left of the turned box"); + // Clockwise, as the text turns: at 30° the box's right end dips below its centre line, at + // -30° it rises (90° alone would look the same either way). + let at = |turn: f64| { + red( + &render(&page(turn, Some(Background::filled(Rgba::rgb(255, 0, 0)))).0, &mut [], 96.0, &PageInfo::default()).unwrap(), + 59.0, + 46.0, + ) + }; + assert!(at(30.0) && !at(-30.0), "turned clockwise"); + // Alone, the element's picture holds no background. + let (alone, _) = render_element(&l, id, &mut [], 96.0, (&PageInfo::default(), &Env::default()), &mut None).unwrap().unwrap(); + assert!(alone.pixels().iter().all(|c| c.alpha() == 0 || c.green() > 0), "no red in the element's own picture"); +} diff --git a/crates/render/src/layout/textbox.rs b/crates/render/src/layout/textbox.rs new file mode 100644 index 0000000000..e8b0d02448 --- /dev/null +++ b/crates/render/src/layout/textbox.rs @@ -0,0 +1,226 @@ +//! Text in a box: style, wrapping, vertical alignment and drawing. + +use super::*; + +/// How a text element's lines are drawn, beyond their size and colour. +#[derive(Clone, Copy)] +pub(crate) struct TextStyle { + /// Bold, italic and the family. + pub(crate) face: text::Face, + pub(crate) align: TextAlign, + /// Letter spacing in points. + pub(crate) spacing: f32, + /// Where its block of lines sits down its box ([`block_shift`]). + pub(crate) valign: TextVAlign, + /// The distance between its lines, a multiple of the usual (0.5 to 3). + pub(crate) line_spacing: f32, +} + +impl TextStyle { + /// This style with a text's block alignment and line spacing, brought into range here, so every + /// reader of `line_spacing` may trust it: an unknown alignment is the top, and the spacing is + /// as [`rustgis_map::layout::line_spacing_in_range`] reads it (not finite is the usual one, one + /// outside 0.5..=3 the nearer limit). The usual spacing is exactly 1, so a plain text is placed + /// as it always was. + pub(crate) fn with_block(self, valign: TextVAlign, line_spacing: f64) -> TextStyle { + TextStyle { valign: valign.kept(), line_spacing: rustgis_map::layout::line_spacing_in_range(line_spacing) as f32, ..self } + } +} + +/// A text element's style: its face in an installed family by name (#762), else its generic one. +/// The app doesn't wait for the font index while it is being built; a script or the command line +/// builds it now (`families::find_ready`). One for the page, its clipping check and the SVG, so +/// each measures and breaks a text alike. +pub(crate) fn text_style( + bold: bool, + italic: bool, + font: rustgis_map::layout::FontFamily, + font_name: Option<&str>, + align: TextAlign, + letter_spacing: f64, +) -> TextStyle { + let family = font_name.and_then(crate::families::find_ready); + let face = text::Face { bold, italic, serif: font == rustgis_map::layout::FontFamily::Serif, family }; + TextStyle { face, align, spacing: letter_spacing as f32, valign: TextVAlign::Top, line_spacing: USUAL_LINE_SPACING } +} + +/// Pixels per millimetre a wrapped text's lines are measured at (300 dpi), whatever the +/// resolution it is drawn at, so the layout view, each export and the SVG break the same lines. +pub(super) const WRAP_PX_PER_MM: f64 = 300.0 / 25.4; + +/// A wrapped text (#2346) as the lines it is drawn in, joined by line breaks: each of its own +/// lines broken at spaces to fit `width` mm at `size` points, a word wider than that broken +/// across lines ([`crate::report::wrap_lines`]). A line is measured as [`text_block`] places it: +/// a left-aligned one from the box's edge to its ink's right, an aligned one by its ink. +pub(crate) fn wrapped(s: &str, width: f64, size: f64, style: TextStyle) -> String { + let ppp = (WRAP_PX_PER_MM / PT_PER_MM) as f32; + let px = (size as f32).clamp(2.0, 400.0) * 1.33 * ppp; + let spacing = style.spacing * 1.33 * ppp; + let measure = |t: &str| { + let (lo, hi) = text::styled_extent(t, px, style.face, spacing); + f64::from(if style.align == TextAlign::Left { hi } else { hi - lo }) + }; + // Lines past the 200 a text draws aren't broken: one more, with text, tells the cut-off check + // it goes on. + crate::report::wrap_lines(s, width * WRAP_PX_PER_MM, measure, 200).join("\n") +} + +/// A text element's lines as they are drawn, from its text with its tokens filled in ([`expand`]): +/// in its case, then, when it wraps, broken to its box `width_mm` wide ([`wrapped`]), so an upper +/// case text breaks at its own, wider, width. One for the page, its cut-off check and the SVG, so +/// they draw and count the same lines. Those that don't fit its box are left out from the bottom +/// whatever its block alignment: a block taller than its box starts at its top ([`block_shift`]). +pub(crate) fn drawn_text(expanded: String, case: TextCase, wrap: bool, width_mm: f64, size: f64, style: TextStyle) -> String { + let s = case.kept().apply(expanded); + if wrap { wrapped(&s, width_mm, size, style) } else { s } +} + +/// The most lines a text draws. +pub(super) const MAX_TEXT_LINES: usize = 200; + +/// [`block_shift`] for the text `s` as it is drawn ([`drawn_text`]), by its lines. A text of more +/// lines than a text draws is cut at them, so it starts at the top like any block that doesn't fit +/// its box, though the lines kept would: one rule for the page, its cut-off check, a turned text's +/// picture and the SVG. +pub(crate) fn text_shift(valign: TextVAlign, box_h: f64, px: f64, s: &str, line_spacing: f64) -> f64 { + let lines = s.lines().take(MAX_TEXT_LINES + 1).count(); + if lines > MAX_TEXT_LINES { 0.0 } else { block_shift(valign, box_h, px, lines, line_spacing) } +} + +/// How far down its box of `box_h` pixels a text's block of `lines` lines at `px` pixels, spaced +/// `line_spacing` times the usual, starts: 0 at the top; half the room it leaves in the middle; +/// all of it at the bottom, its last line's pitch ending on the box's bottom edge. A block taller +/// than its box (or with no line) starts at its top whatever its alignment, so its first lines are +/// the ones kept and none is drawn above the box. +pub(crate) fn block_shift(valign: TextVAlign, box_h: f64, px: f64, lines: usize, line_spacing: f64) -> f64 { + if lines == 0 || valign.kept() == TextVAlign::Top { + return 0.0; + } + let block = px * 1.25 * (1.0 + (lines - 1) as f64 * line_spacing); + let free = box_h - block; + // A measure not a number, or past any page, is no room. + if !free.is_finite() || free <= 0.0 { + return 0.0; + } + match valign.kept() { + TextVAlign::Middle => free / 2.0, + TextVAlign::Bottom => free, + _ => 0.0, + } +} + +/// The lines a wrapped text element (#2346), upright and without letter spacing or a named family, +/// is drawn in: `s`, its text with the dynamic text filled in, in a box `width` mm wide. For a +/// caller that sizes the box around the text. +pub fn wrapped_lines(s: &str, width: f64, size: f64, bold: bool, font: rustgis_map::layout::FontFamily, align: TextAlign) -> Vec { + wrapped(s, width, size, text_style(bold, false, font, None, align, 0.0)).lines().map(str::to_string).collect() +} + +/// The usual line spacing ([`rustgis_map::layout::LINE_SPACING`]) as the drawing holds it. +pub(super) const USUAL_LINE_SPACING: f32 = rustgis_map::layout::LINE_SPACING as f32; + +/// The distance between two lines of text at `size` points, in mm, at the usual line spacing (1), +/// as [`text_block`] sets them there; a text's line spacing multiplies it. +pub fn line_pitch_mm(size: f64) -> f64 { + size.clamp(2.0, 400.0) * 1.33 * 1.25 * 25.4 / 96.0 +} + +/// The part of a text element's box (pixels, from its top-left corner) [`text_block`] inks, a line's +/// height more each way: across, its lines as each is aligned (past the box where one overruns +/// it); down, its lines from where its block starts ([`block_shift`]), or the box and the line +/// [`text_block`] still draws past it. `None` when it has no line. +pub(super) fn text_area(r: Rect, s: &str, size: f32, style: TextStyle, ppp: f64) -> Option { + let px = size.clamp(2.0, 400.0) * 1.33 * ppp as f32; + let spacing = style.spacing * 1.33 * ppp as f32; + let w = r.width(); + let (mut x0, mut x1, mut lines) = (f32::INFINITY, f32::NEG_INFINITY, 0u16); + for line in s.lines().take(200) { + let (lo, hi) = text::styled_extent(line, px, style.face, spacing); + // Where `text_block` puts the ink: from the edge (left), or by the ink (centre, right). + let (a, b) = match style.align { + TextAlign::Left => (lo, hi), + TextAlign::Center => ((w - (hi - lo)) / 2.0, (w + (hi - lo)) / 2.0), + TextAlign::Right => (w - (hi - lo), w), + }; + (x0, x1, lines) = (x0.min(a), x1.max(b), lines + 1); + } + // Down to its last line, where its block alignment and line spacing put it. + let shift = text_shift(style.valign, f64::from(r.height()), f64::from(px), s, f64::from(style.line_spacing)) as f32; + let block = (1.0 + (f32::from(lines) - 1.0) * style.line_spacing) * px * 1.25; + let down = (r.height() + px).min(shift + block); + (lines > 0).then(|| Rect::from_ltrb(x0 - px, shift - px, x1 + px, down + px)).flatten() +} + +/// Draws with `draw` (given the box to draw in and how many of the page's pixels one of its own +/// is) turned `degrees` clockwise about the centre of `r`: kept turned on a recording canvas (a +/// vector PDF), else drawn upright in a picture of `area` (pixels from the box's top-left corner: +/// what it inks), which is placed turned. A picture past the page's budget is drawn at a lower +/// resolution and scaled up, as a frame that large is. Its size is at least a pixel and at most +/// the budget, and `r` and `area` have a size, so the picture is always made. +/// +/// A quarter turn at full resolution maps the picture's pixels one for one onto the page's: it is +/// placed on whole pixels and not filtered, the part of a pixel that moved it drawn into the +/// picture instead, so its text is sampled once, as upright text is, and keeps as sharp. Another +/// turn is sampled once more, by the turn. +pub(super) fn draw_turned_box(pm: &mut Canvas, r: Rect, degrees: f32, area: Rect, draw: impl FnOnce(&mut Canvas, Rect, f64)) { + let (cx, cy) = (r.x() + r.width() / 2.0, r.y() + r.height() / 2.0); + if pm.is_recording() { + pm.with_transform(Transform::from_rotate_at(degrees, cx, cy), |c| draw(c, r, 1.0)); + return; + } + let (w, h) = (f64::from(area.width()), f64::from(area.height())); + let k = (MAX_PIXELS / (w * h)).sqrt().min(MAX_SIDE / w.max(h)).min(1.0) as f32; + let (pw, ph) = ((w as f32 * k).ceil().max(1.0), (h as f32 * k).ceil().max(1.0)); + let mut place = + Transform::from_scale(1.0 / k, 1.0 / k).post_translate(r.x() + area.x(), r.y() + area.y()).post_rotate_at(degrees, cx, cy); + let quarter = k == 1.0 && degrees.rem_euclid(90.0) == 0.0; + let (mut dx, mut dy) = (0.0, 0.0); + if quarter { + // Its turn exactly (0 or ±1 each way), and its corner on a whole pixel: the picture's + // content moves back by as much, turned back (the turn's inverse is its transpose). + let [sx, ky, kx, sy] = [place.sx, place.ky, place.kx, place.sy].map(f32::round); + let (ex, ey) = (place.tx.round() - place.tx, place.ty.round() - place.ty); + (dx, dy) = (-(sx * ex + ky * ey), -(kx * ex + sy * ey)); + place = Transform::from_row(sx, ky, kx, sy, place.tx.round(), place.ty.round()); + } + // The box in the picture: its corner `area`'s offset away from the picture's (and less than a + // pixel more, within the room `area` leaves round the ink). + let inner = Rect::from_xywh(-area.x() * k + dx, -area.y() * k + dy, r.width() * k, r.height() * k); + let (Some(mut pic), Some(inner)) = (Canvas::new(pw as u32, ph as u32), inner) else { return }; + draw(&mut pic, inner, f64::from(k)); + let quality = if quarter { tiny_skia::FilterQuality::Nearest } else { tiny_skia::FilterQuality::Bilinear }; + let paint = PixmapPaint { quality, ..PixmapPaint::default() }; + pm.draw_pixmap(0, 0, pic.pixmap().as_ref(), &paint, place, None); +} + +/// Text in an element: lines split at `\n`, the block of them at the top, middle or bottom of the +/// box ([`block_shift`]) and spaced by the style's line spacing, each placed by the style's +/// alignment. A block taller than its box starts at its top whatever its alignment, so its first +/// lines are drawn and the ones past the box left out ([`text_losses`] counts them). A centred or +/// right-aligned line wider than the element runs out past its left edge, as a left-aligned one +/// runs past its right. +pub(super) fn text_block(pm: &mut Canvas, r: Rect, s: &str, size: f32, color: Rgba, style: TextStyle, ppp: f64) { + let px = size.clamp(2.0, 400.0) * 1.33 * ppp as f32; + // Letter spacing is in points, as the size is. + let spacing = style.spacing * 1.33 * ppp as f32; + let shift = text_shift(style.valign, f64::from(r.height()), f64::from(px), s, f64::from(style.line_spacing)) as f32; + let mut y = r.y() + shift + px * 0.6; + for line in s.lines().take(200) { + if y > r.y() + r.height() + px { + break; + } + // Centred and right-aligned lines are placed by the ink they draw (italic overhang and a + // negative spacing included), which an advance doesn't measure; left-aligned ones start + // at the edge as plain text always has. + let left = match style.align { + TextAlign::Left => r.x(), + aligned => { + let (ink_left, ink_right) = text::styled_extent(line, px, style.face, spacing); + let free = r.width() - (ink_right - ink_left); + r.x() + if aligned == TextAlign::Center { free / 2.0 } else { free } - ink_left + } + }; + text::styled_at(pm, line, left, y, px, color, style.face, spacing); + y += px * 1.25 * style.line_spacing; + } +}