diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index c02f322faf..7d00d7aeba 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -65,6 +65,9 @@ pub(super) fn long_commands(boundaries: bool) { s.run("layer.addDataText", &json!({"fileName": "training.geojson", "text": training.to_string()})).unwrap(); s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "blank"})).unwrap(); s.run("layout.addFrame", &json!({"x": 20, "y": 20, "w": 150, "h": 150})).unwrap(); + // A sorted table and a chart read their layer's rows as the page is drawn (#3493). + s.run("layout.addElement", &json!({"kind": "table", "layer": "Cities", "sort": "pop_max"})).unwrap(); + s.run("layout.addElement", &json!({"kind": "chart", "layer": "Cities", "field": "pop_max"})).unwrap(); // A layer read from a Shapefile, edited, to publish. s.run("share.exportLayer", &json!({"layer": "Cities", "path": out("towns.shp")})).unwrap(); s.run("layer.addData", &json!({"path": out("towns.shp"), "name": "towns"})).unwrap(); diff --git a/crates/map/src/layout/elements.rs b/crates/map/src/layout/elements.rs index 24b8a2d2d7..c2e14b69ad 100644 --- a/crates/map/src/layout/elements.rs +++ b/crates/map/src/layout/elements.rs @@ -487,13 +487,42 @@ pub fn table_listing<'a>(layer: &'a crate::Layer, look: TableRows<'a>) -> TableL TableListing { layer, look, selected } } +/// How many rows a table or a chart reads between looks at Cancel. +const LOOK_EVERY: usize = 4096; + +/// Whether the run reading `read` rows was asked to stop, looked at every [`LOOK_EVERY`] rows. +fn stopped_at(read: usize) -> bool { + read.is_multiple_of(LOOK_EVERY) && rustgis_data::progress::check().is_err() +} + /// A feature in a table's order: by its value, then by its place in the layer. struct Sorted<'a> { value: &'a rustgis_data::Value, + /// A text value in lowercase, once its row is kept: a kept row is compared many times, and + /// lowering both texts each time took seconds over many rows (#3493). A row only weighed + /// against the last kept one holds none, and is lowered no further than their first + /// difference. + lowered: Option, row: usize, descending: bool, } +/// `text` in lowercase, character by character, as +/// [`cmp_values`](rustgis_data::value::cmp_values) reads it. +fn lowered(text: &str) -> impl Iterator + '_ { + text.chars().flat_map(char::to_lowercase) +} + +impl Sorted<'_> { + /// The same, ready to be compared many times. + fn with_lowered(mut self) -> Self { + if let rustgis_data::Value::Text(text) = self.value { + self.lowered = Some(lowered(text).collect()); + } + self + } +} + impl Ord for Sorted<'_> { /// The kind of value first (empty, yes or no, number, date, text), then /// [`cmp_values`](rustgis_data::value::cmp_values) within a kind: a total order, so a heap @@ -514,7 +543,17 @@ impl Ord for Sorted<'_> { let by_value = kind(self.value).cmp(&kind(other.value)).then_with(|| match kind(self.value) { // Two empty values, a NaN among them, are equal. 0 => std::cmp::Ordering::Equal, - _ => rustgis_data::value::cmp_values(self.value, other.value), + _ => match (self.value, other.value) { + // As `cmp_values` orders text, from the lowercase already held. + (Value::Text(a), Value::Text(b)) => match (&self.lowered, &other.lowered) { + (Some(x), Some(y)) => x.cmp(y), + (None, Some(y)) => lowered(a).cmp(y.chars()), + (Some(x), None) => x.chars().cmp(lowered(b)), + (None, None) => lowered(a).cmp(lowered(b)), + } + .then_with(|| a.cmp(b)), + _ => rustgis_data::value::cmp_values(self.value, other.value), + }, }); let by_value = if self.descending { by_value.reverse() } else { by_value }; by_value.then(self.row.cmp(&other.row)) @@ -543,10 +582,10 @@ impl TableListing<'_> { /// The first `limit` rows the table lists: kind by kind, numbers by value, dates by instant, /// text ignoring case and then by case, equal values in the layer's order. One pass over every - /// row of the layer (or every selected one) per call, without looking at Cancel: an export - /// looks between its pages. Sorted, only the `limit` best rows seen so far are held (a - /// heap), not the whole layer's order: a table shows a few hundred rows of what may be - /// millions. + /// row of the layer (or every selected one) per call. Sorted, only the `limit` best rows seen + /// so far are held (a heap), not the whole layer's order: a table shows a few hundred rows of + /// what may be millions. A sorted pass looks at Cancel every few thousand rows and stops + /// there, with the rows kept so far: the export drawing them refuses its page as cancelled. pub fn first(self, limit: usize) -> Vec { let ds = &self.layer.dataset; let descending = self.look.descending; @@ -558,21 +597,27 @@ impl TableListing<'_> { None => (0..ds.features.len().min(limit)).collect(), }; }; + use std::ops::ControlFlow; let mut best = std::collections::BinaryHeap::new(); - let mut offer = |row: usize| { - let next = Sorted { value: ds.value(row, field), row, descending }; + let mut offer = |(read, row): (usize, usize)| { + if stopped_at(read) { + return ControlFlow::Break(()); + } + let next = Sorted { value: ds.value(row, field), lowered: None, row, descending }; if best.len() < limit { - best.push(next); + best.push(next.with_lowered()); } else if let Some(mut last) = best.peek_mut() && next < *last { - *last = next; + *last = next.with_lowered(); } + ControlFlow::Continue(()) + }; + // Cancelled or walked to the end, what is kept by then is returned. + let _ = match self.selected { + Some(rows) => rows.into_iter().enumerate().try_for_each(&mut offer), + None => (0..ds.features.len()).enumerate().try_for_each(&mut offer), }; - match self.selected { - Some(rows) => rows.into_iter().for_each(&mut offer), - None => (0..ds.features.len()).for_each(&mut offer), - } best.into_sorted_vec().into_iter().map(|s| s.row).collect() } } @@ -934,6 +979,9 @@ impl ElementKind { /// bar not yet cut to its limit (every feature with a number, ungrouped), about the label /// field's own text twice over. /// + /// It looks at Cancel every few thousand features, and a cancelled read is no data. Ordering + /// the bars once they are read is one step, without a look. + /// /// It reads no colours ([`ChartData::colors`] stays empty): [`ElementKind::chart_data_of`] reads /// them from the layer for a chart coloured by classes. pub fn chart_data(&self, ds: &rustgis_data::Dataset) -> Option { @@ -1005,6 +1053,9 @@ impl ElementKind { Some(gi) => { let mut index = ValueIndex::default(); for row in 0..ds.features.len() { + if stopped_at(row) { + return None; + } let at = index.slot(ds.value(row, gi)); if at == groups.len() { groups.push(Tally::default()); @@ -1063,6 +1114,9 @@ impl ElementKind { } None => { for row in 0..ds.features.len() { + if stopped_at(row) { + return None; + } match number(row) { Some(n) => drawn.push((n, row)), None => no_number += 1, diff --git a/crates/map/src/layout/tests.rs b/crates/map/src/layout/tests.rs index aafa3a49a9..972b53fc88 100644 --- a/crates/map/src/layout/tests.rs +++ b/crates/map/src/layout/tests.rs @@ -2391,3 +2391,92 @@ fn a_tables_first_rows_of_many_are_the_whole_sorts_first() { assert_eq!(table_listing(&layer, look).first(500), whole[..500]); } } + +/// Counts its looks, and says Cancel from look `from` on (the first is 1). +struct CancelFrom { + from: usize, + looked: std::sync::atomic::AtomicUsize, +} + +impl rustgis_data::progress::Probe for CancelFrom { + fn cancelled(&self) -> bool { + self.looked.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1 >= self.from + } + fn begin(&self, _: u64) {} + fn advance(&self, _: u64) {} +} + +/// What `read` returns while Cancel is asked from look `from` on, and how often it looked. +fn cancelled_from(from: usize, read: impl FnOnce() -> T) -> (T, usize) { + let probe = std::sync::Arc::new(CancelFrom { from, looked: Default::default() }); + let _guard = rustgis_data::progress::install(Some(probe.clone())); + let out = read(); + (out, probe.looked.load(std::sync::atomic::Ordering::Relaxed)) +} + +/// A layer of 10,000 rows: a number and a text in each. +fn ten_thousand() -> crate::Layer { + use rustgis_data::{Dataset, Field, FieldType, Value}; + let fields = vec![Field::new("n", FieldType::Integer), Field::new("t", FieldType::Text)]; + let mut ds = Dataset::new("t", rustgis_data::GeometryType::Point, fields); + for i in 0..10_000_i64 { + ds.push(None, vec![Value::Int(i), Value::Text(format!("group {}", i % 7))]); + } + crate::Layer::new(1, ds) +} + +/// A table's rows are read looking at Cancel every few thousand, sorted and selected alike, and +/// the read stops at the first look that says so (#3493). +#[test] +fn a_tables_sort_looks_at_cancel_between_rows() { + let mut layer = ten_thousand(); + layer.selection = (0..10_000).collect(); + for selected_only in [false, true] { + let look = TableRows { sort: Some("n"), descending: true, selected_only }; + let (rows, looked) = cancelled_from(usize::MAX, || table_listing(&layer, look).first(3)); + assert_eq!((rows, looked), (vec![9999, 9998, 9997], 3), "selected {selected_only}"); + let (rows, looked) = cancelled_from(1, || table_listing(&layer, look).first(3)); + assert_eq!((rows, looked), (vec![], 1), "selected {selected_only}"); + let (rows, looked) = cancelled_from(2, || table_listing(&layer, look).first(3)); + assert_eq!((rows, looked), (vec![4095, 4094, 4093], 2), "selected {selected_only}"); + } +} + +/// A chart's rows too, grouped or not, and a cancelled read is no chart (#3493). +#[test] +fn a_charts_read_looks_at_cancel_between_rows() { + let layer = ten_thousand(); + for group in [None, Some("t")] { + let chart = chart(serde_json::json!({"field":"n", "label":null, "group":group, "statistic":"sum", "order":"layer"})); + let (data, looked) = cancelled_from(usize::MAX, || chart.chart_data(&layer.dataset)); + assert_eq!((data.is_some(), looked), (true, 3), "group {group:?}"); + for from in 1..=3 { + let (data, looked) = cancelled_from(from, || chart.chart_data(&layer.dataset)); + assert_eq!((data.is_none(), looked), (true, from), "group {group:?}, from {from}"); + } + } +} + +/// Text in a table's order reads as it always did: ignoring case, character by character (a final +/// sigma as the character it is), then by case. +#[test] +fn a_tables_sort_of_text_keeps_the_comparators_order() { + use rustgis_data::{Dataset, Field, FieldType, Value}; + let texts = ["", "a", "A", "aB", "Ab", "ab", "İ", "i", "i̇", "ß", "ss", "SS", "ẞ", "ΟΔΟΣ", "οδος", "οδοσ", "Οδός", "Z", "z", "É", "é"]; + let mut ds = Dataset::new("t", rustgis_data::GeometryType::Point, vec![Field::new("v", FieldType::Text)]); + for t in texts { + ds.push(None, vec![Value::Text(t.into())]); + } + let layer = crate::Layer::new(1, ds); + for descending in [false, true] { + let mut want: Vec = (0..texts.len()).collect(); + want.sort_by(|&a, &b| { + let by_value = rustgis_data::value::cmp_values(layer.dataset.value(a, 0), layer.dataset.value(b, 0)); + if descending { by_value.reverse() } else { by_value }.then(a.cmp(&b)) + }); + for limit in 1..=texts.len() { + let look = TableRows { sort: Some("v"), descending, selected_only: false }; + assert_eq!(table_listing(&layer, look).first(limit), want[..limit], "descending {descending} limit {limit}"); + } + } +} diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 504a76d2a3..51be5be5f4 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -196,6 +196,8 @@ pub struct PagePending { /// [`render`], and whether a frame or legend was drawn while content was still on its way. /// The Layout view never waits for legend pictures or cast shadows still being worked out. /// Its caller redraws once the missing content lands, on desktop as well as in the browser. +/// It refuses no cancelled drawing: a table or chart stops reading at a Cancel, so it is not for +/// a run that installs one. pub fn render_pending(layout: &Layout, maps: &mut [Map], dpi: f64, info: &PageInfo) -> Result<(Pixmap, PagePending), String> { render_page(layout, maps, dpi, info, false, None) }