diff --git a/crates/engine/src/cmd/layout/text.rs b/crates/engine/src/cmd/layout/text.rs index 70716bde3d..2cad82ed9c 100644 --- a/crates/engine/src/cmd/layout/text.rs +++ b/crates/engine/src/cmd/layout/text.rs @@ -189,17 +189,21 @@ pub(in crate::cmd::layout) fn first_frame_map(s: &Session, li: usize) -> Option< } } -/// [`say_text_statistics`] for every text of the layout `li`, a publication's or an import's, which -/// come with their texts already in it. +/// What [`say_text_statistics`] says, for every text of the layout `li`, a publication's or an +/// import's, which come with their texts already in it; their figures read together, one pass over +/// each layer. pub(in crate::cmd::layout) fn say_layout_text_statistics(s: &mut Session, li: usize) { - let texts: Vec = s - .project - .layouts - .get(li) - .map(|l| l.elements.iter().filter(|e| matches!(e.kind, ElementKind::Text { .. })).map(|e| e.id).collect()) - .unwrap_or_default(); - for id in texts { - say_text_statistics(s, li, id); + let Some(l) = s.project.layouts.get(li) else { return }; + let texts: Vec<&str> = l + .elements + .iter() + .filter_map(|e| match &e.kind { + ElementKind::Text { text, .. } => Some(text.as_str()), + _ => None, + }) + .collect(); + for w in rustgis_render::layout::statistic_notices_each(l, &s.project.maps, &texts).into_iter().flatten() { + s.warn(w); } } diff --git a/crates/render/src/layout/dynamic_text.rs b/crates/render/src/layout/dynamic_text.rs index 974e54658f..86a2f4cd1f 100644 --- a/crates/render/src/layout/dynamic_text.rs +++ b/crates/render/src/layout/dynamic_text.rs @@ -1,6 +1,13 @@ //! The tokens a layout's texts hold: page, scale and a layer's statistics. use super::*; +use std::collections::{HashMap, HashSet}; + +#[cfg(test)] +thread_local! { + /// The passes [`figures_of`] has made over a layer on this thread. + pub(super) static PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} /// A scale as `{scale}` prints it: `1:6,300,000`, or `1:6.300.000` with a decimal comma. pub fn scale_ratio_text(scale: f64, comma: bool) -> String { @@ -54,6 +61,12 @@ pub fn expand(t: &str, layout: &Layout, info: &PageInfo, frame: Option<(&Map, ru /// a figure over a layer read in place, which covers only the features loaded, has a line for that /// as well. pub fn statistic_notices(layout: &Layout, maps: &[Map], text: &str) -> Vec { + statistic_notices_each(layout, maps, &[text]).pop().unwrap_or_default() +} + +/// [`statistic_notices`] of each of `texts`, their figures read together: one pass over each layer +/// they name, however many of them name it. +pub fn statistic_notices_each(layout: &Layout, maps: &[Map], texts: &[&str]) -> Vec> { let map = layout.first_frame().and_then(|f| match &layout.element(f)?.kind { ElementKind::MapFrame { map, .. } => maps.get(map_index(maps, map)?), _ => None, @@ -62,26 +75,38 @@ pub fn statistic_notices(layout: &Layout, maps: &[Map], text: &str) -> Vec "the map of the layout's first frame is not in the project", None => "the layout has no map frame whose map it would read", }; - notices_over(map.ok_or(no_map), "the map of the layout's first frame", text) + notices_over(map.ok_or(no_map), "the map of the layout's first frame", texts) } /// [`statistic_notices`] for a text whose figures are read from `map`, which the notices call /// `whose`: a presentation map page's title, drawn over that page's own map. pub fn map_statistic_notices(map: &Map, whose: &str, text: &str) -> Vec { - notices_over(Ok(map), whose, text) + notices_over(Ok(map), whose, &[text]).pop().unwrap_or_default() } -/// The notices of `text`'s figures over `map`, or why there is none to read. -pub(super) fn notices_over(map: Result<&Map, &str>, whose: &str, text: &str) -> Vec { +/// The notices of each of `texts`' figures over `map`, or why there is none to read. +fn notices_over(map: Result<&Map, &str>, whose: &str, texts: &[&str]) -> Vec> { + let tokens = distinct_stat_tokens(texts, true); + // Each layer's figures in one pass, whatever their number and the texts that hold them. + let figures: HashMap<&str, Figure> = match map { + Ok(m) => tokens.iter().map(|t| t.token).zip(figures_of(m, &tokens)).collect(), + Err(_) => HashMap::new(), + }; + texts.iter().map(|text| notices_of(map, whose, &distinct_stat_tokens(&[text], true), &figures)).collect() +} + +/// The notices of one text, which holds `tokens`, with `figures` those [`figures_of`] found. +fn notices_of( + map: Result<&Map, &str>, + whose: &str, + tokens: &[rustgis_map::layout::StatToken<'_>], + figures: &HashMap<&str, Figure>, +) -> Vec { use rustgis_map::layout::StatMissing; let mut said: Vec = Vec::new(); - let tokens = distinct_stat_tokens(text, true); - // Each layer's figures in one pass, whatever their number. - let figures: Vec)>>> = match map { - Ok(m) => figures_of(m, &tokens).into_iter().map(Some).collect(), - Err(_) => vec![None; tokens.len()], - }; - for (t, found) in tokens.iter().zip(figures) { + for t in tokens { + // Nothing read: there is no map. + let found = figures.get(t.token).copied(); let (layer, field) = (t.layer, t.field.unwrap_or_default()); // A layer read in place holds only what is loaded, so its figure is partial, and one with // no number yet gets some as more is loaded. @@ -117,7 +142,7 @@ pub(super) fn statistics(t: &str, comma: bool, map: Option<&Map>) -> String { let mut out = t.to_string(); // `replace` below puts in every occurrence, so a repeated token is worked out once, and the // figures of one layer in one pass over it. - let tokens = distinct_stat_tokens(t, false); + let tokens = distinct_stat_tokens(&[t], false); for (s, figure) in tokens.iter().zip(figures_of(m, &tokens)) { if let Some((_, Ok(v))) = figure { out = out.replace(s.token, &decimal(rustgis_map::layout::chart_value_text(v, None), comma)); @@ -130,55 +155,48 @@ pub(super) fn statistics(t: &str, comma: bool, map: Option<&Map>) -> String { /// pairs for the tokens that have a figure, each token once: what a publication measures its texts /// with, so a box is sized for the figures it will show, not for the tokens written. pub fn statistic_figures(map: &Map, comma: bool, texts: &[&str]) -> Vec<(String, String)> { - let mut pairs: Vec<(String, String)> = Vec::new(); - for text in texts { - let tokens = distinct_stat_tokens(text, false); - for (s, figure) in tokens.iter().zip(figures_of(map, &tokens)) { - if let Some((_, Ok(v))) = figure - && !pairs.iter().any(|(token, _)| token == s.token) - { - pairs.push((s.token.to_string(), decimal(rustgis_map::layout::chart_value_text(v, None), comma))); - } - } - } - pairs + let tokens = distinct_stat_tokens(texts, false); + tokens + .iter() + .zip(figures_of(map, &tokens)) + .filter_map(|(s, figure)| { + let v = figure?.1.ok()?; + Some((s.token.to_string(), decimal(rustgis_map::layout::chart_value_text(v, None), comma))) + }) + .collect() } -/// The statistic tokens of `text`, each once, in the order they come; with `gaps`, the figures +/// The statistic tokens of `texts`, each once, in the order they come; with `gaps`, the figures /// written without their field too. -pub(super) fn distinct_stat_tokens(text: &str, gaps: bool) -> Vec> { - let mut tokens: Vec> = Vec::new(); - let read = if gaps { rustgis_map::layout::stat_tokens_and_gaps(text) } else { rustgis_map::layout::stat_tokens(text) }; - for t in read { - if !tokens.iter().any(|seen| seen.token == t.token) { - tokens.push(t); - } - } - tokens +pub(super) fn distinct_stat_tokens<'a>(texts: &[&'a str], gaps: bool) -> Vec> { + let read = if gaps { rustgis_map::layout::stat_tokens_and_gaps } else { rustgis_map::layout::stat_tokens }; + let mut seen = HashSet::new(); + texts.iter().flat_map(|text| read(text)).filter(|t| seen.insert(t.token)).collect() } -/// The figure of each of `tokens` in `map`, with whether its layer is read in place; none for a token -/// whose layer the map lacks. The figures of one layer are worked out in one pass over its rows -/// ([`rustgis_map::layout::layer_statistics`]), so a text with many figures costs a pass for each +/// A token's figure in a map, with whether its layer is read in place; none where the map lacks the +/// layer. +type Figure = Option<(bool, Result)>; + +/// The [`Figure`] of each of `tokens` in `map`. The figures of one layer are worked out in one pass +/// over its rows ([`rustgis_map::layout::layer_statistics`]), so many figures cost a pass for each /// layer, not for each figure. -pub(super) fn figures_of( - map: &Map, - tokens: &[rustgis_map::layout::StatToken<'_>], -) -> Vec)>> { +pub(super) fn figures_of(map: &Map, tokens: &[rustgis_map::layout::StatToken<'_>]) -> Vec
{ + // A layer is named without regard to case. + let mut layers: HashMap> = HashMap::new(); + for (i, t) in tokens.iter().enumerate() { + layers.entry(t.layer.to_ascii_lowercase()).or_default().push(i); + } let mut out = vec![None; tokens.len()]; - let mut done = vec![false; tokens.len()]; - for i in 0..tokens.len() { - if done[i] { - continue; - } - let same: Vec = (i..tokens.len()).filter(|j| !done[*j] && tokens[*j].layer.eq_ignore_ascii_case(tokens[i].layer)).collect(); - for j in &same { - done[*j] = true; - } - let Some(layer) = map.layer_by_name(tokens[i].layer) else { continue }; - let wanted: Vec<_> = same.iter().map(|j| (tokens[*j].stat, tokens[*j].field)).collect(); - for (j, figure) in same.iter().zip(rustgis_map::layout::layer_statistics(layer, &wanted)) { - out[*j] = Some((layer.is_streamed(), figure)); + for same in layers.values() { + let Some(layer) = same.first().and_then(|i| map.layer_by_name(tokens.get(*i)?.layer)) else { continue }; + let wanted: Vec<_> = same.iter().filter_map(|i| tokens.get(*i)).map(|t| (t.stat, t.field)).collect(); + #[cfg(test)] + PASSES.with(|n| n.set(n.get() + 1)); + for (i, figure) in same.iter().zip(rustgis_map::layout::layer_statistics(layer, &wanted)) { + if let Some(slot) = out.get_mut(*i) { + *slot = Some((layer.is_streamed(), figure)); + } } } out diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 1d047805fe..a1ba0c828a 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -5,6 +5,7 @@ mod legend_breaks; mod legend_patch; mod legend_row; mod scale_bar_labels; +mod statistic_passes; thread_local! { /// How often [`LegendRow::symbol_side`] measured a row on this thread, and diff --git a/crates/render/src/layout/tests/statistic_passes.rs b/crates/render/src/layout/tests/statistic_passes.rs new file mode 100644 index 0000000000..0059d25533 --- /dev/null +++ b/crates/render/src/layout/tests/statistic_passes.rs @@ -0,0 +1,78 @@ +//! The statistics of many texts read each layer once (#3132). + +use super::super::dynamic_text::PASSES; +use super::*; +use rustgis_data::{Dataset, Field, FieldType, GeometryType, Value}; + +/// Layers `A` (read in place) and `B`, each of one row with a number in `f`. +fn map() -> Map { + let mut map = Map::new("m"); + for name in ["A", "B"] { + let mut ds = Dataset::new(name, GeometryType::None, vec![Field::new("f", FieldType::Double)]); + ds.push(None, vec![Value::Float(2.0)]); + map.add_dataset(ds); + } + map.layers.iter_mut().find(|l| l.name == "A").unwrap().source = Some(Default::default()); + map +} + +/// A layout with a frame of the map `frame`, or with no frame. +fn layout(frame: Option<&str>) -> Layout { + let mut layout = Layout::new("L", 100.0, 100.0); + if let Some(map) = frame { + let kind = serde_json::from_value(serde_json::json!({"MapFrame": {"map": map, "center": {"x": 0, "y": 0}, "scale": 6300000}})); + layout.add("Frame", (0.0, 0.0, 50.0, 50.0), kind.unwrap()); + } + layout +} + +/// What `work` returns, with the passes over a layer it made. +fn passes(work: impl FnOnce() -> T) -> (T, usize) { + PASSES.with(|n| n.set(0)); + let out = work(); + (out, PASSES.with(std::cell::Cell::get)) +} + +#[test] +fn a_layer_named_in_many_texts_is_read_once_for_their_figures() { + let map = map(); + let texts = ["K {count:A}", "", "T {count:A}", "plain {scale}", "S {count:A}", "N {count:a}", "{count:A}"]; + let (pairs, read) = passes(|| statistic_figures(&map, false, &texts)); + assert_eq!(read, 1); + assert_eq!(pairs, vec![("{count:A}".to_string(), "1".to_string()), ("{count:a}".to_string(), "1".to_string())]); +} + +#[test] +fn each_layer_of_the_texts_is_read_once() { + let map = map(); + let (pairs, read) = passes(|| statistic_figures(&map, false, &["{count:A}", "{sum:B:f} {count:Nowhere}", "{sum:A:f} {count:B}"])); + assert_eq!(read, 2); + let tokens: Vec<&str> = pairs.iter().map(|(t, _)| t.as_str()).collect(); + assert_eq!(tokens, ["{count:A}", "{sum:B:f}", "{sum:A:f}", "{count:B}"]); + assert_eq!(passes(|| statistic_figures(&map, false, &[])), (Vec::new(), 0)); +} + +#[test] +fn the_notices_of_many_texts_read_a_layer_once_and_say_what_each_text_misses() { + let maps = [map()]; + let layout = layout(Some("m")); + let texts = ["{count:A} {sum:A:no}", "", "{sum:A:no} {sum:B} {count:Nowhere}", "{count:Nowhere} {count:A}"]; + let each: Vec> = texts.iter().map(|t| statistic_notices(&layout, &maps, t)).collect(); + let (said, read) = passes(|| statistic_notices_each(&layout, &maps, &texts)); + assert_eq!(read, 2); + assert_eq!(said, each); + // A notice two texts share is each one's. + assert_eq!(said.iter().map(Vec::len).collect::>(), [2, 0, 3, 2]); +} + +#[test] +fn the_notices_of_texts_with_no_map_to_read_make_no_pass() { + let maps = [map()]; + for layout in [layout(None), layout(Some("gone"))] { + let texts = ["{count:A}", "{count:A} {sum:B}"]; + let each: Vec> = texts.iter().map(|t| statistic_notices(&layout, &maps, t)).collect(); + let (said, read) = passes(|| statistic_notices_each(&layout, &maps, &texts)); + assert_eq!(read, 0); + assert_eq!(said, each); + } +}