From 2ca504e3828022e1f6224b9ebc6d7f216f2e2655 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 08:22:30 -0500 Subject: [PATCH 01/38] feat(layout): a layout text shows a layer's count, sum, mean, min or max (#2853) Statistic tokens {count:} and {sum|mean|min|max::} fill in from the first map frame's map, over the features the layer's definition query keeps, written as a chart's values with the layout's decimal mark. A token with no figure is drawn as written and said when the text is added or its text changed. Projects and saved commands that use them require layout-text-statistics. Work in progress: the user guide, the schema's capability list and the Dynamic Text menu entry are still to do. --- crates/engine/src/cmd/layout.rs | 16 +++ crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 61 +++++++++ crates/engine/src/tests.rs | 25 ++++ crates/map/src/layout.rs | 146 ++++++++++++++++++++++ crates/render/src/layout.rs | 103 ++++++++++++++- 6 files changed, 351 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index b4ebd65277..a2abce3fbb 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -3635,6 +3635,18 @@ fn say_text_fit(s: &mut Session, li: usize, id: u32, lines: bool) { } } +/// Says which layer statistics (#2853) of the text `id` of the layout `li` are drawn as written, +/// and what each misses ([`rustgis_render::layout::statistic_notices`]). +fn say_text_statistics(s: &mut Session, li: usize, id: u32) { + let said = match s.project.layouts.get(li).map(|l| (l, l.element(id).map(|e| &e.kind))) { + Some((l, Some(ElementKind::Text { text, .. }))) => rustgis_render::layout::statistic_notices(l, &s.project.maps, text), + _ => return, + }; + for w in said { + s.warn(w); + } +} + /// What the element `id` of the layout `li` loses of its text on the page its series shows, as /// an export at 300 dpi measures it ([`rustgis_render::layout::text_loss`]). fn text_fit_loss(s: &Session, li: usize, id: u32) -> Option { @@ -4072,6 +4084,7 @@ fn add_element(s: &mut Session, p: &Value) -> CmdResult { say_chart_losses(s, i, id); } say_text_fit(s, i, id, true); + say_text_statistics(s, i, id); if let Some(said) = empty_colorbar { s.warn(said); } @@ -5839,6 +5852,9 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { // edge (#2703); a scale bar's labels move with it (#2581). say_text_fit(s, li, id, false); } + if p.get("text").is_some_and(Value::is_string) { + say_text_statistics(s, li, id); + } // A centre the frame's map can't place (a pole on Web Mercator) is said (#2684). if new_center.is_some() || given(&["map"]) { let said = diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index e48df5377f..b98475fd81 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -123,6 +123,7 @@ pub const CAPABILITIES: &[&str] = &[ "label-duplicates", "tile-resampling", "layout-page-color", + "layout-text-statistics", ]; /// An offline area keeping the versions that lost a sync or a Bring Back /// (`OfflineArea::conflicts`, #2468): an older reader would save it again without them. diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 4245c90145..778b75f3c4 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -176,6 +176,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("label-duplicates", command_removes_duplicate_labels), ("tile-resampling", command_resamples_tiles), ("layout-page-color", command_colours_the_page), + ("layout-text-statistics", command_uses_text_statistics), ]; /// A saved `labels.placement` that has a class remove duplicates, read as the command reads it @@ -202,6 +203,23 @@ fn command_resamples_tiles(id: &str, params: &Value) -> bool { } } +/// A layout text holding a layer statistic (#2853): an older reader prints the token as written. +fn text_statistics(e: &rustgis_map::layout::Element) -> bool { + matches!(&e.kind, rustgis_map::layout::ElementKind::Text { text, .. } if !rustgis_map::layout::stat_tokens(text).is_empty()) +} + +/// A layout command that gives a text a layer statistic (#2853), read as a text reads its tokens +/// ([`rustgis_map::layout::stat_tokens`]): only a text takes `"text"`. +fn command_uses_text_statistics(id: &str, params: &Value) -> bool { + let holds = |p: &Value| p.get("text").and_then(Value::as_str).is_some_and(|t| !rustgis_map::layout::stat_tokens(t).is_empty()); + match id { + "layout.addElement" | "layout.update" => holds(params), + "layout.import" => imported_layout_uses(params, &["{count:", "{sum:", "{mean:", "{min:", "{max:"], text_statistics), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_text_statistics)), + _ => false, + } +} + /// A saved `labels.placement` that gives a class a clearance other than 2, read as the command /// reads it (#2828): an older reader runs it without the key, saying nothing, so the labels would /// keep 2 points apart as before. 2 or null is what an older reader keeps. @@ -964,6 +982,7 @@ fn layout_capabilities(layouts: &[rustgis_map::layout::Layout]) -> Vec<&'static (elements().any(|e| e.kind.has_custom_text_size()), "layout-text-size"), (elements().any(bar_details), "layout-scale-bar-details"), (layouts.iter().any(|l| l.paper.is_some()), "layout-page-color"), + (elements().any(text_statistics), "layout-text-statistics"), ] .into_iter() .filter_map(|(used, name)| used.then_some(name)) @@ -2537,6 +2556,48 @@ mod tests { } } + /// A layout text holding a layer statistic (#2853) is required where it is saved, so an older + /// reader refuses the project by name instead of printing the token; a text with other tokens, + /// or braces that aren't one, needs nothing. + #[test] + fn text_statistics_capability_follows_saved_layouts_and_commands() { + use rustgis_map::layout::{ElementKind, Layout}; + let with_text = |text: &str| { + let mut p = Project::default(); + let mut l = Layout::new("L", 100.0, 100.0); + l.add("T", (10.0, 10.0, 50.0, 10.0), ElementKind::text(text, 12.0, rustgis_map::Rgba::rgb(0, 0, 0), false)); + p.layouts.push(l); + serde_json::to_value(&p).unwrap() + }; + let saved = with_text("{count:Sites} sites"); + assert_eq!(saved["requires"], json!(["layout-text-statistics"])); + assert_eq!(Project::from_json(&saved.to_string()).unwrap().layouts[0].elements.len(), 1); + let base = with_text("{scale} {count:} {foo}"); + assert_eq!(base.get("requires"), None); + let layout = saved["layouts"][0].to_string(); + for (id, params, required) in [ + ("layout.addElement", json!({"kind": "text", "text": "{sum:Sites:visits}"}), true), + ("layout.addElement", json!({"kind": "text", "text": "{scale}"}), false), + ("layout.addElement", json!({"kind": "legend", "title": "{count:Sites}"}), false), + ("layout.update", json!({"element": 1, "text": "Mean {mean:Sites:visits}"}), true), + ("layout.update", json!({"element": 1, "text": "{sum:Sites}"}), false), + ("layout.update", json!({"element": 1, "x": 3}), false), + ("layout.import", json!({"text": layout}), true), + ] { + let script = format!("{id} {params}"); + for value in [ + json!([{"name": "Task", "steps": [{"title": "Figure", "command": id, "params": params}]}]), + json!([{"name": "Script", "steps": [{"title": "Figure", "command": "script.run", "params": {"script": script}}]}]), + ] { + let mut document = base.clone(); + document["tasks"] = value; + let saved = serde_json::to_value(Project::from_json(&document.to_string()).unwrap()).unwrap(); + let expected = if required { json!(["layout-text-statistics"]) } else { Value::Null }; + assert_eq!(saved["requires"], expected, "{id} {params}"); + } + } + } + /// A legend's, scale bar's or grid's text size other than its default (#2581) is required /// where it is saved, so an older reader refuses the project instead of drawing it at the /// default and saving it so. Default sizes are not written and need nothing. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e0169b007a..b107f19435 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -39952,6 +39952,31 @@ fn layout_element_inks_from_commands() { } } +/// A layout text's layer statistics (#2853) are said when the text is added or its text changed +/// with a token that has no figure, each with what it misses; one with a figure, or another +/// change to the text's element, says nothing. +#[test] +fn layout_text_statistics_without_a_figure_are_said() { + let mut s = world(); + s.run("layout.new", &json!({"name": "L"})).unwrap(); + let run = |s: &mut Session, id: &str, p: Value| { + let mark = s.notice_mark(); + let out = s.run(id, &p).unwrap(); + let said: Vec = + s.notices_since(mark).iter().map(|n| n.text.as_str().to_string()).filter(|t| t.contains("shows as written")).collect(); + (out, said) + }; + let (out, said) = run(&mut s, "layout.addElement", json!({"kind": "text", "text": "{count:Countries} countries", "x": 10, "y": 10})); + assert_eq!(said, Vec::::new()); + let text = out["element"].clone(); + let (_, said) = run(&mut s, "layout.update", json!({"element": text, "text": "{count:Countries} of {sum:Nowhere:pop}"})); + assert_eq!(said, ["{sum:Nowhere:pop} shows as written: the map of the layout's first frame has no layer named 'Nowhere'"]); + let (_, said) = run(&mut s, "layout.update", json!({"element": text, "x": 20})); + assert_eq!(said, Vec::::new(), "a move doesn't say it again"); + let (_, said) = run(&mut s, "layout.addElement", json!({"kind": "text", "text": "{max:Countries:nosuch}", "x": 10, "y": 40})); + assert_eq!(said, ["{max:Countries:nosuch} shows as written: 'Countries' has no field named 'nosuch'"]); +} + #[test] fn locked_layout_elements_take_no_change_until_unlocked() { use rustgis_map::layout::ElementKind; diff --git a/crates/map/src/layout.rs b/crates/map/src/layout.rs index 6a7f41f2b8..bc825c0ff5 100644 --- a/crates/map/src/layout.rs +++ b/crates/map/src/layout.rs @@ -2414,6 +2414,88 @@ impl GroupKey { } } +/// A layer's figure in a layout text (#2853): `{count:}`, or `{sum::}` and +/// the same with `mean`, `min` and `max`. The layer is everything between the first colon and the +/// field's (the last), so a layer named with a colon still reads; a count's, everything after it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StatToken<'a> { + /// The token as written, braces included. + pub token: &'a str, + pub stat: StatKind, + pub layer: &'a str, + /// None for a count. + pub field: Option<&'a str>, +} + +/// The [`StatToken`]s in `text`, in the order they come; other braces (`{scale}`, `{foo}`, +/// `{sum:}`) are not among them. +pub fn stat_tokens(text: &str) -> Vec> { + let mut out = Vec::new(); + for (open, _) in text.match_indices('{') { + let Some(after) = text.get(open + 1..) else { continue }; + // The first brace after it ends the token; another opening one means this isn't one. + let Some(len) = after.find(['{', '}']).filter(|&i| after.get(i..).is_some_and(|r| r.starts_with('}'))) else { continue }; + let (Some(inner), Some(token)) = (after.get(..len), text.get(open..open + len + 2)) else { continue }; + let Some((code, rest)) = inner.split_once(':') else { continue }; + let stat = match code { + "count" => StatKind::Count, + "sum" => StatKind::Sum, + "mean" => StatKind::Mean, + "min" => StatKind::Min, + "max" => StatKind::Max, + _ => continue, + }; + let (layer, field) = match stat { + StatKind::Count => (rest, None), + _ => match rest.rsplit_once(':') { + Some((layer, field)) if !field.is_empty() => (layer, Some(field)), + _ => continue, + }, + }; + if !layer.is_empty() { + out.push(StatToken { token, stat, layer, field }); + } + } + out +} + +/// Why a [`StatToken`] has no figure: drawn as written instead, and said when the text is set. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StatMissing { + /// The layer has no such field (or a sum, mean, least or greatest names none). + Field, + /// The field holds no numbers to add up. + NotNumeric, + /// None of the features the layer's definition query keeps has a number in the field, or the + /// statistic is past a number's range. + NoValue, +} + +/// `stat` of `layer`'s `field` (none for a count) over the features its definition query keeps +/// ([`crate::Layer::visible_rows`]), its numbers read as a chart's are (finite, nulls skipped). +pub fn layer_statistic(layer: &crate::Layer, stat: StatKind, field: Option<&str>) -> Result { + let ds = &layer.dataset; + let fi = match (stat, field) { + (StatKind::Count, _) => None, + (_, Some(f)) => Some(ds.field_index(f).ok_or(StatMissing::Field)?), + (_, None) => return Err(StatMissing::Field), + }; + if fi.is_some_and(|fi| !ds.fields.get(fi).is_some_and(|f| f.ty.is_numeric())) { + return Err(StatMissing::NotNumeric); + } + let mut t = Tally::default(); + for (row, kept) in layer.visible_rows().into_iter().enumerate() { + if !kept { + continue; + } + t.records += 1; + if let Some(n) = fi.and_then(|fi| ds.value(row, fi).as_f64()).filter(|v| v.is_finite()) { + t.add(n, stat == StatKind::Mean); + } + } + t.value(stat).ok_or(StatMissing::NoValue) +} + /// A chart bar's features as its statistic reads them: how many, and their numbers' sum, mean, /// least and greatest. #[derive(Clone, Copy, Debug)] @@ -3300,6 +3382,70 @@ mod tests { use super::*; use crate::symbology::MAX_DASH_STEP; + /// A text's statistic tokens (#2853): each kind, a layer named with a colon, and braces that + /// aren't one left alone. + #[test] + fn statistic_tokens_are_read_from_a_text() { + fn read(t: &str) -> Vec<(&str, StatKind, &str, Option<&str>)> { + stat_tokens(t).into_iter().map(|s| (s.token, s.stat, s.layer, s.field)).collect() + } + assert_eq!( + read("{count:Houses} houses, {sum:Plants:mw} MW at {scale}"), + vec![("{count:Houses}", StatKind::Count, "Houses", None), ("{sum:Plants:mw}", StatKind::Sum, "Plants", Some("mw")),] + ); + assert_eq!( + read("{mean:Zone: north:pop}{min:A:b}{max:A:b}{count:Zone: north}"), + vec![ + ("{mean:Zone: north:pop}", StatKind::Mean, "Zone: north", Some("pop")), + ("{min:A:b}", StatKind::Min, "A", Some("b")), + ("{max:A:b}", StatKind::Max, "A", Some("b")), + ("{count:Zone: north}", StatKind::Count, "Zone: north", None), + ] + ); + // Not tokens: other names, an empty layer or field, a sum without its field, an alias the + // chart's codes take, a brace left open, a brace inside. + for t in ["{foo}", "{sum:}", "{count:}", "{sum:A}", "{sum::b}", "{sum:A:}", "{average:A:b}", "{Count:A}", "{count:A", "{count:{A}}"] + { + assert_eq!(read(t), vec![], "{t}"); + } + } + + /// A layer's statistic (#2853) over the features its definition query keeps, its numbers read + /// as a chart's: nulls and non-finite values skipped; a field it lacks, one with no numbers, or + /// no number among the kept features, none. + #[test] + fn layer_statistics_read_the_features_the_definition_query_keeps() { + use rustgis_data::{Dataset, Field, FieldType, GeometryType, Value}; + let fields = vec![Field::new("n", FieldType::Double), Field::new("name", FieldType::Text), Field::new("keep", FieldType::Integer)]; + let mut ds = Dataset::new("sites", GeometryType::None, fields); + for (n, keep) in + [(Value::Float(2.5), 1), (Value::Float(-1.0), 1), (Value::Null, 1), (Value::Float(f64::NAN), 1), (Value::Float(100.0), 0)] + { + ds.push(None, vec![n, Value::Text("x".into()), Value::Int(keep)]); + } + let mut layer = crate::Layer::new(1, ds); + let stat = |l: &crate::Layer, s: StatKind, f: Option<&str>| layer_statistic(l, s, f); + // Every feature: five, and the 100 counted. + assert_eq!(stat(&layer, StatKind::Count, None), Ok(5.0)); + assert_eq!(stat(&layer, StatKind::Max, Some("n")), Ok(100.0)); + layer.definition_query = Some("keep = 1".into()); + assert_eq!(stat(&layer, StatKind::Count, None), Ok(4.0)); + assert_eq!(stat(&layer, StatKind::Sum, Some("n")), Ok(1.5)); + assert_eq!(stat(&layer, StatKind::Mean, Some("n")), Ok(0.75)); + assert_eq!(stat(&layer, StatKind::Min, Some("n")), Ok(-1.0)); + assert_eq!(stat(&layer, StatKind::Max, Some("n")), Ok(2.5)); + assert_eq!(stat(&layer, StatKind::Sum, Some("nosuch")), Err(StatMissing::Field)); + assert_eq!(stat(&layer, StatKind::Sum, None), Err(StatMissing::Field)); + assert_eq!(stat(&layer, StatKind::Sum, Some("name")), Err(StatMissing::NotNumeric)); + // A query keeping none: a count of 0, no sum. + layer.definition_query = Some("keep = 7".into()); + assert_eq!(stat(&layer, StatKind::Count, None), Ok(0.0)); + assert_eq!(stat(&layer, StatKind::Sum, Some("n")), Err(StatMissing::NoValue)); + // A query that doesn't read keeps every feature, as the map draws them all. + layer.definition_query = Some("keep = = 1".into()); + assert_eq!(stat(&layer, StatKind::Count, None), Ok(5.0)); + } + /// A chart of layer "t" with `extra` keys (its field among them). fn chart(extra: serde_json::Value) -> ElementKind { let mut c = serde_json::json!({"frame": 1, "layer": "t"}); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 2b132528b3..3735423bbf 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -1135,11 +1135,14 @@ pub fn scale_ratio_text(scale: f64, comma: bool) -> String { pub fn expand(t: &str, layout: &Layout, info: &PageInfo, frame: Option<(&Map, rustgis_map::Camera)>) -> String { // The frame's scale, worked out once for both its forms below. let scale = frame.map(|(m, cam)| m.ground_res_at(&cam) / rustgis_map::layout::PAPER_M_PER_PT); + // The layer statistics first, read from the text as written: a page or layout name put in + // below isn't read as one. + let t = statistics(t, layout.decimal_comma, frame.map(|(m, _)| m)); // A layout with a decimal comma prints its scale with points between thousands: put in first, // so a page or layout name holding "{scale}" isn't read as the token. let t = match scale { Some(scale) if layout.decimal_comma => t.replace("{scale}", &scale_ratio_text(scale, true)), - _ => t.to_string(), + _ => t, }; let t = t .replace("{page}", &info.page.max(1).to_string()) @@ -1168,6 +1171,55 @@ pub fn expand(t: &str, layout: &Layout, info: &PageInfo, frame: Option<(&Map, ru rustgis_map::graphics::expand(&t, &v) } +/// What the layer statistics in `text` (#2853) that [`expand`] draws as written are missing, one +/// line per token, each once: no map frame, no such layer in the first frame's map, or what +/// [`rustgis_map::layout::layer_statistic`] finds missing. +pub fn statistic_notices(layout: &Layout, maps: &[Map], text: &str) -> Vec { + use rustgis_map::layout::StatMissing; + let map = layout.first_frame().and_then(|f| match &layout.element(f)?.kind { + ElementKind::MapFrame { map, .. } => maps.get(map_index(maps, map)?), + _ => None, + }); + let mut said: Vec = Vec::new(); + let mut seen: Vec<&str> = Vec::new(); + for t in rustgis_map::layout::stat_tokens(text) { + if seen.contains(&t.token) { + continue; + } + seen.push(t.token); + let (layer, field) = (t.layer, t.field.unwrap_or_default()); + let why = match map.map(|m| m.layer_by_name(layer).map(|l| rustgis_map::layout::layer_statistic(l, t.stat, t.field))) { + None => "the layout has no map frame whose map it would read".to_string(), + Some(None) => format!("the map of the layout's first frame has no layer named '{layer}'"), + Some(Some(Ok(_))) => continue, + Some(Some(Err(StatMissing::Field))) => format!("'{layer}' has no field named '{field}'"), + Some(Some(Err(StatMissing::NotNumeric))) => format!("'{field}' of '{layer}' holds no numbers"), + Some(Some(Err(StatMissing::NoValue))) => { + format!( + "no feature of '{layer}' its definition query keeps has a number in '{field}', or the figure is past a number's range" + ) + } + }; + said.push(format!("{} shows as written: {why}", t.token)); + } + said +} + +/// `t` with its layer statistics (#2853) from `map`, the first frame's, written as a chart writes +/// its values ([`rustgis_map::layout::chart_value_text`]) with `comma` the decimal mark; a token +/// with no figure stays as written ([`statistic_notices`] says why). +fn statistics(t: &str, comma: bool, map: Option<&Map>) -> String { + let Some(m) = map else { return t.to_string() }; + let mut out = t.to_string(); + for s in rustgis_map::layout::stat_tokens(t) { + let Some(v) = m.layer_by_name(s.layer).and_then(|l| rustgis_map::layout::layer_statistic(l, s.stat, s.field).ok()) else { + continue; + }; + out = out.replace(s.token, &decimal(rustgis_map::layout::chart_value_text(v, None), comma)); + } + out +} + /// `stroke` dashed along `path` by an element's pattern (points, at `ppp` pixels a point), as a /// line layer's stroke is ([`crate::dash_steps`]): solid when it has none, or when the pattern is /// under a pixel a round or would cut the path into too many dashes. @@ -10551,6 +10603,55 @@ Elaboração: RustGIS", assert!(kept_labels(side, (15.0, 500.0), (along, across), 10.0, 1.0).is_empty(), "a narrow one leaves them out"); } + /// A text's layer statistics (#2853) fill in from the frame's map, written as a chart's values + /// with the layout's decimal mark, beside `{scale}`; a token with no figure, or with no frame, + /// is drawn as written. What each such token is missing is said, once. + #[test] + fn a_text_shows_its_layers_statistics() { + use rustgis_data::{Dataset, Field, FieldType, GeometryType, Value}; + let mut ds = + Dataset::new("Plants", GeometryType::None, vec![Field::new("mw", FieldType::Double), Field::new("name", FieldType::Text)]); + for mw in [12_000.5, 11_553.25] { + ds.push(None, vec![Value::Float(mw), Value::Text("x".into())]); + } + let mut map = Map::new("m"); + map.add_dataset(ds); + let cam = frame_camera(&map, Coord::new(0.0, 0.0), 6_300_000.0, 0.0, 0.0); + let info = PageInfo { page: 1, pages: 1, page_name: String::new() }; + let mut layout = Layout::new("L", 100.0, 100.0); + let text = "{count:Plants} plants, {sum:Plants:mw} MW, mean {mean:Plants:mw}; {sum:Plants:name} {count:Nowhere}"; + assert_eq!( + expand(text, &layout, &info, Some((&map, cam))), + "2 plants, 23,553.75 MW, mean 11,776.88; {sum:Plants:name} {count:Nowhere}" + ); + layout.decimal_comma = true; + assert_eq!( + expand(text, &layout, &info, Some((&map, cam))), + "2 plants, 23.553,75 MW, mean 11.776,88; {sum:Plants:name} {count:Nowhere}" + ); + // Without a frame, every token as written, and said so; a text without tokens says nothing. + assert_eq!(expand("{count:Plants} plants", &layout, &info, None), "{count:Plants} plants"); + let maps = [map]; + assert_eq!( + statistic_notices(&layout, &maps, "{count:Plants} and {count:Plants}"), + vec!["{count:Plants} shows as written: the layout has no map frame whose map it would read".to_string()] + ); + assert_eq!(statistic_notices(&layout, &maps, "Plants at {scale}"), Vec::::new()); + let kind = + serde_json::from_value(serde_json::json!({"MapFrame": {"map": "m", "center": {"x": 0, "y": 0}, "scale": 6300000}})).unwrap(); + layout.add("Frame", (0.0, 0.0, 50.0, 50.0), kind); + let said = + statistic_notices(&layout, &maps, "{sum:Plants:name} {sum:Plants:name} {count:Nowhere} {min:Plants:nosuch} {count:Plants}"); + assert_eq!( + said, + vec![ + "{sum:Plants:name} shows as written: 'name' of 'Plants' holds no numbers".to_string(), + "{count:Nowhere} shows as written: the map of the layout's first frame has no layer named 'Nowhere'".to_string(), + "{min:Plants:nosuch} shows as written: 'Plants' has no field named 'nosuch'".to_string(), + ] + ); + } + /// A layout with a decimal comma swaps the marks of the numbers it prints, `{scale}` included, /// and leaves other text alone. #[test] From dd79ea556d4ac9d3be5dad0fe01462cc77e45f5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 25 Nov 2026 16:24:46 -0500 Subject: [PATCH 02/38] docs(layout): the guide, schema, fixture and help for layer statistics in a text (#2853) --- crates/engine/src/cmd/layout.rs | 4 ++-- crates/engine/src/project_capabilities.rs | 1 + docs/maintaining.md | 6 +++++ docs/user-guide/layouts.md | 9 +++++++- schema/fixtures/layout_text_statistics.rgis | 25 +++++++++++++++++++++ schema/project.schema.json | 6 +++-- 6 files changed, 46 insertions(+), 5 deletions(-) create mode 100644 schema/fixtures/layout_text_statistics.rgis diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index a2abce3fbb..4298ffb372 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -117,10 +117,10 @@ pub fn commands() -> Vec { r#"{"layout"?, "shape"?: "rectangle"|"circle"|"ellipse"|"polygon"|"lasso", "points"?: [[u, v], …] (polygon/lasso, 0..1 across the frame), "map"?: name, "x"?, "y"?, "w"?, "h"?: mm}"#, ), C::new("layout.addElement", "Add Element", "Publish › Map Surrounds", add_element).inputs(element_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( - r##"{"layout"?, "kind": "northArrow"|"scaleBar"|"legend"|"colorbar"|"text"|"dynamicText"|"picture"|"table"|"chart"|"rectangle" (a neatline framing the page unless any of x, y, w, h is given)|"ellipse"|"circle"|"line"|"arrow"|"extentIndicator"|"grid", "frame"?: element id (default: the first map frame), "of"?: frame id (extentIndicator, which also takes "color" and "width" in points, default red and 2), "text"?, "size"?, "color"?: "#RRGGBB"|"#RRGGBBAA" (text, dynamicText, line, arrow, rectangle, ellipse, circle: its outline; extentIndicator; grid; scaleBar; legend, colorbar, table, chart: the ink of its text and lines, default #222222, a chart's bars and a colorbar's colours keeping theirs, and a table drawn without its white cells; refused for other kinds), "bold"?: bool (text), "italic"?: bool, "align"?: "left"|"center"|"right", "letterSpacing"?: points, -5 to 50 (text, dynamicText), "rotation"?: degrees clockwise about the box's centre, 90 reading top to bottom and -90 bottom to top, kept within -180 to 180 (text, dynamicText; refused for other kinds), "wrap"?: bool (text, dynamicText: broken into lines at spaces to fit the box's width when drawn, after its dynamic text is filled in, a word wider than the box broken across lines; default false, lines breaking only at the text's own line breaks; refused for other kinds), "font"?: "sans"|"serif"|an installed font family's name, as labels.fonts lists them (text, dynamicText; a family not installed here is drawn in its fallback, and a serif where none is installed in the sans, with a warning; refused for other kinds), "fallback"?: "sans"|"serif" (a named font's, where it isn't installed; default its own class, else sans), "title"?: legend title (default "Legend"); chart: its own title ("" for none; default: its field, or the statistic of its field by the group), "allClasses"?: bool (legend: every class, not only those the frame draws), "hideOther"?: bool (legend: leave out ), "showNoData"?: bool (legend: include Graduated Colors’ missing-value symbol; default false), "exclude"?: [layer names] (legend: layers it leaves out though the map draws them), "columns"?: 1..3 (legend: the columns its rows are laid in; default 1), "textSize"?: points, 4 to 100 (legend: its layers' names and classes' labels, its title, rows, swatches and gaps following in proportion and a point symbol keeping the size the map draws it at; default 9; scaleBar: its labels, the room over the bar and between them following, the bar keeping its size; default 8; refused outside that range, and for other kinds unless null, as showNoData is), "orientation"?: "horizontal"|"vertical" (colorbar; chart: bars running across, the default, or columns standing up, each label centred under its column), "ticks"?: 2..21 (colorbar: labelled values, ends included), "tickSide"?: "below"|"above"|"right"|"left" (colorbar), "reverse"?: bool (colorbar: high values first), "fill"?: "#RRGGBBAA" (rectangle, ellipse, circle, northArrow; scaleBar: the alternating bar's light divisions, default white; refused for other kinds), "width"?: outline width in points (rectangle, ellipse, circle; 0 for none) or line width in points (line, grid), "radius"?: mm, 0 to 50 (rectangle: rounded corners), "dash"?: [points, …] (line, arrow, and a rectangle's, ellipse's or circle's outline: dash, gap, … in turn, as layer.lineStrokes takes it, at most 8, each 0 to 500; an arrow's heads stay solid; [] or null for solid; refused, null too, for other kinds), "dir"?: "horizontal"|"vertical"|"falling"|"rising" (line), "head"?: "none"|"end"|"start"|"both" (line; default "end" for an arrow), "angle"?: degrees anticlockwise from pointing right, centred on the page unless x or y is given (line, arrow; it sets the box and the direction, so w, h and dir are not used with it), "length"?: mm (line, arrow), "image"?: base64, "path"?: picture file, "layer"?: (table, chart; colorbar: a raster layer, default the top visible raster with a colour scale, not drawn by classes, which a legend lists), "field"?: (chart: a numeric field, default the layer's first; any field when it groups and counts, default then the field it groups by), "label"?: a field (chart: each bar's label when not grouped), "group"?: a field (chart: a bar per value of this field, its statistic of field over that value's features; blank values make one "(blank)" bar; default none, a bar per feature), "statistic"?: "sum" (the default)|"count" (features, numbers or not)|"mean"|"min"|"max" (chart, grouped), "order"?: "descending" (the default: largest first)|"ascending"|"category" (by label, A to Z)|"layer" (as the features come) (chart), "bars"?: 1..100 (chart: the most bars drawn, default 20), "other"?: bool (chart: the bars past "bars" gathered in a last Other bar, its statistic over their features, their sum when not grouped, last whatever the order; default false: left out, which a warning says, as it says features with no number left out), "stack"?: a field (chart, grouped by another field, summing or counting: each bar split by this field's values, a stretch per value in the key over the bars, the values its bars show by their total, largest first (A to Z when ordered by category), past 8 values 7 and a grey Other, which a warning counts; in the palette diagrams take, or with classes in the colour each value's features share on the map, a value with several keeping its palette colour, which a warning counts; values written are the bar's total; default none), "values"?: bool (chart: each bar's value written past its end, its thousands apart with commas; default false), "decimals"?: "auto" (the default: a chart's values up to 2, the zeros they end in dropped; a scale bar's labels each the decimals it needs, as before)|0..6 (chart: its values' decimals)|0..3 (scaleBar: its labels' decimals, fixed, with the thousands set apart), "barColor"?: "#RRGGBB"|"#RRGGBBAA" (chart: its bars' colour, default #3B82C4), "classes"?: bool (chart: each bar in the colour its features have on the map, by the layer's symbology classes: a bar per feature its feature's, a grouped bar the colour its features share; a bar whose features have several, which a warning counts, and an Other bar keep barColor; default false), "labelAlign"?: "left" (the default)|"right" (chart: bars running across have their labels at the left of their column, or at its right against the bars), "mirror"?: bool (chart: drawn as its mirror image, its text reading as ever: bars running across from the right, their labels at the right, or columns hanging from the top, their labels over them; beside a chart drawn the usual way the two face each other; default false), "max"?: a number above 0|"auto" (chart: the value at the far end of its bars' room, so charts given the same one share a scale; a bar past it runs to that end, which a warning counts; default "auto", its bars' own), "hideLabels"?: bool (chart: its labels left out, their room given to the bars; default false), "barOutline"?: {"color"?: "#RRGGBB"|"#RRGGBBAA" (default #222222), "width"?: points, 0 to 5 (default 0.5; 0 for none)} (chart: a line round each bar, or each stretch of a stacked one; default none) (label, group, statistic, order, bars, other, stack, values, decimals, barColor, classes, labelAlign, mirror, max, hideLabels and barOutline refused for other kinds unless null, as showNoData is, a scaleBar's decimals aside), "rows"?, "step"?: degrees, or a measured grid's units (metres) (0 picks one), "type"?: "graticule" (latitudes and longitudes, default) | "measured" (eastings and northings in a projected system), "crs"?: a measured grid's coordinate system: EPSG:25832, WKT or a PROJ string ("" or none: the map's when projected, else the UTM zone at the frame's centre), "short"?: bool (a measured grid's labels as their kilometres' last two digits, 43 for 543000), "mgrs"?: bool (a measured grid labelled as MGRS: each 100 km square named with its grid zone designation, 32T MT, and the lines by their kilometres' last two digits; its crs a WGS 84 UTM zone by EPSG code, EPSG:32601–32660 or 32701–32760, or none: the map's when it is one, else the zone at the frame's centre), "labels"?: bool (grid) | {"": "