From 23d2bfbc2da8a3839d11849bfc33f04c5bf7506e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 29 Nov 2026 10:17:33 -0500 Subject: [PATCH 1/7] feat(layout): a legend draws a layer's sizes nested on one base (#3347) --- crates/assistant/skills/print-layout/SKILL.md | 2 +- crates/engine/command-surface.txt | 4 +- crates/engine/src/cmd/layout.rs | 18 ++- crates/engine/src/cmd/layout/elements.rs | 8 +- crates/engine/src/cmd/layout/legend.rs | 14 +- .../engine/src/cmd/layout/publication/mod.rs | 1 + .../src/cmd/layout/publication/parts.rs | 1 + crates/engine/src/cmd/layout/update.rs | 8 + crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 21 +++ crates/engine/src/tests.rs | 7 + crates/engine/src/tests/layout_files.rs | 1 + .../engine/src/tests/layout_legend_sizes.rs | 125 +++++++++++++++ crates/map/src/diagram.rs | 1 + crates/map/src/layout.rs | 2 + crates/map/src/layout/elements.rs | 10 ++ crates/map/src/layout/legend.rs | 63 ++++++++ crates/map/src/symbol_by.rs | 1 + crates/map/src/symbology.rs | 17 +- crates/render/src/layout.rs | 3 + crates/render/src/layout/legend.rs | 67 +++++++- .../render/src/layout/legend/count_tests.rs | 3 + crates/render/src/layout/legend/nested.rs | 106 +++++++++++++ .../render/src/layout/legend/nested/tests.rs | 148 ++++++++++++++++++ crates/render/src/layout/tests.rs | 37 +++++ crates/render/src/stream_tests.rs | 1 + crates/render/src/svg.rs | 2 + crates/ui-egui/src/panes.rs | 1 + docs/maintaining.md | 7 + docs/user-guide/layouts.md | 9 +- .../fixtures/layout_legend_nested_sizes.rgis | 25 +++ schema/project.schema.json | 2 + 32 files changed, 691 insertions(+), 25 deletions(-) create mode 100644 crates/engine/src/tests/layout_legend_sizes.rs create mode 100644 crates/render/src/layout/legend/nested.rs create mode 100644 crates/render/src/layout/legend/nested/tests.rs create mode 100644 schema/fixtures/layout_legend_nested_sizes.rgis diff --git a/crates/assistant/skills/print-layout/SKILL.md b/crates/assistant/skills/print-layout/SKILL.md index 0111d6ad84..3eb6c356e8 100644 --- a/crates/assistant/skills/print-layout/SKILL.md +++ b/crates/assistant/skills/print-layout/SKILL.md @@ -26,7 +26,7 @@ description: Make a printable page layout — map frame, title, legend, north ar (`"auto"`, the default, or 0–3 fixed with the thousands set apart, as a chart's), `"textSize"` (4–100 pt, its labels' size) and `"fit"` (`"adjustDivisionValue"`, `"adjustDivision"`, `"adjustWidth"`). A `"legend"` can take `"columns"` (1–6), `"fit"` (`"manual"`, `"adjustSize"`, `"adjustColumns"`, `"adjustColumnsAndSize"`: shrink its - text or add columns to fit its box), `"subtitle"` (one line under its title), `"showCounts": true` (each class row ends in its number of features; none for a layer read from a database, over the web or a view at a time from other files), + text or add columns to fit its box), `"subtitle"` (one line under its title), `"sizes": "nested"` (a point layer's marker sizes one inside another on a common base), `"showCounts": true` (each class row ends in its number of features; none for a layer read from a database, over the web or a view at a time from other files), `"showLayerNames": false`, `"layerOrder": [""]` (those layers first, the map unchanged) and `"classLabels"` (`{"": {"": ""}}`: its own text for a class, the layer keeping its label). A `"text"` or `"dynamicText"` can take diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 41ac641245..58c0c59c93 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -283,7 +283,7 @@ layer.transparency layer? value layer.visibility layer? visible? layer.zoomTo layer? layout.activate name layout -layout.addElement layout? kind frame? of? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? columns? textSize? classLabels? showCounts? showLayerNames? orientation? ticks? tickSide? reverse? fill? width? radius? dash? dir? head? angle? length? image? path? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? barOutline? rows? step? type? crs? short? mgrs? labels? style? tickLength? format? hemisphere? edges? labelOrientation? labelSize? off? name? direction? at? section? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? outline? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? x? y? w? h? background? +layout.addElement layout? kind frame? of? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? columns? textSize? classLabels? sizes? showCounts? showLayerNames? orientation? ticks? tickSide? reverse? fill? width? radius? dash? dir? head? angle? length? image? path? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? barOutline? rows? step? type? crs? short? mgrs? labels? style? tickLength? format? hemisphere? edges? labelOrientation? labelSize? off? name? direction? at? section? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? outline? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? x? y? w? h? background? layout.addFrame layout? shape? points? map? x? y? w? h? layout.arrange layout? element to layout.arrangement favourite? save? arrangement? remove? @@ -305,7 +305,7 @@ layout.save layout? path layout.series layout? layer nameField? frame? margin? off? layout.seriesPage layout? page layout.seriesRefresh layout? -layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? labels? classLabels? columns? textSize? showLayerNames? showCounts? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? barOutline? hideLabels? rows? background? +layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? labels? classLabels? columns? textSize? showLayerNames? sizes? showCounts? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? barOutline? hideLabels? rows? background? locator.find locator? text limit? zoom? map.activate name map.addTiles url kind? name? bounds? attribution? minZoom? maxZoom? tileSize? singleImage? tms? subdomains? layers? styleLayers? opacity? blend? resampling? overlay? top? replace? id? view? start? end? unit? interval? dates? legend? connection? diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 88a808c7f9..585e4905e6 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -9,11 +9,12 @@ use rustgis_geom::{Coord, Extent}; use rustgis_map::layout::{ Arrange, ArrowStyle, Background, CHART_BAR, CHART_BARS, CHART_OUTLINE, ChartOrder, ChartOutline, ClassLabels, CoordFormat, ElementKind, FeatureCounts, FontFamily, FrameShape, GRID_LABEL_PT, Grid, GridEdges, GridKind, GridStyle, Guides, LAYOUT_TEXT_SIZE, LINE_SPACING, - LayerNames, Layout, LegendFit, LineDir, LineHead, MAX_CHART_BARS, MAX_CHART_DECIMALS, MAX_CHART_OUTLINE_WIDTH, MAX_COLORBAR_TICKS, - MAX_GRID_WIDTH, MAX_GUIDES, MAX_LEGEND_COLUMNS, MAX_LEGEND_LABEL_CHARS, MAX_LEGEND_LABELS, MAX_LINE_SPACING, MAX_SCALE_BEFORE_ZERO, - MAX_SCALE_DECIMALS, MAX_SCALE_DIVISIONS, MAX_SCALE_SUBDIVISIONS, MAX_SECTIONS, MAX_TICK_MM, MAX_UNIT_LABEL_CHARS, MIN_ELEMENT_MM, - MIN_LINE_SPACING, MapSeries, Orientation, PAGES, SCALE_BAR_TEXT_PT, ScaleBarFit, ScaleBarStyle, ScaleLabelPosition, ScaleUnits, - Section, SectionLine, TextAlign, TextCase, TextVAlign, TickSide, UnitLabelPosition, fit_scale, line_angle, line_at_angle, line_length, + LayerNames, Layout, LegendFit, LegendSizes, LineDir, LineHead, MAX_CHART_BARS, MAX_CHART_DECIMALS, MAX_CHART_OUTLINE_WIDTH, + MAX_COLORBAR_TICKS, MAX_GRID_WIDTH, MAX_GUIDES, MAX_LEGEND_COLUMNS, MAX_LEGEND_LABEL_CHARS, MAX_LEGEND_LABELS, MAX_LINE_SPACING, + MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DECIMALS, MAX_SCALE_DIVISIONS, MAX_SCALE_SUBDIVISIONS, MAX_SECTIONS, MAX_TICK_MM, + MAX_UNIT_LABEL_CHARS, MIN_ELEMENT_MM, MIN_LINE_SPACING, MapSeries, Orientation, PAGES, SCALE_BAR_TEXT_PT, ScaleBarFit, ScaleBarStyle, + ScaleLabelPosition, ScaleUnits, Section, SectionLine, TextAlign, TextCase, TextVAlign, TickSide, UnitLabelPosition, fit_scale, + line_angle, line_at_angle, line_length, }; use rustgis_map::report::StatKind; use rustgis_map::symbology::{Dash, MAX_DASH_STEP, MAX_DASH_STEPS}; @@ -41,7 +42,9 @@ pub(crate) use inputs::*; mod legend; pub(in crate::cmd) use legend::say_unfitted_legends_in; use legend::*; -pub(crate) use legend::{legend_columns_param, legend_counts_param, legend_fit_param, legend_names_param, legend_subtitle_param}; +pub(crate) use legend::{ + legend_columns_param, legend_counts_param, legend_fit_param, legend_names_param, legend_sizes_param, legend_subtitle_param, +}; mod page; use page::*; mod profile; @@ -212,6 +215,7 @@ pub fn commands() -> Vec { r##""columns"?: 1..6 (legend: the columns its rows are laid in; default 1; with a fit that adds columns, the fewest it starts from), "##, r##""textSize"?: points, 4 to 100 (legend: its layers' names and classes' labels, its title, rows, swatches and gaps following in proportion and a point symbol keeping the size the map draws it at; default 9; scaleBar: its labels, the room over the bar and between them following, the bar keeping its size; default 8; refused outside that range, and for other kinds unless null, as showNoData is), "##, r##""classLabels"?: {"": {"": ""}} (legend: its own text for a class, by the label the layer shows for it, up to 200 characters; the layer keeps its label; a layer or class it can't find is refused), "##, + r##""sizes"?: "rows" (default) | "nested" (legend: a point layer's rows of marker sizes drawn as one block, the markers one inside another on a common base, each led to its value; refused for other kinds), "##, r##""showCounts"?: bool (legend: each class row, and a one-symbol layer's row, ends in the number of features the layer's filters keep; default false; none for rasters, web layers, size and diagram rows, layers read in place other than from a local Shapefile, GeoPackage, FlatGeobuf or GeoParquet (each of those is read whole to count), or Unique Values by an expression over too many features and classes; refused for other kinds), "##, r##""showLayerNames"?: bool (legend: the name over each layer's classes and over a web layer's legend picture; default true; a layer drawn in one symbol keeps its name; refused for other kinds), "##, r##""orientation"?: "horizontal"|"vertical" (colorbar; chart: bars running across, the default, or columns standing up, each label centred under its column), "##, @@ -327,6 +331,7 @@ pub fn commands() -> Vec { r##""columns"?: 1..6 (legend), "##, r##""textSize"?: points, 4 to 100 (legend, scaleBar, as in layout.addElement, null giving each its default again; refused outside that range, and for other elements unless null), "##, r##""showLayerNames"?: bool (legend, as in layout.addElement; null leaves it as it is), "##, + r##""sizes"?: "rows"|"nested" (legend, as in layout.addElement; null leaves it as it is), "##, r##""showCounts"?: bool (legend, as in layout.addElement; null leaves it as it is), "##, r##""orientation"? (colorbar, chart), "##, r##""ticks"?, "##, @@ -625,6 +630,7 @@ pub(crate) fn new_layout(s: &mut Session, p: &Value) -> CmdResult { class_labels: Default::default(), show_counts: Default::default(), subtitle: Default::default(), + sizes: Default::default(), }, ); l.add("North Arrow", (side + sw / 2.0 - 8.0, m + 16.0 + fh * 0.62, 16.0, 24.0), ElementKind::north_arrow(frame)); diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index bc9d169446..f8b1ca8c53 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -296,6 +296,9 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu if kind != "legend" && gives(p, "subtitle") { return Err(ONLY_LEGEND_SUBTITLE.into()); } + if kind != "legend" && gives(p, "sizes") { + return Err(ONLY_LEGEND_SIZES.into()); + } if legend_names_param(p)?.is_some() && kind != "legend" { return Err(ONLY_LEGEND_NAMES.into()); } @@ -425,6 +428,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu let show_layer_names = legend_names_param(p)?.map_or(LayerNames::Shown, LayerNames::from_shown); let show_counts = legend_counts_param(p)?.map_or(FeatureCounts::Hidden, FeatureCounts::from_shown); let subtitle = legend_subtitle_param(p)?.unwrap_or_default(); + let sizes = legend_sizes_param(p)?.unwrap_or_default(); ( "Legend", place(p, l, (pw - 70.0, 45.0, 60.0, 80.0))?, @@ -445,6 +449,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu class_labels, show_counts, subtitle, + sizes, }, ) } @@ -1015,6 +1020,7 @@ const ADD_LEGEND_KEYS: &[&str] = &[ "fit", "showLayerNames", "showCounts", + "sizes", "color", ]; @@ -1499,7 +1505,7 @@ mod tests { let calls = [ json!({"kind": "northArrow", "layout": 0, "frame": frame, "x": 10, "y": 10, "w": 15, "h": 20, "style": "compass", "fill": "#112233", "outline": "#445566", "background": {"fill": "#FFFFFF"}}), json!({"kind": "scaleBar", "frame": frame, "x": 10, "y": 10, "w": 60, "h": 12, "style": "stepped", "units": "miles", "divisions": 3, "subdivisions": 2, "divisionsBeforeZero": 1, "labelPosition": "below", "unitLabel": "mi", "unitLabelPosition": "afterBar", "fit": "adjustWidth", "decimals": 1, "textSize": 9, "color": "#112233", "fill": "#FFFFFF"}), - json!({"kind": "legend", "frame": frame, "title": "T", "allClasses": true, "hideOther": true, "showNoData": true, "exclude": [], "layerOrder": [], "columns": 2, "labels": {}, "textSize": 8, "fit": "adjustSize", "showLayerNames": false, "showCounts": true, "color": "#112233"}), + json!({"kind": "legend", "frame": frame, "title": "T", "allClasses": true, "hideOther": true, "showNoData": true, "exclude": [], "layerOrder": [], "columns": 2, "labels": {}, "textSize": 8, "fit": "adjustSize", "showLayerNames": false, "showCounts": true, "sizes": "nested", "color": "#112233"}), json!({"kind": "colorbar", "frame": frame, "title": "T", "orientation": "vertical", "ticks": 3, "tickSide": "left", "reverse": true, "color": "#112233"}), json!({"kind": "text", "text": "A", "size": 14, "color": "#112233", "bold": true, "italic": true, "align": "center", "letterSpacing": 1, "font": "Some Family", "fallback": "serif", "rotation": 90, "wrap": true, "valign": "middle", "lineSpacing": 1.5, "case": "upper", "name": "ignored"}), json!({"kind": "dynamicText", "text": "{map}", "size": 10}), diff --git a/crates/engine/src/cmd/layout/legend.rs b/crates/engine/src/cmd/layout/legend.rs index 69cec42bc1..773188628e 100644 --- a/crates/engine/src/cmd/layout/legend.rs +++ b/crates/engine/src/cmd/layout/legend.rs @@ -124,7 +124,7 @@ pub(in crate::cmd::layout) fn tells_legend_fit(kind: &ElementKind, p: &Value) -> let watched = *columns > 1 || *text_size != rustgis_map::layout::LEGEND_TEXT_PT || fit.kept() != LegendFit::Manual; let refitted = ["w", "h", "title", "allClasses", "hideOther", "exclude", "layerOrder", "labels", "classLabels"].iter().any(|k| given(k)); - ["columns", "showNoData", "labels", "classLabels", "fit", "showLayerNames", "showCounts", "subtitle"].iter().any(|k| given(k)) + ["columns", "showNoData", "labels", "classLabels", "fit", "showLayerNames", "showCounts", "subtitle", "sizes"].iter().any(|k| given(k)) || p.get("textSize").is_some() || (watched && refitted) } @@ -152,6 +152,7 @@ pub(in crate::cmd::layout) fn say_legend_fit(s: &mut Session, li: usize, id: u32 class_labels, show_counts, subtitle, + sizes, .. } = &e.kind else { @@ -167,6 +168,7 @@ pub(in crate::cmd::layout) fn say_legend_fit(s: &mut Session, li: usize, id: u32 let (fit, layer_names, class_labels) = (fit.kept(), show_layer_names.shown(), class_labels.clone()); let show_counts = show_counts.shown(); let layer_order = layer_order.clone(); + let sizes = *sizes; let found = shown .and_then(|(name, center, scale)| Some((s.project.maps.iter_mut().find(|m| m.name.eq_ignore_ascii_case(&name))?, center, scale))); let Some((map, center, scale)) = found else { @@ -185,6 +187,7 @@ pub(in crate::cmd::layout) fn say_legend_fit(s: &mut Session, li: usize, id: u32 labels: &labels, class_labels: &class_labels, show_counts, + sizes, }; let measured = if fit == LegendFit::Manual { let n = rustgis_map::layout::legend_columns_in_range(columns); @@ -303,6 +306,15 @@ pub(crate) fn legend_subtitle_param(p: &Value) -> Result, String> .transpose() } +/// The refusal for `sizes` on an element other than a legend. +pub(in crate::cmd::layout) const ONLY_LEGEND_SIZES: &str = "only legends take sizes"; + +/// The `"sizes"` a legend is given (#3347), a name (`null` is not given): the one reader the +/// commands and the `layout-legend-nested-sizes` capability check share. +pub(crate) fn legend_sizes_param(p: &Value) -> Result, String> { + given_choice(p, "sizes", LegendSizes::from_name, "rows or nested") +} + /// The `"showCounts"` a legend is given, `true` or `false` only (`null` is not given): the one /// reader the commands and the `layout-legend-counts` capability check share. pub(crate) fn legend_counts_param(p: &Value) -> Result, String> { diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index 7d556d19f8..bde2f2bec1 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -2080,6 +2080,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu class_labels: Default::default(), show_counts: Default::default(), subtitle: Default::default(), + sizes: Default::default(), }, ); } diff --git a/crates/engine/src/cmd/layout/publication/parts.rs b/crates/engine/src/cmd/layout/publication/parts.rs index ee010df512..b4dcbf4e48 100644 --- a/crates/engine/src/cmd/layout/publication/parts.rs +++ b/crates/engine/src/cmd/layout/publication/parts.rs @@ -172,6 +172,7 @@ impl PublicationLegend { labels: &labels, class_labels: &rustgis_map::layout::ClassLabels::NONE, show_counts: false, + sizes: Default::default(), }; [legend_size_asked_mm(map, scale, &asked, columns)?; PUBLICATION_LEGEND_COLUMNS] } diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index cf27dd6ad1..c3aecd009d 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -483,6 +483,10 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { return Err(ONLY_LEGEND_SUBTITLE.into()); } let new_subtitle = legend_subtitle_param(p)?; + if gives(p, "sizes") && !is_legend { + return Err(ONLY_LEGEND_SIZES.into()); + } + let new_sizes = legend_sizes_param(p)?; if p.get("textSize").is_some_and(|v| !v.is_null()) && !sized { return Err(ONLY_LAYOUT_TEXT_SIZE.into()); } @@ -610,8 +614,12 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { class_labels, show_counts, subtitle, + sizes, .. } => { + if let Some(new) = new_sizes { + *sizes = new; + } if let Some(text) = new_subtitle { *subtitle = text; } diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 3166835486..0eda8fae39 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -123,6 +123,7 @@ pub const CAPABILITIES: &[&str] = &[ "layout-legend-class-labels", "layout-legend-counts", "layout-legend-subtitle", + "layout-legend-nested-sizes", "layout-legend-order", "layout-scale-bar-details", "label-guide", diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 9bc2d6926b..b4bdf3491c 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -176,6 +176,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("layout-legend-class-labels", command_uses_legend_class_labels), ("layout-legend-counts", command_uses_legend_counts), ("layout-legend-subtitle", command_uses_legend_subtitle), + ("layout-legend-nested-sizes", command_uses_legend_nested_sizes), ("layout-legend-order", command_uses_legend_order), ("layout-scale-bar-details", command_uses_scale_bar_details), ("dggs-system", command_uses_dggs_system), @@ -576,6 +577,24 @@ fn command_uses_legend_subtitle(id: &str, params: &Value) -> bool { } } +/// A layout command that nests a legend's sizes (#3347): an older reader ignores `sizes`, and a +/// legend saved with it, drawing rows. `"rows"` and `null` ask for what it draws. +fn command_uses_legend_nested_sizes(id: &str, params: &Value) -> bool { + match id { + "layout.addElement" | "layout.update" => { + crate::cmd::layout::legend_sizes_param(params) == Ok(Some(rustgis_map::layout::LegendSizes::Nested)) + } + "layout.import" | "report.existingTemplate" => imported_layout_uses(params, &["\"sizes\""], legend_nested_sizes_features), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_legend_nested_sizes)), + _ => false, + } +} + +/// Whether a layout element is a legend that draws sizes nested. +fn legend_nested_sizes_features(e: &rustgis_map::layout::Element) -> bool { + e.kind.legend_nested_sizes_features() +} + /// Whether a layout element is a legend with a subtitle. fn legend_subtitle_features(e: &rustgis_map::layout::Element) -> bool { e.kind.legend_subtitle_features() @@ -1458,6 +1477,7 @@ fn layout_capabilities(layouts: &[rustgis_map::layout::Layout]) -> Vec<&'static (elements().any(legend_labels_classes), "layout-legend-class-labels"), (elements().any(legend_counts_features), "layout-legend-counts"), (elements().any(legend_subtitle_features), "layout-legend-subtitle"), + (elements().any(legend_nested_sizes_features), "layout-legend-nested-sizes"), (elements().any(legend_orders_layers), "layout-legend-order"), (elements().any(bar_details), "layout-scale-bar-details"), (layouts.iter().any(|l| l.paper.is_some()), "layout-page-color"), @@ -1811,6 +1831,7 @@ mod tests { (&["layout-legend-fit"], "layout.update", json!({"element": 1, "fit": "adjustSize"})), (&["layout-legend-class-labels"], "layout.update", json!({"element": 1, "classLabels": {"a": {"x": "X"}}})), (&["layout-legend-counts"], "layout.update", json!({"element": 1, "showCounts": true})), + (&["layout-legend-nested-sizes"], "layout.update", json!({"element": 1, "sizes": "nested"})), (&["layout-legend-subtitle"], "layout.update", json!({"element": 1, "subtitle": "a"})), (&["layout-legend-order"], "layout.update", json!({"element": 1, "layerOrder": ["a"]})), (&["dggs-system"], "a5Grid", json!({"system": "H3"})), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1734141af9..a2d0fc2da9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -157,6 +157,9 @@ mod layout_legend_order; #[path = "tests/layout_legend_subtitle.rs"] mod layout_legend_subtitle; +#[path = "tests/layout_legend_sizes.rs"] +mod layout_legend_sizes; + #[path = "tests/layout_report_text.rs"] mod layout_report_text; @@ -13733,6 +13736,7 @@ fn a_manual_legend_that_overflows_still_warns_and_a_fitted_one_does_not() { labels: &labels, class_labels: &NO_CLASS_LABELS, show_counts: false, + sizes: Default::default(), }; // A box as wide as its rows at 9 points, and half-way between their heights at 9 and at 4. let (big, small) = (legend_sizes(&mut s, frame, &at(9.0))[0], legend_sizes(&mut s, frame, &at(4.0))[0]); @@ -13786,6 +13790,7 @@ fn a_fit_that_cannot_make_a_legend_fit_says_so() { labels: &labels, class_labels: &NO_CLASS_LABELS, show_counts: false, + sizes: Default::default(), }; let (big, small) = (legend_sizes(&mut s, frame, &at(9.0)), legend_sizes(&mut s, frame, &at(4.0))); // A box less than half as tall as its rows in six columns at 4 points: no fit makes them fit. @@ -13866,6 +13871,7 @@ fn a_report_says_the_fitted_legends_on_its_layouts_that_no_longer_fit() { labels: &labels, class_labels: &NO_CLASS_LABELS, show_counts: false, + sizes: Default::default(), }; let point = r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[2.35,48.85]}}]}"#; let added = json!({"fileName": "extra.geojson", "text": point, "name": "Extra"}); @@ -13932,6 +13938,7 @@ fn a_fitted_legend_that_no_longer_fits_says_so_at_export() { labels: &labels, class_labels: &NO_CLASS_LABELS, show_counts: false, + sizes: Default::default(), }; let point = r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[2.35,48.85]}}]}"#; let added = json!({"fileName": "extra.geojson", "text": point, "name": "Extra"}); diff --git a/crates/engine/src/tests/layout_files.rs b/crates/engine/src/tests/layout_files.rs index 2c9a0291f1..b71d2a153b 100644 --- a/crates/engine/src/tests/layout_files.rs +++ b/crates/engine/src/tests/layout_files.rs @@ -131,6 +131,7 @@ fn a_saved_layout_file_requires_what_its_elements_use_and_reads_back_the_same() ("legend-class-labels", include_str!("../../../../schema/fixtures/layout_legend_class_labels.rgis")), ("legend-counts", include_str!("../../../../schema/fixtures/layout_legend_counts.rgis")), ("legend-subtitle", include_str!("../../../../schema/fixtures/layout_legend_subtitle.rgis")), + ("legend-nested-sizes", include_str!("../../../../schema/fixtures/layout_legend_nested_sizes.rgis")), ("legend-order", include_str!("../../../../schema/fixtures/layout_legend_order.rgis")), ("scale-grid-text", include_str!("../../../../schema/fixtures/layout_scale_grid_text.rgis")), ("page-color", include_str!("../../../../schema/fixtures/layout_page_color.rgis")), diff --git a/crates/engine/src/tests/layout_legend_sizes.rs b/crates/engine/src/tests/layout_legend_sizes.rs new file mode 100644 index 0000000000..60e5a1426c --- /dev/null +++ b/crates/engine/src/tests/layout_legend_sizes.rs @@ -0,0 +1,125 @@ +//! A legend that draws a layer's sizes nested, on one base (#3347). The sample's cities are drawn +//! with proportional symbols. + +use super::*; + +/// A world layout and its legend. +fn laid_out() -> (Session, u64) { + let mut s = world(); + s.run("layout.new", &json!({"template": "map"})).unwrap(); + let legend = s.project.layouts[0].elements.iter().find(|e| e.kind.code() == "legend").unwrap().id.into(); + (s, legend) +} + +/// The legend's saved way of drawing sizes. +fn saved(s: &Session, legend: u64) -> Value { + let e = s.project.layouts[0].element(legend as u32).unwrap(); + serde_json::to_value(&e.kind).unwrap()["Legend"]["sizes"].clone() +} + +#[test] +fn nested_sizes_are_set_in_one_undo_step_and_left_out_as_rows() { + let (mut s, legend) = laid_out(); + assert_eq!(saved(&s, legend), Value::Null); + let depth = s.undo_depth(); + s.run("layout.update", &json!({"element": legend, "sizes": "nested"})).unwrap(); + assert_eq!(saved(&s, legend), json!("nested")); + assert_eq!(s.undo_depth(), depth + 1); + // `null` leaves it as it is. + s.run("layout.update", &json!({"element": legend, "sizes": null, "title": "Key"})).unwrap(); + assert_eq!(saved(&s, legend), json!("nested")); + s.run("layout.update", &json!({"element": legend, "sizes": "rows"})).unwrap(); + assert_eq!(saved(&s, legend), Value::Null); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!(saved(&s, legend), json!("nested")); +} + +#[test] +fn a_legend_is_added_with_nested_sizes() { + let (mut s, _) = laid_out(); + s.run("layout.addElement", &json!({"kind": "legend", "sizes": "nested"})).unwrap(); + let added = s.project.layouts[0].elements.last().unwrap().id.into(); + assert_eq!(saved(&s, added), json!("nested")); +} + +#[test] +fn sizes_a_legend_cannot_take_are_refused_and_change_nothing() { + let (mut s, legend) = laid_out(); + let frame = s.project.layouts[0].elements.iter().find(|e| e.kind.code() == "mapFrame").unwrap().id; + for (command, p, said) in [ + ("layout.update", json!({"element": legend, "sizes": "big"}), "rows or nested"), + ("layout.addElement", json!({"kind": "legend", "sizes": 7}), "rows or nested"), + ("layout.update", json!({"element": frame, "sizes": "nested"}), "only legends take sizes"), + ("layout.addElement", json!({"kind": "northArrow", "sizes": "nested"}), "only legends take sizes"), + ] { + let before = serde_json::to_value(&s.project).unwrap(); + let err = s.run(command, &p).expect_err(&p.to_string()).to_string(); + assert!(err.contains(said), "{p}: {err}"); + assert_eq!(serde_json::to_value(&s.project).unwrap(), before, "{p}"); + } +} + +#[test] +fn nested_sizes_require_their_capability_wherever_they_are_saved() { + let (mut s, legend) = laid_out(); + let lists = |v: Value| v["requires"].as_array().is_some_and(|r| r.contains(&json!("layout-legend-nested-sizes"))); + assert!(!lists(serde_json::to_value(&s.project).unwrap())); + let plain = serde_json::to_string(&s.project.layouts[0]).unwrap(); + s.run("layout.update", &json!({"element": legend, "sizes": "nested"})).unwrap(); + assert!(lists(serde_json::to_value(&s.project).unwrap())); + let text = serde_json::to_string(&s.project).unwrap(); + let again: Project = serde_json::from_str(&text).unwrap(); + assert_eq!(serde_json::to_string(&again).unwrap(), text); + let nested = serde_json::to_string(&s.project.layouts[0]).unwrap(); + let requires = |id: &str, params: Value| { + let mut p = Project::default(); + p.tasks.push( + serde_json::from_value(json!({"name": "t", "title": "t", "steps": [{"title": "s", "command": id, "params": params}]})).unwrap(), + ); + lists(serde_json::to_value(&p).unwrap()) + }; + for (id, params, required) in [ + ("layout.addElement", json!({"kind": "legend", "sizes": "nested"}), true), + ("layout.update", json!({"element": 3, "sizes": "nested"}), true), + ("layout.update", json!({"element": 3, "sizes": "rows"}), false), + ("layout.update", json!({"element": 3, "sizes": null}), false), + ("layout.import", json!({"text": nested}), true), + ("layout.import", json!({"text": plain}), false), + ("report.existingTemplate", json!({"text": nested}), true), + ("script.run", json!({"script": format!("layout.update {}", json!({"element": 3, "sizes": "nested"}))}), true), + ] { + assert_eq!(requires(id, params.clone()), required, "{id} {params}"); + } +} + +#[test] +fn a_files_unknown_sizes_are_read_as_rows_and_counted() { + let (s, legend) = laid_out(); + let mut layout = serde_json::to_value(&s.project.layouts[0]).unwrap(); + let elements = layout["elements"].as_array_mut().unwrap(); + let e = elements.iter_mut().find(|e| e["id"] == json!(legend)).unwrap(); + e["kind"]["Legend"]["sizes"] = json!("spiral"); + let mut read: rustgis_map::layout::Layout = serde_json::from_value(layout).unwrap(); + assert_eq!(read.clamp().elements_adjusted, 1); + let e = read.element(legend as u32).unwrap(); + assert_eq!(serde_json::to_value(&e.kind).unwrap()["Legend"]["sizes"], Value::Null); +} + +#[test] +fn nested_sizes_fit_a_box_their_rows_do_not() { + let (mut s, legend) = laid_out(); + let said = |s: &mut Session, p: Value| { + s.notices.clear(); + s.run("layout.update", &p).unwrap(); + s.notices.iter().any(|n| n.text.to_lowercase().contains("legend")) + }; + // Only the cities, whose rows are their name and three sizes. + let others = ["Countries", "Lakes", "Rivers"]; + s.run("layout.update", &json!({"element": legend, "exclude": others, "w": 90, "textSize": 10})).unwrap(); + let mut h = 10.0; + while said(&mut s, json!({"element": legend, "h": h, "textSize": 10})) { + h += 1.0; + assert!(h < 200.0, "never fits"); + } + assert!(!said(&mut s, json!({"element": legend, "sizes": "nested", "h": h - 3.0})), "{h}: the block is shorter than the rows"); +} diff --git a/crates/map/src/diagram.rs b/crates/map/src/diagram.rs index 6b92e5e4d3..48f3b3c224 100644 --- a/crates/map/src/diagram.rs +++ b/crates/map/src/diagram.rs @@ -284,6 +284,7 @@ impl DiagramSettings { }, fallback: false, count: None, + sized: false, }) .collect() } diff --git a/crates/map/src/layout.rs b/crates/map/src/layout.rs index ecc606b058..7c052fa979 100644 --- a/crates/map/src/layout.rs +++ b/crates/map/src/layout.rs @@ -628,12 +628,14 @@ impl Layout { class_labels, show_counts, subtitle, + sizes, .. } => { let end = subtitle.char_indices().nth(MAX_LEGEND_SUBTITLE_CHARS).map_or(subtitle.len(), |(i, _)| i); cut |= end < subtitle.len(); subtitle.truncate(end); *show_counts = show_counts.kept(); + *sizes = sizes.kept(); cut |= class_labels.clamp(); *text_size = layout_text_in_range(*text_size, LEGEND_TEXT_PT); // A file's unknown name or wrong kind of value is read as a marker: back to the diff --git a/crates/map/src/layout/elements.rs b/crates/map/src/layout/elements.rs index d49ff916dd..8c49835408 100644 --- a/crates/map/src/layout/elements.rs +++ b/crates/map/src/layout/elements.rs @@ -165,6 +165,10 @@ pub enum ElementKind { /// bytes. #[serde(default, skip_serializing_if = "String::is_empty")] subtitle: String, + /// How it draws a point layer's rows of sizes (#3347). Left out as rows, so layouts saved + /// before keep their bytes. + #[serde(default, skip_serializing_if = "LegendSizes::is_rows")] + sizes: LegendSizes, }, /// The colour scale of a raster layer in a frame's map: a gradient bar for a stretch, steps /// for classes, a block per value for unique values and colour tables (#326). @@ -466,6 +470,12 @@ impl ElementKind { matches!(self, ElementKind::Legend { subtitle, .. } if !subtitle.is_empty()) } + /// Whether this is a legend that draws sizes nested: what a layout file needs a newer reader + /// for. + pub fn legend_nested_sizes_features(&self) -> bool { + matches!(self, ElementKind::Legend { sizes: LegendSizes::Nested, .. }) + } + /// Whether this is a scale bar with any of the details set: subdivisions, divisions before /// zero, a label or unit label placement, a unit label, decimals or a fit. Its text size /// isn't one: [`ElementKind::has_custom_text_size`] tells that. diff --git a/crates/map/src/layout/legend.rs b/crates/map/src/layout/legend.rs index 98499a7515..a7e65f6454 100644 --- a/crates/map/src/layout/legend.rs +++ b/crates/map/src/layout/legend.rs @@ -190,6 +190,69 @@ impl<'de> Deserialize<'de> for LegendFit { } } +/// How a legend draws a point layer's rows of sizes (#3347). +/// +/// `Invalid` is what a file's unknown name or wrong kind of value is read as; it is never kept: +/// [`Layout::clamp`] sends it to the default and counts the element, and a save leaves it out, as +/// it does the default. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum LegendSizes { + /// A row each, its marker beside its value. + #[default] + Rows, + /// One block: the markers one inside another on a common base, each led to its value. + Nested, + /// A value read from a file that is not a name; repaired to the default on load. + #[doc(hidden)] + Invalid, +} + +impl LegendSizes { + pub const ALL: [LegendSizes; 2] = [LegendSizes::Rows, LegendSizes::Nested]; + + pub fn code(self) -> &'static str { + match self { + LegendSizes::Rows | LegendSizes::Invalid => "rows", + LegendSizes::Nested => "nested", + } + } + + /// `rows` or `nested` in any case, trimmed. + pub fn from_name(s: &str) -> Option { + let s = s.trim(); + LegendSizes::ALL.into_iter().find(|v| v.code().eq_ignore_ascii_case(s)) + } + + /// This value, or the default where it is [`LegendSizes::Invalid`]. + pub fn kept(self) -> LegendSizes { + if self == LegendSizes::Invalid { LegendSizes::default() } else { self } + } + + /// Whether a save leaves it out: rows, or a value that is not a name, which reads back as rows. + pub fn is_rows(&self) -> bool { + self.kept() == LegendSizes::Rows + } +} + +impl Serialize for LegendSizes { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.kept().code()) + } +} + +impl<'de> Deserialize<'de> for LegendSizes { + /// A name as [`LegendSizes::from_name`] reads it; null as the default; anything else as + /// `Invalid`, so the read never fails and `Layout::clamp` repairs and counts it. + fn deserialize>(d: D) -> Result { + let v: Option = Deserialize::deserialize(d)?; + Ok(match v { + None | Some(serde_json::Value::Null) => LegendSizes::default(), + Some(serde_json::Value::String(s)) => LegendSizes::from_name(&s).unwrap_or(LegendSizes::Invalid), + Some(_) => LegendSizes::Invalid, + }) + } +} + /// Whether a legend shows each layer's name over the layer's classes. /// /// `Invalid` is what a file's value that is not `true` or `false` is read as; it is never kept: diff --git a/crates/map/src/symbol_by.rs b/crates/map/src/symbol_by.rs index 6e0fefae90..957b73b781 100644 --- a/crates/map/src/symbol_by.rs +++ b/crates/map/src/symbol_by.rs @@ -137,6 +137,7 @@ impl SizeBy { fills: Vec::new(), fallback: false, count: None, + sized: true, } }) .collect() diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 518f09222a..65cd7901bf 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -1012,6 +1012,8 @@ pub struct LegendEntry { pub fallback: bool, /// The features its row stands for, in a legend that counts them (#3237). pub count: Option, + /// Its row shows a marker size, not a class: a layout legend can draw such rows nested (#3347). + pub sized: bool, } impl LegendEntry { @@ -1024,12 +1026,13 @@ impl LegendEntry { fills: fills.cloned().unwrap_or_default(), fallback: false, count: None, + sized: false, } } /// A row with no stacked strokes or fills of its own. pub fn plain(label: String, symbol: Symbol) -> Self { - LegendEntry { label, symbol, strokes: Vec::new(), fills: Vec::new(), fallback: false, count: None } + LegendEntry { label, symbol, strokes: Vec::new(), fills: Vec::new(), fallback: false, count: None, sized: false } } } @@ -1863,6 +1866,7 @@ impl Renderer { fills: other_fills.clone(), fallback: true, count: None, + sized: false, }); } merge_alike(v) @@ -2058,6 +2062,7 @@ impl Renderer { fills: other_fills.clone(), fallback: true, count: None, + sized: false, }); v } @@ -2074,11 +2079,11 @@ impl Renderer { }) .collect() } - Renderer::Proportional { base, min_size, max_size, min, max, .. } => vec![ - LegendEntry::plain(fmt_num(*min), Symbol { size: *min_size, ..*base }), - LegendEntry::plain(fmt_num((min + max) / 2.0), Symbol { size: min_size + (max_size - min_size) * 0.707, ..*base }), - LegendEntry::plain(fmt_num(*max), Symbol { size: *max_size, ..*base }), - ], + Renderer::Proportional { base, min_size, max_size, min, max, .. } => { + [(*min, *min_size), ((min + max) / 2.0, min_size + (max_size - min_size) * 0.707), (*max, *max_size)] + .map(|(v, size)| LegendEntry { sized: true, ..LegendEntry::plain(fmt_num(v), Symbol { size, ..*base }) }) + .into() + } } } diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index f04a141c2e..c0541597bd 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -548,6 +548,7 @@ fn draw_page( class_labels, show_counts, subtitle, + sizes, } => { if let Some(&(_, mi, cam, ..)) = frame(*f) && let Some(map) = maps.get(mi) @@ -585,6 +586,7 @@ fn draw_page( scale, size, text_size: *text_size, + sizes: *sizes, }; // Whether a picture was still on its way when the rows were made: the very lookup // that drew the legend, not an earlier one a retry or an eviction could outdate. @@ -1052,6 +1054,7 @@ pub(crate) fn legend_pin_pages() -> Vec<(Layout, Vec)> { class_labels: Default::default(), show_counts: Default::default(), subtitle: Default::default(), + sizes: Default::default(), }; f(&mut kind); l.add("Legend", at, kind); diff --git a/crates/render/src/layout/legend.rs b/crates/render/src/layout/legend.rs index 23b12dde2d..4e0a5a1810 100644 --- a/crates/render/src/layout/legend.rs +++ b/crates/render/src/layout/legend.rs @@ -1,7 +1,7 @@ //! The legend: its rows, columns, sizes and the wait for service legend pictures. use super::*; -use rustgis_map::layout::ClassLabels; +use rustgis_map::layout::{ClassLabels, LegendSizes}; /// 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 @@ -214,6 +214,8 @@ pub(super) struct LegendOptions<'a> { pub(super) scale: f64, pub(super) size: f32, pub(super) text_size: f64, + /// How a point layer's rows of sizes are drawn (#3347). + pub(super) sizes: LegendSizes, } /// How many times the default a legend of `text_size` points draws its text, rows, swatches and @@ -239,6 +241,9 @@ pub(super) enum LegendRow<'a> { Plain(&'a rustgis_map::Layer, std::borrow::Cow<'a, str>), Head(std::borrow::Cow<'a, str>), Class(&'a rustgis_map::Layer, LegendEntry), + /// A point layer's sizes drawn nested (#3347): the largest first, each with the side of its + /// marker in points. + Sizes(&'a rustgis_map::Layer, Vec<(LegendEntry, f32)>), Picture(std::sync::Arc), } @@ -248,6 +253,9 @@ impl LegendRow<'_> { pub(super) fn symbol_side(&self, scale: f64) -> f32 { #[cfg(test)] tests::SYMBOL_SIDES.with(|n| n.set(n.get() + 1)); + if let LegendRow::Sizes(_, block) = self { + return block.first().map_or(0.0, |(_, side)| *side); + } let (LegendRow::Plain(l, _) | LegendRow::Class(l, _)) = self else { return 0.0 }; if l.geometry_type() != GeometryType::Point { return 0.0; @@ -256,7 +264,7 @@ impl LegendRow<'_> { 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) + point_side(l, &s, strokes, scale) } /// Its height at 1:`scale` in a legend `size` times the default ([`legend_size`]), in points: @@ -274,6 +282,10 @@ impl LegendRow<'_> { fn height_beside(&self, side: f32, size: f32) -> f32 { match self { LegendRow::Picture(p) => picture_size(p).1 * size, + LegendRow::Sizes(_, block) => { + let sides: Vec = block.iter().map(|(_, side)| *side).collect(); + nested::places(&sides, nested::LINE * size).2 + } _ => (LEGEND_ROW * size).max(side), } } @@ -285,6 +297,11 @@ impl LegendRow<'_> { LegendRow::Plain(_, name) => (name.as_ref(), LEGEND_NAME_PT * size, false), LegendRow::Head(name) => (name.as_ref(), LEGEND_NAME_PT * size, true), LegendRow::Class(_, en) => (en.label.as_str(), LEGEND_LABEL_PT * size, false), + LegendRow::Sizes(_, block) => { + #[cfg(test)] + tests::TEXT_MEASURES.with(|n| n.set(n.get() + 1)); + return block.iter().map(|(en, _)| text::measure(&en.label, LEGEND_LABEL_PT * size, false)).fold(0.0, f32::max); + } LegendRow::Picture(_) => return 0.0, }; #[cfg(test)] @@ -299,12 +316,18 @@ impl LegendRow<'_> { match self { LegendRow::Plain(..) => column + LEGEND_INDENT * size + text, LegendRow::Head(_) => text, - LegendRow::Class(..) => column + LEGEND_LABEL_INDENT * size + text, + LegendRow::Class(..) | LegendRow::Sizes(..) => column + LEGEND_LABEL_INDENT * size + text, LegendRow::Picture(_) => text, } } } +/// The side of the square a point layer's symbol `s` with its stacked `strokes` takes at +/// 1:`scale`, in points ([`LegendRow::symbol_side`]). +fn point_side(l: &rustgis_map::Layer, s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke], scale: f64) -> f32 { + (2.0 * point_marks::reach(s, strokes) * l.size_factor(scale)).min(MAX_LEGEND_SIDE as f32) +} + /// The side of each of a legend's `rows`' point symbols at 1:`scale` ([`LegendRow::symbol_side`]), /// which no text size or column count changes, so it is measured once a legend. pub(super) fn symbol_sides(rows: &[LegendRow], scale: f64) -> Vec { @@ -1092,7 +1115,7 @@ pub(super) fn legend_rows_missing<'a>( } // The legend's own text for a class, by the label the layer gives it (#3187). let own = opts.class_labels.of(&l.name); - rows.extend(entries.into_iter().map(|mut en| { + let entries = entries.into_iter().map(|mut en| { if let Some(text) = own.and_then(|o| o.get(&en.label)) { en.label.clone_from(text); } @@ -1100,8 +1123,25 @@ pub(super) fn legend_rows_missing<'a>( if let Some(n) = en.count { en.label = format!("{} ({n})", en.label); } - LegendRow::Class(l, en) - })); + en + }); + if opts.sizes == LegendSizes::Nested && l.geometry_type() == GeometryType::Point { + // Its sizes make one block, where the first of them would be listed. + let (mut sizes, mut at) = (Vec::new(), None); + for en in entries { + if en.sized { + at.get_or_insert(rows.len()); + sizes.push(en); + } else { + rows.push(LegendRow::Class(l, en)); + } + } + if let Some(at) = at { + rows.insert(at, nested::block(l, sizes, opts.scale)); + } + } else { + rows.extend(entries.map(|en| LegendRow::Class(l, en))); + } } (rows, missing) } @@ -1245,7 +1285,7 @@ pub(super) fn legend_column( break; } if let (true, LegendRow::Head(_), Some(&(next, next_height))) = (name_with_class, &row, rows.peek()) - && matches!(next, LegendRow::Class(..)) + && matches!(next, LegendRow::Class(..) | LegendRow::Sizes(..)) && y + height + next_height * ppp > r.bottom() + line * 1e-3 { break; @@ -1286,6 +1326,14 @@ pub(super) fn legend_column( false, ); } + LegendRow::Sizes(l, block) => nested::draw( + pm, + (r.x() + LEGEND_INDENT * size * ppp, y, sw), + (l, block.as_slice()), + (map.layer_opacity(l), opts.scale), + (size, ppp), + (r.x() + sw + LEGEND_LABEL_INDENT * size * ppp, dark), + ), LegendRow::Picture(_) => {} } y += height; @@ -1388,6 +1436,7 @@ pub fn legend_sizes_in_columns_mm( labels, class_labels, show_counts: false, + sizes: Default::default(), }; sizes_asked_mm(map, scale, &asked) } @@ -1406,6 +1455,7 @@ pub struct LegendAsked<'a> { pub labels: &'a BTreeMap, pub class_labels: &'a ClassLabels, pub show_counts: bool, + pub sizes: LegendSizes, } /// The columns and text size a legend's fit draws its rows at, and whether they are still wider @@ -1432,6 +1482,7 @@ fn asked_rows(map: &mut Map, scale: f64, asked: &LegendAsked, with: impl FnOn labels, class_labels, show_counts, + sizes, } = *asked; let env = Env::default(); let drawn = if all_classes { None } else { Some(complete_shown_legends(map, scale, show_no_data, exclude, &mut None, &env)?) }; @@ -1451,6 +1502,7 @@ fn asked_rows(map: &mut Map, scale: f64, asked: &LegendAsked, with: impl FnOn scale, size, text_size, + sizes, }; Some(with(&legend_rows(map, drawn.as_deref(), &opts))) } @@ -1533,3 +1585,4 @@ pub fn legend_head_mm(title: &str, subtitle: &str, text_size: f64) -> f64 { #[cfg(test)] mod count_tests; +mod nested; diff --git a/crates/render/src/layout/legend/count_tests.rs b/crates/render/src/layout/legend/count_tests.rs index fd1a99cc90..7fa16d98cf 100644 --- a/crates/render/src/layout/legend/count_tests.rs +++ b/crates/render/src/layout/legend/count_tests.rs @@ -137,6 +137,7 @@ fn asked(all_classes: bool, show_no_data: bool, show_counts: bool) -> LegendAske labels: &LABELS, class_labels: &NO_CLASS_LABELS, show_counts, + sizes: Default::default(), } } @@ -149,6 +150,7 @@ fn texts(map: &mut Map, asked: &LegendAsked) -> Option> { LegendRow::Plain(_, n) => n.to_string(), LegendRow::Class(_, e) => e.label.clone(), LegendRow::Picture(_) => "picture".into(), + LegendRow::Sizes(..) => "sizes".into(), }) .collect() }) @@ -392,6 +394,7 @@ fn counts_page(all_classes: bool) -> rustgis_map::layout::Layout { class_labels: Default::default(), show_counts: rustgis_map::layout::FeatureCounts::from_shown(true), subtitle: Default::default(), + sizes: Default::default(), }, ); page diff --git a/crates/render/src/layout/legend/nested.rs b/crates/render/src/layout/legend/nested.rs new file mode 100644 index 0000000000..2c9270f2d4 --- /dev/null +++ b/crates/render/src/layout/legend/nested.rs @@ -0,0 +1,106 @@ +//! A point layer's rows of sizes drawn as one block (#3347): its markers one inside another on a +//! common base, each led to its value. + +use super::*; + +/// The width in points, at the default size, of the line that edges a bare marker and of the +/// leaders. +const EDGE: f32 = 0.5; +/// The least two labels' middles are apart in a block, in points at the default size: a line of +/// their text, closer than rows are. +pub(super) const LINE: f32 = 12.0; + +/// The row of the sizes `entries` of the point layer `l` at 1:`scale`: the largest marker first, +/// each with its side. +pub(super) fn block<'a>(l: &'a rustgis_map::Layer, entries: Vec, scale: f64) -> LegendRow<'a> { + let mut block: Vec<(LegendEntry, f32)> = entries + .into_iter() + .map(|en| { + let side = point_side(l, &en.symbol, row_strokes(l, &en), scale); + (en, side) + }) + .collect(); + // Listed smallest value first: reversed, markers of one size keep the largest value on top. + block.reverse(); + block.sort_by(|a, b| b.1.total_cmp(&a.1)); + LegendRow::Sizes(l, block) +} + +/// Where a block's parts go, in points from its top, its labels' lines `line` high, its +/// markers `sides` across, the largest first: the base they stand on, each label's middle, and the +/// block's height. A label is level with the top of its marker, or a line under the label above +/// where the tops are closer than that. +pub(super) fn places(sides: &[f32], line: f32) -> (f32, Vec, f32) { + let base = line / 2.0 + sides.first().copied().unwrap_or(0.0); + let mut above = f32::NEG_INFINITY; + let middles: Vec = sides + .iter() + .map(|&side| { + above = (base - side).max(above + line); + above + }) + .collect(); + let height = middles.last().map_or(base, |&m| (m + line / 2.0).max(base)); + (base, middles, height) +} + +/// Draws a block ([`block`]) of the layer `l` from `y` down: its markers in the column of swatches +/// `column` pixels wide from `x`, over one another from the largest, composited as one when the +/// layer is see-through (`opacity`); then each one's leader, from its top to its label at +/// `text_x`. A marker with no edge of its own gets one in the legend's `ink`, or nested ones of +/// one fill couldn't be told apart. `size` times the default, `ppp` pixels a point. +pub(super) fn draw( + pm: &mut Canvas, + (x, y, column): (f32, f32, f32), + (l, block): (&rustgis_map::Layer, &[(LegendEntry, f32)]), + (opacity, scale): (f32, f64), + (size, ppp): (f32, f32), + (text_x, ink): (f32, Rgba), +) { + let sides: Vec = block.iter().map(|(_, side)| *side).collect(); + let (base, middles, height) = places(&sides, LINE * size); + let (cx, base) = (x + column / 2.0, y + base * ppp); + let k = l.size_factor(scale); + // Room round each marker's box for an edge it didn't have. + let room = EDGE * ppp; + let widest = sides.first().map_or(0.0, |side| side * ppp) + 2.0 * room; + let markers = |c: &mut Canvas, (left, top): (f32, f32)| { + for (en, side) in block { + // A marker sized zero has no ink to edge or to draw. + if *side <= 0.0 { + continue; + } + let strokes = row_strokes(l, en); + let mut symbol = en.symbol; + if point_marks::plain(strokes, 0.0) && (symbol.stroke.a() == 0 || symbol.stroke_width <= 0.0) && k > 0.0 { + (symbol.stroke, symbol.stroke_width) = (ink, EDGE / k); + } + let across = side * ppp + 2.0 * room; + let cell = (cx - across / 2.0 - left, base - side * ppp - room - top, across, across); + point_swatch(c, cell, (&symbol, strokes), 1.0, ppp * k); + } + }; + if opacity >= 0.999 { + markers(pm, (0.0, 0.0)); + } else { + composited(pm, (cx - widest / 2.0, y, widest, height * ppp), opacity, markers); + } + let stroke = Stroke { width: EDGE * size * ppp, ..Stroke::default() }; + for ((en, side), middle) in block.iter().zip(middles) { + let (top, middle) = (base - side * ppp, y + middle * ppp); + let mut leader = PathBuilder::new(); + leader.move_to(cx, top); + // Level to the column's edge, then to a label pushed down. + if middle - top > 0.01 { + leader.line_to(x + column, top); + } + leader.line_to(text_x - 2.0 * size * ppp, middle); + if let Some(path) = leader.finish() { + pm.stroke_path(&path, &paint(ink, 1.0), &stroke, Transform::identity(), None); + } + text::text_at(pm, &en.label, text_x, middle, LEGEND_LABEL_PT * size * 1.33 * ppp, ink, false, text::Align::Left, false); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/render/src/layout/legend/nested/tests.rs b/crates/render/src/layout/legend/nested/tests.rs new file mode 100644 index 0000000000..cd6bba76e7 --- /dev/null +++ b/crates/render/src/layout/legend/nested/tests.rs @@ -0,0 +1,148 @@ +use super::*; +use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; +use rustgis_map::symbology::OTHER_FILL; +use rustgis_map::{Layer, Renderer, Symbol}; + +const RED: Rgba = Rgba::rgb(200, 0, 0); + +/// A map of one point layer of proportional circles, `min` to `max` points across, over the +/// values 1 to 9, filled red, with the outline `edge` wide. +fn circles(min: f32, max: f32, edge: f32) -> Map { + let mut ds = Dataset::new("Towns", GeometryType::Point, vec![Field::new("n", FieldType::Double)]); + for n in [1.0, 9.0] { + ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Float(n)]); + } + let base = Symbol { fill: RED, stroke: RED, stroke_width: edge, size: 6.0, marker: Default::default() }; + let mut map = Map::new("m"); + let id = map.add_dataset(ds); + let l = map.layer_mut(id).unwrap(); + l.renderer = Renderer::Proportional { field: "n".into(), base, min_size: min, max_size: max, min: 1.0, max: 9.0 }; + map +} + +fn options(sizes: LegendSizes) -> LegendOptions<'static> { + static LABELS: BTreeMap = BTreeMap::new(); + static CLASSES: std::sync::LazyLock = std::sync::LazyLock::new(Default::default); + LegendOptions { + hide_other: false, + show_no_data: false, + names: false, + exclude: &[], + layer_order: &[], + labels: &LABELS, + class_labels: &CLASSES, + counts: None, + scale: 1e6, + size: 1.0, + text_size: rustgis_map::layout::LEGEND_TEXT_PT, + sizes, + } +} + +/// The legend of `map` in a white picture 200 points square, a pixel a point. +fn drawn(map: &Map, sizes: LegendSizes) -> Pixmap { + drawn_at(map, sizes, 1) +} + +/// [`drawn`] at `ppp` pixels a point. +fn drawn_at(map: &Map, sizes: LegendSizes, ppp: u32) -> Pixmap { + let mut pm = Pixmap::new(200 * ppp, 200 * ppp).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let pm_side = (200 * ppp) as f32; + crate::canvas::with_canvas(&mut pm, |c| { + let r = Rect::from_xywh(0.0, 0.0, pm_side, pm_side).unwrap(); + legend_missing(c, r, map, (("", ""), 1, LegendFit::Manual), None, options(sizes), INK, f64::from(ppp)); + }); + pm +} + +fn is_red(pm: &Pixmap, x: u32, y: u32) -> bool { + pm.pixel(x, y).is_some_and(|p| p.red() > 150 && p.green() < 60 && p.blue() < 60) +} + +/// The first and last pixel rows with red in them. +fn red_rows(pm: &Pixmap) -> (u32, u32) { + let rows: Vec = (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| is_red(pm, x, y))).collect(); + (rows[0], *rows.last().unwrap()) +} + +#[test] +fn a_label_is_level_with_its_markers_top_or_a_line_under_the_one_above() { + // Tops far enough apart: each label at its top. + assert_eq!(places(&[60.0, 40.0, 10.0], 16.0), (68.0, vec![8.0, 28.0, 58.0], 68.0)); + // Closer than a line: pushed down, and the block grows to hold the last. + assert_eq!(places(&[20.0, 19.0, 18.0], 16.0), (28.0, vec![8.0, 24.0, 40.0], 48.0)); + // One marker, and none sized. + assert_eq!(places(&[20.0], 16.0), (28.0, vec![8.0], 28.0)); + assert_eq!(places(&[20.0, 0.0], 16.0), (28.0, vec![8.0, 28.0], 36.0)); +} + +#[test] +fn nested_sizes_make_one_row_largest_first() { + let map = circles(10.0, 40.0, 1.0); + let rows = legend_rows(&map, None, &options(LegendSizes::Rows)); + assert_eq!(rows.len(), 3); + let nested = legend_rows(&map, None, &options(LegendSizes::Nested)); + let [LegendRow::Sizes(_, block)] = nested.as_slice() else { panic!("{} rows", nested.len()) }; + let labels: Vec<&str> = block.iter().map(|(e, _)| e.label.as_str()).collect(); + assert_eq!(labels, ["9", "5", "1"]); + assert!(block[0].1 > block[1].1 && block[1].1 > block[2].1); +} + +#[test] +fn nested_circles_stand_on_one_base() { + let map = circles(10.0, 40.0, 1.0); + let (rows, nested) = (drawn(&map, LegendSizes::Rows), drawn(&map, LegendSizes::Nested)); + let ((top, bottom), (rows_top, rows_bottom)) = (red_rows(&nested), red_rows(&rows)); + // As tall as the largest circle alone, where the rows stack all three. + assert!((40..=43).contains(&(bottom - top)), "{top} {bottom}"); + assert!(rows_bottom - rows_top > 60, "{rows_top} {rows_bottom}"); + // The smallest reaches the base too: red on the axis just above it, and the outline of each + // meets there. + let axis: Vec = (0..200).filter(|&x| is_red(&nested, x, bottom - 2)).collect(); + assert!(!axis.is_empty()); +} + +#[test] +fn a_circle_without_an_edge_gets_one_in_the_legends_ink() { + let nested = drawn_at(&circles(10.0, 40.0, 0.0), LegendSizes::Nested, 4); + let (_, bottom) = red_rows(&nested); + let red: Vec = (0..nested.width()).filter(|&x| (0..nested.height()).any(|y| is_red(&nested, x, y))).collect(); + let (left, axis) = (red[0], (red[0] + red[red.len() - 1]) / 2); + // Left of the axis, where no leader runs, the two inner circles' edges cross the red. + let y = bottom - 20; + let first = (left..axis).find(|&x| is_red(&nested, x, y)).unwrap(); + let edges = (first..axis).filter(|&x| !is_red(&nested, x, y)).count(); + assert!(edges >= 2, "{edges}"); +} + +#[test] +fn classes_stay_rows_over_a_size_block() { + let mut map = circles(10.0, 40.0, 1.0); + let l: &mut Layer = &mut map.layers[0]; + l.renderer = Renderer::Unique { + field: "n".into(), + classes: vec![("1".into(), l.renderer.base_symbol()), ("9".into(), l.renderer.base_symbol())], + other: Symbol { fill: OTHER_FILL, ..l.renderer.base_symbol() }, + ramp: rustgis_map::Ramp::Lagoon, + 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, + }; + l.size_by = Some(rustgis_map::symbol_by::SizeBy { + field: "n".into(), + min: 1.0, + max: 9.0, + min_size: 4.0, + max_size: 20.0, + scaling: Default::default(), + }); + let rows = legend_rows(&map, None, &options(LegendSizes::Nested)); + let classes = rows.iter().filter(|r| matches!(r, LegendRow::Class(..))).count(); + assert_eq!((classes, rows.len()), (3, 4)); + assert!(matches!(rows.last(), Some(LegendRow::Sizes(_, block)) if block.len() == 3)); +} diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index f7595ba99a..14402cc912 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -744,6 +744,7 @@ fn an_ink_colours_legends_colorbars_tables_and_charts() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; 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 { @@ -814,6 +815,7 @@ fn layout_no_data_legend_follows_the_frame() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; legend_rows(map, drawn.as_deref(), &opts) .into_iter() @@ -883,6 +885,7 @@ fn layout_text_clipping_uses_ink_and_visibility() { class_labels: Default::default(), show_counts: Default::default(), subtitle: Default::default(), + sizes: Default::default(), }, ); assert_eq!(clipped_text(&l, &[Map::new("m")], 96.0, &info), vec![(legend, "Legend".into())]); @@ -938,6 +941,7 @@ fn legend_page(url: &str) -> (Layout, Vec) { class_labels: Default::default(), show_counts: Default::default(), subtitle: Default::default(), + sizes: Default::default(), }, ); let mut tile = rustgis_map::TileLayer::new("Walls", rustgis_map::TileKind::Raster, "https://tiles.test/red/{z}/{x}/{y}.png"); @@ -1051,6 +1055,7 @@ fn an_svg_export_gives_up_on_held_legends_at_one_deadline() { class_labels: Default::default(), show_counts: Default::default(), subtitle: Default::default(), + sizes: Default::default(), }, ); // The thread-local budget and the shortened wait belong to this worker alone. @@ -1113,6 +1118,7 @@ fn a_legend_says_from_the_lookup_that_draws_it_whether_a_picture_is_missing() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; let mut canvas = Canvas::new(200, 200).unwrap(); let draw = |canvas: &mut Canvas| { @@ -1428,6 +1434,7 @@ fn a_web_layers_legend_is_its_services_picture() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; 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()) @@ -1470,6 +1477,7 @@ fn a_web_layers_legend_is_its_services_picture() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; 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 = @@ -1796,6 +1804,7 @@ fn a_legends_rows_go_into_columns() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; let rows = legend_rows(&map, None, &opts()); assert_eq!(rows.len(), 32); @@ -1900,6 +1909,7 @@ fn a_layers_name_stays_with_its_class_only_in_columns() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; let rows = legend_rows(&map, None, &opts()); let (starts, _) = flow_at(&rows, 2, LEGEND_ROW, (1e6, 1.0)); @@ -1936,6 +1946,7 @@ fn a_legends_columns_hold_large_point_symbols() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; let rows = legend_rows(&map, None, &opts); let tall = rows[1].height(1e6, 1.0); @@ -2014,6 +2025,7 @@ fn opts(names: bool) -> LegendOptions<'static> { text_size, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), } } @@ -2136,6 +2148,7 @@ fn row_kinds(rows: &[LegendRow]) -> Vec { LegendRow::Head(_) => "Head".into(), LegendRow::Class(..) => "Class".into(), LegendRow::Picture(_) => "Picture".into(), + LegendRow::Sizes(..) => "Sizes".into(), }) .collect() } @@ -2186,6 +2199,7 @@ fn layer_names_can_be_left_off_a_legend() { labels: &NO_LABELS, class_labels: &NO_CLASS_LABELS, show_counts: false, + sizes: Default::default(), }; legend_sizes_asked_mm(&mut map.clone(), 1e6, &asked).unwrap()[0].1 }; @@ -2291,6 +2305,7 @@ fn fit_page(map: Map, (w, h): (f64, f64), (columns, fit): (usize, LegendFit), (t class_labels: Default::default(), show_counts: Default::default(), subtitle: Default::default(), + sizes: Default::default(), }, ); let scale = frame_render_scale(&map, Coord::new(0.0, 0.0), 150_000_000.0); @@ -2314,6 +2329,7 @@ fn a_legends_fit_is_the_same_at_every_resolution() { labels: &NO_LABELS, class_labels: &NO_CLASS_LABELS, show_counts: false, + sizes: Default::default(), }; for (fit, room) in [(LegendFit::AdjustSize, (40.0, 20.0 * row)), (LegendFit::AdjustColumns, (100.0, 12.0 * row))] { let (page, mut maps, scale) = fit_page(rows_map(32), room, (1, fit), ("", 9.0)); @@ -2354,6 +2370,7 @@ fn a_fitted_legend_exports_as_a_manual_legend_of_its_fitted_size() { labels: &NO_LABELS, class_labels: &NO_CLASS_LABELS, show_counts: false, + sizes: Default::default(), }; let info = PageInfo::default(); let export = |(page, mut maps, _): (Layout, Vec, f64)| { @@ -2684,6 +2701,7 @@ fn a_legend_measured_in_its_own_columns_lays_out_only_those() { labels: &NO_LABELS, class_labels: &NO_CLASS_LABELS, show_counts: false, + sizes: Default::default(), }; let six = legend_sizes_asked_mm(&mut map, 1e6, &asked).unwrap(); for (columns, laid_in) in [(0, 1), (1, 1), (2, 2), (3, 3), (6, 6), (9, 6)] { @@ -2736,6 +2754,7 @@ fn a_legend_shows_a_layers_label() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; legend_rows(&map, None, &opts) .iter() @@ -2774,6 +2793,7 @@ fn a_legend_shows_a_layers_label() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; 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) @@ -2829,6 +2849,7 @@ fn legends_leave_out_what_the_frame_does_not_draw() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; 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) @@ -2870,6 +2891,7 @@ fn legends_leave_out_what_the_frame_does_not_draw() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }, 1.0, ) @@ -3380,6 +3402,7 @@ fn a_legend_lists_a_classified_rasters_classes() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; let labels = |rows: &[LegendRow]| -> Vec { rows.iter() @@ -3388,6 +3411,7 @@ fn a_legend_lists_a_classified_rasters_classes() { LegendRow::Class(_, en) => en.label.clone(), LegendRow::Plain(_, name) => format!("plain {name}"), LegendRow::Picture(_) => "picture".into(), + LegendRow::Sizes(..) => "sizes".into(), }) .collect() }; @@ -7284,6 +7308,7 @@ fn point_legend(map: &Map) -> Pixmap { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; 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 @@ -7305,6 +7330,7 @@ fn recorded_legend(map: &Map, side: u32) -> Pixmap { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; 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(); @@ -7532,6 +7558,7 @@ fn a_legend_grows_to_hold_a_large_point() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; 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()); @@ -7579,6 +7606,7 @@ fn a_legends_text_size_scales_its_rows_but_not_its_point_symbols() { text_size: 18.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; 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"); @@ -8001,6 +8029,7 @@ fn a_recorded_point_is_cut_at_its_box() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; 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(); @@ -8137,6 +8166,7 @@ fn an_oversized_point_stays_in_its_row() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; 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) @@ -8178,6 +8208,7 @@ fn a_see_through_point_larger_than_the_canvas_covers_it_from_off_its_edge() { text_size: 9.0, class_labels: &NO_CLASS_LABELS, counts: None, + sizes: Default::default(), }; 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) @@ -8569,6 +8600,7 @@ fn a_legend_labels_a_layers_classes_itself() { scale: 1e6, size: 1.0, text_size: 9.0, + sizes: Default::default(), }; assert_eq!(labels_of(&legend_rows(&map, None, &opts(&listed, false))), ["c0", "c1", "c99"]); assert_eq!(class_row_labels(&map.layers[0]), ["c0", "c1", "c99"]); @@ -8629,6 +8661,7 @@ fn a_legend_labels_a_layers_classes_itself() { labels: &NO_LABELS, class_labels, show_counts: false, + sizes: Default::default(), }; legend_size_asked_mm(&mut map, 1e6, &asked, 1).unwrap().0 }; @@ -8671,12 +8704,14 @@ fn a_legend_lists_its_layers_in_its_own_order() { scale: 1e6, size: 1.0, text_size: 9.0, + sizes: Default::default(), }; legend_rows(map, None, &opts) .iter() .map(|r| match r { LegendRow::Plain(l, _) => l.name.clone(), LegendRow::Picture(_) => "picture".into(), + LegendRow::Sizes(..) => "sizes".into(), _ => "other".into(), }) .collect() @@ -8746,6 +8781,7 @@ fn a_legend_counts_the_features_of_each_row() { scale: 1e6, size: 1.0, text_size: 9.0, + sizes: Default::default(), }; legend_rows(map, drawn.as_deref(), &opts) .iter() @@ -8754,6 +8790,7 @@ fn a_legend_counts_the_features_of_each_row() { LegendRow::Plain(_, n) => n.to_string(), LegendRow::Class(_, e) => e.label.clone(), LegendRow::Picture(_) => "picture".into(), + LegendRow::Sizes(..) => "sizes".into(), }) .collect() }; diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index eac91e1faf..9ec00dfcd3 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -590,6 +590,7 @@ fn layout_export_keeps_all_drawn_legend_classes() { class_labels: Default::default(), show_counts: Default::default(), subtitle: Default::default(), + sizes: Default::default(), }, ); let expected = layout::render(&page, &mut [base.clone()], 96.0, &layout::PageInfo::default()).unwrap(); diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index f41a247ef7..02e8454cfa 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -526,6 +526,7 @@ mod tests { class_labels: Default::default(), show_counts: Default::default(), subtitle: Default::default(), + sizes: Default::default(), }, ); assert_eq!(picture_dpi(&layout, 600.0, |e| !written_as_svg(e)), 600.0); @@ -574,6 +575,7 @@ mod tests { class_labels: Default::default(), show_counts: Default::default(), subtitle: Default::default(), + sizes: Default::default(), }, ); let info = PageInfo::default(); diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 19edf08f6f..6b6a1a2e56 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -8304,6 +8304,7 @@ pub(crate) mod tests { fills: Vec::new(), fallback: false, count: None, + sized: false, }; assert_eq!(size_rows_scale(cities, &[row(10.0, 4.0), row(20.0, 7.0)]), 1.0, "marks that fit as drawn"); assert_eq!(size_rows_scale(cities, &[row(10.0, 14.0), row(20.0, 28.0)]), 0.5, "the largest marks, not the symbol"); diff --git a/docs/maintaining.md b/docs/maintaining.md index 866119bc7b..851a579cbe 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -339,6 +339,13 @@ whose `subtitle` is text require it too; `""` and `null` need nothing. A saved ` `report.existingTemplate` carrying such a legend requires it as well, and a layout file (`.rgislayout`) with one lists it in its header. +Projects with a legend that nests a layer's sizes (`"sizes": "nested"` on a legend element) +require `layout-legend-nested-sizes`, so an older reader refuses them instead of drawing rows and +saving the legend again without the setting (#3347). Saved `layout.addElement` and `layout.update` +commands with that value require it too; `"rows"` and `null` need nothing. A saved `layout.import` +or `report.existingTemplate` carrying such a legend requires it as well, and a layout file +(`.rgislayout`) with one lists it in its header. + Projects with a legend that shows feature counts (`show_counts` on a legend element) require `layout-legend-counts`, so an older reader refuses them instead of drawing no numbers and saving the legend again without the setting (#3237). Saved `layout.addElement` and `layout.update` diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index b46d0b27df..e56fa37e3f 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -453,7 +453,7 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu short fills each column in turn and leaves out the last rows (a **Fit**, below, can change that). A legend says when its box loses rows or closes its columns up when it is given `"columns"`, - `"textSize"` (`null` included), `"showNoData"`, `"labels"`, `"classLabels"`, `"fit"`, `"showLayerNames"`, `"showCounts"` or `"subtitle"`, and, + `"textSize"` (`null` included), `"showNoData"`, `"labels"`, `"classLabels"`, `"fit"`, `"showLayerNames"`, `"showCounts"`, `"subtitle"` or `"sizes"`, and, in columns, at a text size of its own or with a fit, when its box, the order of its layers or what it lists changes. A legend in one column at the default size and with no fit is told so only when given one of those. A manual legend is checked when it is added or changed, as it always has been, not again @@ -480,6 +480,13 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu line. The rows start under it, so a box holds one row less, which the fit and its warnings count; a fit shrinks the rows, not the subtitle. Like the title, a line wider than the box runs past it. `""` takes it away. + - **Sizes** (`"sizes"`, set with a command): how the legend draws the rows that show a point + layer's marker sizes, those of Proportional Symbols and those a layer sized by a field lists + after its classes. `"rows"`, the default, gives each its own row. `"nested"` draws a layer's + as one block: the markers one inside another, the largest first, on a common base, each with a + thin line from its top to its value. A marker with no outline gets a thin one in the legend's + ink. The markers keep the size the map draws them at, and the block is never split between + columns. Class rows stay as rows. - **Layer names** (`"showLayerNames"`, on by default): off, the name over each layer's classes, and over a web layer's legend picture, is left off. A layer drawn in one symbol keeps its name beside its swatch, since that is what labels it; classes that carry no label of their own diff --git a/schema/fixtures/layout_legend_nested_sizes.rgis b/schema/fixtures/layout_legend_nested_sizes.rgis new file mode 100644 index 0000000000..36c89e80ad --- /dev/null +++ b/schema/fixtures/layout_legend_nested_sizes.rgis @@ -0,0 +1,25 @@ +{ + "format": 2, + "name": "Legend nested sizes", + "requires": ["layout-legend-nested-sizes"], + "active_map": 0, + "maps": [ + { + "name": "Map", + "layers": [], + "basemap": "Paper", + "camera": {"center": {"x": 0, "y": 0}, "res": 30000} + } + ], + "layouts": [ + { + "name": "Legends", + "width": 200, + "height": 100, + "elements": [ + {"id": 1, "name": "Map Frame", "x": 5, "y": 5, "w": 90, "h": 90, "kind": {"MapFrame": {"map": "Map", "center": {"x": 0, "y": 0}, "scale": 1000000}}}, + {"id": 2, "name": "Nested", "x": 100, "y": 5, "w": 95, "h": 90, "kind": {"Legend": {"frame": 1, "title": "Legend", "sizes": "nested"}}} + ] + } + ] +} diff --git a/schema/project.schema.json b/schema/project.schema.json index 681fa14e11..4150fbec7d 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1284,6 +1284,7 @@ "layout-legend-class-labels", "layout-legend-counts", "layout-legend-subtitle", + "layout-legend-nested-sizes", "layout-legend-order", "layout-scale-bar-details", "label-guide", @@ -1415,6 +1416,7 @@ "layout-legend-class-labels", "layout-legend-counts", "layout-legend-subtitle", + "layout-legend-nested-sizes", "layout-legend-order", "layout-scale-bar-details", "label-guide", From 4b8b9b0abdd2d960b81541cb0f9fba6f806117f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 29 Nov 2026 10:30:23 -0500 Subject: [PATCH 2/7] test(layout): cover junk sizes and markers of one size in a nested legend --- crates/engine/src/tests.rs | 1 + crates/render/src/layout/legend/nested.rs | 3 ++- crates/render/src/layout/legend/nested/tests.rs | 10 ++++++++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a2d0fc2da9..2a62281f32 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8780,6 +8780,7 @@ fn hostile_junk() -> Vec { json!({"kind": "legend", "element": 1, "classLabels": [{"Countries": [null]}]}), json!({"kind": "legend", "element": 1, "classLabels": {"Countries": {"Africa": f64::MAX}}}), json!({"kind": "legend", "element": 1, "showCounts": [{"x": f64::MAX}]}), + json!({"kind": "legend", "element": 1, "sizes": [{"x": f64::MAX}]}), json!({"kind": "legend", "element": 1, "layerOrder": vec!["x".repeat(64); 1001]}), json!({"kind": "legend", "element": 1, "layerOrder": [{"Countries": [null]}, f64::MAX]}), json!({"kind": "legend", "element": 1, "layerOrder": f64::MAX}), diff --git a/crates/render/src/layout/legend/nested.rs b/crates/render/src/layout/legend/nested.rs index 2c9270f2d4..ddd82319c7 100644 --- a/crates/render/src/layout/legend/nested.rs +++ b/crates/render/src/layout/legend/nested.rs @@ -20,7 +20,8 @@ pub(super) fn block<'a>(l: &'a rustgis_map::Layer, entries: Vec, sc (en, side) }) .collect(); - // Listed smallest value first: reversed, markers of one size keep the largest value on top. + // The entries list the smallest value first. The sort is stable, so reversed before it, markers + // of one size are labelled from the largest value down, as the others are. block.reverse(); block.sort_by(|a, b| b.1.total_cmp(&a.1)); LegendRow::Sizes(l, block) diff --git a/crates/render/src/layout/legend/nested/tests.rs b/crates/render/src/layout/legend/nested/tests.rs index cd6bba76e7..029b3024b0 100644 --- a/crates/render/src/layout/legend/nested/tests.rs +++ b/crates/render/src/layout/legend/nested/tests.rs @@ -89,6 +89,16 @@ fn nested_sizes_make_one_row_largest_first() { assert!(block[0].1 > block[1].1 && block[1].1 > block[2].1); } +#[test] +fn markers_of_one_size_are_labelled_from_the_largest_value_down() { + let map = circles(20.0, 20.0, 1.0); + // The middle one's size is worked out from the ends, so all three are alike. + let rows = legend_rows(&map, None, &options(LegendSizes::Nested)); + let [LegendRow::Sizes(_, block)] = rows.as_slice() else { panic!("{} rows", rows.len()) }; + let labels: Vec<&str> = block.iter().map(|(e, _)| e.label.as_str()).collect(); + assert_eq!(labels, ["9", "5", "1"]); +} + #[test] fn nested_circles_stand_on_one_base() { let map = circles(10.0, 40.0, 1.0); From 10f330c34da01ae54ba700716a43eee6e9e5fda9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 29 Nov 2026 10:37:17 -0500 Subject: [PATCH 3/7] fix(layout): stand nested legend markers on their ink, so they share one base --- crates/render/src/layout/legend.rs | 13 ++- crates/render/src/layout/legend/nested.rs | 79 ++++++++++++++----- .../render/src/layout/legend/nested/tests.rs | 18 ++++- 3 files changed, 83 insertions(+), 27 deletions(-) diff --git a/crates/render/src/layout/legend.rs b/crates/render/src/layout/legend.rs index 4e0a5a1810..db195e0464 100644 --- a/crates/render/src/layout/legend.rs +++ b/crates/render/src/layout/legend.rs @@ -241,9 +241,9 @@ pub(super) enum LegendRow<'a> { Plain(&'a rustgis_map::Layer, std::borrow::Cow<'a, str>), Head(std::borrow::Cow<'a, str>), Class(&'a rustgis_map::Layer, LegendEntry), - /// A point layer's sizes drawn nested (#3347): the largest first, each with the side of its - /// marker in points. - Sizes(&'a rustgis_map::Layer, Vec<(LegendEntry, f32)>), + /// A point layer's sizes drawn nested (#3347): the tallest first, each with what its marker + /// takes. + Sizes(&'a rustgis_map::Layer, Vec<(LegendEntry, nested::Ink)>), Picture(std::sync::Arc), } @@ -254,7 +254,7 @@ impl LegendRow<'_> { #[cfg(test)] tests::SYMBOL_SIDES.with(|n| n.set(n.get() + 1)); if let LegendRow::Sizes(_, block) = self { - return block.first().map_or(0.0, |(_, side)| *side); + return block.iter().map(|(_, ink)| ink.side).fold(0.0, f32::max); } let (LegendRow::Plain(l, _) | LegendRow::Class(l, _)) = self else { return 0.0 }; if l.geometry_type() != GeometryType::Point { @@ -282,10 +282,7 @@ impl LegendRow<'_> { fn height_beside(&self, side: f32, size: f32) -> f32 { match self { LegendRow::Picture(p) => picture_size(p).1 * size, - LegendRow::Sizes(_, block) => { - let sides: Vec = block.iter().map(|(_, side)| *side).collect(); - nested::places(&sides, nested::LINE * size).2 - } + LegendRow::Sizes(_, block) => nested::places(&nested::heights(block), nested::LINE * size).2, _ => (LEGEND_ROW * size).max(side), } } diff --git a/crates/render/src/layout/legend/nested.rs b/crates/render/src/layout/legend/nested.rs index ddd82319c7..2491e4ad18 100644 --- a/crates/render/src/layout/legend/nested.rs +++ b/crates/render/src/layout/legend/nested.rs @@ -10,25 +10,67 @@ const EDGE: f32 = 0.5; /// their text, closer than rows are. pub(super) const LINE: f32 = 12.0; -/// The row of the sizes `entries` of the point layer `l` at 1:`scale`: the largest marker first, -/// each with its side. +/// What a marker of a block takes at the frame's scale, in points: how far its ink reaches above +/// and below its point, and the square its row would give it ([`point_side`]), which can be larger. +#[derive(Clone, Copy)] +pub(in crate::layout) struct Ink { + up: f32, + down: f32, + pub(super) side: f32, +} + +impl Ink { + /// From the marker's top to its bottom, which stands on the block's base. + pub(super) fn height(self) -> f32 { + self.up + self.down + } +} + +/// Whether a block gives a marker an edge of its own: one drawn by its symbol alone, with no +/// outline that shows. +fn bare(s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke]) -> bool { + point_marks::plain(strokes, 0.0) && (s.stroke.a() == 0 || s.stroke_width <= 0.0) +} + +/// The [`Ink`] of the layer `l`'s marker `s` with its stacked `strokes` at 1:`scale`. A shape's is +/// its path's, as the map draws it, and half its outline; a picture's or a stack's, its square's. +fn ink_of(l: &rustgis_map::Layer, s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke], scale: f64) -> Ink { + let side = point_side(l, s, strokes, scale); + let square = Ink { up: side / 2.0, down: side / 2.0, side }; + if side <= 0.0 || !point_marks::plain(strokes, 0.0) || matches!(s.marker, rustgis_map::Marker::Picture(_)) { + return square; + } + let k = l.size_factor(scale); + let Some(path) = crate::marker_path_report(0.0, 0.0, s.size.max(1.0) * k / 2.0, s.marker).0 else { return square }; + let half = if bare(s, strokes) { EDGE } else { s.stroke_width * k } / 2.0; + let (up, down) = (half - path.bounds().top(), path.bounds().bottom() + half); + // One past the largest a legend draws is cut to its square. + if up + down > MAX_LEGEND_SIDE as f32 { square } else { Ink { up, down, side } } +} + +/// The row of the sizes `entries` of the point layer `l` at 1:`scale`: the tallest marker first. pub(super) fn block<'a>(l: &'a rustgis_map::Layer, entries: Vec, scale: f64) -> LegendRow<'a> { - let mut block: Vec<(LegendEntry, f32)> = entries + let mut block: Vec<(LegendEntry, Ink)> = entries .into_iter() .map(|en| { - let side = point_side(l, &en.symbol, row_strokes(l, &en), scale); - (en, side) + let ink = ink_of(l, &en.symbol, row_strokes(l, &en), scale); + (en, ink) }) .collect(); // The entries list the smallest value first. The sort is stable, so reversed before it, markers // of one size are labelled from the largest value down, as the others are. block.reverse(); - block.sort_by(|a, b| b.1.total_cmp(&a.1)); + block.sort_by(|a, b| b.1.height().total_cmp(&a.1.height())); LegendRow::Sizes(l, block) } +/// The heights of a block's markers, in its order. +pub(super) fn heights(block: &[(LegendEntry, Ink)]) -> Vec { + block.iter().map(|(_, ink)| ink.height()).collect() +} + /// Where a block's parts go, in points from its top, its labels' lines `line` high, its -/// markers `sides` across, the largest first: the base they stand on, each label's middle, and the +/// markers `sides` high, the tallest first: the base they stand on, each label's middle, and the /// block's height. A label is level with the top of its marker, or a line under the label above /// where the tops are closer than that. pub(super) fn places(sides: &[f32], line: f32) -> (f32, Vec, f32) { @@ -53,31 +95,32 @@ pub(super) fn places(sides: &[f32], line: f32) -> (f32, Vec, f32) { pub(super) fn draw( pm: &mut Canvas, (x, y, column): (f32, f32, f32), - (l, block): (&rustgis_map::Layer, &[(LegendEntry, f32)]), + (l, block): (&rustgis_map::Layer, &[(LegendEntry, Ink)]), (opacity, scale): (f32, f64), (size, ppp): (f32, f32), (text_x, ink): (f32, Rgba), ) { - let sides: Vec = block.iter().map(|(_, side)| *side).collect(); - let (base, middles, height) = places(&sides, LINE * size); + let (base, middles, height) = places(&heights(block), LINE * size); let (cx, base) = (x + column / 2.0, y + base * ppp); let k = l.size_factor(scale); // Room round each marker's box for an edge it didn't have. let room = EDGE * ppp; - let widest = sides.first().map_or(0.0, |side| side * ppp) + 2.0 * room; + let widest = block.iter().map(|(_, ink)| ink.side * ppp).fold(0.0, f32::max) + 2.0 * room; let markers = |c: &mut Canvas, (left, top): (f32, f32)| { - for (en, side) in block { + for (en, ink_box) in block { // A marker sized zero has no ink to edge or to draw. - if *side <= 0.0 { + if ink_box.side <= 0.0 { continue; } let strokes = row_strokes(l, en); let mut symbol = en.symbol; - if point_marks::plain(strokes, 0.0) && (symbol.stroke.a() == 0 || symbol.stroke_width <= 0.0) && k > 0.0 { + if bare(&symbol, strokes) && k > 0.0 { (symbol.stroke, symbol.stroke_width) = (ink, EDGE / k); } - let across = side * ppp + 2.0 * room; - let cell = (cx - across / 2.0 - left, base - side * ppp - room - top, across, across); + let across = ink_box.side * ppp + 2.0 * room; + // Its point as far above the base as its ink reaches below it. + let cy = base - ink_box.down * ppp; + let cell = (cx - across / 2.0 - left, cy - across / 2.0 - top, across, across); point_swatch(c, cell, (&symbol, strokes), 1.0, ppp * k); } }; @@ -87,8 +130,8 @@ pub(super) fn draw( composited(pm, (cx - widest / 2.0, y, widest, height * ppp), opacity, markers); } let stroke = Stroke { width: EDGE * size * ppp, ..Stroke::default() }; - for ((en, side), middle) in block.iter().zip(middles) { - let (top, middle) = (base - side * ppp, y + middle * ppp); + for ((en, ink_box), middle) in block.iter().zip(middles) { + let (top, middle) = (base - ink_box.height() * ppp, y + middle * ppp); let mut leader = PathBuilder::new(); leader.move_to(cx, top); // Level to the column's edge, then to a label pushed down. diff --git a/crates/render/src/layout/legend/nested/tests.rs b/crates/render/src/layout/legend/nested/tests.rs index 029b3024b0..107de14c24 100644 --- a/crates/render/src/layout/legend/nested/tests.rs +++ b/crates/render/src/layout/legend/nested/tests.rs @@ -86,7 +86,7 @@ fn nested_sizes_make_one_row_largest_first() { let [LegendRow::Sizes(_, block)] = nested.as_slice() else { panic!("{} rows", nested.len()) }; let labels: Vec<&str> = block.iter().map(|(e, _)| e.label.as_str()).collect(); assert_eq!(labels, ["9", "5", "1"]); - assert!(block[0].1 > block[1].1 && block[1].1 > block[2].1); + assert!(block[0].1.height() > block[1].1.height() && block[1].1.height() > block[2].1.height()); } #[test] @@ -113,6 +113,22 @@ fn nested_circles_stand_on_one_base() { assert!(!axis.is_empty()); } +#[test] +fn the_markers_ink_meets_at_the_base_and_each_leader_starts_on_it() { + let mut map = circles(10.0, 40.0, 1.0); + // Rings: beside the axis, each marker's top shows, and one bottom for all of them. + let Renderer::Proportional { base, .. } = &mut map.layers[0].renderer else { panic!() }; + base.fill = Rgba::new(0, 0, 0, 0); + let pm = drawn_at(&map, LegendSizes::Nested, 4); + let (top, bottom) = red_rows(&pm); + // As tall as the largest ring and its outline: 41 points. + assert!((161..=167).contains(&(bottom - top)), "{top} {bottom}"); + let red: Vec = (0..pm.width()).filter(|&x| (0..pm.height()).any(|y| is_red(&pm, x, y))).collect(); + let x = (red[0] + red[red.len() - 1]) / 2 - 3; + let runs = (top.saturating_sub(2)..=bottom).filter(|&y| is_red(&pm, x, y) && !is_red(&pm, x, y - 1)).count(); + assert_eq!(runs, 4); +} + #[test] fn a_circle_without_an_edge_gets_one_in_the_legends_ink() { let nested = drawn_at(&circles(10.0, 40.0, 0.0), LegendSizes::Nested, 4); From d4312556c7bb0dffcbdf9b3d59d7621a3199a1cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 29 Nov 2026 11:11:20 -0500 Subject: [PATCH 4/7] test(layout): fail the nested sizes fit test when nothing is ever said --- crates/engine/src/tests/layout_legend_sizes.rs | 1 + crates/render/src/layout/legend/nested.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/layout_legend_sizes.rs b/crates/engine/src/tests/layout_legend_sizes.rs index 60e5a1426c..73bfa63128 100644 --- a/crates/engine/src/tests/layout_legend_sizes.rs +++ b/crates/engine/src/tests/layout_legend_sizes.rs @@ -121,5 +121,6 @@ fn nested_sizes_fit_a_box_their_rows_do_not() { h += 1.0; assert!(h < 200.0, "never fits"); } + assert!(h > 10.0, "nothing said at any height, so the fit was never checked"); assert!(!said(&mut s, json!({"element": legend, "sizes": "nested", "h": h - 3.0})), "{h}: the block is shorter than the rows"); } diff --git a/crates/render/src/layout/legend/nested.rs b/crates/render/src/layout/legend/nested.rs index 2491e4ad18..09f8378090 100644 --- a/crates/render/src/layout/legend/nested.rs +++ b/crates/render/src/layout/legend/nested.rs @@ -42,7 +42,7 @@ fn ink_of(l: &rustgis_map::Layer, s: &rustgis_map::Symbol, strokes: &[rustgis_ma } let k = l.size_factor(scale); let Some(path) = crate::marker_path_report(0.0, 0.0, s.size.max(1.0) * k / 2.0, s.marker).0 else { return square }; - let half = if bare(s, strokes) { EDGE } else { s.stroke_width * k } / 2.0; + let half = (if bare(s, strokes) { EDGE } else { s.stroke_width * k }) / 2.0; let (up, down) = (half - path.bounds().top(), path.bounds().bottom() + half); // One past the largest a legend draws is cut to its square. if up + down > MAX_LEGEND_SIDE as f32 { square } else { Ink { up, down, side } } From 50af689530435c34fd21a5482765422b344e27d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 29 Nov 2026 11:17:11 -0500 Subject: [PATCH 5/7] fix(layout): measure nested legend markers by their ink, stacked marks and zero sizes included --- crates/render/src/layout/legend/nested.rs | 37 +++++++------- .../render/src/layout/legend/nested/tests.rs | 48 +++++++++++++++++++ crates/render/src/lib.rs | 5 ++ crates/render/src/point_marks.rs | 39 +++++++++++++++ 4 files changed, 111 insertions(+), 18 deletions(-) diff --git a/crates/render/src/layout/legend/nested.rs b/crates/render/src/layout/legend/nested.rs index 09f8378090..e237d0b4c8 100644 --- a/crates/render/src/layout/legend/nested.rs +++ b/crates/render/src/layout/legend/nested.rs @@ -26,26 +26,30 @@ impl Ink { } } -/// Whether a block gives a marker an edge of its own: one drawn by its symbol alone, with no -/// outline that shows. -fn bare(s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke]) -> bool { - point_marks::plain(strokes, 0.0) && (s.stroke.a() == 0 || s.stroke_width <= 0.0) +/// The symbol a block draws for `s` with its stacked `strokes` at the reference factor `k`: one +/// drawn by its symbol alone, with no outline that shows, gets one in `ink`. A marker sized zero +/// stays without ink. +fn edged(s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke], k: f32, ink: Rgba) -> rustgis_map::Symbol { + let mut symbol = *s; + let bare = point_marks::plain(strokes, 0.0) && (s.stroke.a() == 0 || s.stroke_width <= 0.0); + if bare && s.size > 0.0 && k > 0.0 { + (symbol.stroke, symbol.stroke_width) = (ink, EDGE / k); + } + symbol } -/// The [`Ink`] of the layer `l`'s marker `s` with its stacked `strokes` at 1:`scale`. A shape's is -/// its path's, as the map draws it, and half its outline; a picture's or a stack's, its square's. +/// The [`Ink`] of the layer `l`'s marker `s` with its stacked `strokes` at 1:`scale`, as a block +/// draws it ([`edged`]); one with no ink takes nothing. fn ink_of(l: &rustgis_map::Layer, s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke], scale: f64) -> Ink { let side = point_side(l, s, strokes, scale); - let square = Ink { up: side / 2.0, down: side / 2.0, side }; - if side <= 0.0 || !point_marks::plain(strokes, 0.0) || matches!(s.marker, rustgis_map::Marker::Picture(_)) { - return square; - } let k = l.size_factor(scale); - let Some(path) = crate::marker_path_report(0.0, 0.0, s.size.max(1.0) * k / 2.0, s.marker).0 else { return square }; - let half = (if bare(s, strokes) { EDGE } else { s.stroke_width * k }) / 2.0; - let (up, down) = (half - path.bounds().top(), path.bounds().bottom() + half); + // Its colour changes nothing here. + let Some((up, down)) = point_marks::ink_reach(&edged(s, strokes, k, INK), strokes) else { + return Ink { up: 0.0, down: 0.0, side: 0.0 }; + }; + let (up, down) = (up * k, down * k); // One past the largest a legend draws is cut to its square. - if up + down > MAX_LEGEND_SIDE as f32 { square } else { Ink { up, down, side } } + if up + down > MAX_LEGEND_SIDE as f32 { Ink { up: side / 2.0, down: side / 2.0, side } } else { Ink { up, down, side } } } /// The row of the sizes `entries` of the point layer `l` at 1:`scale`: the tallest marker first. @@ -113,10 +117,7 @@ pub(super) fn draw( continue; } let strokes = row_strokes(l, en); - let mut symbol = en.symbol; - if bare(&symbol, strokes) && k > 0.0 { - (symbol.stroke, symbol.stroke_width) = (ink, EDGE / k); - } + let symbol = edged(&en.symbol, strokes, k, ink); let across = ink_box.side * ppp + 2.0 * room; // Its point as far above the base as its ink reaches below it. let cy = base - ink_box.down * ppp; diff --git a/crates/render/src/layout/legend/nested/tests.rs b/crates/render/src/layout/legend/nested/tests.rs index 107de14c24..fa607e98e0 100644 --- a/crates/render/src/layout/legend/nested/tests.rs +++ b/crates/render/src/layout/legend/nested/tests.rs @@ -172,3 +172,51 @@ fn classes_stay_rows_over_a_size_block() { assert_eq!((classes, rows.len()), (3, 4)); assert!(matches!(rows.last(), Some(LegendRow::Sizes(_, block)) if block.len() == 3)); } + +#[test] +fn stacked_markers_are_measured_by_their_ink() { + use rustgis_map::{LineMark, LineMarkers, LineStroke, Marker}; + let map = circles(10.0, 40.0, 0.0); + let l = &map.layers[0]; + // A 20 point circle shifted 3 points down. + let mark = LineMarkers { mark: LineMark::Marker(Marker::Circle), size: 20.0, ..LineMarkers::default() }; + let stroke = LineStroke { color: Some(RED), width: Some(0.0), offset: 3.0, markers: Some(mark), ..LineStroke::default() }; + let mut entry = l.renderer.legend().remove(0); + entry.strokes = vec![stroke]; + let LegendRow::Sizes(_, block) = block(l, vec![entry], 1e6) else { panic!() }; + let ink = block[0].1; + assert!((ink.height() - 20.0).abs() < 0.1 && (ink.down - 13.0).abs() < 0.1, "{} {}", ink.height(), ink.down); +} + +#[test] +fn a_size_of_zero_takes_no_ink_and_gets_no_edge() { + let mut map = circles(10.0, 40.0, 1.0); + let l = &mut map.layers[0]; + let base = l.renderer.base_symbol(); + l.renderer = Renderer::Unique { + field: "n".into(), + classes: vec![("1".into(), base)], + other: base, + ramp: rustgis_map::Ramp::Lagoon, + 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, + }; + l.size_by = Some(rustgis_map::symbol_by::SizeBy { + field: "n".into(), + min: 1.0, + max: 9.0, + min_size: 0.0, + max_size: 20.0, + scaling: Default::default(), + }); + let rows = legend_rows(&map, None, &options(LegendSizes::Nested)); + let Some(LegendRow::Sizes(_, block)) = rows.last() else { panic!("no block") }; + let smallest = &block[block.len() - 1]; + assert_eq!(smallest.0.label, "n 1"); + assert_eq!((smallest.1.height(), smallest.1.side), (0.0, 0.0)); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f4621419d2..4fce501d5e 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2101,6 +2101,11 @@ pub(crate) fn picture_marker( !image || picture::draw_marker(pm, p, width, t, opacity) } +/// Picture marker `p`'s height for its width; `None` where it is drawn as a circle. +pub(crate) fn picture_marker_height(p: rustgis_map::Picture) -> Option { + picture::marker_aspect(p) +} + /// How far a `marker` reaches from its centre, in its sizes: a shape (a star's points) 0.6, a /// character as far as its outline does. pub(crate) fn marker_reach(marker: Marker) -> f32 { diff --git a/crates/render/src/point_marks.rs b/crates/render/src/point_marks.rs index d33794a8c1..0732383dc6 100644 --- a/crates/render/src/point_marks.rs +++ b/crates/render/src/point_marks.rs @@ -64,6 +64,45 @@ fn marks(sym: &Symbol, strokes: &[LineStroke]) -> Vec { .collect() } +/// How far the ink of a point of symbol `sym` reaches above and below it (points), unturned, by +/// the paths [`draw`] draws: `strokes`' marks, else its marker. `None` when no mark has ink. +pub(crate) fn ink_reach(sym: &Symbol, strokes: &[LineStroke]) -> Option<(f32, f32)> { + marks(sym, strokes) + .iter() + .filter_map(|m| { + let (sin, cos) = m.angle.to_radians().sin_cos(); + let (ox, oy) = m.offset; + let t = Transform::from_rotate(m.angle).post_translate(ox * cos - oy * sin, ox * sin + oy * cos); + let hash = matches!(m.shape, LineMark::Hash); + let picture = match m.shape { + LineMark::Marker(rustgis_map::Marker::Picture(p)) => crate::picture_marker_height(p), + _ => None, + }; + let path = match (m.shape, picture) { + // An image as tall as its width makes it, whatever its fill. + (_, Some(aspect)) => { + let w = m.size.max(1.0); + tiny_skia::Rect::from_xywh(-w / 2.0, -w * aspect / 2.0, w, w * aspect).map(PathBuilder::from_rect) + } + (LineMark::Marker(shape), None) => marker_path(0.0, 0.0, m.size.max(1.0) / 2.0, shape), + (LineMark::Hash, None) => { + let mut pb = PathBuilder::new(); + pb.move_to(0.0, -m.size / 2.0); + pb.line_to(0.0, m.size / 2.0); + pb.finish() + } + }; + let outline = m.outline.filter(|(c, w)| c.a() > 0 && *w > 0.0); + if picture.is_none() && outline.is_none() && (hash || m.fill.a() == 0) { + return None; + } + let bounds = path?.transform(t)?.bounds(); + let half = outline.filter(|_| picture.is_none()).map_or(0.0, |(_, w)| w / 2.0); + Some((half - bounds.top(), bounds.bottom() + half)) + }) + .reduce(|a, b| (a.0.max(b.0), a.1.max(b.1))) +} + /// Draws a point of symbol `sym` at (`x`, `y`) device pixels: `strokes`' marks, else its marker, /// turned `turn` degrees clockwise about the point; with `halo`, a selection halo round each. pub(crate) fn draw(pm: &mut Canvas, x: f32, y: f32, sym: &Symbol, strokes: &[LineStroke], turn: f32, halo: Option, ppp: f32) { From 9721ac191bcb3cb04c552b2530aec0c2de574fa0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 29 Nov 2026 11:26:19 -0500 Subject: [PATCH 6/7] fix(layout): give a nested marker its row draws nowhere no height --- crates/render/src/layout/legend/nested.rs | 8 ++++++-- crates/render/src/layout/legend/nested/tests.rs | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/render/src/layout/legend/nested.rs b/crates/render/src/layout/legend/nested.rs index e237d0b4c8..901856073b 100644 --- a/crates/render/src/layout/legend/nested.rs +++ b/crates/render/src/layout/legend/nested.rs @@ -3,8 +3,8 @@ use super::*; -/// The width in points, at the default size, of the line that edges a bare marker and of the -/// leaders. +/// The width in points of the line that edges a bare marker, which keeps it as the marker keeps +/// its size, and of the leaders at the default size, which follow the legend's. const EDGE: f32 = 0.5; /// The least two labels' middles are apart in a block, in points at the default size: a line of /// their text, closer than rows are. @@ -42,6 +42,10 @@ fn edged(s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke], k: f32, i /// draws it ([`edged`]); one with no ink takes nothing. fn ink_of(l: &rustgis_map::Layer, s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke], scale: f64) -> Ink { let side = point_side(l, s, strokes, scale); + // One its row would give no room is not drawn. + if side <= 0.0 { + return Ink { up: 0.0, down: 0.0, side: 0.0 }; + } let k = l.size_factor(scale); // Its colour changes nothing here. let Some((up, down)) = point_marks::ink_reach(&edged(s, strokes, k, INK), strokes) else { diff --git a/crates/render/src/layout/legend/nested/tests.rs b/crates/render/src/layout/legend/nested/tests.rs index fa607e98e0..6653c7b266 100644 --- a/crates/render/src/layout/legend/nested/tests.rs +++ b/crates/render/src/layout/legend/nested/tests.rs @@ -220,3 +220,17 @@ fn a_size_of_zero_takes_no_ink_and_gets_no_edge() { assert_eq!(smallest.0.label, "n 1"); assert_eq!((smallest.1.height(), smallest.1.side), (0.0, 0.0)); } + +#[test] +fn a_stacked_mark_sized_zero_takes_no_height() { + use rustgis_map::{LineMark, LineMarkers, LineStroke, Marker}; + let map = circles(10.0, 40.0, 0.0); + let l = &map.layers[0]; + // A stack's mark scaled to nothing, in a colour of its own and with no outline. + let mark = LineMarkers { mark: LineMark::Marker(Marker::Circle), size: 0.0, ..LineMarkers::default() }; + let stroke = LineStroke { color: Some(RED), width: Some(0.0), markers: Some(mark), ..LineStroke::default() }; + let mut entry = l.renderer.legend().remove(0); + (entry.symbol.size, entry.strokes) = (0.0, vec![stroke]); + let LegendRow::Sizes(_, block) = block(l, vec![entry], 1e6) else { panic!() }; + assert_eq!((block[0].1.height(), block[0].1.side), (0.0, 0.0)); +} From 149789f7d983eb9d705d6123538b7f6d074b4310 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 29 Nov 2026 11:28:50 -0500 Subject: [PATCH 7/7] fix(layout): edge a nested stack of markers that has no outline --- crates/render/src/layout/legend/nested.rs | 51 ++++++++++++++----- .../render/src/layout/legend/nested/tests.rs | 27 +++++++++- docs/user-guide/layouts.md | 7 +-- 3 files changed, 67 insertions(+), 18 deletions(-) diff --git a/crates/render/src/layout/legend/nested.rs b/crates/render/src/layout/legend/nested.rs index 901856073b..fabd875946 100644 --- a/crates/render/src/layout/legend/nested.rs +++ b/crates/render/src/layout/legend/nested.rs @@ -2,6 +2,7 @@ //! common base, each led to its value. use super::*; +use std::borrow::Cow; /// The width in points of the line that edges a bare marker, which keeps it as the marker keeps /// its size, and of the leaders at the default size, which follow the legend's. @@ -26,16 +27,40 @@ impl Ink { } } -/// The symbol a block draws for `s` with its stacked `strokes` at the reference factor `k`: one -/// drawn by its symbol alone, with no outline that shows, gets one in `ink`. A marker sized zero -/// stays without ink. -fn edged(s: &rustgis_map::Symbol, strokes: &[rustgis_map::LineStroke], k: f32, ink: Rgba) -> rustgis_map::Symbol { - let mut symbol = *s; - let bare = point_marks::plain(strokes, 0.0) && (s.stroke.a() == 0 || s.stroke_width <= 0.0); - if bare && s.size > 0.0 && k > 0.0 { - (symbol.stroke, symbol.stroke_width) = (ink, EDGE / k); +/// The symbol and stacked strokes a block draws for `s` with `strokes` at the reference factor +/// `k`. A marker with no outline that shows gets one in `ink`: its symbol's, or each mark of a +/// stack none of whose marks has one (a stack that outlines any is drawn as it is). A marker sized +/// zero stays without ink. +fn edged<'a>( + s: &rustgis_map::Symbol, + strokes: &'a [rustgis_map::LineStroke], + k: f32, + ink: Rgba, +) -> (rustgis_map::Symbol, Cow<'a, [rustgis_map::LineStroke]>) { + let (mut symbol, mut stack) = (*s, Cow::Borrowed(strokes)); + if k <= 0.0 { + return (symbol, stack); } - symbol + if point_marks::plain(strokes, 0.0) { + if (s.stroke.a() == 0 || s.stroke_width <= 0.0) && s.size > 0.0 { + (symbol.stroke, symbol.stroke_width) = (ink, EDGE / k); + } + return (symbol, stack); + } + let outlined = strokes + .iter() + .any(|st| st.markers.is_some_and(|m| m.outline.is_some_and(|c| c.a() > 0)) && st.width.unwrap_or(s.stroke_width) > 0.0); + if !outlined { + for st in stack.to_mut() { + if let Some(m) = &mut st.markers + && matches!(m.mark, rustgis_map::LineMark::Marker(_)) + && m.size > 0.0 + { + (m.outline, st.width) = (Some(ink), Some(EDGE / k)); + } + } + } + (symbol, stack) } /// The [`Ink`] of the layer `l`'s marker `s` with its stacked `strokes` at 1:`scale`, as a block @@ -48,7 +73,8 @@ fn ink_of(l: &rustgis_map::Layer, s: &rustgis_map::Symbol, strokes: &[rustgis_ma } let k = l.size_factor(scale); // Its colour changes nothing here. - let Some((up, down)) = point_marks::ink_reach(&edged(s, strokes, k, INK), strokes) else { + let (symbol, stack) = edged(s, strokes, k, INK); + let Some((up, down)) = point_marks::ink_reach(&symbol, &stack) else { return Ink { up: 0.0, down: 0.0, side: 0.0 }; }; let (up, down) = (up * k, down * k); @@ -120,13 +146,12 @@ pub(super) fn draw( if ink_box.side <= 0.0 { continue; } - let strokes = row_strokes(l, en); - let symbol = edged(&en.symbol, strokes, k, ink); + let (symbol, strokes) = edged(&en.symbol, row_strokes(l, en), k, ink); let across = ink_box.side * ppp + 2.0 * room; // Its point as far above the base as its ink reaches below it. let cy = base - ink_box.down * ppp; let cell = (cx - across / 2.0 - left, cy - across / 2.0 - top, across, across); - point_swatch(c, cell, (&symbol, strokes), 1.0, ppp * k); + point_swatch(c, cell, (&symbol, &strokes), 1.0, ppp * k); } }; if opacity >= 0.999 { diff --git a/crates/render/src/layout/legend/nested/tests.rs b/crates/render/src/layout/legend/nested/tests.rs index 6653c7b266..19d6fac297 100644 --- a/crates/render/src/layout/legend/nested/tests.rs +++ b/crates/render/src/layout/legend/nested/tests.rs @@ -178,14 +178,14 @@ fn stacked_markers_are_measured_by_their_ink() { use rustgis_map::{LineMark, LineMarkers, LineStroke, Marker}; let map = circles(10.0, 40.0, 0.0); let l = &map.layers[0]; - // A 20 point circle shifted 3 points down. + // A 20 point circle shifted 3 points down, edged by half a point as it has no outline. let mark = LineMarkers { mark: LineMark::Marker(Marker::Circle), size: 20.0, ..LineMarkers::default() }; let stroke = LineStroke { color: Some(RED), width: Some(0.0), offset: 3.0, markers: Some(mark), ..LineStroke::default() }; let mut entry = l.renderer.legend().remove(0); entry.strokes = vec![stroke]; let LegendRow::Sizes(_, block) = block(l, vec![entry], 1e6) else { panic!() }; let ink = block[0].1; - assert!((ink.height() - 20.0).abs() < 0.1 && (ink.down - 13.0).abs() < 0.1, "{} {}", ink.height(), ink.down); + assert!((ink.height() - 20.5).abs() < 0.1 && (ink.down - 13.25).abs() < 0.1, "{} {}", ink.height(), ink.down); } #[test] @@ -234,3 +234,26 @@ fn a_stacked_mark_sized_zero_takes_no_height() { let LegendRow::Sizes(_, block) = block(l, vec![entry], 1e6) else { panic!() }; assert_eq!((block[0].1.height(), block[0].1.side), (0.0, 0.0)); } + +#[test] +fn a_stack_with_no_outline_gets_one_in_the_legends_ink_and_an_outlined_one_stays() { + use rustgis_map::{LineMark, LineMarkers, LineStroke, Marker}; + let ink = Rgba::rgb(1, 2, 3); + let mark = |size, outline| LineStroke { + color: Some(RED), + width: Some(2.0), + markers: Some(LineMarkers { mark: LineMark::Marker(Marker::Circle), size, outline, ..LineMarkers::default() }), + ..LineStroke::default() + }; + let symbol = circles(10.0, 40.0, 0.0).layers[0].renderer.base_symbol(); + // Fills alone: each mark is edged, as wide as a bare marker's edge at any reference factor. + let bare = [mark(20.0, None), mark(0.0, None)]; + let (_, edged_marks) = edged(&symbol, &bare, 2.0, ink); + assert_eq!(edged_marks[0].markers.unwrap().outline, Some(ink)); + assert_eq!(edged_marks[0].width, Some(EDGE / 2.0)); + // One sized zero stays without ink. + assert_eq!(edged_marks[1].markers.unwrap().outline, None); + // A stack that outlines any of its marks is drawn as it is. + let designed = [mark(20.0, Some(RED)), mark(10.0, None)]; + assert_eq!(edged(&symbol, &designed, 1.0, ink).1.as_ref(), &designed); +} diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 05cddc5a33..c1be02eb9c 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -512,9 +512,10 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu layer's marker sizes, those of Proportional Symbols and those a layer sized by a field lists after its classes. `"rows"`, the default, gives each its own row. `"nested"` draws a layer's as one block: the markers one inside another, the largest first, on a common base, each with a - thin line from its top to its value. A marker with no outline gets a thin one in the legend's - ink. The markers keep the size the map draws them at, and the block is never split between - columns. Class rows stay as rows. + thin line from its top to its value. A marker with no outline (a stack of + markers, when none of them has one) gets a thin one in the legend's ink. The markers keep the + size the map draws them at, and the block is never split between columns. Class rows stay as + rows. - **Layer names** (`"showLayerNames"`, on by default): off, the name over each layer's classes, and over a web layer's legend picture, is left off. A layer drawn in one symbol keeps its name beside its swatch, since that is what labels it; classes that carry no label of their own