diff --git a/crates/assistant/skills/print-layout/SKILL.md b/crates/assistant/skills/print-layout/SKILL.md index e19b32df9a..fec779c158 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), `"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), + text or add columns to fit its box), `"subtitle"` (one line under its title), `"patchWidth"` (4 to 100) and `"patchHeight"` (3 to 100) (points; the size of a line, polygon or raster class row's patch, default 16 and 9), `"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), `"columnBreaks": [""]` (each starts a column; no `"columns"` above 1 beside them), `"oneRow": true` (every entry side by side in one row, however many; no `"columns"` above 1 or `"columnBreaks"` beside it) and `"classLabels"` (`{"": {"": ""}}`: its own text for a class, the layer keeping its label). A `"picture"` takes a `"path"` (a PNG or JPEG file; it remembers the file) or an `"image"` (base64); diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 139954cb86..7969bb2305 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -284,7 +284,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? columnBreaks? oneRow? 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? fields? header? sort? descending? selectedOnly? 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? columnBreaks? oneRow? columns? textSize? classLabels? patchWidth? patchHeight? 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? fields? header? sort? descending? selectedOnly? 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? @@ -306,7 +306,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? columnBreaks? labels? classLabels? oneRow? 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? extentNumbers? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? barOutline? hideLabels? rows? fields? header? sort? descending? selectedOnly? image? path? 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? columnBreaks? labels? classLabels? oneRow? columns? textSize? showLayerNames? patchWidth? patchHeight? 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? extentNumbers? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? barOutline? hideLabels? rows? fields? header? sort? descending? selectedOnly? image? path? 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? anonymous? diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index f1aa746a56..0ed777926f 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -44,8 +44,8 @@ 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_one_row_param, legend_sizes_param, - legend_subtitle_param, + legend_columns_param, legend_counts_param, legend_fit_param, legend_names_param, legend_one_row_param, legend_patch_height_param, + legend_patch_width_param, legend_sizes_param, legend_subtitle_param, }; mod picture; pub(crate) use picture::gives_picture; @@ -228,6 +228,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; table: its text, its rows and columns following; default 8; colorbar: its labels, the bar making room for them; 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##""patchWidth"?: 4..100, "patchHeight"?: 3..100 (legend: the points a line, polygon or raster class row's patch is wide and tall at the default text size, 16 and 9 unless set; they grow with textSize; a point symbol keeps the size the map draws it at, and a legend of points only keeps the patch width's room before its labels; refused for other kinds), "##, 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), "##, @@ -351,6 +352,7 @@ pub fn commands() -> Vec { r##""columns"?: 1..6 (legend), "##, r##""textSize"?: points, 4 to 100 (legend, scaleBar, table, colorbar, 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##""patchWidth"?: 4..100, "patchHeight"?: 3..100 (legend, as in layout.addElement; null leaves each 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), "##, @@ -671,6 +673,8 @@ pub(crate) fn new_layout(s: &mut Session, p: &Value) -> CmdResult { show_counts: Default::default(), subtitle: Default::default(), sizes: Default::default(), + patch_width: rustgis_map::layout::LEGEND_PATCH_WIDTH_PT, + patch_height: rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT, }, ); 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 d46b0affa5..534921707a 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -398,6 +398,12 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu if kind != "legend" && gives(p, "sizes") { return Err(ONLY_LEGEND_SIZES.into()); } + if kind != "legend" && gives(p, "patchWidth") { + return Err(ONLY_LEGEND_PATCH_WIDTH.into()); + } + if kind != "legend" && gives(p, "patchHeight") { + return Err(ONLY_LEGEND_PATCH_HEIGHT.into()); + } if legend_names_param(p)?.is_some() && kind != "legend" { return Err(ONLY_LEGEND_NAMES.into()); } @@ -531,6 +537,8 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu 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(); + let patch_width = legend_patch_width_param(p)?.unwrap_or(rustgis_map::layout::LEGEND_PATCH_WIDTH_PT); + let patch_height = legend_patch_height_param(p)?.unwrap_or(rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT); let one_row = legend_one_row_param(p)?.unwrap_or(false); columns_set_elsewhere(one_row, (&column_breaks, true), (columns, true), (fit, true))?; ( @@ -556,6 +564,8 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu show_counts, subtitle, sizes, + patch_width, + patch_height, }, ) } @@ -1198,6 +1208,8 @@ const ADD_LEGEND_KEYS: &[&str] = &[ "showLayerNames", "showCounts", "sizes", + "patchWidth", + "patchHeight", "color", ]; @@ -1722,7 +1734,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", "font": "sans", "fallback": null, "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", "font": "sans", "fallback": null}), - 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": "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", "patchWidth": 20, "patchHeight": 12, "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 02f978a88f..4deef86428 100644 --- a/crates/engine/src/cmd/layout/legend.rs +++ b/crates/engine/src/cmd/layout/legend.rs @@ -133,6 +133,8 @@ pub(in crate::cmd::layout) fn tells_legend_fit(kind: &ElementKind, p: &Value) -> ["columns", "showNoData", "labels", "classLabels", "fit", "showLayerNames", "showCounts", "subtitle", "sizes", "oneRow"] .iter() .any(|k| given(k)) + || given("patchWidth") + || given("patchHeight") || p.get("textSize").is_some() || (watched && refitted) || given("columnBreaks") @@ -164,6 +166,8 @@ pub(in crate::cmd::layout) fn say_legend_fit(s: &mut Session, li: usize, id: u32 show_counts, subtitle, sizes, + patch_width, + patch_height, .. } = &e.kind else { @@ -181,6 +185,7 @@ pub(in crate::cmd::layout) fn say_legend_fit(s: &mut Session, li: usize, id: u32 let layer_order = layer_order.clone(); let column_breaks = column_breaks.clone(); let sizes = *sizes; + let patch = (*patch_width, *patch_height); let one_row = *one_row; 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))); @@ -203,6 +208,7 @@ pub(in crate::cmd::layout) fn say_legend_fit(s: &mut Session, li: usize, id: u32 class_labels: &class_labels, show_counts, sizes, + patch, }; // Broken into columns or in one row, how many it draws is the drawing's to say. let measured = if fit == LegendFit::Manual && column_breaks.is_empty() && !one_row { @@ -337,6 +343,33 @@ pub(crate) fn legend_subtitle_param(p: &Value) -> Result, String> .transpose() } +/// The refusal for `patchWidth` and `patchHeight` on an element other than a legend. +pub(in crate::cmd::layout) const ONLY_LEGEND_PATCH_WIDTH: &str = "only legends take patchWidth"; +pub(in crate::cmd::layout) const ONLY_LEGEND_PATCH_HEIGHT: &str = "only legends take patchHeight"; + +/// The `"patchWidth"` a legend is given (#3559), in points at the default text size, 4 to 100 +/// (`null` is not given): the one reader the commands and the `layout-legend-patch-size` +/// capability check share. +pub(crate) fn legend_patch_width_param(p: &Value) -> Result, String> { + patch_param(p, "patchWidth", &rustgis_map::layout::LEGEND_PATCH_WIDTH_RANGE) +} + +/// The `"patchHeight"` a legend is given, 3 to 100: see [`legend_patch_width_param`]. +pub(crate) fn legend_patch_height_param(p: &Value) -> Result, String> { + patch_param(p, "patchHeight", &rustgis_map::layout::LEGEND_PATCH_HEIGHT_RANGE) +} + +fn patch_param(p: &Value, key: &str, range: &std::ops::RangeInclusive) -> Result, String> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_f64() + .filter(|v| range.contains(v)) + .map(Some) + .ok_or_else(|| format!("{key} is a number of points, {} to {}", range.start(), range.end())), + } +} + /// 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"; diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index 2d0a661334..afb1ac4d91 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -2138,6 +2138,8 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu show_counts: Default::default(), subtitle: Default::default(), sizes: Default::default(), + patch_width: rustgis_map::layout::LEGEND_PATCH_WIDTH_PT, + patch_height: rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT, }, ); } diff --git a/crates/engine/src/cmd/layout/publication/parts.rs b/crates/engine/src/cmd/layout/publication/parts.rs index 6e37e6a6e0..fd0a80d284 100644 --- a/crates/engine/src/cmd/layout/publication/parts.rs +++ b/crates/engine/src/cmd/layout/publication/parts.rs @@ -175,6 +175,7 @@ impl PublicationLegend { class_labels: &rustgis_map::layout::ClassLabels::NONE, show_counts: false, sizes: Default::default(), + patch: (rustgis_map::layout::LEGEND_PATCH_WIDTH_PT, rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT), }; [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 610b370882..5db36a8d5f 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -555,6 +555,13 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { return Err(ONLY_LEGEND_SIZES.into()); } let new_sizes = legend_sizes_param(p)?; + if gives(p, "patchWidth") && !is_legend { + return Err(ONLY_LEGEND_PATCH_WIDTH.into()); + } + if gives(p, "patchHeight") && !is_legend { + return Err(ONLY_LEGEND_PATCH_HEIGHT.into()); + } + let new_patch = (legend_patch_width_param(p)?, legend_patch_height_param(p)?); if p.get("textSize").is_some_and(|v| !v.is_null()) && !sized && !is_table && !is_colorbar { return Err(ONLY_LAYOUT_TEXT_SIZE.into()); } @@ -743,11 +750,19 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { show_counts, subtitle, sizes, + patch_width, + patch_height, .. } => { if let Some(new) = new_sizes { *sizes = new; } + if let Some(width) = new_patch.0 { + *patch_width = width; + } + if let Some(height) = new_patch.1 { + *patch_height = height; + } if let Some(text) = new_subtitle { *subtitle = text; } diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index e479348a81..b5b557cae4 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -131,6 +131,7 @@ pub const CAPABILITIES: &[&str] = &[ "layout-legend-class-labels", "layout-legend-counts", "layout-legend-subtitle", + "layout-legend-patch-size", "layout-legend-nested-sizes", "layout-extent-indicators", "layout-extent-numbers", diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 73bc820c98..a68712dc4d 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -189,6 +189,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-patch-size", command_uses_legend_patch_size), ("layout-legend-nested-sizes", command_uses_legend_nested_sizes), ("layout-extent-indicators", command_uses_extent_indicators), ("layout-extent-numbers", command_numbers_extents), @@ -760,6 +761,42 @@ fn command_uses_legend_subtitle(id: &str, params: &Value) -> bool { } } +/// A layout command that gives a legend patches of another size than the default (#3559): an older +/// reader ignores `patchWidth` and `patchHeight`, and saves the legend again without them, +/// drawing the patches at the default. The defaults and `null` ask for what it draws. +fn command_uses_legend_patch_size(id: &str, params: &Value) -> bool { + match id { + "layout.addElement" | "layout.update" => { + let (width, height) = + (crate::cmd::layout::legend_patch_width_param(params), crate::cmd::layout::legend_patch_height_param(params)); + width.is_ok_and(|w| w.is_some_and(|w| w != rustgis_map::layout::LEGEND_PATCH_WIDTH_PT)) + || height.is_ok_and(|h| h.is_some_and(|h| h != rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT)) + } + "layout.import" | "report.existingTemplate" => { + imported_layout_uses(id, params, &["\"patch_width\"", "\"patch_height\""], legend_patch_features) + } + // It opens its `text` only, whatever else the step holds. + "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_gives_legend_patch_size), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_legend_patch_size)), + _ => false, + } +} + +/// Whether a project's saved text requires `layout-legend-patch-size`: for its layouts, its steps +/// or its notebooks. Parsed only when the text names a key, either way it is written, may hide it +/// ([`may_hide_a_key`]), or holds a step's base64 `data` ([`names_data`]). +fn text_gives_legend_patch_size(text: &str) -> bool { + (["patch_width", "patchWidth", "patch_height", "patchHeight"].iter().any(|key| text.contains(key)) + || may_hide_a_key(text) + || names_data(text)) + && inline_project_requires(text, "layout-legend-patch-size") == Some(true) +} + +/// Whether a layout element is a legend whose patches aren't at the default size. +fn legend_patch_features(e: &rustgis_map::layout::Element) -> bool { + e.kind.legend_patch_features() +} + /// A layout command that may give a frame more than one extent indicator, or names one of /// several (#3394): an older reader replaces the indicator on adding another, and ignores `of` /// and `remove`. A saved command can't tell what its frame outlines already, so every indicator @@ -1949,6 +1986,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_patch_features), "layout-legend-patch-size"), (elements().any(legend_nested_sizes_features), "layout-legend-nested-sizes"), (elements().any(extent_indicators_features), "layout-extent-indicators"), (elements().any(extent_numbers_features), "layout-extent-numbers"), @@ -2050,6 +2088,21 @@ mod tests { } } + /// A project's saved step that sets a legend's patch size needs the capability, whichever way + /// it spells the key; one that sets the default doesn't. + #[test] + fn a_saved_step_that_sets_a_patch_size_is_found_in_text_a_project_opens() { + let opens = |params: Value| { + let mut project = serde_json::to_value(Project::default()).unwrap(); + project["tasks"] = json!([{"name": "Size", "steps": [{"title": "Size", "command": "layout.update", "params": params}]}]); + command_uses_legend_patch_size("project.openText", &json!({"text": project.to_string()})) + }; + assert!(opens(json!({"element": 1, "patchWidth": 20}))); + assert!(opens(json!({"element": 1, "patchHeight": 12}))); + assert!(!opens(json!({"element": 1, "patchWidth": 16, "patchHeight": 9}))); + assert!(!opens(json!({"element": 1, "subtitle": "a"}))); + } + /// A session holding what `check` asks for, when `wanted`, beside a raster read in place /// from `scene`. Its name passes every check's text pre-filter, so each one loads it. fn inline_project_with(capability: &str, wanted: bool, scene: &str) -> Project { @@ -2068,6 +2121,11 @@ mod tests { let frame = element(&s, "mapFrame"); s.run("layout.update", &json!({"element": frame, "extentNumbers": true})).unwrap(); } + "layout-legend-patch-size" if wanted => { + s.run("layout.new", &json!({"template": "map"})).unwrap(); + let legend = s.project.layouts[0].elements.iter().find(|e| e.kind.code() == "legend").unwrap().id; + s.run("layout.update", &json!({"element": legend, "patchWidth": 20})).unwrap(); + } "layout-north-arrow-font" if wanted => { s.run("layout.addElement", &json!({"kind": "northArrow", "font": "serif"})).unwrap(); } @@ -2083,8 +2141,9 @@ mod tests { /// as saved, without its header, from a script and from a step of a step (#3530). #[test] fn the_checks_of_an_inline_project_read_nothing_it_names() { - let checks: [(&str, CommandCheck); 4] = [ + let checks: [(&str, CommandCheck); 5] = [ ("shaded-relief-generalize", command_sets_generalize), + ("layout-legend-patch-size", command_uses_legend_patch_size), ("layout-extent-numbers", command_numbers_extents), ("layout-north-arrow-font", command_uses_north_arrow_font), ("layout-scale-bar-font", command_uses_scale_bar_font), @@ -2470,6 +2529,7 @@ mod tests { (&["layout-extent-indicators"], "layout.addElement", json!({"kind": "extentIndicator", "frame": 1, "of": 2})), (&["layout-extent-numbers"], "layout.update", json!({"element": 1, "extentNumbers": true})), (&["layout-legend-subtitle"], "layout.update", json!({"element": 1, "subtitle": "a"})), + (&["layout-legend-patch-size"], "layout.update", json!({"element": 1, "patchWidth": 20})), (&["layout-legend-order"], "layout.update", json!({"element": 1, "layerOrder": ["a"]})), (&["layout-legend-column-breaks"], "layout.update", json!({"element": 1, "columnBreaks": ["a"]})), (&["layout-legend-one-row"], "layout.update", json!({"element": 1, "oneRow": true})), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2b65676ea9..1e0ae4de31 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -175,6 +175,9 @@ mod layout_legend_subtitle; #[path = "tests/layout_import_reads.rs"] mod layout_import_reads; +#[path = "tests/layout_legend_patch.rs"] +mod layout_legend_patch; + #[path = "tests/layout_legend_sizes.rs"] mod layout_legend_sizes; @@ -9041,6 +9044,9 @@ fn hostile_junk() -> Vec { 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}]}), + // A legend's patch: junk of the wrong type, and numbers far past its range. + json!({"kind": "legend", "element": 1, "patchWidth": [{"x": f64::MAX}], "patchHeight": "x".repeat(5000)}), + json!({"kind": "legend", "element": 1, "patchWidth": -1e308, "patchHeight": 1e308}), 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}), @@ -14205,6 +14211,7 @@ fn a_manual_legend_that_overflows_still_warns_and_a_fitted_one_does_not() { class_labels: &NO_CLASS_LABELS, show_counts: false, sizes: Default::default(), + patch: (16.0, 9.0), }; // 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]); @@ -14261,6 +14268,7 @@ fn a_fit_that_cannot_make_a_legend_fit_says_so() { class_labels: &NO_CLASS_LABELS, show_counts: false, sizes: Default::default(), + patch: (16.0, 9.0), }; 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. @@ -14344,6 +14352,7 @@ fn a_report_says_the_fitted_legends_on_its_layouts_that_no_longer_fit() { class_labels: &NO_CLASS_LABELS, show_counts: false, sizes: Default::default(), + patch: (16.0, 9.0), }; 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"}); @@ -14413,6 +14422,7 @@ fn a_fitted_legend_that_no_longer_fits_says_so_at_export() { class_labels: &NO_CLASS_LABELS, show_counts: false, sizes: Default::default(), + patch: (16.0, 9.0), }; 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 6ef803cd0f..ecb97b0bf1 100644 --- a/crates/engine/src/tests/layout_files.rs +++ b/crates/engine/src/tests/layout_files.rs @@ -138,6 +138,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-patch-size", include_str!("../../../../schema/fixtures/layout_legend_patch_size.rgis")), ("legend-nested-sizes", include_str!("../../../../schema/fixtures/layout_legend_nested_sizes.rgis")), ("extent-indicators", include_str!("../../../../schema/fixtures/layout_extent_indicators.rgis")), ("extent-numbers", include_str!("../../../../schema/fixtures/layout_extent_numbers.rgis")), diff --git a/crates/engine/src/tests/layout_legend_patch.rs b/crates/engine/src/tests/layout_legend_patch.rs new file mode 100644 index 0000000000..f365c10b54 --- /dev/null +++ b/crates/engine/src/tests/layout_legend_patch.rs @@ -0,0 +1,153 @@ +//! The size of the patches a legend draws for lines and polygons (#3559). + +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 settings. +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"].clone() +} + +#[test] +fn a_legends_patch_is_set_in_one_undo_step_and_left_out_at_its_default() { + let (mut s, legend) = laid_out(); + assert_eq!((saved(&s, legend)["patch_width"].clone(), saved(&s, legend)["patch_height"].clone()), (Value::Null, Value::Null)); + let depth = s.undo_depth(); + s.run("layout.update", &json!({"element": legend, "patchWidth": 30, "patchHeight": 12.5})).unwrap(); + assert_eq!((saved(&s, legend)["patch_width"].clone(), saved(&s, legend)["patch_height"].clone()), (json!(30.0), json!(12.5))); + assert_eq!(s.undo_depth(), depth + 1); + // `null` leaves each as it is, and one given leaves the other. + s.run("layout.update", &json!({"element": legend, "patchWidth": null, "patchHeight": null, "title": "Key"})).unwrap(); + assert_eq!((saved(&s, legend)["patch_width"].clone(), saved(&s, legend)["patch_height"].clone()), (json!(30.0), json!(12.5))); + s.run("layout.update", &json!({"element": legend, "patchHeight": 9})).unwrap(); + assert_eq!((saved(&s, legend)["patch_width"].clone(), saved(&s, legend)["patch_height"].clone()), (json!(30.0), Value::Null)); + // The defaults are left out, so layouts saved before keep their bytes. + s.run("layout.update", &json!({"element": legend, "patchWidth": 16})).unwrap(); + assert_eq!((saved(&s, legend)["patch_width"].clone(), saved(&s, legend)["patch_height"].clone()), (Value::Null, Value::Null)); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!(saved(&s, legend)["patch_width"], json!(30.0)); +} + +#[test] +fn a_legend_is_added_with_a_patch_and_the_limits_are_kept() { + let (mut s, _) = laid_out(); + s.run("layout.addElement", &json!({"kind": "legend", "patchWidth": 40, "patchHeight": 20})).unwrap(); + let added = s.project.layouts[0].elements.last().unwrap().id.into(); + assert_eq!((saved(&s, added)["patch_width"].clone(), saved(&s, added)["patch_height"].clone()), (json!(40.0), json!(20.0))); + for (width, height) in [(4.0, 3.0), (100.0, 100.0)] { + s.run("layout.update", &json!({"element": added, "patchWidth": width, "patchHeight": height})).unwrap(); + assert_eq!((saved(&s, added)["patch_width"].clone(), saved(&s, added)["patch_height"].clone()), (json!(width), json!(height))); + } +} + +#[test] +fn a_patch_a_legend_cannot_take_is_refused_and_changes_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, "patchWidth": 3.9}), "patchWidth"), + ("layout.update", json!({"element": legend, "patchWidth": 100.1}), "4 to 100"), + ("layout.update", json!({"element": legend, "patchHeight": 2.9}), "patchHeight"), + ("layout.update", json!({"element": legend, "patchHeight": 101}), "3 to 100"), + ("layout.update", json!({"element": legend, "patchWidth": "wide"}), "patchWidth"), + ("layout.update", json!({"element": legend, "patchHeight": true}), "patchHeight"), + ("layout.addElement", json!({"kind": "legend", "patchWidth": -1}), "patchWidth"), + ("layout.addElement", json!({"kind": "legend", "patchHeight": [9]}), "patchHeight"), + ("layout.update", json!({"element": frame, "patchWidth": 20}), "only legends take patchWidth"), + ("layout.addElement", json!({"kind": "scaleBar", "patchHeight": 9}), "only legends take patchHeight"), + ] { + 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 a_patch_requires_its_capability_wherever_it_is_saved() { + let (mut s, legend) = laid_out(); + let lists = |v: Value| v["requires"].as_array().is_some_and(|r| r.contains(&json!("layout-legend-patch-size"))); + 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, "patchHeight": 20})).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 sized = 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", "patchWidth": 20}), true), + ("layout.update", json!({"element": 3, "patchHeight": 20}), true), + ("layout.update", json!({"element": 3, "patchWidth": 16, "patchHeight": 9}), false), + ("layout.update", json!({"element": 3, "patchWidth": null}), false), + ("layout.update", json!({"element": 3, "patchWidth": "wide"}), false), + ("layout.import", json!({"text": sized}), true), + ("layout.import", json!({"text": plain}), false), + ("report.existingTemplate", json!({"text": sized}), true), + ("script.run", json!({"script": format!("layout.update {}", json!({"element": 3, "patchWidth": 20}))}), true), + ] { + assert_eq!(requires(id, params.clone()), required, "{id} {params}"); + } +} + +#[test] +fn a_files_patch_out_of_range_is_brought_in_and_counted() { + let (s, legend) = laid_out(); + let read = |width: Value, height: Value| { + let mut layout = serde_json::to_value(&s.project.layouts[0]).unwrap(); + let e = layout["elements"].as_array_mut().unwrap().iter_mut().find(|e| e["id"] == json!(legend)).unwrap(); + e["kind"]["Legend"]["patch_width"] = width; + e["kind"]["Legend"]["patch_height"] = height; + let mut read: rustgis_map::layout::Layout = serde_json::from_value(layout).unwrap(); + let adjusted = read.clamp().elements_adjusted; + let kind = serde_json::to_value(&read.element(legend as u32).unwrap().kind).unwrap(); + (kind["Legend"]["patch_width"].clone(), kind["Legend"]["patch_height"].clone(), adjusted) + }; + assert_eq!(read(json!(1000.0), json!(0.5)), (json!(100.0), json!(3.0), 1)); + assert_eq!(read(json!(0.0), json!(1e9)), (json!(4.0), json!(100.0), 1)); + // Below the least goes to the least. + assert_eq!(read(json!(-5.0), json!(30.0)), (json!(4.0), json!(30.0), 1)); + assert_eq!(read(json!(20.0), json!(12.0)), (json!(20.0), json!(12.0), 0)); +} + +#[test] +fn a_patch_takes_the_legends_room_and_the_fit_says_so() { + let (mut s, legend) = laid_out(); + // A box its title and rows fill: found by growing it until nothing is said. + let said = |s: &mut Session, p: Value, notice: &[&str]| { + s.notices.clear(); + s.run("layout.update", &p).unwrap(); + s.notices.iter().any(|n| n.text.starts_with("the legend") && notice.iter().any(|k| n.text.contains(k))) + }; + // What the fit says of a legend that is too tall for its box, and of one too wide. + let (tall_notice, wide_notice) = (["lists more than fits its box"], ["columns are wider than its box", "lists more than fits its box"]); + let mut h = 10.0; + while said(&mut s, json!({"element": legend, "w": 90, "h": h, "textSize": 10, "patchWidth": 16, "patchHeight": 9}), &tall_notice) { + h += 1.0; + assert!(h < 300.0, "never fits"); + } + assert!(said(&mut s, json!({"element": legend, "patchHeight": 40}), &tall_notice), "{h}: taller patches take taller rows"); + assert!(!said(&mut s, json!({"element": legend, "patchHeight": 3}), &tall_notice), "{h}: smaller patches never need more room"); + // As wide as its box: a wider patch pushes the text out of it. + let mut w = 20.0; + while said(&mut s, json!({"element": legend, "w": w, "h": 200, "patchHeight": 9}), &wide_notice) { + w += 1.0; + assert!(w < 300.0, "never fits"); + } + assert!(said(&mut s, json!({"element": legend, "patchWidth": 60}), &wide_notice), "{w}: wider patches take a wider legend"); +} diff --git a/crates/map/src/layout.rs b/crates/map/src/layout.rs index 72473c0727..9a9fbc9e5e 100644 --- a/crates/map/src/layout.rs +++ b/crates/map/src/layout.rs @@ -685,8 +685,14 @@ impl Layout { show_counts, subtitle, sizes, + patch_width, + patch_height, .. } => { + *patch_width = finite_or(*patch_width, LEGEND_PATCH_WIDTH_PT) + .clamp(*LEGEND_PATCH_WIDTH_RANGE.start(), *LEGEND_PATCH_WIDTH_RANGE.end()); + *patch_height = finite_or(*patch_height, LEGEND_PATCH_HEIGHT_PT) + .clamp(*LEGEND_PATCH_HEIGHT_RANGE.start(), *LEGEND_PATCH_HEIGHT_RANGE.end()); let end = subtitle.char_indices().nth(MAX_LEGEND_SUBTITLE_CHARS).map_or(subtitle.len(), |(i, _)| i); cut |= end < subtitle.len(); subtitle.truncate(end); diff --git a/crates/map/src/layout/elements.rs b/crates/map/src/layout/elements.rs index 58f2723d10..12e9af8538 100644 --- a/crates/map/src/layout/elements.rs +++ b/crates/map/src/layout/elements.rs @@ -201,6 +201,15 @@ pub enum ElementKind { /// before keep their bytes. #[serde(default, skip_serializing_if = "LegendSizes::is_rows")] sizes: LegendSizes, + /// How wide and how tall the patch of a line or polygon row is (#3559), in points at the + /// default text size within [`LEGEND_PATCH_WIDTH_RANGE`] and [`LEGEND_PATCH_HEIGHT_RANGE`]: + /// they grow with `text_size`, a point symbol keeps the size the map draws it at, and its + /// column is as wide as the widest. Each is left out at its default, so layouts saved + /// before keep their bytes. + #[serde(default = "legend_patch_width", skip_serializing_if = "is_legend_patch_width")] + patch_width: f64, + #[serde(default = "legend_patch_height", skip_serializing_if = "is_legend_patch_height")] + patch_height: f64, }, /// 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). @@ -720,6 +729,13 @@ impl ElementKind { matches!(self, ElementKind::Legend { show_counts, .. } if show_counts.shown()) } + /// Whether this is a legend whose patches aren't drawn at their default size: what a layout file + /// needs a newer reader for (#3559). + pub fn legend_patch_features(&self) -> bool { + matches!(self, ElementKind::Legend { patch_width, patch_height, .. } + if !is_legend_patch_width(patch_width) || !is_legend_patch_height(patch_height)) + } + /// Whether this is a legend with a subtitle: what a layout file needs a newer reader for. pub fn legend_subtitle_features(&self) -> bool { matches!(self, ElementKind::Legend { subtitle, .. } if !subtitle.is_empty()) diff --git a/crates/map/src/layout/legend.rs b/crates/map/src/layout/legend.rs index 23e6a09d96..316a5c603d 100644 --- a/crates/map/src/layout/legend.rs +++ b/crates/map/src/layout/legend.rs @@ -14,6 +14,30 @@ pub const MAX_LEGEND_LABEL_CHARS: usize = 200; /// The longest subtitle a legend keeps, in characters (#3324). pub const MAX_LEGEND_SUBTITLE_CHARS: usize = 200; +/// The size of a legend's line and polygon patches at its default text size, in points (#3559): +/// the width and height they have always been drawn at, and what each may be set to. They grow and +/// shrink with the legend's text size, as its rows do. +pub const LEGEND_PATCH_WIDTH_PT: f64 = 16.0; +pub const LEGEND_PATCH_HEIGHT_PT: f64 = 9.0; +pub const LEGEND_PATCH_WIDTH_RANGE: std::ops::RangeInclusive = 4.0..=100.0; +pub const LEGEND_PATCH_HEIGHT_RANGE: std::ops::RangeInclusive = 3.0..=100.0; + +pub(super) fn legend_patch_width() -> f64 { + LEGEND_PATCH_WIDTH_PT +} + +pub(super) fn is_legend_patch_width(width: &f64) -> bool { + *width == LEGEND_PATCH_WIDTH_PT +} + +pub(super) fn legend_patch_height() -> f64 { + LEGEND_PATCH_HEIGHT_PT +} + +pub(super) fn is_legend_patch_height(height: &f64) -> bool { + *height == LEGEND_PATCH_HEIGHT_PT +} + /// A legend's own labels for its layers' classes (#3187): by the layer's name (any case), the /// label the layer gives a class, and the text this legend shows instead. /// diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 0060e4d73c..c9812c52ca 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -612,6 +612,8 @@ fn draw_page( show_counts, subtitle, sizes, + patch_width, + patch_height, } => { if let Some(&(_, mi, cam, ..)) = frame(*f) && let Some(map) = maps.get(mi) @@ -652,6 +654,7 @@ fn draw_page( size, text_size: *text_size, sizes: *sizes, + patch: Patch::new(*patch_width, *patch_height), }; // 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. @@ -1132,6 +1135,8 @@ pub(crate) fn legend_pin_pages() -> Vec<(Layout, Vec)> { show_counts: Default::default(), subtitle: Default::default(), sizes: Default::default(), + patch_width: rustgis_map::layout::LEGEND_PATCH_WIDTH_PT, + patch_height: rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT, }; 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 9793d62e83..6bf8a153b9 100644 --- a/crates/render/src/layout/legend.rs +++ b/crates/render/src/layout/legend.rs @@ -198,7 +198,7 @@ pub(super) struct Counts<'a> { /// (unless `names`), and layers by name; the labels it shows for layers instead of their names; the /// scale denominator whose legend pictures a WMS or WMTS layer shows; its text size in points, and /// how many times its default size its rows are drawn at ([`legend_size`]): that of `text_size`, -/// until [`fit_legend`] picks another. +/// until [`fit_legend_patched`] picks another. #[derive(Clone, Copy)] pub(super) struct LegendOptions<'a> { pub(super) hide_other: bool, @@ -220,6 +220,8 @@ pub(super) struct LegendOptions<'a> { pub(super) text_size: f64, /// How a point layer's rows of sizes are drawn (#3347). pub(super) sizes: LegendSizes, + /// How big its line and polygon patches are (#3559). + pub(super) patch: Patch, } /// How many times the default a legend of `text_size` points draws its text, rows, swatches and @@ -288,17 +290,19 @@ impl LegendRow<'_> { #[cfg(test)] pub(super) fn height(&self, scale: f64, size: f32) -> f32 { match self { - LegendRow::Picture(_) => self.height_beside(0.0, size), - _ => self.height_beside(self.symbol_side(scale), size), + LegendRow::Picture(_) => self.height_beside(0.0, size, Patch::default()), + _ => self.height_beside(self.symbol_side(scale), size, Patch::default()), } } - /// [`LegendRow::height`], its point symbol `side` points across ([`LegendRow::symbol_side`]). - fn height_beside(&self, side: f32, size: f32) -> f32 { + /// [`LegendRow::height`], its point symbol `side` points across ([`LegendRow::symbol_side`]); a + /// line or polygon row holds its `patch` (#3559). + fn height_beside(&self, side: f32, size: f32, patch: Patch) -> f32 { match self { LegendRow::Picture(p) => picture_size(p).1 * size, LegendRow::Break | LegendRow::OneRow => 0.0, LegendRow::Sizes(_, block) => nested::places(&nested::heights(block), nested::LINE * size).2, + LegendRow::Plain(l, _) | LegendRow::Class(l, _) if l.geometry_type() != GeometryType::Point => patch.row(size), _ => (LEGEND_ROW * size).max(side), } } @@ -352,6 +356,7 @@ pub(super) fn symbol_sides(rows: &[LegendRow], scale: f64) -> Vec { /// indent), made once a size. pub(super) struct RowSizes { size: f32, + patch: Patch, heights: Vec, texts: Vec, } @@ -359,8 +364,8 @@ pub(super) struct RowSizes { impl RowSizes { /// `rows` beside their point symbols' `sides` ([`symbol_sides`]), measured at `size` times the /// default. - pub(super) fn of(rows: &[LegendRow], sides: &[f32], size: f32) -> Self { - let mut heights: Vec = rows.iter().zip(sides).map(|(row, &side)| row.height_beside(side, size)).collect(); + pub(super) fn of(rows: &[LegendRow], sides: &[f32], size: f32, patch: Patch) -> Self { + let mut heights: Vec = rows.iter().zip(sides).map(|(row, &side)| row.height_beside(side, size, patch)).collect(); // In one row, every entry is as tall as the tallest, so their labels share one line; a // block of nested sizes keeps its own height. if matches!(rows.first(), Some(LegendRow::OneRow)) { @@ -377,7 +382,7 @@ impl RowSizes { _ => row.text_width(size), }) .collect(); - RowSizes { size, heights, texts } + RowSizes { size, patch, heights, texts } } /// These measures as a box `room` points wide draws the rows: a legend picture wider than it, @@ -412,19 +417,21 @@ pub(super) struct Measured<'m, 'a> { texts: &'m [f32], /// How many times the default the rows are measured at ([`legend_size`]). size: f32, + /// How big their line and polygon patches are (#3559). + patch: Patch, } impl<'m, 'a> Measured<'m, 'a> { /// `rows` beside their point symbols' `sides`, with their `sizes` at one size. pub(super) fn new(rows: &'m [LegendRow<'a>], sides: &'m [f32], sizes: &'m RowSizes) -> Self { - Measured { rows, sides, heights: &sizes.heights, texts: &sizes.texts, size: sizes.size } + Measured { rows, sides, heights: &sizes.heights, texts: &sizes.texts, size: sizes.size, patch: sizes.patch } } /// Its rows in `range`, with their measures. fn part(self, range: std::ops::Range) -> Self { let cut = |v: &'m [f32]| v.get(range.clone()).unwrap_or_default(); let rows = self.rows.get(range.clone()).unwrap_or_default(); - Measured { rows, sides: cut(self.sides), heights: cut(self.heights), texts: cut(self.texts), size: self.size } + Measured { rows, sides: cut(self.sides), heights: cut(self.heights), texts: cut(self.texts), size: self.size, patch: self.patch } } /// The rows of each column, from where they start, with their measures. @@ -500,7 +507,7 @@ fn column_ranges(starts: &[usize], len: usize) -> impl Iterator f32 { - let column = swatch_column(m.sides.iter().copied(), m.size); + let column = swatch_column(m.sides.iter().copied(), (m.patch, m.size)); m.rows.iter().zip(m.texts).map(|(row, &text)| row.width(column, m.size, text)).fold(0.0, f32::max) } @@ -519,8 +526,8 @@ pub(super) fn row_fills<'a>(l: &'a rustgis_map::Layer, en: &'a LegendEntry) -> & /// The width of a legend's column of swatches beside point symbols `sides` points across /// ([`LegendRow::symbol_side`]) in a legend `size` times the default, in points: it grows to hold /// the widest point symbol, so the labels line up. -pub(super) fn swatch_column(sides: impl IntoIterator, size: f32) -> f32 { - sides.into_iter().fold(LEGEND_SWATCH * size, f32::max) +pub(super) fn swatch_column(sides: impl IntoIterator, (patch, size): (Patch, f32)) -> f32 { + sides.into_iter().fold(patch.width * size, f32::max) } /// A legend picture's size in points (a pixel a point). @@ -654,7 +661,7 @@ pub(crate) fn legend_budget() -> LegendBudget { /// A legend under a fit other than manual that the page drew still wider or taller than the room /// its title leaves in its box ([`unfitted_legends`]): the columns and verdict of the very fit -/// ([`fit_legend`]) its rows were drawn by. +/// ([`fit_legend_patched`]) its rows were drawn by. #[derive(Clone, Debug, PartialEq)] pub struct UnfittedLegend { /// The legend element's id. @@ -775,15 +782,51 @@ pub(super) const LEGEND_LABEL_PT: f32 = 8.5; pub(super) const LEGEND_TITLE_ROWS: f32 = 1.3; pub(super) const LEGEND_INDENT: f32 = 6.0; pub(super) const LEGEND_LABEL_INDENT: f32 = 12.0; -/// A legend swatch's width, in points. -pub(super) const LEGEND_SWATCH: f32 = 16.0; +/// A line or polygon patch's width, in points at the default text size: what a legend draws it at +/// unless it is given another ([`Patch`]). Its height is [`LEGEND_PATCH_HEIGHT`]. +pub(super) const LEGEND_SWATCH: f32 = rustgis_map::layout::LEGEND_PATCH_WIDTH_PT as f32; +pub(super) const LEGEND_PATCH_HEIGHT: f32 = rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT as f32; + +/// How wide and how tall a legend draws the patch of a line or polygon row, in points at its +/// default text size (#3559): [`LEGEND_SWATCH`] and [`LEGEND_PATCH_HEIGHT`] unless set, which they +/// have always been. A legend of another text size draws them in proportion ([`legend_size`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct Patch { + pub(super) width: f32, + pub(super) height: f32, +} + +impl Default for Patch { + fn default() -> Self { + Patch { width: LEGEND_SWATCH, height: LEGEND_PATCH_HEIGHT } + } +} + +impl Patch { + /// The patch a legend saves `width` and `height` for. + pub(super) fn new(width: f64, height: f64) -> Self { + Patch { width: width as f32, height: height as f32 } + } + + /// The height of a line or polygon row, in a legend `size` times the default: its patch and + /// what a row has always had around one, never less than a row. + pub(super) fn row(self, size: f32) -> f32 { + LEGEND_ROW.max(self.height + LEGEND_ROW - LEGEND_PATCH_HEIGHT) * size + } + + /// The patch's sides in pixels, at `size` times the default and `ppp` pixels a point. + pub(super) fn across(self, size: f32, ppp: f32) -> (f32, f32) { + (self.width * size * ppp, self.height * size * ppp) + } +} + /// The room between a legend's columns, in points. pub(super) const LEGEND_COLUMN_GAP: f32 = 10.0; /// The step a fit that shrinks a legend's text takes it down by, in points. pub(super) const LEGEND_FIT_STEP_PT: f64 = 0.25; -/// The columns and text size [`fit_legend`] draws a legend's rows at, and whether its rows are +/// The columns and text size [`fit_legend_patched`] draws a legend's rows at, and whether its rows are /// still wider or taller than its room there. #[derive(Clone, Debug, PartialEq)] pub(super) struct Fitted { @@ -850,28 +893,40 @@ pub(super) fn beyond(measured: f32, room: f32, size: f32) -> bool { /// no rows always fit. At most 11 sizes are tried ([`largest_fitting`]), in at most /// [`MAX_LEGEND_COLUMNS`] columns each: 66 layouts, whatever is asked. The rows' point symbols are /// measured once, and their heights and texts once a size tried ([`Trials`]). +pub(super) fn fit_legend_patched( + rows: &[LegendRow], + patch: Patch, + (columns, fit): (usize, LegendFit), + (room_w, room_h): (f32, f32), + (scale, text_size): (f64, f64), +) -> Fitted { + fit_measured(rows, &symbol_sides(rows, scale), (columns, fit), (room_w, room_h), (text_size, patch)).0 +} + +/// [`fit_legend_patched`] of a legend with the default patch. +#[cfg(test)] pub(super) fn fit_legend( rows: &[LegendRow], (columns, fit): (usize, LegendFit), (room_w, room_h): (f32, f32), (scale, text_size): (f64, f64), ) -> Fitted { - fit_measured(rows, &symbol_sides(rows, scale), (columns, fit), (room_w, room_h), text_size).0 + fit_legend_patched(rows, Patch::default(), (columns, fit), (room_w, room_h), (scale, text_size)) } -/// [`fit_legend`] of `rows` beside their point symbols' `sides` ([`symbol_sides`]), and the rows' +/// [`fit_legend_patched`] of `rows` beside their point symbols' `sides` ([`symbol_sides`]), and the rows' /// measures at the size it picks, which the drawing lays them out by. fn fit_measured( rows: &[LegendRow], sides: &[f32], (columns, fit): (usize, LegendFit), (room_w, room_h): (f32, f32), - text_size: f64, + (text_size, patch): (f64, Patch), ) -> (Fitted, RowSizes) { let safe = |v: f32| if v.is_nan() { 0.0 } else { v.max(0.0) }; let n = legend_columns_in_range(columns); let text_size = layout_text_in_range(text_size, LEGEND_TEXT_PT); - let mut trials = Trials { rows, sides, room: (safe(room_w), safe(room_h)), sizes: Vec::new() }; + let mut trials = Trials { rows, sides, patch, room: (safe(room_w), safe(room_h)), sizes: Vec::new() }; let fitted = match fit.kept() { LegendFit::Manual | LegendFit::Invalid => trials.at(n, text_size), LegendFit::AdjustSize => largest_fitting(text_size, |pt| { @@ -892,6 +947,7 @@ fn fit_measured( struct Trials<'m, 'a> { rows: &'m [LegendRow<'a>], sides: &'m [f32], + patch: Patch, room: (f32, f32), sizes: Vec, } @@ -919,7 +975,7 @@ impl Trials<'_, '_> { fn take(&mut self, size: f32) -> RowSizes { match self.sizes.iter().position(|s| s.size.to_bits() == size.to_bits()) { Some(k) => self.sizes.swap_remove(k), - None => RowSizes::of(self.rows, self.sides, size).narrowed(self.rows, self.room.0), + None => RowSizes::of(self.rows, self.sides, size, self.patch).narrowed(self.rows, self.room.0), } } @@ -1005,7 +1061,7 @@ pub(super) fn column_widths(m: Measured, starts: &[usize]) -> Vec { while let Some(part) = parts.get(first) { let end = first + 1 + parts.iter().skip(first + 1).take_while(|part| goes_on(part)).count(); if end > first + 1 { - let column = swatch_column(part.sides.iter().copied(), part.size); + let column = swatch_column(part.sides.iter().copied(), (part.patch, part.size)); let (mut name, mut under) = (0.0f32, 0.0f32); for (row, &text) in part.rows.iter().zip(part.texts) { let width = row.width(column, part.size, text); @@ -1270,7 +1326,7 @@ fn counted_name(name: &str, count: Option) -> std::borrow::Cow<'_, str> { /// less, each is filled in turn and the last rows are left out. In a box too narrow they close up, /// so that none is left out for it: long labels run into the next, and the last column's past the /// box, as a long label does in one column. A `fit` other than manual first picks the columns and -/// text size its rows are drawn at in the room the title leaves ([`fit_legend`]); the title keeps +/// text size its rows are drawn at in the room the title leaves ([`fit_legend_patched`]); the title keeps /// the legend's own size, and the rows are then drawn as a manual legend of those. Either way its /// rows' point symbols are measured once, and their heights and texts once a size. /// @@ -1309,13 +1365,13 @@ pub(super) fn legend_missing( let (opts, columns, sizes, starts, fitted) = match fit.kept() { LegendFit::Manual | LegendFit::Invalid => { let columns = legend_columns_in_range(columns); - let sizes = RowSizes::of(&rows, &sides, opts.size); + let sizes = RowSizes::of(&rows, &sides, opts.size, opts.patch); let m = Measured::new(&rows, &sides, &sizes); let starts = drawn_starts(m, columns, balanced(m, columns).1, room_h); (opts, columns, sizes, starts, None) } _ => { - let (fitted, sizes) = fit_measured(&rows, &sides, (columns, fit), (r.width() / ppp, room_h), opts.text_size); + let (fitted, sizes) = fit_measured(&rows, &sides, (columns, fit), (r.width() / ppp, room_h), (opts.text_size, opts.patch)); let starts = fitted.starts.clone(); (LegendOptions { size: fitted.size, text_size: fitted.text_size, ..opts }, fitted.columns, sizes, starts, Some(fitted)) } @@ -1371,9 +1427,9 @@ pub(super) fn legend_column( let mut y = r.y(); let size = opts.size; let line = LEGEND_ROW * size * ppp; - let sw = swatch_column(m.sides.iter().copied(), size) * ppp; + let sw = swatch_column(m.sides.iter().copied(), (opts.patch, size)) * ppp; // A line's or polygon's swatch, across the column of swatches. - let across = LEGEND_SWATCH * size * ppp; + let across = opts.patch.across(size, ppp); let mut rows = m.rows.iter().zip(m.heights).zip(m.sides).peekable(); while let Some(((row, &row_height), &side)) = rows.next() { if let LegendRow::Picture(p) = row { @@ -1408,7 +1464,7 @@ pub(super) fn legend_column( } // An entry given more than it takes, as in one row, is drawn at its own height in the // middle of it. - let own = (row.height_beside(side, size) * ppp).min(height); + let own = (row.height_beside(side, size, opts.patch) * ppp).min(height); let top = y + (height - own) / 2.0; match row { LegendRow::Plain(l, name) => { @@ -1559,6 +1615,7 @@ pub fn legend_sizes_in_columns_mm( class_labels, show_counts: false, sizes: Default::default(), + patch: (rustgis_map::layout::LEGEND_PATCH_WIDTH_PT, rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT), }; sizes_asked_mm(map, scale, &asked) } @@ -1582,6 +1639,9 @@ pub struct LegendAsked<'a> { pub class_labels: &'a ClassLabels, pub show_counts: bool, pub sizes: LegendSizes, + /// How wide and how tall its line and polygon patches are, in points at its default text + /// size (#3559). + pub patch: (f64, f64), } /// The columns and text size a legend's fit draws its rows at, and whether they are still wider @@ -1611,6 +1671,7 @@ fn asked_rows(map: &mut Map, scale: f64, asked: &LegendAsked, with: impl FnOn class_labels, show_counts, sizes, + patch, } = *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)?) }; @@ -1633,6 +1694,7 @@ fn asked_rows(map: &mut Map, scale: f64, asked: &LegendAsked, with: impl FnOn size, text_size, sizes, + patch: Patch::new(patch.0, patch.1), }; Some(with(&legend_rows(map, drawn.as_deref(), &opts))) } @@ -1662,7 +1724,7 @@ fn asked_measures(map: &mut Map, scale: f64, asked: &LegendAsked, with: impl let size = legend_size(asked.text_size); asked_rows(map, scale, asked, |rows| { let sides = symbol_sides(rows, scale); - let sizes = RowSizes::of(rows, &sides, size); + let sizes = RowSizes::of(rows, &sides, size, Patch::new(asked.patch.0, asked.patch.1)); with(Measured::new(rows, &sides, &sizes)) }) } @@ -1677,7 +1739,7 @@ fn measure_mm(m: Measured, columns: usize) -> (f64, f64) { /// The columns and text size the legend `asked` of `map` at the renderer's scale denominator /// `scale` is drawn at under its `fit` from its `columns`, in a room of `room_mm` (its box less its /// title, as [`legend_title_mm`] gives it), and whether it is still wider or taller than that: the -/// drawing's own rule ([`fit_legend`]). `None` when a listed layer's complete source can't be read. +/// drawing's own rule ([`fit_legend_patched`]). `None` when a listed layer's complete source can't be read. pub fn legend_fitted_mm( map: &mut Map, scale: f64, @@ -1687,7 +1749,7 @@ pub fn legend_fitted_mm( ) -> Option { let room = ((room_mm.0 * PT_PER_MM) as f32, (room_mm.1 * PT_PER_MM) as f32); asked_rows(map, scale, asked, |rows| { - let f = fit_legend(rows, (columns, fit), room, (scale, asked.text_size)); + let f = fit_legend_patched(rows, Patch::new(asked.patch.0, asked.patch.1), (columns, fit), room, (scale, asked.text_size)); LegendFitted { columns: f.columns, text_size: f.text_size, too_wide: f.too_wide, too_tall: f.too_tall } }) } diff --git a/crates/render/src/layout/legend/count_tests.rs b/crates/render/src/layout/legend/count_tests.rs index 71a66e2535..43d615fbc1 100644 --- a/crates/render/src/layout/legend/count_tests.rs +++ b/crates/render/src/layout/legend/count_tests.rs @@ -141,6 +141,7 @@ fn asked(all_classes: bool, show_no_data: bool, show_counts: bool) -> LegendAske class_labels: &NO_CLASS_LABELS, show_counts, sizes: Default::default(), + patch: (16.0, 9.0), } } @@ -404,6 +405,8 @@ fn counts_page(all_classes: bool) -> rustgis_map::layout::Layout { show_counts: rustgis_map::layout::FeatureCounts::from_shown(true), subtitle: Default::default(), sizes: Default::default(), + patch_width: rustgis_map::layout::LEGEND_PATCH_WIDTH_PT, + patch_height: rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT, }, ); page diff --git a/crates/render/src/layout/legend/nested/tests.rs b/crates/render/src/layout/legend/nested/tests.rs index 8c6d79e57f..1403f072f3 100644 --- a/crates/render/src/layout/legend/nested/tests.rs +++ b/crates/render/src/layout/legend/nested/tests.rs @@ -38,6 +38,7 @@ fn options(sizes: LegendSizes) -> LegendOptions<'static> { size: 1.0, text_size: rustgis_map::layout::LEGEND_TEXT_PT, sizes, + patch: Default::default(), } } diff --git a/crates/render/src/layout/swatch.rs b/crates/render/src/layout/swatch.rs index 326163b5bf..0dafca379e 100644 --- a/crates/render/src/layout/swatch.rs +++ b/crates/render/src/layout/swatch.rs @@ -4,7 +4,7 @@ use super::*; /// A legend entry's symbol `s` of the layer `l` in the box (`x`, `y`, `w`, `h`), with its stacked /// `strokes` and `fills` (#2490): a point as [`point_swatch`] draws it, or a line or a filled box a -/// swatch wide in the middle of the box (`across` pixels: [`LEGEND_SWATCH`] in the legend's size), +/// swatch wide in the middle of the box (`across` pixels: the legend's [`Patch`] at its size), /// by the paths the map draws its features with, its widths at `ppp`. A line or polygon swatch's /// ink ([`swatch_ink`]) is held to its row's top and bottom and, at its sides, to the `room` (left, /// right, in pixels) its row leaves empty: left, its indent and what lies left of its column, none @@ -18,7 +18,7 @@ pub(super) fn swatch( (s, strokes, fills): (&rustgis_map::Symbol, &[rustgis_map::LineStroke], &[rustgis_map::fills::FillLayer]), opacity: f32, scale: f64, - (ppp, across, (lead, gap)): (f32, f32, (f32, f32)), + (ppp, across, (lead, gap)): (f32, PatchSize, (f32, f32)), ) { let gt = l.geometry_type(); let k = l.size_factor(scale); @@ -50,7 +50,7 @@ pub(super) fn swatch( }); } -/// Where a line or polygon swatch drawn in `cell`, `across` pixels wide, its widths at `wppp`, +/// Where a line or polygon swatch drawn in `cell`, `across` pixels, its widths at `wppp`, /// puts ink: a plain one's line stroked as [`flat_swatch`] strokes it (its joins too); a stacked /// line's `strokes` the map draws, as it strokes them ([`crate::line_stroke`]), an offset one as /// wide as its width and twice its offset, mitred, as its shifted line's corners are @@ -61,7 +61,7 @@ pub(super) fn swatch_ink( cell: (f32, f32, f32, f32), gt: GeometryType, (s, strokes, fills): (&rustgis_map::Symbol, &[rustgis_map::LineStroke], &[rustgis_map::fills::FillLayer]), - (across, wppp): (f32, f32), + (across, wppp): (PatchSize, f32), ) -> Option { let line = gt == GeometryType::Polyline; if (line && strokes.is_empty()) || (!line && fills.is_empty()) { @@ -100,7 +100,7 @@ pub(super) fn swatch_ink( } /// A line swatch's zigzag ([`swatch_line`]) as a path. -pub(super) fn swatch_line_path(cell: (f32, f32, f32, f32), across: f32) -> Option { +pub(super) fn swatch_line_path(cell: (f32, f32, f32, f32), across: PatchSize) -> Option { let [a, b, c] = swatch_line(cell, across); let mut pb = PathBuilder::new(); pb.move_to(a.0, a.1); @@ -109,13 +109,13 @@ pub(super) fn swatch_line_path(cell: (f32, f32, f32, f32), across: f32) -> Optio pb.finish() } -/// A plain line or polygon swatch's line, `across` pixels wide in the box: a line's zigzag or a +/// A plain line or polygon swatch's line, `across` pixels in the box: a line's zigzag or a /// polygon's box, and the stroke it is drawn with, its width at `wppp`. pub(super) fn flat_swatch_outline( cell: (f32, f32, f32, f32), gt: GeometryType, s: &rustgis_map::Symbol, - (across, wppp): (f32, f32), + (across, wppp): (PatchSize, f32), ) -> Option<(tiny_skia::Path, Stroke)> { if gt == GeometryType::Polyline { Some((swatch_line_path(cell, across)?, Stroke { width: s.stroke_width.max(1.0) * wppp, ..Stroke::default() })) @@ -124,27 +124,33 @@ pub(super) fn flat_swatch_outline( } } -/// The part of the box (`x`, `w`) a line or polygon swatch `across` pixels wide takes, in its +/// The part of the box (`x`, `w`) a line or polygon swatch `across` pixels takes, in its /// middle. pub(super) fn swatch_across(x: f32, w: f32, across: f32) -> (f32, f32) { (x + (w - across) / 2.0, across) } -/// The three points of a line swatch `across` pixels wide in the box, in pixels. -pub(super) fn swatch_line((x, y, w, h): (f32, f32, f32, f32), across: f32) -> [(f32, f32); 3] { +/// How wide and how tall a line or polygon swatch is, in pixels, as `(width, height)` (#3559): +/// its box's sides, a line's zigzag as wide and its bends within the same height. +pub(super) type PatchSize = (f32, f32); + +/// The three points of a line swatch `across` pixels in the box, in pixels. +pub(super) fn swatch_line((x, y, w, h): (f32, f32, f32, f32), (across, tall): PatchSize) -> [(f32, f32); 3] { let (x, w) = swatch_across(x, w, across); let cy = y + h / 2.0; - [(x, cy + h * 0.2), (x + w * 0.4, cy - h * 0.2), (x + w, cy + h * 0.1)] + // A third of the patch's height either way: 3 points at the default 9, the 3 a row of 15 always had. + let bend = tall / 3.0; + [(x, cy + bend), (x + w * 0.4, cy - bend), (x + w, cy + bend / 2.0)] } -/// A polygon swatch's box, `across` pixels wide, in the box, in pixels. -pub(super) fn swatch_box((x, y, w, h): (f32, f32, f32, f32), across: f32) -> Option { +/// A polygon swatch's box, `across` pixels, in the box, in pixels. +pub(super) fn swatch_box((x, y, w, h): (f32, f32, f32, f32), (across, tall): PatchSize) -> Option { let (x, w) = swatch_across(x, w, across); - Rect::from_xywh(x, y + h * 0.2, w, h * 0.6) + Rect::from_xywh(x, y + (h - tall) / 2.0, w, tall) } -/// A line or polygon swatch of the symbol `s` alone, `across` pixels wide, its widths at `wppp`. -pub(super) fn flat_swatch(pm: &mut Canvas, cell: (f32, f32, f32, f32), gt: GeometryType, s: &rustgis_map::Symbol, at: (f32, f32)) { +/// A line or polygon swatch of the symbol `s` alone, in the box `cell`, drawn at the patch size and the widths' scale `at`. +pub(super) fn flat_swatch(pm: &mut Canvas, cell: (f32, f32, f32, f32), gt: GeometryType, s: &rustgis_map::Symbol, at: (PatchSize, f32)) { let Some((p, stroke)) = flat_swatch_outline(cell, gt, s, at) else { return }; if gt != GeometryType::Polyline { pm.fill_rect(p.bounds(), &paint(s.fill, 1.0), Transform::identity(), None); @@ -161,7 +167,7 @@ pub(super) fn stacked_swatch( cell: (f32, f32, f32, f32), l: &rustgis_map::Layer, (s, strokes, fills): (&rustgis_map::Symbol, &[rustgis_map::LineStroke], &[rustgis_map::fills::FillLayer]), - (ppp, across): (f32, f32), + (ppp, across): (f32, PatchSize), k: f32, ) { let (w, h) = (f64::from(pm.width()) / f64::from(ppp), f64::from(pm.height()) / f64::from(ppp)); diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 772dfa2601..6a9bfa761f 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -2,6 +2,7 @@ use super::*; mod colorbar_labels; mod legend_breaks; +mod legend_patch; mod legend_row; mod scale_bar_labels; @@ -19,7 +20,7 @@ thread_local! { /// ([`Measured`]), given to `with`. fn measured(rows: &[LegendRow], (scale, size): (f64, f32), with: impl FnOnce(Measured) -> T) -> T { let sides = symbol_sides(rows, scale); - let sizes = RowSizes::of(rows, &sides, size); + let sizes = RowSizes::of(rows, &sides, size, Patch::default()); with(Measured::new(rows, &sides, &sizes)) } @@ -752,6 +753,7 @@ fn an_ink_colours_legends_colorbars_tables_and_charts() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: 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 { @@ -916,6 +918,7 @@ fn layout_no_data_legend_follows_the_frame() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: Default::default(), }; legend_rows(map, drawn.as_deref(), &opts) .into_iter() @@ -988,6 +991,8 @@ fn layout_text_clipping_uses_ink_and_visibility() { show_counts: Default::default(), subtitle: Default::default(), sizes: Default::default(), + patch_width: rustgis_map::layout::LEGEND_PATCH_WIDTH_PT, + patch_height: rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT, }, ); assert_eq!(clipped_text(&l, &[Map::new("m")], 96.0, &info), vec![(legend, "Legend".into())]); @@ -1046,6 +1051,8 @@ fn legend_page(url: &str) -> (Layout, Vec) { show_counts: Default::default(), subtitle: Default::default(), sizes: Default::default(), + patch_width: rustgis_map::layout::LEGEND_PATCH_WIDTH_PT, + patch_height: rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT, }, ); let mut tile = rustgis_map::TileLayer::new("Walls", rustgis_map::TileKind::Raster, "https://tiles.test/red/{z}/{x}/{y}.png"); @@ -1162,6 +1169,8 @@ fn an_svg_export_gives_up_on_held_legends_at_one_deadline() { show_counts: Default::default(), subtitle: Default::default(), sizes: Default::default(), + patch_width: rustgis_map::layout::LEGEND_PATCH_WIDTH_PT, + patch_height: rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT, }, ); // The thread-local budget and the shortened wait belong to this worker alone. @@ -1227,6 +1236,7 @@ fn a_legend_says_from_the_lookup_that_draws_it_whether_a_picture_is_missing() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: Default::default(), }; let mut canvas = Canvas::new(200, 200).unwrap(); let draw = |canvas: &mut Canvas| { @@ -1545,6 +1555,7 @@ fn a_web_layers_legend_is_its_services_picture() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: 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()) @@ -1590,6 +1601,7 @@ fn a_web_layers_legend_is_its_services_picture() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: 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 = @@ -1923,6 +1935,7 @@ fn a_legends_rows_go_into_columns() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: Default::default(), }; let rows = legend_rows(&map, None, &opts()); assert_eq!(rows.len(), 32); @@ -2031,6 +2044,7 @@ fn a_layers_name_stays_with_its_class_only_in_columns() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: Default::default(), }; let rows = legend_rows(&map, None, &opts()); let (starts, _) = flow_at(&rows, 2, LEGEND_ROW, (1e6, 1.0)); @@ -2070,6 +2084,7 @@ fn a_legends_columns_hold_large_point_symbols() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: Default::default(), }; let rows = legend_rows(&map, None, &opts); let tall = rows[1].height(1e6, 1.0); @@ -2090,7 +2105,7 @@ fn a_legends_columns_hold_large_point_symbols() { assert_eq!( widest_at(&rows, (1e6, 1.0)), widest_at(parts[0], (1e6, 1.0)) - .max(swatch_column(rows.iter().map(|row| row.symbol_side(1e6)), 1.0) + 12.0 + widest_label(parts[1])) + .max(swatch_column(rows.iter().map(|row| row.symbol_side(1e6)), (Patch::default(), 1.0)) + 12.0 + widest_label(parts[1])) ); } @@ -2152,6 +2167,7 @@ fn opts(names: bool) -> LegendOptions<'static> { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: Default::default(), } } @@ -2330,6 +2346,7 @@ fn layer_names_can_be_left_off_a_legend() { class_labels: &NO_CLASS_LABELS, show_counts: false, sizes: Default::default(), + patch: (16.0, 9.0), }; legend_sizes_asked_mm(&mut map.clone(), 1e6, &asked).unwrap()[0].1 }; @@ -2438,6 +2455,8 @@ fn fit_page(map: Map, (w, h): (f64, f64), (columns, fit): (usize, LegendFit), (t show_counts: Default::default(), subtitle: Default::default(), sizes: Default::default(), + patch_width: rustgis_map::layout::LEGEND_PATCH_WIDTH_PT, + patch_height: rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT, }, ); let scale = frame_render_scale(&map, Coord::new(0.0, 0.0), 150_000_000.0); @@ -2464,6 +2483,7 @@ fn a_legends_fit_is_the_same_at_every_resolution() { class_labels: &NO_CLASS_LABELS, show_counts: false, sizes: Default::default(), + patch: (16.0, 9.0), }; 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)); @@ -2507,6 +2527,7 @@ fn a_fitted_legend_exports_as_a_manual_legend_of_its_fitted_size() { class_labels: &NO_CLASS_LABELS, show_counts: false, sizes: Default::default(), + patch: (16.0, 9.0), }; let info = PageInfo::default(); let export = |(page, mut maps, _): (Layout, Vec, f64)| { @@ -2840,6 +2861,7 @@ fn a_legend_measured_in_its_own_columns_lays_out_only_those() { class_labels: &NO_CLASS_LABELS, show_counts: false, sizes: Default::default(), + patch: (16.0, 9.0), }; 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)] { @@ -2896,6 +2918,7 @@ fn a_legend_shows_a_layers_label() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: Default::default(), }; legend_rows(&map, None, &opts) .iter() @@ -2937,6 +2960,7 @@ fn a_legend_shows_a_layers_label() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: 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) @@ -2996,6 +3020,7 @@ fn legends_leave_out_what_the_frame_does_not_draw() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: 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) @@ -3040,6 +3065,7 @@ fn legends_leave_out_what_the_frame_does_not_draw() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: Default::default(), }, 1.0, ) @@ -3579,6 +3605,7 @@ fn a_legend_lists_a_classified_rasters_classes() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: Default::default(), }; let labels = |rows: &[LegendRow]| -> Vec { rows.iter() @@ -7902,6 +7929,7 @@ fn point_legend(map: &Map) -> Pixmap { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: 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 @@ -7926,6 +7954,7 @@ fn recorded_legend(map: &Map, side: u32) -> Pixmap { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: 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(); @@ -8157,6 +8186,7 @@ fn a_legend_grows_to_hold_a_large_point() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: 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()); @@ -8207,6 +8237,7 @@ fn a_legends_text_size_scales_its_rows_but_not_its_point_symbols() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: 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"); @@ -8249,7 +8280,7 @@ fn a_legends_text_size_scales_its_rows_but_not_its_point_symbols() { // A thin one stays within its row and keeps the plain swatch it always had. let thin = rustgis_map::Symbol { stroke_width: 1.0, ..wide }; let row = (0.0, 0.0, LEGEND_SWATCH, LEGEND_ROW); - let b = swatch_ink(row, GeometryType::Polyline, (&thin, &[], &[]), (LEGEND_SWATCH, 1.0)).unwrap(); + let b = swatch_ink(row, GeometryType::Polyline, (&thin, &[], &[]), ((LEGEND_SWATCH, LEGEND_PATCH_HEIGHT), 1.0)).unwrap(); assert!(b.top() >= 0.0 && b.bottom() <= LEGEND_ROW, "{b:?}"); // A polygon's wide outline is cut at its row's top and bottom, plain or stacked, and on the // left at the legend's edge, where nothing lies before its column. @@ -8282,7 +8313,7 @@ fn a_legends_text_size_scales_its_rows_but_not_its_point_symbols() { (&outlined, &[], &[]), 1.0, 1e6, - (1.0, LEGEND_SWATCH, (lead, 6.0)), + (1.0, (LEGEND_SWATCH, LEGEND_PATCH_HEIGHT), (lead, 6.0)), ) }); let (_, left) = ink(&pm, (0, 0, 255)); @@ -8633,6 +8664,7 @@ fn a_recorded_point_is_cut_at_its_box() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: 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(); @@ -8773,6 +8805,7 @@ fn an_oversized_point_stays_in_its_row() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: 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) @@ -8817,6 +8850,7 @@ fn a_see_through_point_larger_than_the_canvas_covers_it_from_off_its_edge() { class_labels: &NO_CLASS_LABELS, counts: None, sizes: Default::default(), + patch: 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) @@ -9214,6 +9248,7 @@ fn a_legend_labels_a_layers_classes_itself() { size: 1.0, text_size: 9.0, sizes: Default::default(), + patch: 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"]); @@ -9272,6 +9307,7 @@ fn a_legend_labels_a_layers_classes_itself() { class_labels, show_counts: false, sizes: Default::default(), + patch: (16.0, 9.0), }; legend_size_asked_mm(&mut map, 1e6, &asked, 1).unwrap().0 }; @@ -9317,6 +9353,7 @@ fn a_legend_lists_its_layers_in_its_own_order() { size: 1.0, text_size: 9.0, sizes: Default::default(), + patch: Default::default(), }; legend_rows(map, None, &opts) .iter() @@ -9396,6 +9433,7 @@ fn a_legend_counts_the_features_of_each_row() { size: 1.0, text_size: 9.0, sizes: Default::default(), + patch: Default::default(), }; legend_rows(map, drawn.as_deref(), &opts) .iter() diff --git a/crates/render/src/layout/tests/legend_patch.rs b/crates/render/src/layout/tests/legend_patch.rs new file mode 100644 index 0000000000..898ffab34c --- /dev/null +++ b/crates/render/src/layout/tests/legend_patch.rs @@ -0,0 +1,157 @@ +//! The size of the patches a legend draws for lines and polygons (#3559). + +use super::*; + +/// A polygon layer drawn in one red symbol with no outline, so its patch is a plain red box. +fn red_polygon() -> Map { + let red = Rgba::rgb(255, 0, 0); + let fill = rustgis_map::Symbol { fill: red, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) }; + shape_legend_map(GeometryType::Polygon, |l| l.renderer = rustgis_map::Renderer::Single(fill)) +} + +/// The legend of `map` in a 300 × 300 box at `ppp` pixels a point, its patches `patch` points +/// across, its text `size` times the default. +fn drawn(map: &Map, patch: Patch, size: f32, ppp: f32) -> Pixmap { + let side = (300.0 * ppp) as u32; + let mut pm = Pixmap::new(side, side).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let opts = LegendOptions { patch, size, text_size: f64::from(size) * LEGEND_TEXT_PT, ..opts(true) }; + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(0.0, 0.0, side as f32, side as f32).unwrap(), map, ("", 1), None, opts, f64::from(ppp)) + }); + pm +} + +/// The pixels, across and down, the red patch's box takes: its outline's edge pixels aren't red, so +/// a box of `w` × `h` pixels shows `w - 2` × `h - 2`, which this adds back. +fn red_box(pm: &Pixmap) -> (usize, usize) { + let red = |x: u32, y: u32| pm.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == (255, 0, 0)); + let across = (0..pm.width()).filter(|&x| (0..pm.height()).any(|y| red(x, y))).count(); + let down = (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| red(x, y))).count(); + (across + 2, down + 2) +} + +fn patch(width: f32, height: f32) -> Patch { + Patch { width, height } +} + +#[test] +fn the_default_patch_is_the_one_legends_always_had() { + let default = Patch::default(); + assert_eq!( + (f64::from(default.width), f64::from(default.height)), + (rustgis_map::layout::LEGEND_PATCH_WIDTH_PT, rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT) + ); + assert_eq!(default.row(1.0), LEGEND_ROW); + assert_eq!(default.row(2.0), 2.0 * LEGEND_ROW); + // At the default, the box is 9 points of the row's 15, as it always was. + assert_eq!(red_box(&drawn(&red_polygon(), default, 1.0, 1.0)), (16, 9)); +} + +#[test] +fn a_patch_is_drawn_at_its_width_and_height() { + let map = red_polygon(); + assert_eq!(red_box(&drawn(&map, patch(32.0, 9.0), 1.0, 1.0)), (32, 9)); + assert_eq!(red_box(&drawn(&map, patch(16.0, 24.0), 1.0, 1.0)), (16, 24)); + assert_eq!(red_box(&drawn(&map, patch(4.0, 3.0), 1.0, 1.0)), (4, 3)); + // At two pixels a point, the same patch takes twice the pixels. + assert_eq!(red_box(&drawn(&map, patch(20.0, 12.0), 1.0, 2.0)), (40, 24)); +} + +#[test] +fn a_patch_follows_the_legends_text_size_with_the_rest() { + let map = red_polygon(); + assert_eq!(patch(16.0, 9.0).across(2.0, 1.0), (32.0, 18.0)); + assert_eq!(red_box(&drawn(&map, patch(20.0, 12.0), 2.0, 1.0)), (40, 24)); +} + +#[test] +fn a_line_patch_takes_the_patch_width_and_bends_within_its_height() { + let blue = Rgba::rgb(0, 0, 255); + let line = rustgis_map::Symbol { stroke: blue, stroke_width: 1.0, ..rustgis_map::Symbol::default_for(GeometryType::Polyline, 0) }; + let map = shape_legend_map(GeometryType::Polyline, |l| l.renderer = rustgis_map::Renderer::Single(line)); + let box_of = |patch: Patch| { + let pm = drawn(&map, patch, 1.0, 1.0); + let on = |x: u32, y: u32| pm.pixel(x, y).is_some_and(|p| p.blue() > 200 && p.red() < 100); + let across = (0..pm.width()).filter(|&x| (0..pm.height()).any(|y| on(x, y))).count(); + let down = (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| on(x, y))).count(); + (across, down) + }; + let (wide, _) = box_of(patch(40.0, 9.0)); + let (narrow, _) = box_of(patch(16.0, 9.0)); + assert!(wide >= narrow + 15, "{narrow} and {wide} px across"); + let (_, tall) = box_of(patch(16.0, 30.0)); + let (_, short) = box_of(patch(16.0, 9.0)); + assert!(tall > short + 5, "{short} and {tall} px down"); +} + +#[test] +fn a_patch_sets_the_height_of_line_and_polygon_rows_only() { + let polygon = red_polygon(); + let points = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { + size: 4.0, + stroke_width: 0.0, + ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) + }) + }); + let heights = |map: &Map, patch: Patch| { + let rows = legend_rows(map, None, &LegendOptions { patch, ..opts(true) }); + let sides = symbol_sides(&rows, 1e6); + let sizes = RowSizes::of(&rows, &sides, 1.0, patch); + Measured::new(&rows, &sides, &sizes).heights.to_vec() + }; + // A polygon layer's name beside its patch: one row, as tall as its patch and what it has around. + assert_eq!(heights(&polygon, patch(16.0, 9.0)), [LEGEND_ROW]); + assert_eq!(heights(&polygon, patch(16.0, 18.0)), [LEGEND_ROW + 9.0]); + assert_eq!(heights(&polygon, patch(16.0, 3.0)), [LEGEND_ROW]); + assert_eq!(heights(&polygon, patch(100.0, 100.0)), [LEGEND_ROW + 91.0]); + // A point layer's row is its symbol's, whatever the patch. + assert_eq!(heights(&points, patch(16.0, 9.0)), heights(&points, patch(16.0, 60.0))); +} + +#[test] +fn a_patch_sets_the_height_of_a_classified_rasters_class_rows() { + let map = classes_map(5); + let heights = |patch: Patch| { + let rows = legend_rows(&map, None, &LegendOptions { patch, ..opts(true) }); + let sides = symbol_sides(&rows, 1e6); + let sizes = RowSizes::of(&rows, &sides, 1.0, patch); + Measured::new(&rows, &sides, &sizes).heights.to_vec() + }; + let default = heights(patch(16.0, 9.0)); + let tall = heights(patch(16.0, 18.0)); + assert_eq!(default.len(), tall.len()); + // Each of the five classes grows by what the patch does; the layer's name row, with no patch, doesn't. + let grown: Vec = default.iter().zip(&tall).map(|(d, t)| t - d).collect(); + assert_eq!(grown.iter().filter(|g| **g == 9.0).count(), 5, "{grown:?}"); + assert!(grown.iter().all(|g| *g == 0.0 || *g == 9.0), "{grown:?}"); + assert!(tall.iter().filter(|h| **h == LEGEND_ROW + 9.0).count() >= 5, "{tall:?}"); +} + +#[test] +fn a_wider_patch_widens_the_column_and_a_point_symbol_keeps_its_own_size() { + let column = |patch: Patch, size: f32, sides: &[f32]| swatch_column(sides.iter().copied(), (patch, size)); + assert_eq!(column(Patch::default(), 1.0, &[]), LEGEND_SWATCH); + assert_eq!(column(patch(32.0, 9.0), 1.0, &[0.0, 10.0]), 32.0); + assert_eq!(column(patch(32.0, 9.0), 2.0, &[]), 64.0); + // A point symbol wider than the patch widens it; one narrower doesn't narrow it. + assert_eq!(column(patch(16.0, 9.0), 1.0, &[40.0]), 40.0); + assert_eq!(column(patch(40.0, 9.0), 1.0, &[24.0]), 40.0); +} + +#[test] +fn a_taller_or_wider_patch_needs_more_room_to_fit() { + let map = red_polygon(); + let rows = legend_rows(&map, None, &opts(true)); + let fit = |patch: Patch, room: (f32, f32)| fit_legend_patched(&rows, patch, (1, LegendFit::Manual), room, (1e6, LEGEND_TEXT_PT)); + let room = (200.0, LEGEND_ROW); + assert!(fit(Patch::default(), room).fits()); + assert!(fit(patch(16.0, 9.0), room).fits()); + assert!(fit(patch(16.0, 30.0), room).too_tall); + let wide = fit(patch(100.0, 9.0), (60.0, 100.0)); + assert!(wide.too_wide && !wide.too_tall, "{wide:?}"); + // The sizes the engine measures for the same legend are the drawing's. + let shrinks = fit_legend_patched(&rows, patch(16.0, 30.0), (1, LegendFit::AdjustSize), room, (1e6, LEGEND_TEXT_PT)); + assert!(shrinks.text_size < LEGEND_TEXT_PT, "{shrinks:?}"); +} diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index 658f1b7750..c21445c2bc 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -595,6 +595,8 @@ fn layout_export_keeps_all_drawn_legend_classes() { show_counts: Default::default(), subtitle: Default::default(), sizes: Default::default(), + patch_width: rustgis_map::layout::LEGEND_PATCH_WIDTH_PT, + patch_height: rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT, }, ); 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 363ac09a6f..50810492f1 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -529,6 +529,8 @@ mod tests { show_counts: Default::default(), subtitle: Default::default(), sizes: Default::default(), + patch_width: rustgis_map::layout::LEGEND_PATCH_WIDTH_PT, + patch_height: rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT, }, ); assert_eq!(picture_dpi(&layout, 600.0, |e| !written_as_svg(e)), 600.0); @@ -580,6 +582,8 @@ mod tests { show_counts: Default::default(), subtitle: Default::default(), sizes: Default::default(), + patch_width: rustgis_map::layout::LEGEND_PATCH_WIDTH_PT, + patch_height: rustgis_map::layout::LEGEND_PATCH_HEIGHT_PT, }, ); let info = PageInfo::default(); diff --git a/docs/maintaining.md b/docs/maintaining.md index 2690209f5d..1c07bfc8fb 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -396,6 +396,15 @@ 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 whose line and polygon patches aren't at their default size +(`patch_width` other than 16 or `patch_height` other than 9 on a legend element) require +`layout-legend-patch-size`, so an older reader refuses them instead of drawing the patches at the +default and saving the legend again without the size (#3559). Saved `layout.addElement` and +`layout.update` commands whose `patchWidth` or `patchHeight` is a number other than the default +require it too; `null` and the defaults 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 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` diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 02318123cc..e4cba47aba 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -532,7 +532,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"`, `"subtitle"` or `"sizes"`, and, + `"textSize"` (`null` included), `"showNoData"`, `"labels"`, `"classLabels"`, `"fit"`, `"showLayerNames"`, `"showCounts"`, `"subtitle"`, `"sizes"`, `"patchWidth"` or `"patchHeight"`, 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 @@ -567,6 +567,16 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu outline (each such mark of a stack of markers) 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. + - **Patch size** (`"patchWidth"` 4 to 100 and `"patchHeight"` 3 to 100, in points at the default + text size; 16 and 9 unless set): how wide and how tall the patch of a line or polygon row, or of a classified raster's class, is. + They grow and shrink with the legend's text size, as its rows do. A taller patch makes the + rows of lines, polygons and raster classes taller (a row is never shorter than the default's), and a wider one + widens the column of patches, so the labels stay lined up. A point symbol keeps the size the + map draws it at, and its column is as wide as the wider of it and the patch; a layer's name + and a web layer's legend picture don't change, and a nested block keeps its marker sizes, though its + markers and labels move with the widened column. The column is as wide as the patch even for a + legend of point layers only, which draws no patch: the width is the legend's, so it leaves that + room before the labels. `null` leaves each as it is. - **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_patch_size.rgis b/schema/fixtures/layout_legend_patch_size.rgis new file mode 100644 index 0000000000..be52a8757b --- /dev/null +++ b/schema/fixtures/layout_legend_patch_size.rgis @@ -0,0 +1,25 @@ +{ + "format": 2, + "name": "Legend patch size", + "requires": ["layout-legend-patch-size"], + "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": "Patched", "x": 100, "y": 5, "w": 95, "h": 90, "kind": {"Legend": {"frame": 1, "title": "Legend", "patch_width": 30.0, "patch_height": 14.0}}} + ] + } + ] +} diff --git a/schema/project.schema.json b/schema/project.schema.json index cac9792a1d..a385fb66a7 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1300,6 +1300,7 @@ "layout-legend-class-labels", "layout-legend-counts", "layout-legend-subtitle", + "layout-legend-patch-size", "layout-legend-nested-sizes", "layout-extent-indicators", "layout-extent-numbers", @@ -1447,6 +1448,7 @@ "layout-legend-class-labels", "layout-legend-counts", "layout-legend-subtitle", + "layout-legend-patch-size", "layout-legend-nested-sizes", "layout-extent-indicators", "layout-extent-numbers",