diff --git a/crates/assistant/skills/print-layout/SKILL.md b/crates/assistant/skills/print-layout/SKILL.md index 75a352e869..2678ff4fb3 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), `"showCounts": true` (each class row ends in its number of features), + text or add columns to fit its box), `"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` and `"classLabels"` (`{"": {"": ""}}`: its own text for a class, the layer keeping its label). A `"text"` or `"dynamicText"` can take diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index a0f3c90a18..1cd2a36b26 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -208,7 +208,7 @@ pub fn commands() -> Vec { r##""columns"?: 1..6 (legend: the columns its rows are laid in; default 1; with a fit that adds columns, the fewest it starts from), "##, r##""textSize"?: points, 4 to 100 (legend: its layers' names and classes' labels, its title, rows, swatches and gaps following in proportion and a point symbol keeping the size the map draws it at; default 9; scaleBar: its labels, the room over the bar and between them following, the bar keeping its size; default 8; refused outside that range, and for other kinds unless null, as showNoData is), "##, r##""classLabels"?: {"": {"": ""}} (legend: its own text for a class, by the label the layer shows for it, up to 200 characters; the layer keeps its label; a layer or class it can't find is refused), "##, - r##""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, streamed layers, or Unique Values by an expression over too many features and classes; refused for other kinds), "##, + r##""showCounts"?: bool (legend: each class row, and a one-symbol layer's row, ends in the number of features the layer's filters keep; default false; none for rasters, web layers, size and diagram rows, layers read in place other than from a local Shapefile, GeoPackage, FlatGeobuf or GeoParquet (each of those is read whole to count), or Unique Values by an expression over too many features and classes; refused for other kinds), "##, r##""showLayerNames"?: bool (legend: the name over each layer's classes and over a web layer's legend picture; default true; a layer drawn in one symbol keeps its name; refused for other kinds), "##, r##""orientation"?: "horizontal"|"vertical" (colorbar; chart: bars running across, the default, or columns standing up, each label centred under its column), "##, r##""ticks"?: 2..21 (colorbar: labelled values, ends included), "##, diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 868991549a..778d6b30cf 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -169,6 +169,27 @@ pub struct Unreadable { pub zm_noted: bool, } +/// What a legend counts of a layer's features (#3237), added to as they are read +/// ([`Layer::count_for_legend`]). +#[derive(Debug, Default)] +pub struct LegendCount { + /// Every feature read, drawn or not. + features: usize, + /// Those drawn. + total: u64, + /// Those drawn in each class, as [`Renderer`] counts them. + classes: Vec, + /// Those drawn with no value for Graduated Colors. + missing: u64, +} + +impl LegendCount { + /// The number of features drawn. + pub fn total(&self) -> u64 { + self.total + } +} + /// A layer: a dataset drawn with a renderer and labels. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Layer { @@ -1892,7 +1913,7 @@ impl Layer { /// [`Layer::shown_legend_with`] for a legend that counts features (#3237): its rows at 1:`scale` /// with their numbers (with `all`, every class), and the number of rows the layer draws, which /// a layer of one symbol shows beside its name. With `no_data`, Graduated Colors' missing-value - /// row after the classes, counted. + /// row after the classes, counted. For a layer that holds all its features. pub fn counted_legend( &self, scale: f64, @@ -1900,21 +1921,42 @@ impl Layer { all: bool, no_data: bool, ) -> (Vec, u64) { + let mut count = LegendCount::default(); + self.count_for_legend(scale, env, &mut count); + self.legend_of_count(&count, all, no_data) + } + + /// Adds the features this layer holds and draws at 1:`scale` to a legend's `count`: a layer's + /// own, or each chunk of a source read whole (#3238). + pub fn count_for_legend(&self, scale: f64, env: &rustgis_data::query::Env, count: &mut LegendCount) { let rows = self.drawn_rows_with(scale, env); - let total = rows.iter().filter(|r| **r).count() as u64; - let mut entries = self.with_size_legend(self.renderer.legend_counted(&self.dataset, &rows, env.at_scale(Some(scale)), all)); - let missing = (!all).then_some(rows.as_slice()); - if no_data && let Some(mut entry) = self.renderer.no_data_legend(&self.dataset, missing) { - if let Renderer::Graduated { field, .. } = &self.renderer { - let fi = self.dataset.field_index(field); - let n = (0..rows.len()) - .filter(|r| rows.get(*r) == Some(&true) && fi.and_then(|fi| self.dataset.value(*r, fi).as_f64()).is_none()) - .count(); - entry.count = Some(n as u64); - } + count.total += rows.iter().filter(|r| **r).count() as u64; + // Bounded over every feature counted, however many chunks they come in. + count.features = count.features.saturating_add(self.dataset.features.len()); + if !self.renderer.too_many_to_class(count.features) { + self.renderer.count_classes(&self.dataset, &rows, env.at_scale(Some(scale)), &mut count.classes); + } + if let Renderer::Graduated { field, .. } = &self.renderer { + let fi = self.dataset.field_index(field); + let missing = (0..rows.len()) + .filter(|r| rows.get(*r) == Some(&true) && fi.and_then(|fi| self.dataset.value(*r, fi).as_f64()).is_none()) + .count(); + count.missing += missing as u64; + } + } + + /// The legend rows and number of drawn features ([`Layer::counted_legend`]) of `count`. + pub fn legend_of_count(&self, count: &LegendCount, all: bool, no_data: bool) -> (Vec, u64) { + let classes = (!self.renderer.too_many_to_class(count.features)).then_some(count.classes.as_slice()); + let mut entries = self.with_size_legend(self.renderer.counted_entries(&self.dataset, classes, all)); + if no_data + && (all || count.missing > 0) + && let Some(mut entry) = self.renderer.no_data_legend(&self.dataset, None) + { + entry.count = Some(count.missing); entries.push(entry); } - (entries, total) + (entries, count.total) } /// A legend's colour classes with the sizes of [`Layer::size_by`] after them, where it applies: diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index 6f9d2588e7..59c31d2cb7 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -1309,6 +1309,13 @@ impl SourceLayer { self.handle.as_ref().filter(|h| h.visits_chunks()).cloned() } + /// [`SourceLayer::visit_source`] for a legend's counts, which every drawing of the page reads + /// again: not a live service's, which a tool or an export may page through whole, and never + /// past the refusal of an incompatible schema. + pub fn count_source(&self) -> Option> { + self.visit_source().filter(|h| !self.schema_refused && h.info().format != rustgis_data::source::arcgis::FORMAT) + } + /// A source that can provide all features in an extent a chunk at a time. pub(super) fn visit_extent_source(&self) -> Option> { self.handle.as_ref().filter(|h| h.visits_extent_chunks()).cloned() diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 3c6bfe4e75..c284893939 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -1774,23 +1774,13 @@ impl Renderer { /// Classes present among the kept rows at the drawing scale and page. pub fn legend_with(&self, ds: &Dataset, rows: &[bool], env: rustgis_data::query::Env) -> Vec { - let Renderer::Unique { - classes, - other, - class_labels, - other_label, - expression, - other_fills, - other_strokes, - class_strokes, - class_fills, - .. - } = self + let Renderer::Unique { classes, other, class_labels, other_label, other_fills, other_strokes, class_strokes, class_fills, .. } = + self else { return self.legend(); }; let visible = self.fallback_draws(ds); - if expression.is_some() && ds.features.len().saturating_mul(classes.len().max(1)) > MAX_LEGEND_STEPS { + if self.too_many_to_class(ds.features.len()) { let mut all = self.legend(); all.retain(|e| visible || !e.fallback); return all; @@ -1877,43 +1867,30 @@ impl Renderer { } } - /// The rows of a legend that counts features (#3237): those [`Renderer::legend_with`] lists of - /// the kept `rows` (with `all`, every row of [`Renderer::legend`]), each with the number of - /// those rows it stands for. No number for Proportional sizes, nor by an expression past - /// [`MAX_LEGEND_STEPS`], which is listed without classing its features. - pub fn legend_counted(&self, ds: &Dataset, rows: &[bool], env: rustgis_data::query::Env, all: bool) -> Vec { - let listed = || if all { self.legend() } else { self.legend_with(ds, rows, env.clone()) }; + /// Whether classing `features` features by expression takes more than [`MAX_LEGEND_STEPS`]. + pub(crate) fn too_many_to_class(&self, features: usize) -> bool { + let Renderer::Unique { classes, expression, .. } = self else { return false }; + expression.is_some() && features.saturating_mul(classes.len().max(1)) > MAX_LEGEND_STEPS + } + + /// Adds to `counts` the kept `rows` of each class (#3237): Unique Values' in `classes` order, + /// then ``; Graduated Colors' in the order of its breaks. Nothing for the + /// other renderers. + pub(crate) fn count_classes(&self, ds: &Dataset, rows: &[bool], env: rustgis_data::query::Env, counts: &mut Vec) { match self { - Renderer::Unique { classes, expression, .. } => { - if expression.is_some() && ds.features.len().saturating_mul(classes.len().max(1)) > MAX_LEGEND_STEPS { - return listed(); - } - let mut counts = vec![0u64; classes.len()]; - let mut other = 0u64; + Renderer::Unique { classes, .. } => { + counts.resize(classes.len().saturating_add(1), 0); self.visit_unique(ds, rows, env, |class| { - match class.and_then(|i| counts.get_mut(i)) { - Some(n) => *n += 1, - None => other += 1, + let slot = class.unwrap_or(classes.len()).min(classes.len()); + if let Some(n) = counts.get_mut(slot) { + *n += 1; } true }); - // `legend()` lists the classes in `class_order`, then the fallback: so do the counts. - let counts = self.class_order().into_iter().filter_map(|i| counts.get(i).copied()); - let mut entries: Vec = self.legend(); - for (e, n) in entries.iter_mut().zip(counts.chain([other])) { - e.count = Some(n); - } - if !all { - // As `legend_with` lists them: the classes with a feature, and the fallback - // when it has one and draws something. - let visible = self.fallback_draws(ds); - entries.retain(|e| e.count != Some(0) && (!e.fallback || visible)); - } - entries } Renderer::Graduated { breaks, .. } => { - let classer = self.classer_with(ds, env.clone()); - let mut counts = vec![0u64; breaks.len()]; + counts.resize(breaks.len(), 0); + let classer = self.classer_with(ds, env); for r in (0..ds.features.len()).filter(|r| rows.get(*r).copied().unwrap_or(true)) { if let Some(Slot::Class(i)) = self.class_in(ds, r, &classer) && let Some(n) = counts.get_mut(i) @@ -1921,14 +1898,43 @@ impl Renderer { *n += 1; } } - let mut entries = listed(); - for (e, n) in entries.iter_mut().zip(counts) { - e.count = Some(n); + } + Renderer::Single(_) | Renderer::Proportional { .. } => {} + } + } + + /// [`Renderer::legend`] with each entry's number of features, from [`Renderer::count_classes`]; + /// without `all`, only the rows [`Renderer::legend_with`] would list. No `counts`, no numbers: + /// Unique Values by expression too large to class ([`Renderer::too_many_to_class`]). `ds` gives + /// the geometry family alone. + pub(crate) fn counted_entries(&self, ds: &Dataset, counts: Option<&[u64]>, all: bool) -> Vec { + let mut entries = self.legend(); + match self { + Renderer::Unique { classes, .. } => { + if let Some(counts) = counts { + // `legend()` lists the classes in `class_order`, then the fallback: so do these. + let slots = self.class_order().into_iter().chain([classes.len()]); + for (e, slot) in entries.iter_mut().zip(slots) { + e.count = Some(counts.get(slot).copied().unwrap_or(0)); + } + } + if !all { + // As `legend_with` lists them: the classes with a feature, and the fallback + // when it has one and draws something. + let visible = self.fallback_draws(ds); + entries.retain(|e| e.count != Some(0) && (!e.fallback || visible)); + } + } + Renderer::Graduated { .. } => { + if let Some(counts) = counts { + for (slot, e) in entries.iter_mut().enumerate() { + e.count = Some(counts.get(slot).copied().unwrap_or(0)); + } } - entries } - Renderer::Single(_) | Renderer::Proportional { .. } => listed(), + Renderer::Single(_) | Renderer::Proportional { .. } => {} } + entries } /// The order `legend()` lists the Unique Values classes in: their indices in `classes`, by diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 04df8125ab..e2f69ab964 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -373,10 +373,13 @@ fn draw_page( // What each legend's frame draws, worked out before any element is drawn: its map is synced // to that frame's view first, so a streamed layer holds that frame's features whichever order // the frames and legends come in, and whichever other frame showed the map last. + // A legend that counts features reads its streamed layers whole here too (#3238). let mut shown = Vec::new(); + let mut counted = Vec::new(); for e in layout.elements.iter().filter(visible) { - if let ElementKind::Legend { frame: f, all_classes: false, show_no_data, .. } = &e.kind - && !shown.iter().any(|(id, no_data, _)| id == f && no_data == show_no_data) + if let ElementKind::Legend { frame: f, all_classes, show_no_data, show_counts, exclude, .. } = &e.kind + && let classes = (!*all_classes && !shown.iter().any(|(id, no_data, _)| id == f && no_data == show_no_data)) + && (classes || show_counts.shown()) && let Some(&(_, mi, cam, fw, fh)) = frame(*f) && let Some(map) = maps.get_mut(mi) { @@ -386,13 +389,23 @@ fn draw_page( let scale = map.ground_res_at(&cam) / rustgis_geom::PIXEL_M; map.sync_sources_in(&lonlat, own.as_ref(), scale, true, env); let mut failed_source = None; - // Every layer, those a legend leaves out too: the frame draws them, and the legends of - // a frame share this read, each leaving out its own as it lists its rows. - let Some(entries) = complete_shown_legends(map, scale, *show_no_data, &[], &mut failed_source, env) else { - *source_error = failed_source_error(map, failed_source); - return None; - }; - shown.push((*f, *show_no_data, entries)); + if classes { + // Every layer, those a legend leaves out too: the frame draws them, and the legends + // of a frame share this read, each leaving out its own as it lists its rows. + let Some(entries) = complete_shown_legends(map, scale, *show_no_data, &[], &mut failed_source, env) else { + *source_error = failed_source_error(map, failed_source); + return None; + }; + shown.push((*f, *show_no_data, entries)); + } + if show_counts.shown() { + let asked = (*all_classes, *show_no_data); + let Some(counts) = complete_counted_legends(map, scale, asked, exclude, &mut failed_source, env) else { + *source_error = failed_source_error(map, failed_source); + return None; + }; + counted.push((e.id, counts)); + } } } for e in layout.elements.iter().filter(visible) { @@ -557,7 +570,10 @@ fn draw_page( exclude, labels, class_labels, - counts: show_counts.shown().then_some(env), + counts: show_counts.shown().then(|| Counts { + env, + streamed: counted.iter().find(|(id, _)| *id == e.id).map_or(&[][..], |(_, c)| c.as_slice()), + }), scale, size, text_size: *text_size, diff --git a/crates/render/src/layout/legend.rs b/crates/render/src/layout/legend.rs index 1192da57ec..44ef59c62a 100644 --- a/crates/render/src/layout/legend.rs +++ b/crates/render/src/layout/legend.rs @@ -86,7 +86,9 @@ pub(super) fn complete_shown_legends( } continue; }; - let unique = match &layer.renderer { + // Its own copy: the read below holds the layer. + let renderer = layer.renderer.clone(); + let unique = match &renderer { rustgis_map::Renderer::Unique { field, classes, .. } => Some((field, classes)), _ => None, }; @@ -104,13 +106,7 @@ pub(super) fn complete_shown_legends( let mut used = std::collections::HashSet::new(); let mut any = false; let mut no_data = None; - let mut chunk = layer.clone(); - chunk.source = None; - // Its chunks come in the source's own system. - chunk.dataset.held_in = source.coord_crs(); - chunk.clear_cache(); - let result = crate::visit_complete(source.as_ref(), &mut |features| { - chunk.dataset.features = features.into(); + read_whole(layer, source.as_ref(), failed_source, &mut |chunk| { let rows = chunk.drawn_rows_with(scale, env); if show_no_data && no_data.is_none() { no_data = chunk.renderer.no_data_legend(&chunk.dataset, Some(&rows)); @@ -136,19 +132,7 @@ pub(super) fn complete_shown_legends( } } } - chunk.dataset.features = Vec::new().into(); - Ok(()) - }); - if let Err(e) = result { - if let Some(source) = &mut layer.source { - source.error = Some(e.to_string()); - } - *failed_source = Some(layer.instance_id()); - return None; - } - if let Some(source) = &mut layer.source { - source.clear_error(); - } + })?; if any { // (A sample of the classes seen: classed again at this scale, by expression.) let mut entries = layer.with_size_legend(layer.renderer.legend_with(&sample, &[], style_env.clone())); @@ -159,6 +143,87 @@ pub(super) fn complete_shown_legends( Some(out) } +/// Gives `visit` each chunk of `layer`'s `source` read whole, as a copy of the layer holding it. A +/// failed traversal leaves the layer's error, gives its live identity for the page's source-error +/// report and returns `None`. +fn read_whole( + layer: &mut rustgis_map::Layer, + source: &dyn rustgis_data::source::FeatureSource, + failed_source: &mut Option, + visit: &mut dyn FnMut(&rustgis_map::Layer), +) -> Option<()> { + let mut chunk = layer.clone(); + chunk.source = None; + // Its chunks come in the source's own system. + chunk.dataset.held_in = source.coord_crs(); + chunk.clear_cache(); + let result = crate::visit_complete(source, &mut |features| { + chunk.dataset.features = features.into(); + visit(&chunk); + chunk.dataset.features = Vec::new().into(); + Ok(()) + }); + if let Err(e) = result { + if let Some(source) = &mut layer.source { + source.error = Some(e.to_string()); + } + *failed_source = Some(layer.instance_id()); + return None; + } + if let Some(source) = &mut layer.source { + source.clear_error(); + } + Some(()) +} + +/// What a streamed layer's legend shows from its whole source: its rows with their numbers and its +/// number of drawn features; `None` for one a legend of what its frame draws leaves out. +pub(super) type StreamedCount = (u32, Option<(Vec, u64)>); + +/// Counts the features of a legend's streamed layers (#3238), whose own features are the view's: +/// one whole read of each source that offers one (a local file). A layer read from a database or +/// over the web has no entry here, and shows no numbers. With `all`, every visible layer and class; +/// without, what the frame draws at 1:`scale`. A layer named in `exclude` isn't read. It reads on +/// the caller's thread, as [`complete_shown_legends`] does: the layout view's is the UI's (#3253). +pub(super) fn complete_counted_legends( + map: &mut Map, + scale: f64, + (all, show_no_data): (bool, bool), + exclude: &[String], + failed_source: &mut Option, + env: &Env, +) -> Option> { + let excluded = |name: &str| exclude.iter().any(|n| n.eq_ignore_ascii_case(name)); + let wanted: Vec = map + .layers + .iter() + .enumerate() + .filter(|(_, l)| { + let listed = if all { map.shows(l) } else { map.draws_at(l, scale) }; + l.dataset.windowed && !l.is_raster() && listed && legend_lists(l) && !excluded(&l.name) + }) + .map(|(i, _)| i) + .collect(); + let mut out = Vec::new(); + for index in wanted { + let layer = map.layers.get_mut(index)?; + let Some(source) = layer.source.as_ref().and_then(|s| s.count_source()) else { continue }; + let mut count = rustgis_map::LegendCount::default(); + read_whole(layer, source.as_ref(), failed_source, &mut |chunk| chunk.count_for_legend(scale, env, &mut count))?; + let shown = (all || count.total() > 0).then(|| layer.legend_of_count(&count, all, show_no_data)); + out.push((layer.id, shown)); + } + Some(out) +} + +/// The features a legend counts (#3237): those of the layers holding all of theirs, on the page +/// `env`, and the streamed layers' from [`complete_counted_legends`]. +#[derive(Clone, Copy)] +pub(super) struct Counts<'a> { + pub(super) env: &'a Env, + pub(super) streamed: &'a [StreamedCount], +} + /// What a legend leaves out: ``, layers' names over their classes and pictures /// (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 @@ -172,8 +237,8 @@ pub(super) struct LegendOptions<'a> { pub(super) exclude: &'a [String], pub(super) labels: &'a BTreeMap, pub(super) class_labels: &'a ClassLabels, - /// The page its features are counted on (#3237); none, no numbers. - pub(super) counts: Option<&'a Env>, + /// Its features' numbers (#3237); none, no numbers. + pub(super) counts: Option>, pub(super) scale: f64, pub(super) size: f32, pub(super) text_size: f64, @@ -967,27 +1032,34 @@ pub(super) fn legend_rows_missing<'a>( if !(map.shows(l) && legend_lists(l) && !excluded(&l.name)) { continue; } - let listed = match drawn { - Some(d) => match d.iter().find(|(id, _)| *id == l.id) { - Some((_, entries)) => Some(entries), - None => continue, - }, - None => None, - }; - // Counted from the features themselves, so only a vector layer holding all of them: a - // streamed one holds the view's (#3237, #3238). - let counted = opts - .counts - .filter(|_| !l.is_raster() && !l.dataset.windowed) - .map(|env| l.counted_legend(opts.scale, env, listed.is_none(), opts.show_no_data)); - let (mut entries, total) = match counted { - Some((entries, total)) => (entries, Some(total)), - None => { - let mut entries = listed.map_or_else(|| every_class(l), Clone::clone); - if listed.is_none() && opts.show_no_data { - entries.extend(l.renderer.no_data_legend(&l.dataset, None)); + // A streamed layer read whole for its numbers lists what the whole source gives. + let streamed = opts.counts.and_then(|c| c.streamed.iter().find(|(id, _)| *id == l.id)); + let (mut entries, total) = if let Some((_, shown)) = streamed { + let Some((entries, total)) = shown else { continue }; + (entries.clone(), Some(*total)) + } else { + let listed = match drawn { + Some(d) => match d.iter().find(|(id, _)| *id == l.id) { + Some((_, entries)) => Some(entries), + None => continue, + }, + None => None, + }; + // Counted from the features themselves, so only a vector layer holding all of them: a + // streamed one holds the view's (#3237). + let counted = opts + .counts + .filter(|_| !l.is_raster() && !l.dataset.windowed) + .map(|c| l.counted_legend(opts.scale, c.env, listed.is_none(), opts.show_no_data)); + match counted { + Some((entries, total)) => (entries, Some(total)), + None => { + let mut entries = listed.map_or_else(|| every_class(l), Clone::clone); + if listed.is_none() && opts.show_no_data { + entries.extend(l.renderer.no_data_legend(&l.dataset, None)); + } + (entries, None) } - (entries, None) } }; // The fallback row only (a class that happens to bear its name stays). @@ -1340,10 +1412,11 @@ pub struct LegendFitted { fn asked_rows(map: &mut Map, scale: f64, asked: &LegendAsked, with: impl FnOnce(&[LegendRow]) -> T) -> Option { let LegendAsked { all_classes, hide_other, show_no_data, layer_names, text_size, exclude, labels, class_labels, show_counts } = *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::default())?) }; + let drawn = if all_classes { None } else { Some(complete_shown_legends(map, scale, show_no_data, exclude, &mut None, &env)?) }; let size = legend_size(text_size); - let counts = show_counts.then_some(&env); + let streamed = + if show_counts { complete_counted_legends(map, scale, (all_classes, show_no_data), exclude, &mut None, &env)? } else { Vec::new() }; + let counts = show_counts.then_some(Counts { env: &env, streamed: &streamed }); let opts = LegendOptions { show_no_data, hide_other, names: layer_names, exclude, labels, class_labels, counts, scale, size, text_size }; Some(with(&legend_rows(map, drawn.as_deref(), &opts))) @@ -1415,3 +1488,6 @@ pub fn legend_title_width_mm(title: &str, text_size: f64) -> f64 { pub fn legend_title_mm(text_size: f64) -> f64 { f64::from(LEGEND_ROW * legend_size(text_size)) * f64::from(LEGEND_TITLE_ROWS) * 25.4 / 96.0 } + +#[cfg(test)] +mod count_tests; diff --git a/crates/render/src/layout/legend/count_tests.rs b/crates/render/src/layout/legend/count_tests.rs new file mode 100644 index 0000000000..11abcea534 --- /dev/null +++ b/crates/render/src/layout/legend/count_tests.rs @@ -0,0 +1,421 @@ +//! Feature counts of a legend's streamed layers (#3238). + +use super::*; +use rustgis_data::source::{Batch, FeatureSource, Request, SourceInfo}; +use rustgis_data::{Dataset, Feature, Field, FieldType, Geometry, Value}; +use rustgis_map::source::SourceLayer; +use rustgis_map::{Layer, Renderer, Symbol}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// A file source holding `ds`, whose view reads the first feature alone. +struct Whole { + info: SourceInfo, + ds: Dataset, + /// Whether the map draws it by complete traversal, as a Shapefile; else it can only be read + /// whole, as a GeoPackage. + streams: bool, + visits: bool, + /// A whole read stops after its first chunk. + fails: bool, + passes: Arc, +} + +impl FeatureSource for Whole { + fn info(&self) -> &SourceInfo { + &self.info + } + fn read(&self, _: &Request) -> rustgis_data::Result { + Ok(Batch { + features: self.ds.features.iter().take(1).cloned().collect(), + matched: self.ds.features.len() as u64, + ..Default::default() + }) + } + fn streams_chunks(&self) -> bool { + self.streams + } + fn visits_chunks(&self) -> bool { + self.visits + } + fn visit_chunks( + &self, + _: Option, + _: usize, + visit: &mut dyn FnMut(Vec) -> rustgis_data::Result<()>, + ) -> rustgis_data::Result { + self.passes.fetch_add(1, Ordering::Relaxed); + for chunk in self.ds.features.chunks(2) { + visit(chunk.to_vec())?; + if self.fails { + return Err(rustgis_data::DataError::Format("the file broke off".into())); + } + } + Ok(Batch { complete: true, matched: self.ds.features.len() as u64, ..Default::default() }) + } +} + +#[derive(Clone, Copy)] +struct Reads { + streams: bool, + visits: bool, + fails: bool, + format: &'static str, +} + +const FILE: Reads = Reads { streams: false, visits: true, fails: false, format: "test" }; + +/// `layer` read in place from a source holding all its features, holding the first alone, and the +/// source's count of whole reads. +fn in_place(layer: &mut Layer, reads: Reads) -> Arc { + let ds = layer.dataset.clone(); + let info = SourceInfo { + name: ds.name.clone(), + format: reads.format, + geometry_type: ds.geometry_type, + fields: ds.fields.clone(), + extent: ds.extent(), + count: Some(ds.features.len() as u64), + crs: "EPSG:4326".into(), + indexed: true, + notes: Default::default(), + zm_dropped: false, + }; + let passes = Arc::new(AtomicUsize::new(0)); + let Reads { streams, visits, fails, .. } = reads; + layer.dataset.features = ds.features.iter().take(1).cloned().collect::>().into(); + layer.dataset.windowed = true; + let source = Whole { info, ds, streams, visits, fails, passes: passes.clone() }; + layer.source = Some(SourceLayer::from_path("test.gpkg", None, Box::new(source))); + passes +} + +/// Points `"pts"` with these values of `g`, in Unique Values of `a`, `b` and `c`. +fn classed(values: &[&str]) -> Map { + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); + for v in values { + ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text((*v).into())]); + } + let mut map = Map::new("m"); + map.add_dataset(ds); + let symbol = Symbol::default_for(GeometryType::Point, 0); + map.layers[0].renderer = unique(["a", "b", "c"].map(String::from).to_vec(), symbol, None); + map +} + +fn unique(classes: Vec, symbol: Symbol, expression: Option) -> Renderer { + Renderer::Unique { + field: "g".into(), + classes: classes.into_iter().map(|c| (c, symbol)).collect(), + other: symbol, + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression, + } +} + +/// `a` three times, `b` twice and one value no class has: in chunks of two, in file order. +const VALUES: [&str; 6] = ["a", "b", "a", "zz", "b", "a"]; + +static NO_CLASS_LABELS: ClassLabels = ClassLabels::NONE; + +fn asked(all_classes: bool, show_no_data: bool, show_counts: bool) -> LegendAsked<'static> { + static LABELS: BTreeMap = BTreeMap::new(); + LegendAsked { + all_classes, + hide_other: false, + show_no_data, + layer_names: true, + text_size: 9.0, + exclude: &[], + labels: &LABELS, + class_labels: &NO_CLASS_LABELS, + show_counts, + } +} + +/// The text of each row of the legend `asked`, or `None` when it can't be read. +fn texts(map: &mut Map, asked: &LegendAsked) -> Option> { + asked_rows(map, 1e6, asked, |rows| { + rows.iter() + .map(|r| match r { + LegendRow::Head(n) => n.to_string(), + LegendRow::Plain(_, n) => n.to_string(), + LegendRow::Class(_, e) => e.label.clone(), + LegendRow::Picture(_) => "picture".into(), + }) + .collect() + }) +} + +fn counted(map: &mut Map, all_classes: bool, show_no_data: bool) -> Vec { + texts(map, &asked(all_classes, show_no_data, true)).unwrap() +} + +#[test] +fn a_streamed_layers_classes_count_the_whole_source() { + for streams in [false, true] { + let mut map = classed(&VALUES); + in_place(&mut map.layers[0], Reads { streams, ..FILE }); + assert_eq!(counted(&mut map, false, false), ["pts", "a (3)", "b (2)", " (1)"], "streams {streams}"); + assert_eq!(counted(&mut map, true, false), ["pts", "a (3)", "b (2)", "c (0)", " (1)"], "streams {streams}"); + } +} + +#[test] +fn a_streamed_layer_of_one_symbol_counts_the_whole_source() { + let mut map = classed(&VALUES); + map.layers[0].renderer = Renderer::Single(Symbol::default_for(GeometryType::Point, 0)); + in_place(&mut map.layers[0], FILE); + assert_eq!(counted(&mut map, false, false), ["pts (6)"]); + assert_eq!(counted(&mut map, true, false), ["pts (6)"]); +} + +/// Points `"g"` with these values of `v`, in two ranges of Graduated Colors. +fn graduated(values: &[Value]) -> Map { + let mut ds = Dataset::new("g", GeometryType::Point, vec![Field::new("v", FieldType::Double)]); + for v in values.iter().cloned() { + ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![v]); + } + let mut map = Map::new("m"); + map.add_dataset(ds); + let symbol = Symbol::default_for(GeometryType::Point, 0); + map.layers[0].renderer = Renderer::Graduated { + field: "v".into(), + breaks: vec![5.0, 10.0], + symbols: vec![symbol, symbol], + ramp: rustgis_map::Ramp::Ember, + method: rustgis_map::ClassMethod::NaturalBreaks, + min: 0.0, + classes: 2, + class_labels: BTreeMap::from([(0, "Low".into()), (1, "High".into())]), + class_strokes: Default::default(), + class_fills: Default::default(), + }; + map +} + +#[test] +fn a_streamed_layers_ranges_and_missing_values_are_counted() { + let mut map = graduated(&[Value::Float(1.0), Value::Float(2.0), Value::Null, Value::Float(9.0), Value::Null]); + in_place(&mut map.layers[0], FILE); + assert_eq!(counted(&mut map, false, true), ["g", "Low (2)", "High (1)", "No data (2)"]); +} + +#[test] +fn a_streamed_layer_counts_only_what_it_draws() { + let mut map = classed(&VALUES); + in_place(&mut map.layers[0], FILE); + map.layers[0].definition_query = Some("g <> 'b'".into()); + assert_eq!(counted(&mut map, false, false), ["pts", "a (3)", " (1)"]); + map.layers[0].display_filters = + vec![rustgis_map::effects::DisplayFilter { name: "a".into(), min_scale: None, max_scale: None, where_: "g = 'a'".into() }]; + assert_eq!(counted(&mut map, false, false), ["pts", "a (3)"]); + // Nothing kept: what the frame draws leaves it out, and every class says none. + map.layers[0].definition_query = Some("g = 'nothing'".into()); + assert_eq!(counted(&mut map, false, false), [""; 0]); + assert_eq!(counted(&mut map, true, false), ["pts", "a (0)", "b (0)", "c (0)", " (0)"]); + // Out of its scale range at the frame's 1:1,000,000. + map.layers[0].definition_query = None; + map.layers[0].display_filters = Vec::new(); + map.layers[0].max_scale = Some(5e6); + assert_eq!(counted(&mut map, false, false), [""; 0]); +} + +/// A database, a file read over the web or a source not open: no whole read, so no numbers, and +/// the classes of what the layer holds, as before. +#[test] +fn a_layer_whose_source_cannot_be_read_whole_has_no_counts() { + let mut map = classed(&VALUES); + let passes = in_place(&mut map.layers[0], Reads { visits: false, ..FILE }); + assert_eq!(counted(&mut map, false, false), ["pts", "a"]); + assert_eq!(passes.load(Ordering::Relaxed), 0); + map.layers[0].source = None; + assert_eq!(counted(&mut map, false, false), ["pts", "a"]); +} + +#[test] +fn a_failed_count_stops_the_legend() { + for all_classes in [false, true] { + let mut map = classed(&VALUES); + in_place(&mut map.layers[0], Reads { fails: true, ..FILE }); + assert_eq!(texts(&mut map, &asked(all_classes, false, true)), None); + assert!(map.layers[0].source.as_ref().unwrap().read_error().unwrap().contains("the file broke off")); + } +} + +#[test] +fn a_legend_without_counts_reads_no_source_whole() { + let mut map = classed(&VALUES); + let passes = in_place(&mut map.layers[0], FILE); + for all_classes in [false, true] { + texts(&mut map, &asked(all_classes, false, false)).unwrap(); + } + assert_eq!(passes.load(Ordering::Relaxed), 0); + // A layer the legend leaves out isn't read for it. + let exclude = ["PTS".to_string()]; + texts(&mut map, &LegendAsked { exclude: &exclude, ..asked(false, false, true) }).unwrap(); + assert_eq!(passes.load(Ordering::Relaxed), 0); +} + +/// Classing by expression is bounded over the whole source, not chunk by chunk. +#[test] +fn a_streamed_layer_too_large_to_class_by_expression_has_no_counts() { + let mut map = classed(&["0"; 101]); + let symbol = Symbol::default_for(GeometryType::Point, 0); + let classes: Vec = (0..20_000).map(|n| n.to_string()).collect(); + map.layers[0].renderer = unique(classes, symbol, Some("g".into())); + let loaded = counted(&mut map, false, false); + in_place(&mut map.layers[0], FILE); + let streamed = counted(&mut map, false, false); + assert_eq!(streamed, loaded); + assert!(streamed.iter().all(|t| !t.ends_with(')')), "{:?}", &streamed[..3]); +} + +#[test] +fn a_streamed_layers_diagram_rows_have_no_counts() { + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + for n in 0..3 { + ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Int(n)]); + } + let mut map = Map::new("m"); + map.add_dataset(ds); + map.layers[0].renderer = Renderer::Single(Symbol::default_for(GeometryType::Point, 0)); + map.layers[0].diagram = Some(rustgis_map::DiagramSettings { + kind: rustgis_map::DiagramKind::Pie, + categories: vec![rustgis_map::DiagramCategory { field: "n".into(), colour: Rgba::rgb(255, 0, 0) }], + size: rustgis_map::DiagramSize::Fixed(12.0), + start_angle: 0.0, + background: None, + stroke: rustgis_map::DiagramSettings::default_stroke(), + stroke_width: 0.75, + labels: rustgis_map::DiagramLabel::None, + }); + in_place(&mut map.layers[0], FILE); + assert_eq!(counted(&mut map, false, false), ["pts (3)", "n"]); +} + +/// A live service is read a view at a time, whatever it can give a tool or an export. +#[test] +fn a_live_service_is_not_read_for_counts() { + let mut map = classed(&VALUES); + let passes = in_place(&mut map.layers[0], Reads { format: rustgis_data::source::arcgis::FORMAT, ..FILE }); + assert_eq!(counted(&mut map, false, false), ["pts", "a"]); + assert_eq!(passes.load(Ordering::Relaxed), 0); +} + +#[test] +fn a_streamed_layer_of_no_features_counts_none_in_every_class() { + let mut map = classed(&[]); + in_place(&mut map.layers[0], FILE); + assert_eq!(counted(&mut map, true, false), ["pts", "a (0)", "b (0)", "c (0)", " (0)"]); + let mut map = graduated(&[]); + in_place(&mut map.layers[0], FILE); + assert_eq!(counted(&mut map, true, true), ["g", "Low (0)", "High (0)", "No data (0)"]); +} + +/// A legend's size is measured on the rows as drawn, numbers included. +#[test] +fn a_streamed_legend_is_measured_with_its_numbers() { + let mut loaded = classed(&VALUES); + let mut map = classed(&VALUES); + in_place(&mut map.layers[0], FILE); + for all_classes in [false, true] { + let asked = asked(all_classes, false, true); + assert_eq!(legend_size_asked_mm(&mut map, 1e6, &asked, 1), legend_size_asked_mm(&mut loaded, 1e6, &asked, 1)); + } +} + +/// A map frame of the map `"m"` and a legend of it that counts features. +fn counts_page(all_classes: bool) -> rustgis_map::layout::Layout { + use rustgis_map::layout::{ElementKind, Layout}; + let mut page = Layout::new("Counts", 120.0, 90.0); + let frame = page.add( + "Frame", + (5.0, 5.0, 50.0, 50.0), + ElementKind::MapFrame { + map: "m".into(), + center: Coord::new(0.0, 0.0), + scale: 1e6, + bearing: 0.0, + pitch: 0.0, + shape: Default::default(), + grid: None, + sections: Vec::new(), + extent_of: None, + extent_color: rustgis_map::layout::INDICATOR_COLOR, + extent_width: rustgis_map::layout::INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + }, + ); + page.add( + "Legend", + (60.0, 5.0, 55.0, 80.0), + ElementKind::Legend { + frame, + title: String::new(), + all_classes, + hide_other: false, + show_no_data: false, + exclude: Vec::new(), + columns: 1, + labels: BTreeMap::new(), + color: None, + text_size: rustgis_map::layout::LEGEND_TEXT_PT, + fit: rustgis_map::layout::LegendFit::Manual, + show_layer_names: rustgis_map::layout::LayerNames::Shown, + class_labels: Default::default(), + show_counts: rustgis_map::layout::FeatureCounts::from_shown(true), + }, + ); + page +} + +/// The page draws a streamed layer's numbers as it does a loaded one's, whether the legend lists +/// every class or what its frame draws; a count that fails stops the page, naming the source. +#[test] +fn a_page_counts_a_streamed_layer() { + let page = counts_page; + // The legend element alone: the frame's own drawing reads a GeoPackage by view. + let draw = |page: &Layout, map: &Map| { + let legend = page.elements[1].id; + crate::layout::render_element(page, legend, &mut [map.clone()], 96.0, (&Default::default(), &Env::default()), &mut None) + .map(|e| e.unwrap().0.data().to_vec()) + }; + for all_classes in [false, true] { + let page = page(all_classes); + let loaded = classed(&VALUES); + let mut map = classed(&VALUES); + in_place(&mut map.layers[0], FILE); + assert_eq!(draw(&page, &map), draw(&page, &loaded), "all classes {all_classes}"); + in_place(&mut map.layers[0], Reads { fails: true, ..FILE }); + let error = crate::layout::render(&page, &mut [map], 96.0, &Default::default()).unwrap_err(); + assert!(error.contains("pts") && error.contains("the file broke off"), "{error}"); + } +} + +/// Legends sharing a frame share its classes' read; each still counts its own numbers. +#[test] +fn every_legend_of_a_frame_counts_a_streamed_layer() { + use rustgis_map::layout::ElementKind; + for kinds in [[false, false], [false, true], [true, false]] { + let mut page = counts_page(kinds[0]); + // The legends alone are drawn: the frame's own drawing reads a GeoPackage by view. + page.elements[0].visible = false; + let mut second = page.elements[1].kind.clone(); + if let ElementKind::Legend { all_classes, .. } = &mut second { + *all_classes = kinds[1]; + } + page.add("Second", (5.0, 5.0, 50.0, 80.0), second); + let draw = |map: Map| crate::layout::render(&page, &mut [map], 96.0, &Default::default()).unwrap().data().to_vec(); + let mut map = classed(&VALUES); + in_place(&mut map.layers[0], FILE); + assert!(draw(map) == draw(classed(&VALUES)), "all classes {kinds:?}"); + } +} diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index dcc228b30b..d999147ba8 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -8409,7 +8409,7 @@ fn a_legend_counts_the_features_of_each_row() { exclude: &[], labels: &NO_LABELS, class_labels: own, - counts: counted.then_some(&env), + counts: counted.then_some(Counts { env: &env, streamed: &[] }), scale: 1e6, size: 1.0, text_size: 9.0, diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 71098f5d41..0b40712e77 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -466,9 +466,12 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu layer drawn in one symbol, ends in the number of features it stands for, such as `Highway (12)`: those the layer's definition query, display filters and time window keep (the page's in a map series), wherever the frame looks. A class with none shows `(0)` where every - class is listed. Rasters, web layers, size and diagram rows, streamed layers (read in place, a - view at a time), and Unique Values by an expression over too many features and classes show no - number. + class is listed. A layer read in place from a Shapefile, GeoPackage, FlatGeobuf or GeoParquet + file on this computer is counted by reading the whole file each time the page is drawn; with + the classes limited to what the frame draws, it then lists those of the whole file. Rasters, + web layers, size and diagram rows, layers read from a database, over the web or a view at a + time from other files, and Unique Values by an expression over too many features and classes + show no number. A project with such a legend can't be opened by an older RustGIS. - **In scripts and files**: scripts set `"fit": "adjustSize"` and `"showLayerNames": false` on `layout.addElement` and `layout.update` (a scale bar's `fit` takes its own values); an unknown