diff --git a/crates/analysis/src/stats.rs b/crates/analysis/src/stats.rs index 45ed1dcb31..1e71f9b2bb 100644 --- a/crates/analysis/src/stats.rs +++ b/crates/analysis/src/stats.rs @@ -16,6 +16,8 @@ use std::cell::OnceCell; use std::cmp::Ordering; use std::collections::HashMap; +pub(crate) use rustgis_data::value::cmp_number; +use rustgis_data::value::cmp_values; use rustgis_data::{Dataset, FieldType, Value}; use serde_json::Value as Json; @@ -253,85 +255,13 @@ pub fn group_rows(ds: &Dataset, rows: &[usize], keys: &[usize]) -> Vec { groups } -/// Orders group keys value by value: nulls, then numbers (true and false as 1 and 0) by value, +/// Orders group keys value by value ([`cmp_values`]): nulls, then numbers (true and false as 1 and 0) by value, /// then dates and date-times by instant (and then by their text), then text by its lower case and /// then by character code. Numbers equal in value are ordered by /// kind (1 before 1.0). This is a total order, whatever mix of kinds a field holds (text that reads /// as a number is still text), so the order never depends on the records'. fn cmp_keys(a: &[Value], b: &[Value]) -> Ordering { - a.iter().zip(b).map(|(x, y)| cmp_key(x, y)).find(|o| o.is_ne()).unwrap_or(Ordering::Equal) -} - -/// Orders two group key values (see [`cmp_keys`]). -fn cmp_key(x: &Value, y: &Value) -> Ordering { - /// A number's kind, the tie-break between equal values: true/false, then whole, then decimal. - fn kind(v: &Value) -> u8 { - match v { - Value::Bool(_) => 0, - Value::Int(_) => 1, - _ => 2, - } - } - let rank = |v: &Value| match v { - Value::Null => 0, - Value::Date(_) | Value::DateTime(_) => 2, - Value::Text(_) => 3, - _ => 1, - }; - rank(x).cmp(&rank(y)).then_with(|| match (x, y) { - (Value::Date(_) | Value::DateTime(_), _) => x.temporal_key().cmp(&y.temporal_key()).then_with(|| x.to_string().cmp(&y.to_string())), - (Value::Text(a), Value::Text(b)) => { - a.chars().flat_map(char::to_lowercase).cmp(b.chars().flat_map(char::to_lowercase)).then_with(|| a.cmp(b)) - } - (Value::Null, Value::Null) => Ordering::Equal, - _ => cmp_number(x, y).then_with(|| kind(x).cmp(&kind(y))), - }) -} - -/// Orders two numbers (true and false as 1 and 0) by value, exactly: a whole number against a -/// decimal without rounding it to f64. Every NaN is one value, above all others; −0 is 0. -pub(crate) fn cmp_number(x: &Value, y: &Value) -> Ordering { - /// A number as a whole number or a decimal. - enum N { - I(i64), - F(f64), - } - let n = |v: &Value| match v { - Value::Bool(b) => N::I(i64::from(*b)), - Value::Int(i) => N::I(*i), - Value::Float(f) if f.is_nan() => N::F(f64::NAN), - Value::Float(f) => N::F(f + 0.0), - Value::Null | Value::Text(_) | Value::Date(_) | Value::DateTime(_) => N::F(f64::NAN), - }; - match (n(x), n(y)) { - (N::I(a), N::I(b)) => a.cmp(&b), - (N::F(a), N::F(b)) => a.total_cmp(&b), - (N::I(a), N::F(b)) => cmp_int_float(a, b), - (N::F(a), N::I(b)) => cmp_int_float(b, a).reverse(), - } -} - -/// Orders a whole number against a decimal exactly; NaN is above every number. -fn cmp_int_float(i: i64, f: f64) -> Ordering { - // 2^63: no i64 reaches it, every i64 is at least its negative. - const TWO_63: f64 = 9_223_372_036_854_775_808.0; - if f.is_nan() || f >= TWO_63 { - return Ordering::Less; - } - if f < -TWO_63 { - return Ordering::Greater; - } - let t = f.trunc(); - // In range, so the truncated decimal is a whole number an i64 holds exactly. - i.cmp(&(t as i64)).then_with(|| { - if f > t { - Ordering::Less - } else if f < t { - Ordering::Greater - } else { - Ordering::Equal - } - }) + a.iter().zip(b).map(|(x, y)| cmp_values(x, y)).find(|o| o.is_ne()).unwrap_or(Ordering::Equal) } /// One field's values within a group, without its nulls, in record order. @@ -1258,14 +1188,14 @@ mod tests { // Whole numbers and decimals compare exactly past 2^53, and NaNs of either sign are one // group, after the numbers. let big = (1i64 << 53) + 1; - assert_eq!(cmp_key(&Value::Int(big), &Value::Float(9_007_199_254_740_992.0)), Ordering::Greater); + assert_eq!(cmp_values(&Value::Int(big), &Value::Float(9_007_199_254_740_992.0)), Ordering::Greater); let mixed_big = table(&[(Value::Int(big), ""), (Value::Float(9_007_199_254_740_992.0), "")]); let order: Vec> = group_rows(&mixed_big, &[0, 1], &[0]).into_iter().map(|g| g.key).collect(); assert_eq!(order, vec![vec![Value::Float(9_007_199_254_740_992.0)], vec![Value::Int(big)]]); - assert_eq!(cmp_key(&Value::Int(i64::MAX), &Value::Float(9.3e18)), Ordering::Less); - assert_eq!(cmp_key(&Value::Int(i64::MIN), &Value::Float(f64::NEG_INFINITY)), Ordering::Greater); - assert_eq!(cmp_key(&Value::Int(3), &Value::Float(3.5)), Ordering::Less); - assert_eq!(cmp_key(&Value::Int(-3), &Value::Float(-3.5)), Ordering::Greater); + assert_eq!(cmp_values(&Value::Int(i64::MAX), &Value::Float(9.3e18)), Ordering::Less); + assert_eq!(cmp_values(&Value::Int(i64::MIN), &Value::Float(f64::NEG_INFINITY)), Ordering::Greater); + assert_eq!(cmp_values(&Value::Int(3), &Value::Float(3.5)), Ordering::Less); + assert_eq!(cmp_values(&Value::Int(-3), &Value::Float(-3.5)), Ordering::Greater); let nans = table(&[(Value::Float(-f64::NAN), ""), (Value::Float(f64::INFINITY), ""), (Value::Float(f64::NAN), "")]); let keys: Vec> = group_rows(&nans, &[0, 1, 2], &[0]).into_iter().map(|g| g.key).collect(); assert_eq!(keys.len(), 2); diff --git a/crates/data/src/value.rs b/crates/data/src/value.rs index d6133b7470..21a5dd846a 100644 --- a/crates/data/src/value.rs +++ b/crates/data/src/value.rs @@ -407,6 +407,85 @@ impl PartialOrd for Value { } } +/// Orders any two values: nulls, then numbers (true and false as 1 and 0) by value, then dates and +/// date-times by instant (and then by their text), then text by its lower case and then by +/// character code. Numbers equal in value are ordered by kind (1 before 1.0). This is a total +/// order, whatever mix of kinds a field holds (text that reads as a number is still text), so an +/// order made with it never depends on how the values came. [`PartialOrd`] isn't one: it reads +/// text as a number beside a number, and compares a number that isn't finite as its text. +pub fn cmp_values(x: &Value, y: &Value) -> std::cmp::Ordering { + use std::cmp::Ordering; + /// A number's kind, the tie-break between equal values: true/false, then whole, then decimal. + fn kind(v: &Value) -> u8 { + match v { + Value::Bool(_) => 0, + Value::Int(_) => 1, + _ => 2, + } + } + let rank = |v: &Value| match v { + Value::Null => 0, + Value::Date(_) | Value::DateTime(_) => 2, + Value::Text(_) => 3, + _ => 1, + }; + rank(x).cmp(&rank(y)).then_with(|| match (x, y) { + (Value::Date(_) | Value::DateTime(_), _) => x.temporal_key().cmp(&y.temporal_key()).then_with(|| x.to_string().cmp(&y.to_string())), + (Value::Text(a), Value::Text(b)) => { + a.chars().flat_map(char::to_lowercase).cmp(b.chars().flat_map(char::to_lowercase)).then_with(|| a.cmp(b)) + } + (Value::Null, Value::Null) => Ordering::Equal, + _ => cmp_number(x, y).then_with(|| kind(x).cmp(&kind(y))), + }) +} + +/// Orders two numbers (true and false as 1 and 0) by value, exactly: a whole number against a +/// decimal without rounding it to f64. Every NaN is one value, above all others; −0 is 0. +pub fn cmp_number(x: &Value, y: &Value) -> std::cmp::Ordering { + /// A number as a whole number or a decimal. + enum N { + I(i64), + F(f64), + } + let n = |v: &Value| match v { + Value::Bool(b) => N::I(i64::from(*b)), + Value::Int(i) => N::I(*i), + Value::Float(f) if f.is_nan() => N::F(f64::NAN), + Value::Float(f) => N::F(f + 0.0), + Value::Null | Value::Text(_) | Value::Date(_) | Value::DateTime(_) => N::F(f64::NAN), + }; + match (n(x), n(y)) { + (N::I(a), N::I(b)) => a.cmp(&b), + (N::F(a), N::F(b)) => a.total_cmp(&b), + (N::I(a), N::F(b)) => cmp_int_float(a, b), + (N::F(a), N::I(b)) => cmp_int_float(b, a).reverse(), + } +} + +/// Orders a whole number against a decimal exactly; NaN is above every number. +fn cmp_int_float(i: i64, f: f64) -> std::cmp::Ordering { + use std::cmp::Ordering; + // 2^63: no i64 reaches it, every i64 is at least its negative. + const TWO_63: f64 = 9_223_372_036_854_775_808.0; + if f.is_nan() || f >= TWO_63 { + return Ordering::Less; + } + if f < -TWO_63 { + return Ordering::Greater; + } + let t = f.trunc(); + // In range, so the truncated decimal is a whole number an i64 holds exactly. + i.cmp(&(t as i64)).then_with(|| { + if f > t { + Ordering::Less + } else if f < t { + Ordering::Greater + } else { + Ordering::Equal + } + }) +} + /// `i` against `f` exactly, without rounding `i` to the nearest f64: unknown for NaN. fn int_cmp_f64(i: i64, f: f64) -> Option { use std::cmp::Ordering; diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 01c6a4e3ea..2b08e43ad5 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -284,7 +284,7 @@ layer.transparency layer? value layer.visibility layer? visible? layer.zoomTo layer? layout.activate name layout -layout.addElement layout? kind frame? of? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? columnBreaks? columns? textSize? classLabels? sizes? showCounts? showLayerNames? orientation? ticks? tickSide? reverse? fill? width? radius? dash? dir? head? angle? length? image? path? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? barOutline? rows? fields? header? step? type? crs? short? mgrs? labels? style? tickLength? format? hemisphere? edges? labelOrientation? labelSize? off? name? direction? at? section? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? outline? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? x? y? w? h? background? +layout.addElement layout? kind frame? of? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? columnBreaks? columns? textSize? classLabels? sizes? showCounts? showLayerNames? orientation? ticks? tickSide? reverse? fill? width? radius? dash? dir? head? angle? length? image? path? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? barOutline? rows? fields? header? sort? descending? selectedOnly? step? type? crs? short? mgrs? labels? style? tickLength? format? hemisphere? edges? labelOrientation? labelSize? off? name? direction? at? section? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? outline? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? x? y? w? h? background? layout.addFrame layout? shape? points? map? x? y? w? h? layout.arrange layout? element to layout.arrangement favourite? save? arrangement? remove? @@ -306,7 +306,7 @@ layout.save layout? path layout.series layout? layer nameField? frame? margin? off? layout.seriesPage layout? page layout.seriesRefresh layout? -layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? columnBreaks? labels? classLabels? columns? textSize? showLayerNames? sizes? showCounts? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? extentNumbers? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? barOutline? hideLabels? rows? fields? header? image? path? background? +layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? columnBreaks? labels? classLabels? columns? textSize? showLayerNames? sizes? showCounts? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? extentNumbers? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? barOutline? hideLabels? rows? fields? header? sort? descending? selectedOnly? image? path? background? locator.find locator? text limit? zoom? map.activate name map.addTiles url kind? name? bounds? attribution? minZoom? maxZoom? tileSize? singleImage? tms? subdomains? layers? styleLayers? opacity? blend? resampling? overlay? top? replace? id? view? start? end? unit? interval? dates? legend? connection? anonymous? diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 377e4e39b2..d0118ce09a 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -261,6 +261,9 @@ pub fn commands() -> Vec { r##""rows"?, "##, r##""fields"?: [field names] (table: its columns, in this order; default [], every field in the layer's order), "##, r##""header"?: bool (table: the row of field names; default true), "##, + r##""sort"?: field (table: its rows ordered by this field, empty values first, numbers by value, dates by instant, text ignoring case; default none, the layer's order), "##, + r##""descending"?: bool (table: the largest value of "sort" first; default false), "##, + r##""selectedOnly"?: bool (table: only the layer's selected features, none selected leaving it without rows; default false), "##, r##""step"?: degrees, or a measured grid's units (metres) (0 picks one), "##, r##""type"?: "graticule" (latitudes and longitudes, default) | "measured" (eastings and northings in a projected system), "##, r##""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), "##, @@ -406,6 +409,8 @@ pub fn commands() -> Vec { r##""rows"?, "##, r##""fields"?: [field names] (table, as in layout.addElement, of the layer it will show, plus any the table already shows of that layer and it has lost, spelled the same; [] returns to every field, null leaves them; another "layer" without them drops them), "##, r##""header"?: bool (table, as in layout.addElement; null leaves it as it is), "##, + r##""sort"?: field|null (table, as in layout.addElement, of the layer it will show; null returns to the layer's order; another "layer" without it drops it), "##, + r##""descending"?: bool, "selectedOnly"?: bool (table, as in layout.addElement; null leaves each as it is), "##, r##""image"?: base64 (picture: its new image, its file no longer remembered, which is said when it had one), "##, r##""path"?: a PNG or JPEG file (picture: read again, its image replacing the one it has, and remembered as its file; a file missing, over 16 MB, not a PNG or JPEG, or one that can't be drawn is refused and the picture left as it was; image and path together are refused; refused in the browser, which has no file paths: give its image; null leaves each as it is; refused for other elements), "##, r##""background"?: {"fill"?, "outline"?, "width"?, "radius"?, "padding"?, as in layout.addElement, the keys not given keeping theirs} | null (removes it); a map frame takes none}"##, diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index 3698c06d7e..3fe88fd696 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -72,7 +72,10 @@ pub(in crate::cmd::layout) fn table_rows(p: &Value) -> Result, Str } } -pub(in crate::cmd::layout) const ONLY_TABLE_LOOK: &str = "only tables take fields and header"; +/// The keys only a table takes. +pub(in crate::cmd::layout) const TABLE_ONLY_KEYS: [&str; 5] = ["fields", "header", "sort", "descending", "selectedOnly"]; + +pub(in crate::cmd::layout) const ONLY_TABLE_LOOK: &str = "only tables take fields, header, sort, descending and selectedOnly"; /// The field names a table is given as `"fields"`, when it's given (and not null): an error when /// it's not a list of names. [`table_columns`] reads them against its layer. @@ -116,6 +119,21 @@ pub(in crate::cmd::layout) fn table_header(p: &Value) -> Result, St } } +/// A table's switch `k`, when it's given (and not null): an error when it's not true or false. +pub(in crate::cmd::layout) fn table_switch(p: &Value, k: &str) -> Result, String> { + match p.get(k).filter(|v| !v.is_null()) { + Some(v) => crate::cmd::bool_value(v).map(Some).ok_or_else(|| format!("{k} must be true or false")), + None => Ok(None), + } +} + +/// The field a table is given to sort by, when it's given (and not null), spelled as `ds` spells +/// it: the one it already sorts that layer by (`held`) stays, as a column the layer lost does. +pub(in crate::cmd::layout) fn table_sort(ds: &rustgis_data::Dataset, name: &str, held: Option<&str>) -> Result { + let held = held.map(str::to_string).into_iter().collect::>(); + table_columns(ds, &[name], &held)?.pop().ok_or_else(|| format!("no field '{name}' in {}", ds.name)) +} + /// A line's "dir": `default` when it's not given (or null), an error when it's not a direction's /// name. pub(in crate::cmd::layout) fn line_dir(p: &Value, default: LineDir) -> Result { @@ -295,21 +313,23 @@ pub(in crate::cmd::layout) fn held_rows(p: &Value) -> Option { (n != kept).then(|| format!("rows {n} held to {kept} ({least} to {most})")) } -/// Says the rows and columns the box of the table `id` of layout `li` leaves out (#3416), -/// measured as [`super::text::text_fit_loss`] measures a text; nothing of another element. +/// Says the rows and columns the box of the table `id` of layout `li` leaves out (#3416), and a +/// sort field its layer no longer has (#3409), measured as [`super::text::text_fit_loss`] measures +/// a text; nothing of another element. pub(in crate::cmd::layout) fn say_table_cut(s: &mut Session, li: usize, id: u32) { let Some(l) = s.project.layouts.get(li) else { return }; // The counts don't depend on the resolution: the box, its columns and its rows scale with it. // Nothing is drawn here, so a layer read in place counts the rows it holds now. let mut cut = rustgis_render::layout::tables_cut(l, &s.project.maps, 300.0); cut.retain(|t| t.id == id); - if let Some(note) = rustgis_render::layout::table_cut_notice(&cut) { + for note in rustgis_render::layout::table_notices(&cut) { s.warn(note); } } -/// What a table is given that changes what its box holds, or shows it. -pub(in crate::cmd::layout) const TABLE_FIT_KEYS: [&str; 8] = ["w", "h", "rows", "fields", "textSize", "header", "layer", "visible"]; +/// What a table is given that changes what its box holds or the rows it lists, or shows it. +pub(in crate::cmd::layout) const TABLE_FIT_KEYS: [&str; 11] = + ["w", "h", "rows", "fields", "textSize", "header", "sort", "descending", "selectedOnly", "layer", "visible"]; /// Says what [`held_to_limits`] found, in one notice for the command `title`. pub(in crate::cmd::layout) fn say_held(s: &mut Session, title: &str, held: Vec) { @@ -344,7 +364,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu if !matches!(kind, "legend" | "scaleBar" | "table" | "colorbar") && p.get("textSize").is_some_and(|v| !v.is_null()) { return Err(ONLY_LAYOUT_TEXT_SIZE.into()); } - if kind != "table" && (gives(p, "fields") || gives(p, "header")) { + if kind != "table" && TABLE_ONLY_KEYS.iter().any(|k| gives(p, k)) { return Err(ONLY_TABLE_LOOK.into()); } if kind != "grid" && p.get("labelSize").is_some_and(|v| !v.is_null()) { @@ -606,7 +626,13 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu }; let text_size = text_size_param(p, "textSize", TABLE_TEXT_PT)?.unwrap_or(TABLE_TEXT_PT); let header = table_header(p)?.unwrap_or(true); - let k = ElementKind::Table { frame, layer, rows, color: ink, fields, text_size, header }; + let sort = match given_name(p, "sort", "a field's name")? { + Some(name) => Some(table_sort(frame_dataset(s, l, frame, &layer).ok_or("no such layer")?, name, None)?), + None => None, + }; + let descending = table_switch(p, "descending")?.unwrap_or(false); + let selected_only = table_switch(p, "selectedOnly")?.unwrap_or(false); + let k = ElementKind::Table { frame, layer, rows, color: ink, fields, text_size, header, sort, descending, selected_only }; ("Table Frame", place(p, l, (15.0, ph * 0.6, pw * 0.5, ph * 0.35))?, k) } "chart" => { @@ -1209,8 +1235,25 @@ const ADD_TEXT_KEYS: &[&str] = &[ const ADD_PICTURE_KEYS: &[&str] = &["layout", "kind", "x", "y", "w", "h", "background", "image", "path"]; /// Keys read by `layout.addElement` for a table (#3074). -const ADD_TABLE_KEYS: &[&str] = - &["layout", "kind", "frame", "x", "y", "w", "h", "background", "layer", "rows", "color", "fields", "textSize", "header"]; +const ADD_TABLE_KEYS: &[&str] = &[ + "layout", + "kind", + "frame", + "x", + "y", + "w", + "h", + "background", + "layer", + "rows", + "color", + "fields", + "textSize", + "header", + "sort", + "descending", + "selectedOnly", +]; /// Keys read by `layout.addElement` for a chart (#3074). const ADD_CHART_KEYS: &[&str] = &[ diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index d6467efdf1..e50750c952 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -112,7 +112,7 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]> s.warn(note); } say_unfitted_legends(s, &unfitted); - if let Some(note) = rustgis_render::layout::table_cut_notice(&cut) { + for note in rustgis_render::layout::table_notices(&cut) { s.warn(note); } for note in chart_notice_lines(&layout, &charts) { @@ -235,7 +235,7 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( let mut gaps = SectionGaps::new(); let mut profiles = ProfileNotes::new(); // Each table cut on a page, as its first such page cut it. - let mut cut = BTreeMap::new(); + let mut cut = BTreeMap::::new(); let render_pages = || -> Result<(Vec, Option>), String> { let mut out = Vec::new(); let mut png = None; @@ -306,7 +306,13 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( // Counted once the page is drawn: a layer read in place holds that page's rows. if let Some(layout) = s.project.layouts.get(li) { for table in rustgis_render::layout::tables_cut(layout, &s.project.maps, dpi) { - cut.entry(table.id).or_insert(table); + // As the first page that cuts it counts it; a lost sort field is every page's. + match cut.get(&table.id) { + Some(kept) if kept.is_cut() => {} + _ => { + cut.insert(table.id, table); + } + } } } // A cancelled export stops here, its layout put back below. @@ -343,7 +349,7 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( s.warn(note); } say_unfitted_legends(s, &unfitted); - if let Some(note) = rustgis_render::layout::table_cut_notice(&cut.into_values().collect::>()) { + for note in rustgis_render::layout::table_notices(&cut.into_values().collect::>()) { s.warn(note); } for note in chart_notice_lines(&saved, &charts) { @@ -592,7 +598,7 @@ fn layout_svg(s: &mut Session, li: usize, dpi: f64, download: Option<(crate::cmd let (text, pictured) = drawn?; let chart_notes = chart_notice_lines(layout, &charts); // After drawing, as the other exports count. - let cut = rustgis_render::layout::table_cut_notice(&rustgis_render::layout::tables_cut(layout, &s.project.maps, dpi)); + let cut = rustgis_render::layout::tables_cut(layout, &s.project.maps, dpi); for note in [note, rustgis_render::layout::sections_notice(&gaps, 1)].into_iter().flatten() { s.warn(note); } @@ -601,7 +607,7 @@ fn layout_svg(s: &mut Session, li: usize, dpi: f64, download: Option<(crate::cmd s.warn(note); } say_unfitted_legends(s, &unfitted); - if let Some(note) = cut { + for note in rustgis_render::layout::table_notices(&cut) { s.warn(note); } for note in chart_notes { diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 6d7bb6aed7..05c783fbdb 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -228,11 +228,14 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { _ => None, }; // A table's fields, read against the layer it will show; its header. - if !matches!(current, Some(ElementKind::Table { .. })) && (gives(p, "fields") || gives(p, "header")) { + if !matches!(current, Some(ElementKind::Table { .. })) && TABLE_ONLY_KEYS.iter().any(|k| gives(p, k)) { return Err(ONLY_TABLE_LOOK.into()); } let new_header = table_header(p)?; let new_fields = table_update(s, p, li, id, checked.as_ref())?; + let new_sort = table_sort_update(s, p, li, id, checked.as_ref())?; + let new_descending = table_switch(p, "descending")?; + let new_selected_only = table_switch(p, "selectedOnly")?; // A chart's options, read over its own on the layer it will chart. let (new_chart, chart_field, chart_said) = match chart_update(s, p, li, id, checked.as_ref())? { Some((o, f, said)) => (Some(o), f, said), @@ -588,6 +591,15 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { } _ => None, }; + // And one that was sorted is no longer, unless a field of the new layer comes. + let sort_dropped = match (s.project.layouts.get(li).and_then(|l| l.element(id)), moved) { + (Some(rustgis_map::layout::Element { name, kind: ElementKind::Table { layer, sort: Some(sort), .. }, .. }), Some(to)) + if new_sort.is_none() && !to.eq_ignore_ascii_case(layer) => + { + Some(format!("Update Element: {name} ({id}) is no longer sorted: {sort} was a field of {layer}")) + } + _ => None, + }; let l = active(s, p)?; let e = l.element_mut(id).ok_or_else(|| format!("no element {id}"))?; // A text or scale bar with no ink isn't measured: given a colour that shows it, it is told @@ -815,7 +827,7 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { *center = c; } } - ElementKind::Table { rows, layer, fields, text_size, header, .. } => { + ElementKind::Table { rows, layer, fields, text_size, header, sort, descending, selected_only, .. } => { if let Some(v) = new_rows { *rows = v; } @@ -823,6 +835,7 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { // Another layer's fields aren't this one's: they go unless new ones come. if !l.eq_ignore_ascii_case(layer) { fields.clear(); + *sort = None; } *layer = l.clone(); } @@ -835,6 +848,15 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { if let Some(v) = new_header { *header = v; } + if let Some(v) = new_sort { + *sort = v; + } + if let Some(v) = new_descending { + *descending = v; + } + if let Some(v) = new_selected_only { + *selected_only = v; + } } ElementKind::Chart { field, @@ -896,7 +918,7 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { if forgotten { s.notify(PICTURE_FORGOTTEN, false); } - if let Some(said) = fields_dropped { + for said in [fields_dropped, sort_dropped].into_iter().flatten() { s.notify(said, false); } if fit { @@ -1022,6 +1044,26 @@ fn table_update( Ok(Some(table_columns(frame_dataset(s, l, *frame, layer).ok_or("no such layer")?, &names, held)?)) } +/// The sort a table is given, read against the layer it will show: `Some(None)` takes it away. +fn table_sort_update( + s: &Session, + p: &Value, + li: usize, + id: u32, + checked: Option<&(String, Option)>, +) -> Result>, String> { + let Some(l) = s.project.layouts.get(li) else { return Ok(None) }; + let Some(ElementKind::Table { frame, layer: shown, sort, .. }) = l.element(id).map(|e| &e.kind) else { return Ok(None) }; + if p.get("sort").is_some_and(Value::is_null) { + return Ok(Some(None)); + } + let Some(name) = given_name(p, "sort", "a field's name")? else { return Ok(None) }; + let Some((layer, _)) = checked else { return Err("sort needs the table's layer".into()) }; + // Another layer's sort field isn't held for this one. + let held = sort.as_deref().filter(|_| layer.eq_ignore_ascii_case(shown)); + Ok(Some(Some(table_sort(frame_dataset(s, l, *frame, layer).ok_or("no such layer")?, name, held)?))) +} + /// Validates a table/chart's effective layer and field before mutation; input binding uses this same choice. pub(in crate::cmd::layout) fn checked_update( input: &impl crate::cmd::InputSource, @@ -1042,8 +1084,8 @@ pub(in crate::cmd::layout) fn checked_update( ElementKind::Chart { .. } => given_name(p, "field", "a field's name")?, _ => ps(p, "field"), }; - // A table's fields are read against its layer, so they bind it too. - let columns = matches!(e.kind, ElementKind::Table { .. }) && gives(p, "fields"); + // A table's fields and sort are read against its layer, so they bind it too. + let columns = matches!(e.kind, ElementKind::Table { .. }) && (gives(p, "fields") || gives(p, "sort")); match (&e.kind, new_layer, new_field) { (ElementKind::Table { frame, layer, .. } | ElementKind::Chart { frame, layer, .. }, nl, nf) if nl.is_some() || nf.is_some() || columns => diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 5b6ef5db2a..aae0d2cd28 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1275,17 +1275,20 @@ fn report_pages_bytes( fn keep_tables(s: &Session, kept: &mut Vec<(usize, rustgis_render::layout::TableCut)>, layout: Option, dpi: f64) { let Some((li, layout)) = layout.and_then(|li| Some((li, s.project.layouts.get(li)?))) else { return }; for mut table in rustgis_render::layout::tables_cut(layout, &s.project.maps, dpi) { - if !kept.iter().any(|(at, t)| *at == li && t.id == table.id) { - table.layout = Some(layout.name.clone()); - kept.push((li, table)); + table.layout = Some(layout.name.clone()); + match kept.iter_mut().find(|(at, t)| *at == li && t.id == table.id) { + // Not cut where it was first seen, it is counted where it is. + Some((_, t)) if !t.is_cut() => *t = table, + Some(_) => {} + None => kept.push((li, table)), } } } -/// Says the tables [`keep_tables`] kept in one notice however many layouts cut one. +/// Says the tables [`keep_tables`] kept, one notice of each kind however many layouts have one. fn say_report_tables(s: &mut Session, kept: Vec<(usize, rustgis_render::layout::TableCut)>) { let cut: Vec<_> = kept.into_iter().map(|(_, table)| table).collect(); - if let Some(note) = rustgis_render::layout::table_cut_notice(&cut) { + for note in rustgis_render::layout::table_notices(&cut) { s.warn(format!("The report: {note}")); } } diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 71c74eea19..63bbef1814 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -111,6 +111,7 @@ pub const CAPABILITIES: &[&str] = &[ "layout-chart-facing", "layout-chart-outline", "layout-table-look", + "layout-table-rows", "layout-colorbar-labels", "field-generation", "field-package", diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 9d6c11e5e3..81af82b1c8 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -175,6 +175,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("layout-chart-facing", command_uses_chart_facing), ("layout-chart-outline", command_uses_chart_outline), ("layout-table-look", command_uses_table_look), + ("layout-table-rows", command_uses_table_rows), ("layout-colorbar-labels", command_uses_colorbar_labels), ("blank-paper", command_uses_blank_paper), ("layout-frame-border", command_uses_frame_border), @@ -1208,6 +1209,30 @@ fn command_uses_table_look(id: &str, params: &Value) -> bool { } } +fn tables_with_rows(e: &rustgis_map::layout::Element) -> bool { + e.kind.table_uses_rows() +} + +/// A layout command that sorts a table's rows or lists only the selected ones (#3409). No sort +/// and both switches off need nothing on a new table; a saved `layout.update` isn't told what it +/// changes, so any of the keys given requires it there, `"sort": null` aside. +fn command_uses_table_rows(id: &str, params: &Value) -> bool { + let given = |k: &str| params.get(k).is_some_and(|v| !v.is_null()); + let on = |k: &str| params.get(k).and_then(crate::cmd::bool_value) == Some(true); + match id { + "layout.addElement" => { + params.get("kind").and_then(Value::as_str).is_some_and(|k| k.trim().eq_ignore_ascii_case("table")) + && (given("sort") || on("descending") || on("selectedOnly")) + } + "layout.update" => given("sort") || given("descending") || given("selectedOnly"), + "layout.import" | "report.existingTemplate" => { + imported_layout_uses(params, &["\"sort\"", "\"descending\"", "\"selected_only\""], tables_with_rows) + } + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_table_rows)), + _ => false, + } +} + fn colorbars_with_labels(e: &rustgis_map::layout::Element) -> bool { e.kind.colorbar_uses_labels() } @@ -1812,6 +1837,7 @@ fn layout_capabilities(layouts: &[rustgis_map::layout::Layout]) -> Vec<&'static (elements().any(charts_facing), "layout-chart-facing"), (elements().any(charts_outlined), "layout-chart-outline"), (elements().any(tables_with_a_look), "layout-table-look"), + (elements().any(tables_with_rows), "layout-table-rows"), (elements().any(colorbars_with_labels), "layout-colorbar-labels"), (elements().any(|e| e.kind.has_custom_border()), "layout-frame-border"), (elements().any(|e| e.kind.has_sections()), "layout-section"), @@ -2212,6 +2238,7 @@ mod tests { (&["layout-chart-facing"], "layout.update", json!({"element": 1, "mirror": true})), (&["layout-chart-outline"], "layout.update", json!({"element": 1, "barOutline": {"width": 1}})), (&["layout-table-look"], "layout.update", json!({"element": 1, "header": false})), + (&["layout-table-rows"], "layout.update", json!({"element": 1, "selectedOnly": true})), (&["layout-scale-bar-details"], "layout.update", json!({"element": 1, "subdivisions": 2})), (&["blank-paper"], "map.basemap", json!({"name": "blank", "color": "#112233"})), (&["layout-frame-border"], "layout.update", json!({"element": 1, "border": {}})), @@ -2600,6 +2627,7 @@ mod tests { "layout-chart-facing", "layout-chart-outline", "layout-table-look", + "layout-table-rows", "layout-colorbar-labels", "layout-frame-border", "layout-text-size", @@ -3730,6 +3758,46 @@ mod tests { } } + /// A table's sort and row switches (#3409) require `layout-table-rows`, in a saved layout and + /// in a saved command. + #[test] + fn table_rows_capability_follows_saved_layouts_and_commands() { + use rustgis_map::layout::ElementKind; + let fixture = Project::from_json(include_str!("../../../schema/fixtures/layout_table_rows.rgis")).unwrap(); + let saved = serde_json::to_value(&fixture).unwrap(); + assert_eq!(saved["requires"], json!(["layout-table-rows"])); + let mut clean = fixture; + for e in &mut clean.layouts[0].elements { + if let ElementKind::Table { sort, descending, selected_only, .. } = &mut e.kind { + (*sort, *descending, *selected_only) = (None, false, false); + } + } + let base = serde_json::to_value(&clean).unwrap(); + assert!(base.get("requires").is_none(), "a plain table needs nothing"); + for (id, params, required) in [ + ("layout.addElement", json!({"kind": "table", "sort": "name"}), true), + ("layout.addElement", json!({"kind": "table", "descending": true}), true), + ("layout.addElement", json!({"kind": "table", "selectedOnly": true}), true), + ("layout.addElement", json!({"kind": "table", "sort": null, "descending": false, "selectedOnly": false}), false), + ("layout.update", json!({"element": 2, "descending": false}), true), + ("layout.update", json!({"element": 2, "sort": null, "selectedOnly": null}), false), + ("layout.import", json!({"text": saved["layouts"][0].to_string()}), true), + ("layout.import", json!({"text": base["layouts"][0].to_string()}), false), + ] { + let script = format!("{id}= {params}"); + for value in [ + json!([{"name": "Task", "steps": [{"title": "Table", "command": id, "params": params}]}]), + json!([{"name": "Script", "steps": [{"title": "Table", "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-table-rows"]) } else { Value::Null }; + assert_eq!(saved.get("requires").cloned().unwrap_or(Value::Null), expected, "{id} {params}"); + } + } + } + /// A colorbar's label size and decimals (#3437) require `layout-colorbar-labels`, in a saved /// layout and in a saved command. #[test] diff --git a/crates/engine/src/tests/layout_table.rs b/crates/engine/src/tests/layout_table.rs index bf629d91c7..1bf05cc415 100644 --- a/crates/engine/src/tests/layout_table.rs +++ b/crates/engine/src/tests/layout_table.rs @@ -497,3 +497,202 @@ fn an_export_counts_a_layer_read_in_place_after_drawing_it() { assert_eq!(said, [want], "{ext}"); } } + +/// The selected rows of layer `name`, set as given. +fn select(s: &mut Session, name: &str, rows: &[usize]) { + let layer = s.map_mut().layers.iter_mut().find(|l| l.name == name).unwrap(); + layer.selection = rows.to_vec(); +} + +#[test] +fn a_table_is_sorted_by_a_field_kept_by_its_own_name() { + let (mut s, id) = tabled(); + let [b, a] = two_fields(&s); + update(&mut s, id, json!({"sort": b.to_uppercase(), "descending": true, "selectedOnly": true})).unwrap(); + let stored = table(&s, id); + assert_eq!((&stored["sort"], &stored["descending"], &stored["selected_only"]), (&json!(b), &json!(true), &json!(true))); + // Null leaves the switches; it takes the sort away. + update(&mut s, id, json!({"descending": null, "selectedOnly": null, "rows": 3})).unwrap(); + assert_eq!(table(&s, id)["sort"], json!(b)); + update(&mut s, id, json!({"sort": null})).unwrap(); + assert!(table(&s, id).get("sort").is_none()); + assert_eq!(table(&s, id)["descending"], json!(true)); + update(&mut s, id, json!({"descending": false, "selectedOnly": false})).unwrap(); + let stored = table(&s, id); + for key in ["sort", "descending", "selected_only"] { + assert!(stored.get(key).is_none(), "{key}: {stored}"); + } + let out = s + .run("layout.addElement", &json!({"kind": "table", "layer": "Countries", "sort": a, "descending": true, "selectedOnly": true})) + .unwrap(); + let added = table(&s, out["element"].as_u64().unwrap()); + assert_eq!((&added["sort"], &added["descending"], &added["selected_only"]), (&json!(a), &json!(true), &json!(true))); +} + +#[test] +fn a_sort_or_a_row_switch_of_the_wrong_kind_is_refused() { + let (mut s, id) = tabled(); + for (key, value, said) in [ + ("sort", json!("nope"), "no field 'nope'"), + ("sort", json!(""), "no field ''"), + ("sort", json!(3), "sort is "), + ("sort", json!(["f1"]), "sort is "), + ("descending", json!("sideways"), "descending must be"), + ("descending", json!(2), "descending must be"), + ("selectedOnly", json!("some"), "selectedOnly must be"), + ("selectedOnly", json!([]), "selectedOnly must be"), + ] { + let mut add = json!({"kind": "table", "layer": "Countries"}); + add[key] = value.clone(); + refused(&mut s, "layout.addElement", add, said); + let mut change = json!({"element": id}); + change[key] = value; + refused(&mut s, "layout.update", change, said); + } +} + +#[test] +fn only_tables_take_a_sort_and_selected_rows() { + let (mut s, _) = tabled(); + let other = s.run("layout.addElement", &json!({"kind": "legend"})).unwrap()["element"].clone(); + for (key, value) in [("sort", json!("NAME")), ("descending", json!(true)), ("selectedOnly", json!(true))] { + let mut add = json!({"kind": "legend"}); + add[key] = value.clone(); + refused(&mut s, "layout.addElement", add, "only tables take"); + let mut change = json!({"element": other}); + change[key] = value; + refused(&mut s, "layout.update", change, "only tables take"); + } +} + +#[test] +fn another_layer_drops_the_sort_unless_it_comes_with_its_own_and_says_so() { + let (mut s, id) = tabled(); + let [b, _] = two_fields(&s); + let cities = s.map().layer_by_name("Cities").unwrap().dataset.fields[0].name.clone(); + let said = |s: &Session, mark: u64| { + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("no longer sorted")).collect::>() + }; + update(&mut s, id, json!({"sort": b})).unwrap(); + let mark = s.notice_mark(); + update(&mut s, id, json!({"layer": "countries"})).unwrap(); + assert_eq!(table(&s, id)["sort"], json!(b)); + assert!(said(&s, mark).is_empty()); + update(&mut s, id, json!({"layer": "Cities"})).unwrap(); + assert!(table(&s, id).get("sort").is_none()); + assert_eq!(said(&s, mark), [format!("Update Element: Table Frame ({id}) is no longer sorted: {b} was a field of Countries")]); + // A sort of the new layer is read against it, and nothing is said. + update(&mut s, id, json!({"layer": "Countries", "sort": b})).unwrap(); + let mark = s.notice_mark(); + update(&mut s, id, json!({"layer": "Cities", "sort": cities.to_uppercase()})).unwrap(); + assert_eq!(table(&s, id)["sort"], json!(cities)); + assert!(said(&s, mark).is_empty()); + refused(&mut s, "layout.update", json!({"element": id, "layer": "Countries", "sort": "nope"}), "no field 'nope'"); +} + +/// A sort field removed afterwards stays as stored, and the table can still be changed. +#[test] +fn a_sort_field_the_layer_loses_stays_until_changed() { + let (mut s, id) = tabled(); + let [b, _] = two_fields(&s); + update(&mut s, id, json!({"sort": b})).unwrap(); + s.run("edit.deleteField", &json!({"layer": "Countries", "field": b})).unwrap(); + update(&mut s, id, json!({"rows": 3})).unwrap(); + assert_eq!(table(&s, id)["sort"], json!(b)); + // Given again as stored, it is kept, as a column's name is. + update(&mut s, id, json!({"sort": b})).unwrap(); + assert_eq!(table(&s, id)["sort"], json!(b)); + refused(&mut s, "layout.update", json!({"element": id, "sort": b.to_uppercase()}), "no field"); +} + +#[test] +fn undo_redo_and_a_reopened_project_keep_the_sort_and_the_row_switches() { + let (mut s, id) = tabled(); + let plain = table(&s, id); + let [b, _] = two_fields(&s); + update(&mut s, id, json!({"sort": b, "descending": true, "selectedOnly": true})).unwrap(); + let set = table(&s, id); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!(table(&s, id), plain); + s.run("edit.redo", &Value::Null).unwrap(); + assert_eq!(table(&s, id), set); + let saved = serde_json::to_value(&s.project).unwrap(); + let requires = saved["requires"].as_array().unwrap(); + assert!(requires.contains(&json!("layout-table-rows")), "{requires:?}"); + assert!(!requires.contains(&json!("layout-table-look")), "{requires:?}"); + let reopened = Project::from_json(&saved.to_string()).unwrap(); + assert_eq!(serde_json::to_value(&reopened.layouts).unwrap(), saved["layouts"]); +} + +#[test] +fn selected_rows_alone_are_counted_as_asked_for() { + let mut s = parcels(); + // No selection: no rows asked for, so nothing cut. + let (id, said) = added(&mut s, 100.0, 42.0, json!({"selectedOnly": true})); + assert!(said.is_empty(), "{said:?}"); + select(&mut s, "Parcels", &[7, 2]); + assert!(table_exported(&mut s, "png").is_empty()); + assert_eq!(cut_said(&mut s, "layout.update", json!({"element": id, "h": 10})), [cut(&s, id, "1 of 2 rows")]); + // Turned off, all twenty are asked for again. + assert_eq!(cut_said(&mut s, "layout.update", json!({"element": id, "selectedOnly": false})), [cut(&s, id, "1 of 20 rows")]); +} + +/// What `command` with `p` says of tables whose sort field is gone. +fn unsorted_said(s: &mut Session, command: &str, p: Value) -> Vec { + let mark = s.notice_mark(); + s.run(command, &p).unwrap(); + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("no longer")).collect() +} + +/// A table sorted by a field its layer then loses draws in the layer's order: a change to it, an +/// export and a report say so (#3409), and say nothing while the field is there. +#[test] +fn a_lost_sort_field_is_said_by_changes_exports_and_reports() { + let mut s = parcels(); + let (id, _) = added(&mut s, 100.0, 100.0, json!({"rows": 5, "sort": "f2"})); + let dir = Dir::new("unsorted"); + let export = + |s: &mut Session, ext: &str| unsorted_said(s, "layout.export", json!({"path": dir.0.join(format!("page.{ext}")), "dpi": 36})); + let report = |s: &mut Session| unsorted_said(s, "report.export", json!({"report": "R", "path": dir.0.join("r.pdf"), "dpi": 36})); + s.run("report.new", &json!({"layer": "Few", "name": "R"})).unwrap(); + for _ in 0..2 { + s.run("report.existingTemplate", &json!({"report": "R", "layout": "Tables", "end": true})).unwrap(); + } + assert!(export(&mut s, "png").is_empty() && report(&mut s).is_empty()); + assert!(unsorted_said(&mut s, "layout.update", json!({"element": id, "rows": 4})).is_empty()); + s.run("edit.deleteField", &json!({"layer": "Parcels", "field": "f2"})).unwrap(); + let name = s.project.layouts[0].element(id as u32).unwrap().name.clone(); + let one = format!( + "Table \"{name}\" ({id}): its layer no longer has the field \"f2\" it sorts by, so its rows come in the layer's order; choose another field to sort by, or none" + ); + for ext in ["png", "pdf", "svg"] { + assert_eq!(export(&mut s, ext), std::slice::from_ref(&one), "{ext}"); + } + assert_eq!(report(&mut s), [format!("The report: {}", in_layout(&one, id, "Tables"))]); + assert_eq!(unsorted_said(&mut s, "layout.update", json!({"element": id, "rows": 3})), std::slice::from_ref(&one)); + // Whatever changes the rows it lists says it. + for change in [json!({"descending": true}), json!({"selectedOnly": false}), json!({"sort": "f2"}), json!({"fields": ["f1"]})] { + let mut p = change.clone(); + p["element"] = json!(id); + let said = unsorted_said(&mut s, "layout.update", p); + // The same field named again is held, as a lost column's name is. + assert_eq!(said, std::slice::from_ref(&one), "{change}"); + } + // Two of them, in one notice; cut as well, each kind says its own. + let (other, _) = added(&mut s, 100.0, 100.0, json!({"rows": 3, "sort": "f3", "y": 110})); + s.run("edit.deleteField", &json!({"layer": "Parcels", "field": "f3"})).unwrap(); + let second = s.project.layouts[0].element(other as u32).unwrap().name.clone(); + let both = format!( + "2 tables sort by a field their layer no longer has, so their rows come in the layer's order: \"{name}\" ({id}) by \"f2\"; \"{second}\" ({other}) by \"f3\"; choose another field to sort each by, or none" + ); + assert_eq!(export(&mut s, "png"), [both]); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": other, "h": 9})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert_eq!(said.iter().filter(|t| t.contains("box shows")).count(), 1, "{said:?}"); + assert_eq!(said.iter().filter(|t| t.contains("no longer")).count(), 1, "{said:?}"); + // Sorted by a field it has, or by none, there is nothing to say. + assert!(unsorted_said(&mut s, "layout.update", json!({"element": id, "sort": "f1"})).is_empty()); + assert!(unsorted_said(&mut s, "layout.update", json!({"element": other, "sort": null})).is_empty()); + assert!(export(&mut s, "png").is_empty()); +} diff --git a/crates/map/src/layout/elements.rs b/crates/map/src/layout/elements.rs index d705073ffc..e3037d7fd2 100644 --- a/crates/map/src/layout/elements.rs +++ b/crates/map/src/layout/elements.rs @@ -303,6 +303,16 @@ pub enum ElementKind { /// The row of field names over its rows. #[serde(default = "yes", skip_serializing_if = "is_true")] header: bool, + /// The field its rows are ordered by, by its own name; none, the layer's order. Kept when + /// the layer loses the field, and its rows then come in the layer's order. + #[serde(default, skip_serializing_if = "Option::is_none")] + sort: Option, + /// The largest value of `sort` first. + #[serde(default, skip_serializing_if = "is_false")] + descending: bool, + /// Only the layer's selected features: with none selected, no rows. + #[serde(default, skip_serializing_if = "is_false")] + selected_only: bool, }, /// A bar chart of a numeric field of a layer in a frame's map: one bar per feature, or one /// per value of a `group` field ([`ElementKind::chart_data`], #2487). @@ -440,6 +450,127 @@ pub fn table_field(ds: &rustgis_data::Dataset, name: &str) -> Option { ds.fields.iter().position(|f| f.name == name).or_else(|| ds.field_index(name)) } +/// Which of a layer's features a table lists, and in what order. +#[derive(Clone, Copy, Debug, Default)] +pub struct TableRows<'a> { + /// The field they are ordered by, spelled as the layer stores it; none, the layer's order. + pub sort: Option<&'a str>, + /// The largest value of `sort` first. + pub descending: bool, + /// Only the layer's selected features. + pub selected_only: bool, +} + +/// The features of a layer a table has to list from, whatever rows it asks for: its selected rows, +/// worked out once for the count and the order, or all of them. +pub struct TableListing<'a> { + layer: &'a crate::Layer, + look: TableRows<'a>, + /// The selected rows, each once, in the layer's order; none when every row is listed from. + selected: Option>, +} + +/// What a table showing `look` lists from in `layer`. +pub fn table_listing<'a>(layer: &'a crate::Layer, look: TableRows<'a>) -> TableListing<'a> { + let selected = look.selected_only.then(|| { + let mut rows: Vec = layer.selection.iter().copied().filter(|r| *r < layer.dataset.features.len()).collect(); + rows.sort_unstable(); + rows.dedup(); + rows + }); + TableListing { layer, look, selected } +} + +/// 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, + row: usize, + descending: bool, +} + +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 + /// keeps the same rows however the layer holds them, which [`Value`]'s own order isn't (kinds + /// compare as text, and so does an infinity). A float that is no number is an empty value. + /// + /// [`Value`]: rustgis_data::Value + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + use rustgis_data::Value; + let kind = |v: &Value| match v { + Value::Null => 0, + Value::Float(f) if f.is_nan() => 0, + Value::Bool(_) => 1, + Value::Int(_) | Value::Float(_) => 2, + Value::Date(_) | Value::DateTime(_) => 3, + Value::Text(_) => 4, + }; + 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), + }); + let by_value = if self.descending { by_value.reverse() } else { by_value }; + by_value.then(self.row.cmp(&other.row)) + } +} + +impl PartialOrd for Sorted<'_> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl PartialEq for Sorted<'_> { + fn eq(&self, other: &Self) -> bool { + self.cmp(other).is_eq() + } +} + +impl Eq for Sorted<'_> {} + +impl TableListing<'_> { + /// How many features there are to list. + pub fn count(&self) -> usize { + self.selected.as_ref().map_or(self.layer.dataset.features.len(), Vec::len) + } + + /// 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. + pub fn first(self, limit: usize) -> Vec { + let ds = &self.layer.dataset; + let descending = self.look.descending; + // Spelled as stored, as a column's field is. + let field = self.look.sort.and_then(|name| ds.fields.iter().position(|f| f.name == name)); + let Some(field) = field else { + return match self.selected { + Some(rows) => rows.into_iter().take(limit).collect(), + None => (0..ds.features.len().min(limit)).collect(), + }; + }; + let mut best = std::collections::BinaryHeap::new(); + let mut offer = |row: usize| { + let next = Sorted { value: ds.value(row, field), row, descending }; + if best.len() < limit { + best.push(next); + } else if let Some(mut last) = best.peek_mut() + && next < *last + { + *last = next; + } + }; + 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() + } +} + impl ElementKind { /// A text element in the plain style: upright, left-aligned, normally spaced. pub fn text(text: impl Into, size: f64, color: Rgba, bold: bool) -> ElementKind { @@ -623,9 +754,9 @@ impl ElementKind { /// Whether `key` given as null changes an element of this kind, giving it back its default: /// an ink's `color`, a chart's `title` (the title it is given), `barColor`, `max` (its bars' - /// own scale) and `barOutline` (none), a legend's, scale bar's or table's `textSize` (#2581), and a - /// scale bar's `unitLabel` (its unit's abbreviation), and a profile's `fill` (none), `min` and - /// `max` (its samples' own). + /// own scale) and `barOutline` (none), a legend's, scale bar's or table's `textSize` (#2581), a + /// scale bar's `unitLabel` (its unit's abbreviation), a table's `sort` (none), and a profile's + /// `fill` (none), `min` and `max` (its samples' own). pub fn null_resets(&self, key: &str) -> bool { (self.takes_ink() && key == "color") || (matches!(self, ElementKind::Chart { .. }) && matches!(key, "title" | "barColor" | "max" | "barOutline")) @@ -634,6 +765,7 @@ impl ElementKind { ElementKind::Legend { .. } | ElementKind::ScaleBar { .. } | ElementKind::Table { .. } | ElementKind::Colorbar { .. } ) && key == "textSize") || (matches!(self, ElementKind::ScaleBar { .. }) && key == "unitLabel") + || (matches!(self, ElementKind::Table { .. }) && key == "sort") || (self.is_profile() && matches!(key, "fill" | "min" | "max")) } @@ -739,6 +871,13 @@ impl ElementKind { if !fields.is_empty() || !is_table_text_pt(text_size) || !header) } + /// Whether this is a table with its rows sorted or only the selected ones listed (#3409): an + /// older reader would draw the layer's first rows and save it again without. + pub fn table_uses_rows(&self) -> bool { + matches!(self, ElementKind::Table { sort, descending, selected_only, .. } + if sort.is_some() || *descending || *selected_only) + } + /// Whether this is a colorbar with its labels sized or their decimals chosen (#3437): an /// older reader would draw it without and save it again without. pub fn colorbar_uses_labels(&self) -> bool { diff --git a/crates/map/src/layout/tests.rs b/crates/map/src/layout/tests.rs index 3c6b639478..aafa3a49a9 100644 --- a/crates/map/src/layout/tests.rs +++ b/crates/map/src/layout/tests.rs @@ -2254,3 +2254,140 @@ fn a_colorbars_label_size_and_decimals_out_of_range_are_counted() { assert_eq!(((*text_size, *d), repairs.elements_adjusted), (kept, adjusted), "{size} {decimals}"); } } + +/// The rows a table lists: the layer's first, a field's order either way with equal values as the +/// layer holds them, the selected ones alone, and never more than asked (#3409). +#[test] +fn a_table_lists_rows_sorted_and_selected() { + let mut layer = crate::Layer::new(1, places()); + let order = |layer: &crate::Layer, sort: Option<&str>, descending, selected_only, limit| { + table_listing(layer, TableRows { sort, descending, selected_only }).first(limit) + }; + assert_eq!(order(&layer, None, false, false, 3), [0, 1, 2]); + assert_eq!(order(&layer, None, true, false, 20), [0, 1, 2, 3, 4, 5, 6], "no field to turn round"); + // The missing number first going up, last going down. + assert_eq!(order(&layer, Some("people"), false, false, 20), [4, 6, 5, 2, 1, 3, 0]); + assert_eq!(order(&layer, Some("people"), true, false, 20), [0, 3, 1, 2, 5, 6, 4]); + assert_eq!(order(&layer, Some("people"), true, false, 2), [0, 3]); + assert_eq!(order(&layer, Some("people"), false, false, 3), [4, 6, 5]); + assert!(order(&layer, Some("people"), false, false, 0).is_empty()); + // Equal values in the layer's order, either way. + assert_eq!(order(&layer, Some("region"), false, false, 20), [5, 3, 0, 2, 1, 4, 6]); + assert_eq!(order(&layer, Some("region"), true, false, 20), [6, 1, 4, 0, 2, 3, 5]); + // A field the layer hasn't, or spelled another way, leaves the layer's order. + assert_eq!(order(&layer, Some("gone"), true, false, 3), [0, 1, 2]); + assert_eq!(order(&layer, Some("PEOPLE"), false, false, 3), [0, 1, 2]); + let selected = TableRows { selected_only: true, ..TableRows::default() }; + assert!(order(&layer, None, false, true, 20).is_empty() && table_listing(&layer, selected).count() == 0); + // Each once, in the layer's order, and none past its last row. + layer.selection = vec![6, 0, 3, 0, 99]; + assert_eq!(table_listing(&layer, selected).count(), 3); + assert_eq!(order(&layer, None, false, true, 20), [0, 3, 6]); + assert_eq!(order(&layer, None, false, true, 2), [0, 3]); + assert_eq!(order(&layer, Some("people"), false, true, 20), [6, 3, 0]); + assert_eq!(order(&layer, Some("people"), true, true, 2), [0, 3]); + assert_eq!(table_listing(&layer, TableRows::default()).count(), 7); + layer.dataset.features.clear(); + assert!(order(&layer, Some("people"), false, false, 500).is_empty()); +} + +/// Text sorts ignoring case, dates by instant, and a number that isn't one with the nulls. +#[test] +fn a_tables_sort_reads_values_as_the_attribute_table_does() { + use rustgis_data::{Dataset, Field, FieldType, Value}; + let sorted = |ty: FieldType, values: Vec| { + let mut ds = Dataset::new("t", rustgis_data::GeometryType::Point, vec![Field::new("v", ty)]); + for v in values { + ds.push(None, vec![v]); + } + let look = TableRows { sort: Some("v"), ..TableRows::default() }; + table_listing(&crate::Layer::new(1, ds), look).first(10) + }; + let text = |t: &str| Value::Text(t.into()); + assert_eq!(sorted(FieldType::Text, vec![text("beta"), text("Alpha"), text("gamma")]), [1, 0, 2]); + let date = |d: &str| Value::Date(rustgis_data::Date::parse(d).unwrap()); + assert_eq!(sorted(FieldType::Date, vec![date("2024-02-01"), date("2023-12-31"), date("2024-01-15")]), [1, 2, 0]); + let float = Value::Float; + assert_eq!(sorted(FieldType::Double, vec![float(2.0), float(f64::NAN), float(1.0), Value::Null]), [1, 3, 2, 0]); +} + +/// A field holding several kinds of value still lists the first rows of one order, however the +/// layer holds them: empty, yes or no, numbers, dates, then text. +#[test] +fn a_tables_sort_of_mixed_values_does_not_depend_on_the_rows_order() { + use rustgis_data::{Dataset, Field, FieldType, Value}; + let date = Value::Date(rustgis_data::Date::parse("2024-01-15").unwrap()); + let noon = Value::DateTime(rustgis_data::DateTime::parse("2024-01-15T12:00Z").unwrap()); + let text = |t: &str| Value::Text(t.into()); + let float = Value::Float; + // Infinities and the floats whose text is "inf" among them, zero twice, and a negative one. + let ordered = [ + Value::Null, + Value::Bool(false), + Value::Bool(true), + float(f64::NEG_INFINITY), + float(-1e303), + Value::Int(-5), + float(-0.5), + Value::Int(0), + float(-0.0), + float(0.5), + Value::Int(9), + float(9.5), + float(1e303), + float(1e304), + float(f64::INFINITY), + date, + noon, + text("10a"), + text("Alpha"), + text("alpha"), + text("beta"), + ]; + // Every rotation of them, forwards and backwards. + for turn in 0..ordered.len() { + for back in [false, true] { + let mut values = ordered.to_vec(); + values.rotate_left(turn); + if back { + values.reverse(); + } + let mut ds = Dataset::new("t", rustgis_data::GeometryType::Point, vec![Field::new("v", FieldType::Text)]); + for v in &values { + ds.push(None, vec![v.clone()]); + } + let layer = crate::Layer::new(1, ds); + for descending in [false, true] { + let mut want = ordered.to_vec(); + if descending { + want.reverse(); + } + for limit in 1..=ordered.len() { + let look = TableRows { sort: Some("v"), descending, selected_only: false }; + let listed: Vec = table_listing(&layer, look).first(limit).into_iter().map(|row| values[row].clone()).collect(); + assert_eq!(listed, want[..limit], "turn {turn} back {back} descending {descending}"); + } + } + } + } +} + +/// Many rows give the same first ones a whole sort would. +#[test] +fn a_tables_first_rows_of_many_are_the_whole_sorts_first() { + use rustgis_data::{Dataset, Field, FieldType, Value}; + let mut ds = Dataset::new("t", rustgis_data::GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + for i in 0..20_000_i64 { + ds.push(None, vec![Value::Int((i * 7919) % 1009)]); + } + let layer = crate::Layer::new(1, ds); + for descending in [false, true] { + let mut whole: Vec = (0..layer.dataset.features.len()).collect(); + whole.sort_by_key(|&row| { + let n = layer.dataset.value(row, 0).as_f64().unwrap_or_default() as i64; + (if descending { -n } else { n }, row) + }); + let look = TableRows { sort: Some("n"), descending, selected_only: false }; + assert_eq!(table_listing(&layer, look).first(500), whole[..500]); + } +} diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 2136197a9a..6816375c97 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -10,8 +10,8 @@ use rustgis_geom::{Coord, Extent}; use rustgis_map::layout::{ ArrowStyle, COLORBAR_TEXT_PT, ChartLook, ColorScale, ElementKind, FrameShape, GRID_LABEL_PT, Grid, GridKind, INK, LAYOUT_TEXT_SIZE, LEGEND_TEXT_PT, Layout, LegendFit, LineHead, MAX_LEGEND_COLUMNS, Orientation, PT_PER_MM, SCALE_BAR_TEXT_PT, ScaleBarFit, ScaleBarStyle, - ScaleLabelPosition, ScaleUnits, Section, SectionLine, TextAlign, TextCase, TextVAlign, TickSide, UnitLabelPosition, frame_camera, - layout_text_in_range, layout_text_scale, legend_columns_in_range, + ScaleLabelPosition, ScaleUnits, Section, SectionLine, TableRows, TextAlign, TextCase, TextVAlign, TickSide, UnitLabelPosition, + frame_camera, layout_text_in_range, layout_text_scale, legend_columns_in_range, }; use rustgis_map::symbology::LegendEntry; use rustgis_map::{Map, Rgba}; @@ -51,7 +51,7 @@ pub use scale_bar::*; pub use section::*; use swatch::*; use table::*; -pub use table::{TableCut, table_cut_notice, tables_cut}; +pub use table::{TableCut, table_notices, tables_cut}; pub use textbox::*; /// Page values for dynamic text. @@ -734,12 +734,12 @@ fn draw_page( } None => draw_picture_box(&mut pm, r, source.as_deref(), ppp), }, - ElementKind::Table { frame: f, layer, rows, color, fields, text_size, header } => { - let ds = frame(*f).and_then(|fr| maps.get(fr.1)).and_then(|m| m.layer_by_name(layer)).map(|l| &l.dataset); - match ds { - Some(ds) => { - let look = TableLook { rows: *rows, fields, text_size: *text_size, header: *header }; - table(&mut pm, r, ds, look, *color, ppp) + ElementKind::Table { frame: f, layer, rows, color, fields, text_size, header, sort, descending, selected_only } => { + match frame(*f).and_then(|fr| maps.get(fr.1)).and_then(|m| m.layer_by_name(layer)) { + Some(shown) => { + let listed = TableRows { sort: sort.as_deref(), descending: *descending, selected_only: *selected_only }; + let look = TableLook { rows: *rows, fields, text_size: *text_size, header: *header, listed }; + table(&mut pm, r, shown, look, *color, ppp) } None => placeholder(&mut pm, r, "Table", ppp), } diff --git a/crates/render/src/layout/table.rs b/crates/render/src/layout/table.rs index 59fd8b0995..66a4a9b290 100644 --- a/crates/render/src/layout/table.rs +++ b/crates/render/src/layout/table.rs @@ -1,7 +1,7 @@ //! The attribute table element. use super::*; -use rustgis_map::layout::TABLE_TEXT_PT; +use rustgis_map::layout::{TABLE_TEXT_PT, TableRows, table_listing}; /// How a table is laid out: the rows and fields it shows, its text and whether it is headed. #[derive(Clone, Copy)] @@ -11,6 +11,8 @@ pub(super) struct TableLook<'a> { pub fields: &'a [String], pub text_size: f64, pub header: bool, + /// Which features its rows are, in what order. + pub listed: TableRows<'a>, } /// How much of a table its box holds: the size it draws at and the columns and rows shown. @@ -25,7 +27,7 @@ pub(super) struct TableFit { pub rows: usize, } -/// What a table of a layer with `fields` fields and `features` features shows in `r`: what +/// What a table of a layer with `fields` fields and `features` features to list shows in `r`: what /// [`table`] draws and [`tables_cut`] counts. pub(super) fn table_fit(r: Rect, look: TableLook, fields: usize, features: usize, ppp: f32) -> TableFit { let pt = rustgis_map::layout::layout_text_in_range(look.text_size, TABLE_TEXT_PT) as f32; @@ -44,7 +46,8 @@ fn asked_columns(look: TableLook, fields: usize) -> usize { if look.fields.is_empty() { fields } else { look.fields.len() } } -/// A table whose box leaves out rows or columns it is asked to show, each as shown and asked. +/// A table that draws other than it is asked to: its box leaves out rows or columns, each as shown +/// and asked, or its layer no longer has the field it sorts by. #[derive(Debug, Clone, PartialEq)] pub struct TableCut { pub id: u32, @@ -53,74 +56,121 @@ pub struct TableCut { pub layout: Option, pub rows: (usize, usize), pub cols: (usize, usize), + /// The field it sorts by that its layer no longer has: its rows come in the layer's order. + pub lost_sort: Option, +} + +impl TableCut { + /// Whether its box leaves any of them out. + pub fn is_cut(&self) -> bool { + self.rows.0 < self.rows.1 || self.cols.0 < self.cols.1 + } } /// The tables of `layout` drawn at `dpi` whose boxes don't hold the rows and columns they are -/// asked to show (#3416). A hidden table, one with none of its box on the page and one drawn as a -/// placeholder (no frame, map or layer) show nothing to count. +/// asked to show (#3416), or whose sort field is gone (#3409). A hidden table, one with none of +/// its box on the page and one drawn as a placeholder (no frame, map or layer) show nothing to +/// count. pub fn tables_cut(layout: &Layout, maps: &[Map], dpi: f64) -> Vec { let k = page_geometry(layout, dpi).2; let ppp = (k / PT_PER_MM) as f32; let cut = layout.elements.iter().filter(|e| e.visible && on_page(layout, e)).filter_map(|e| { - let ElementKind::Table { frame, layer, rows, fields, text_size, header, .. } = &e.kind else { return None }; + let ElementKind::Table { frame, layer, rows, fields, text_size, header, sort, descending, selected_only, .. } = &e.kind else { + return None; + }; let ElementKind::MapFrame { map, .. } = &layout.element(*frame)?.kind else { return None }; - let ds = &maps.get(map_index(maps, map)?)?.layer_by_name(layer)?.dataset; + let shown = maps.get(map_index(maps, map)?)?.layer_by_name(layer)?; + let ds = &shown.dataset; // At least a pixel each way, as the page draws it. let r = Rect::from_xywh((e.x * k) as f32, (e.y * k) as f32, ((e.w * k) as f32).max(1.0), ((e.h * k) as f32).max(1.0))?; - let look = TableLook { rows: *rows, fields, text_size: *text_size, header: *header }; - let fit = table_fit(r, look, ds.fields.len(), ds.features.len(), ppp); + let listed = TableRows { sort: sort.as_deref(), descending: *descending, selected_only: *selected_only }; + let look = TableLook { rows: *rows, fields, text_size: *text_size, header: *header, listed }; + let listable = table_listing(shown, listed).count(); + let fit = table_fit(r, look, ds.fields.len(), listable, ppp); let asked = asked_columns(look, ds.fields.len()); - let shown_rows = (fit.rows, (*rows).min(ds.features.len())); + let shown_rows = (fit.rows, (*rows).min(listable)); let shown_cols = (fit.cols.min(asked), asked); - (shown_rows.0 < shown_rows.1 || shown_cols.0 < shown_cols.1).then(|| TableCut { - id: e.id, - name: e.name.clone(), - layout: None, - rows: shown_rows, - cols: shown_cols, - }) + // Spelled as stored, as the rows are ordered. + let lost_sort = sort.as_ref().filter(|name| ds.fields.iter().all(|f| f.name != **name)).cloned(); + let table = TableCut { id: e.id, name: e.name.clone(), layout: None, rows: shown_rows, cols: shown_cols, lost_sort }; + (table.is_cut() || table.lost_sort.is_some()).then_some(table) }); cut.collect() } -/// One notice for the tables [`tables_cut`] found: each with what it shows of what it is asked -/// to, the first ten by name and id, and how many more. `None` when there are none. -pub fn table_cut_notice(cut: &[TableCut]) -> Option { +/// A table as a notice names it: by name and id, and in a report by its layout. +fn named(t: &TableCut) -> String { + let layout = t.layout.as_ref().map(|l| format!(" in \"{}\"", notice_cut(l))).unwrap_or_default(); + format!("\"{}\" ({}){layout}", notice_cut(&t.name), t.id) +} + +/// The first ten of `tables`, each as `said` says it, and how many more. +fn listed(tables: &[&TableCut], said: impl Fn(&TableCut) -> String) -> String { + let mut each = tables.iter().take(10).map(|t| said(t)).collect::>().join("; "); + if tables.len() > 10 { + each.push_str(&format!("; and {} more", tables.len() - 10)); + } + each +} + +/// What to say of the tables [`tables_cut`] found: one notice for those whose boxes leave rows or +/// columns out, and one for those whose sort field is gone. +pub fn table_notices(found: &[TableCut]) -> impl Iterator { + [table_cut_notice(found), table_sort_notice(found)].into_iter().flatten() +} + +/// One notice for the tables whose sort field is gone, each with that field. `None` when there are +/// none. +fn table_sort_notice(found: &[TableCut]) -> Option { + let lost: Vec<&TableCut> = found.iter().filter(|t| t.lost_sort.is_some()).collect(); + let field = |t: &TableCut| notice_cut(t.lost_sort.as_deref().unwrap_or_default()).to_string(); + match lost.as_slice() { + [] => None, + [t] => Some(format!( + "Table {}: its layer no longer has the field \"{}\" it sorts by, so its rows come in the layer's order; choose another field to sort by, or none", + named(t), + field(t) + )), + _ => Some(format!( + "{} tables sort by a field their layer no longer has, so their rows come in the layer's order: {}; choose another field to sort each by, or none", + lost.len(), + listed(&lost, |t| format!("{} by \"{}\"", named(t), field(t))) + )), + } +} + +/// One notice for the tables whose boxes leave some out: each with what it shows of what it is +/// asked to, the first ten by name and id, and how many more. `None` when there are none. +fn table_cut_notice(found: &[TableCut]) -> Option { + let cut: Vec<&TableCut> = found.iter().filter(|t| t.is_cut()).collect(); let shown = |t: &TableCut| { let part = |(shown, asked): (usize, usize), what: &str| (shown < asked).then(|| format!("{shown} of {asked} {what}")); [part(t.rows, "rows"), part(t.cols, "columns")].into_iter().flatten().collect::>().join(" and ") }; - let named = |t: &TableCut| { - let layout = t.layout.as_ref().map(|l| format!(" in \"{}\"", notice_cut(l))).unwrap_or_default(); - format!("\"{}\" ({}){layout}", notice_cut(&t.name), t.id) - }; - match cut { + match cut.as_slice() { [] => None, [t] => Some(format!( "Table {}: its box shows {}; make it larger, reduce its text size, or show fewer rows or fields", named(t), shown(t) )), - _ => { - let mut each = cut.iter().take(10).map(|t| format!("{} {}", named(t), shown(t))).collect::>().join("; "); - if cut.len() > 10 { - each.push_str(&format!("; and {} more", cut.len() - 10)); - } - Some(format!( - "{} tables show only part of what they are asked to: {each}; make them larger, reduce their text size, or show fewer rows or fields", - cut.len() - )) - } + _ => Some(format!( + "{} tables show only part of what they are asked to: {}; make them larger, reduce their text size, or show fewer rows or fields", + cut.len(), + listed(&cut, |t| format!("{} {}", named(t), shown(t))) + )), } } -/// The first rows of a table, with as many columns as fit: on white cells in dark grey, or +/// The rows of a table, with as many columns as fit: on white cells in dark grey, or /// with an `ink` (#2257) in it on no paper of its own, its header and stripes a tint of the ink, so /// it reads on whatever is behind it (a dark page, or the element's background). A column whose /// field the layer hasn't (removed or renamed since) keeps its name, its cells a dash. -pub(super) fn table(pm: &mut Canvas, r: Rect, ds: &rustgis_data::Dataset, look: TableLook, ink: Option, ppp: f64) { +pub(super) fn table(pm: &mut Canvas, r: Rect, layer: &rustgis_map::Layer, look: TableLook, ink: Option, ppp: f64) { let ppp = ppp as f32; - let TableFit { pt, px, row_h, col_w, cols, rows: n } = table_fit(r, look, ds.fields.len(), ds.features.len(), ppp); + let ds = &layer.dataset; + let listing = table_listing(layer, look.listed); + let TableFit { pt, px, row_h, col_w, cols, rows: n } = table_fit(r, look, ds.fields.len(), listing.count(), ppp); // Each column shown: its field's place in the layer, and its heading. let columns: Vec<(Option, &str)> = if look.fields.is_empty() { ds.fields.iter().enumerate().take(cols).map(|(i, f)| (Some(i), f.display())).collect() @@ -175,9 +225,9 @@ pub(super) fn table(pm: &mut Canvas, r: Rect, ds: &rustgis_data::Dataset, look: ); } } - for row in 0..n { - let y = r.y() + row_h * (row + head) as f32; - if row % 2 == 1 + for (line, row) in listing.first(n).into_iter().enumerate() { + let y = r.y() + row_h * (line + head) as f32; + if line % 2 == 1 && let Some(b) = Rect::from_xywh(r.x(), y, col_w * cols as f32, row_h) { pm.fill_rect(b, &paint(stripe, stripe_alpha), Transform::identity(), None); diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 344e4d31e4..f353c61c6b 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -773,9 +773,10 @@ fn an_ink_colours_legends_colorbars_tables_and_charts() { } // Two columns 90 px wide, a header and two rows 17 px high: (175, 25) is in the first // row's empty right end, (175, 8) in the header's. - let look = TableLook { rows: 5, fields: &[], text_size: 8.0, header: true }; - let plain = draw(&|c| table(c, r, &ds, look, None, 1.0)); - let inked = draw(&|c| table(c, r, &ds, look, Some(red), 1.0)); + let look = TableLook { rows: 5, fields: &[], text_size: 8.0, header: true, listed: Default::default() }; + let layer = rustgis_map::Layer::new(1, ds.clone()); + let plain = draw(&|c| table(c, r, &layer, look, None, 1.0)); + let inked = draw(&|c| table(c, r, &layer, look, Some(red), 1.0)); assert!(!reddish(&plain) && reddish(&inked)); let at = |c: &Canvas, x, y| c.pixmap().pixel(x, y).unwrap(); assert_eq!((at(&plain, 175, 25).red(), at(&plain, 175, 25).alpha()), (255, 255), "white cells without an ink"); @@ -797,7 +798,8 @@ fn a_table_draws_its_fields_at_its_size_headed_or_not() { let draw = |ds: &Dataset, fields: &[&str], text_size: f64, header: bool| { let fields: Vec = fields.iter().map(|f| (*f).to_string()).collect(); let mut c = Canvas::new(300, 120).unwrap(); - table(&mut c, r, ds, TableLook { rows: 20, fields: &fields, text_size, header }, None, 1.0); + let look = TableLook { rows: 20, fields: &fields, text_size, header, listed: Default::default() }; + table(&mut c, r, &rustgis_map::Layer::new(1, ds.clone()), look, None, 1.0); c.pixmap().data().to_vec() }; // The white paper's right and bottom ends, from the pixels painted. @@ -839,6 +841,37 @@ fn a_table_draws_its_fields_at_its_size_headed_or_not() { assert_eq!(ends(&draw(&short, &["n"], 8.0, false)).1, 35, "two rows"); } +/// A table sorted, or of the selected features alone, draws those rows in that order, striped by +/// their place in the table (#3409). +#[test] +fn a_table_draws_its_rows_sorted_and_selected() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; + use rustgis_map::layout::TableRows; + let places = |values: &[i64]| { + let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + for n in values { + ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Int(*n)]); + } + rustgis_map::Layer::new(1, ds) + }; + let r = Rect::from_xywh(0.0, 0.0, 120.0, 120.0).unwrap(); + let draw = |layer: &rustgis_map::Layer, listed: TableRows| { + let mut c = Canvas::new(120, 120).unwrap(); + table(&mut c, r, layer, TableLook { rows: 20, fields: &[], text_size: 8.0, header: true, listed }, None, 1.0); + c.pixmap().data().to_vec() + }; + let mut layer = places(&[30, 10, 40, 20]); + let sorted = TableRows { sort: Some("n"), ..TableRows::default() }; + assert_eq!(draw(&layer, sorted), draw(&places(&[10, 20, 30, 40]), TableRows::default())); + let down = TableRows { descending: true, ..sorted }; + assert_eq!(draw(&layer, down), draw(&places(&[40, 30, 20, 10]), TableRows::default())); + layer.selection = vec![3, 0]; + let only = TableRows { selected_only: true, ..TableRows::default() }; + assert_eq!(draw(&layer, only), draw(&places(&[30, 20]), TableRows::default())); + layer.selection.clear(); + assert_eq!(draw(&layer, only), draw(&places(&[]), TableRows::default()), "a header and no rows"); +} + /// No-data rows reuse the map's fallback symbol, respect filters, and never appear by /// default. All-classes mode can key the symbol even when the current frame doesn't use it. #[test] @@ -9191,11 +9224,11 @@ fn a_tables_fit_is_what_it_draws() { for (ppp, header) in [(1.0_f32, true), (1.0, false), (3.125, true), (3.125, false)] { let (w, h) = ((200.0 * ppp) as u32, (120.0 * ppp) as u32); let r = Rect::from_xywh(0.0, 0.0, w as f32, h as f32).unwrap(); - let look = TableLook { rows: 20, fields: &[], text_size: 8.0, header }; + let look = TableLook { rows: 20, fields: &[], text_size: 8.0, header, listed: Default::default() }; let fit = table_fit(r, look, ds.fields.len(), ds.features.len(), ppp); assert_eq!((fit.cols, fit.rows), (2, if header { 6 } else { 7 }), "{ppp} {header}"); let mut c = Canvas::new(w, h).unwrap(); - table(&mut c, r, &ds, look, None, f64::from(ppp)); + table(&mut c, r, &rustgis_map::Layer::new(1, ds.clone()), look, None, f64::from(ppp)); // The white paper's right and bottom ends: two columns of 90, and its rows of 17.024. let painted = c.pixmap().pixels().iter().enumerate().filter(|(_, p)| p.alpha() > 0); let (right, bottom) = painted.fold((0, 0), |(x, y), (i, _)| (x.max(i as u32 % w + 1), y.max(i as u32 / w + 1))); diff --git a/crates/ui-egui/src/layoutview/format/table.rs b/crates/ui-egui/src/layoutview/format/table.rs index 4a06b834c7..7e34890916 100644 --- a/crates/ui-egui/src/layoutview/format/table.rs +++ b/crates/ui-egui/src/layoutview/format/table.rs @@ -5,13 +5,21 @@ use super::*; use crate::RustGisApp; use crate::widgets::Dragged; use egui::Ui; +use rustgis_engine::data::Dataset; use rustgis_engine::map::layout::{Element, ElementKind, Layout}; use serde_json::{Value, json}; use std::collections::HashSet; -/// A table's rows, text size and header in the grid. +/// The data of the layer a table lists, in its frame's map; none when either is gone. +fn table_data<'a>(app: &'a RustGisApp, layout: &Layout, frame: u32, layer: &str) -> Option<&'a Dataset> { + let ElementKind::MapFrame { map, .. } = &layout.element(frame)?.kind else { return None }; + let map = app.session.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(map))?; + map.layer_by_name(layer).map(|l| &l.dataset) +} + +/// A table's rows, text size, header and order in the grid. pub(super) fn table_look(app: &mut RustGisApp, ui: &mut Ui, li: usize, e: &Element, update: &dyn Fn(&mut RustGisApp, Value)) { - let ElementKind::Table { rows, text_size, header, .. } = &e.kind else { return }; + let ElementKind::Table { frame, layer, rows, text_size, header, sort, descending, selected_only, .. } = &e.kind else { return }; let id = e.id; let drag_key = |field: &str| number_key(li, id, field); let input_label = ui.label(tl!("Rows")); @@ -32,17 +40,60 @@ pub(super) fn table_look(app: &mut RustGisApp, ui: &mut Ui, li: usize, e: &Eleme update(app, json!({"header": headed})); } ui.end_row(); + let fields: Vec = app + .session + .project + .layouts + .get(li) + .and_then(|layout| table_data(app, layout, *frame, layer)) + .map(|ds| ds.fields.iter().map(|f| f.name.clone()).collect()) + .unwrap_or_default(); + let input_label = ui.label(tl!("Sort by")); + // A field the layer has lost still shows by its name, until another is picked. + let chosen = sort.as_deref().map_or_else(|| tl!("None").to_string(), str::to_string); + let mut picked: Option> = None; + egui::ComboBox::from_id_salt(("table_sort", li, id)) + .selected_text(chosen) + .show_ui(ui, |ui| { + if ui.selectable_label(sort.is_none(), tl!("None")).clicked() { + picked = Some(None); + } + for f in &fields { + if ui.selectable_label(sort.as_deref() == Some(f), f.as_str()).clicked() { + picked = Some(Some(f)); + } + } + }) + .response + .labelled_by(input_label.id); + if let Some(to) = picked + && to != sort.as_deref() + { + update(app, json!({"sort": to})); + } + ui.end_row(); + let input_label = ui.label(tl!("Descending")); + let mut down = *descending; + // Without a sort there is no order to turn; a kept one can still be turned off. + let turns = sort.is_some() || down; + if ui.add_enabled(turns, egui::Checkbox::new(&mut down, "")).labelled_by(input_label.id).changed() { + update(app, json!({"descending": down})); + } + ui.end_row(); + let input_label = ui.label(tl!("Selected only")); + let mut only = *selected_only; + let hover = tl!("Only the layer's selected features"); + if ui.checkbox(&mut only, "").labelled_by(input_label.id).on_hover_text(hover).changed() { + update(app, json!({"selectedOnly": only})); + } + ui.end_row(); } /// A table's columns, below the grid: every field of its layer, those it shows ticked and first, /// in the order drawn (#3409). pub(super) fn table_columns(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, e: &Element, update: &dyn Fn(&mut RustGisApp, Value)) { let ElementKind::Table { frame, layer, fields, .. } = &e.kind else { return }; - let map = match layout.element(*frame).map(|f| &f.kind) { - Some(ElementKind::MapFrame { map, .. }) => app.session.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(map)), - _ => None, - }; - let Some(ds) = map.and_then(|m| m.layer_by_name(layer)).map(|l| &l.dataset) else { return }; + let Some(ds) = table_data(app, layout, *frame, layer) else { return }; let all = || ds.fields.iter().map(|f| f.name.as_str()); let rows = || { let row = |name: &str, ticked: bool| Row { diff --git a/crates/ui-egui/src/layoutview/table_tests.rs b/crates/ui-egui/src/layoutview/table_tests.rs index b1c427bf93..00c8869cd1 100644 --- a/crates/ui-egui/src/layoutview/table_tests.rs +++ b/crates/ui-egui/src/layoutview/table_tests.rs @@ -232,3 +232,37 @@ fn another_layer_lists_its_own_fields_and_a_lost_one_shows_no_section() { h.run_steps(3); assert!(h.query_by_label("Columns").is_none() && h.query_by_label("Select All").is_none()); } + +/// What the table keeps of its order: the sort field, descending and selected rows only. +fn order(h: &Harness, li: usize, id: u32) -> (Option, bool, bool) { + match &h.state().session.project.layouts[li].element(id).unwrap().kind { + ElementKind::Table { sort, descending, selected_only, .. } => (sort.clone(), *descending, *selected_only), + k => panic!("{k:?}"), + } +} + +/// Sort by, Descending and Selected only change the table, each in one undo step; without a sort +/// there is nothing to turn round (#3409). +#[test] +fn rows_are_sorted_and_limited_to_the_selection_from_the_pane() { + let (mut h, li, id, fields) = columns(0, json!({})); + assert!(disabled(&h, "Descending")); + let depth = h.state().session.undo_depth(); + h.get_by_role_and_label(Role::ComboBox, "Sort by").click(); + h.run_steps(3); + // The field's own row in the open list, not its Columns box. + h.get_by_role_and_label(Role::Button, &fields[1]).click(); + h.run_steps(3); + assert_eq!(order(&h, li, id), (Some(fields[1].clone()), false, false)); + assert_eq!(h.state().session.undo_depth(), depth + 1); + press(&mut h, "Descending"); + press(&mut h, "Selected only"); + assert_eq!(order(&h, li, id), (Some(fields[1].clone()), true, true)); + h.get_by_role_and_label(Role::ComboBox, "Sort by").click(); + h.run_steps(3); + press(&mut h, "None"); + assert_eq!(order(&h, li, id), (None, true, true)); + // Left on, it can still be turned off. + press(&mut h, "Descending"); + assert!(disabled(&h, "Descending")); +} diff --git a/crates/ui-egui/src/layoutview/tests.rs b/crates/ui-egui/src/layoutview/tests.rs index 7a563e0d3e..e20d8f6fcb 100644 --- a/crates/ui-egui/src/layoutview/tests.rs +++ b/crates/ui-egui/src/layoutview/tests.rs @@ -35,7 +35,18 @@ fn inked(paper: Rgba, background: Option, under: impl FnOnce(&mut Layout), let id = layout.add( "Table", (10.0, 10.0, 40.0, 40.0), - ElementKind::Table { frame: 1, layer: "Cities".into(), rows: 3, color: None, fields: Vec::new(), text_size: 8.0, header: true }, + ElementKind::Table { + frame: 1, + layer: "Cities".into(), + rows: 3, + color: None, + fields: Vec::new(), + text_size: 8.0, + header: true, + sort: None, + descending: false, + selected_only: false, + }, ); layout.element_mut(id).unwrap().background = background.map(Background::filled); over(&mut layout); diff --git a/docs/maintaining.md b/docs/maintaining.md index 9f58f2c75f..39f155ebe2 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -311,6 +311,13 @@ as a value out of range. Saved `layout.addElement` commands for a table with any `layout.update` commands that give `fields` or `header`, require it too; `null` needs nothing. A saved `layout.import` whose `text` has such a table requires it as well. +Projects with a layout table that is sorted (`sort`), largest first (`descending`) or lists only +selected features (`selected_only`) require `layout-table-rows`, so an older reader refuses them +instead of drawing the layer's first rows and saving it again without (#3409). Saved +`layout.addElement` commands for a table with any of them, and `layout.update` commands that give +one, require it too; `null` needs nothing. A saved `layout.import` whose `text` has such a table +requires it as well. + Projects with a layout colorbar whose labels aren't 8 points (`text_size`) or have their decimals chosen (`decimals`) require `layout-colorbar-labels`, so an older reader refuses them instead of drawing the default labels and saving the colorbar again without (#3437). In a hand-edited file, a diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index ea6767f809..7a8031caad 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -894,7 +894,16 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu shows every field again, and another layer without fields of its own does too. A field removed or renamed afterwards keeps its column, headed by that name over a dash in every row, until the layer has a field of exactly that name again, which the column then shows; a new list of - `"fields"` may still name it, spelled so. When its box doesn't + `"fields"` may still name it, spelled so. It lists the layer's first rows in the layer's order. + **Sort by** a field lists the first rows in that field's order instead: empty values first, + numbers by value, dates by instant, text ignoring case (then by case), equal values in the + layer's order; in a field holding several kinds of value, yes or no come first, then numbers, + dates and text. **Descending** turns it round. **Selected only** lists the layer's selected + features, and no rows while none is selected. From a command: + `layout.update={"element":6,"sort":"POP","descending":true,"selectedOnly":false}`, `"sort":null` + returning to the layer's order; another layer without a sort of its own drops it. A sort field + removed or renamed afterwards is kept by name and its rows come in the layer's order; a change + to the table's box or to what it lists says so, as an export and a report do. When its box doesn't hold the rows and columns it is asked to show, adding or changing the table says how many it shows, and so does an export or a report. - **Chart frame**: a bar chart of a layer of the frame's map. Its properties pick the **Layer** diff --git a/schema/fixtures/layout_table_rows.rgis b/schema/fixtures/layout_table_rows.rgis new file mode 100644 index 0000000000..33b62bd1a3 --- /dev/null +++ b/schema/fixtures/layout_table_rows.rgis @@ -0,0 +1 @@ +{"format":2,"requires":["layout-table-rows"],"name":"Table rows","maps":[{"name":"Map","layers":[],"basemap":"Paper","camera":{"center":{"x":0.0,"y":2000000.0},"res":30000.0,"bearing":0.0,"pitch":0.0},"bookmarks":[],"graticule":true,"projection":"WebMercator","popup_mode":"Topmost","label_display":{"paused":false,"locked":false,"show_unplaced":false},"editing":{"relationships":[],"snapping":{"enabled":false,"tolerance_px":10.0,"vertex":true,"edge":true,"end":true},"topology":[],"settings":{"enabled":true,"show_vertices":true,"elevation":"None","ground_to_grid":null}},"swipe":null,"view":{"effects":{"stars":true,"sun_time":null,"weather":"None","vignette":false,"edges":false,"tilt_shift":false,"grain":false,"brightness":0.0,"contrast":0.0,"saturation":0.0,"sepia":0.0},"wireframe":false,"clip_distance":null,"terrain":null},"animation":[],"next_layer_id":1}],"active_map":0,"tables":[],"next_table_id":1,"gp_history":[],"layouts":[{"name":"Listed","width":120,"height":90,"elements":[{"id":1,"name":"Frame","x":10,"y":10,"w":60,"h":70,"kind":{"MapFrame":{"map":"Map","center":{"x":0,"y":0},"scale":1000000}}},{"id":2,"name":"Table","x":75,"y":10,"w":35,"h":40,"kind":{"Table":{"frame":1,"layer":"Places","rows":5,"sort":"people","descending":true,"selected_only":true}}}]}],"folders":[],"styles":[],"ramps":[],"tasks":[],"gp_env":{"extent":null,"cell_size":null},"models":[],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[]} diff --git a/schema/project.schema.json b/schema/project.schema.json index 6fa3014cd4..19a6e91110 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1280,6 +1280,7 @@ "layout-chart-facing", "layout-chart-outline", "layout-table-look", + "layout-table-rows", "layout-colorbar-labels", "field-generation", "field-package", @@ -1423,6 +1424,7 @@ "layout-chart-facing", "layout-chart-outline", "layout-table-look", + "layout-table-rows", "layout-colorbar-labels", "field-generation", "field-package",