Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/assistant/skills/print-layout/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"` (`{"<layer>": {"<class label>": "<text>"}}`: its own text for a
class, the layer keeping its label).
A `"text"` or `"dynamicText"` can take
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ pub fn commands() -> Vec<C> {
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"?: {"<layer>": {"<class label>": "<text>"}} (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), "##,
Expand Down
68 changes: 55 additions & 13 deletions crates/map/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u64>,
/// 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 {
Expand Down Expand Up @@ -1892,29 +1913,50 @@ 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,
env: &rustgis_data::query::Env,
all: bool,
no_data: bool,
) -> (Vec<symbology::LegendEntry>, 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;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// 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<symbology::LegendEntry>, 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:
Expand Down
7 changes: 7 additions & 0 deletions crates/map/src/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Arc<dyn FeatureSource>> {
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<Arc<dyn FeatureSource>> {
self.handle.as_ref().filter(|h| h.visits_extent_chunks()).cloned()
Expand Down
102 changes: 54 additions & 48 deletions crates/map/src/symbology.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<LegendEntry> {
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;
Expand Down Expand Up @@ -1877,58 +1867,74 @@ 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<LegendEntry> {
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 `<all other values>`; 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<u64>) {
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<LegendEntry> = 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)
{
*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<LegendEntry> {
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
Expand Down
36 changes: 26 additions & 10 deletions crates/render/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand All @@ -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) {
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading