From f22fa03b8767c34fa483b8cffcb53d4e6040ba74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 23 Nov 2026 18:13:52 -0500 Subject: [PATCH 1/3] feat(ui): Calculate Field previews what it would write in the first rows as the expression is typed (#2817) --- crates/engine/src/cmd/edit.rs | 179 +++++++++++++++++++++++++++++---- crates/ui-egui/src/dialogs.rs | 127 +++++++++++++++++++++-- docs/user-guide/expressions.md | 6 +- 3 files changed, 287 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 59ca51479f..7a192eecf9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -466,6 +466,54 @@ enum Loss { Error(rustgis_data::query::Fault), } +impl Loss { + /// The loss as a preview names it; `None` for a cut that took nothing. + fn previewed(self) -> Option { + Some(match self { + Loss::Cut(Cut::None) => return None, + Loss::Cut(Cut::Fraction) => PreviewLoss::Fraction, + Loss::Cut(Cut::Range) => PreviewLoss::Range, + Loss::Cut(Cut::NotANumber) => PreviewLoss::NotANumber, + Loss::Cut(Cut::NotFinite) => PreviewLoss::NotFinite, + Loss::Cut(Cut::Time) => PreviewLoss::Time, + Loss::Unread => PreviewLoss::Unheld, + Loss::Error(fault) => PreviewLoss::Error(fault), + }) + } +} + +/// What writing a row's result into its field loses, as a Calculate Field preview says it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreviewLoss { + /// A whole-number field drops the fraction. + Fraction, + /// A number past the 64-bit integer range is null. + Range, + /// Not a number (NaN), or a word read as one, is null. + NotANumber, + /// An infinity is null. + NotFinite, + /// A date field keeps a date-time's day. + Time, + /// A result the field can't hold (text that isn't a number or a date) is null. + Unheld, + /// The expression's error made it null. + Error(rustgis_data::query::Fault), +} + +/// A result and the error that made it null, if one did, as a `ty` field holds it, with what +/// that lost: a cut, then the error or, for a null nobody asked for, the value not read. +fn written((v, fault): (Value, Option), ty: FieldType) -> (Value, [Option; 2]) { + let asked_null = v.asks_null(); + let (v, cut) = coerce_cut(v, ty); + let cut_loss = (cut != Cut::None).then_some(Loss::Cut(cut)); + let other = match fault.filter(|_| v.is_null()) { + Some(fault) => Some(Loss::Error(fault)), + None => (!asked_null && v.is_null() && cut == Cut::None).then_some(Loss::Unread), + }; + (v, [cut_loss, other]) +} + impl WriteLosses { /// A tally for an edit that may write the same row more than once, counting each kind of /// loss once per row: a later write that loses something else is still counted. @@ -480,27 +528,25 @@ impl WriteLosses { /// Row `row`'s result and the error that made it null, if one did, as a `ty` field holds it, /// counting what that lost. - pub(crate) fn write(&mut self, row: usize, (v, fault): (Value, Option), ty: FieldType) -> Value { - let asked_null = v.asks_null(); - let (v, cut) = coerce_cut(v, ty); - if cut != Cut::None && self.first(row, Loss::Cut(cut)) { - self.cuts.add(cut); - } - if let Some(fault) = fault.filter(|_| v.is_null()) { - if !self.first(row, Loss::Error(fault)) { - return v; + pub(crate) fn write(&mut self, row: usize, result: (Value, Option), ty: FieldType) -> Value { + let (v, losses) = written(result, ty); + for loss in losses.into_iter().flatten() { + if !self.first(row, loss) { + continue; } - match self.errors.iter_mut().find(|(f, ..)| *f == fault) { - Some((_, n, rows)) => { - *n += 1; - if rows.len() < LISTED_ROWS { - rows.push(row); + match loss { + Loss::Cut(cut) => self.cuts.add(cut), + Loss::Unread => self.unread += 1, + Loss::Error(fault) => match self.errors.iter_mut().find(|(f, ..)| *f == fault) { + Some((_, n, rows)) => { + *n += 1; + if rows.len() < LISTED_ROWS { + rows.push(row); + } } - } - None => self.errors.push((fault, 1, vec![row])), + None => self.errors.push((fault, 1, vec![row])), + }, } - } else if !asked_null && v.is_null() && cut == Cut::None && self.first(row, Loss::Unread) { - self.unread += 1; } v } @@ -1592,6 +1638,36 @@ pub fn check_calculation(expr: &str, ds: &rustgis_data::Dataset) -> Result<(), S Calculation::parse(expr, ds).map(|_| ()) } +/// One row of a Calculate Field preview: the value the field would get, and what writing it +/// loses, the kind the run's notices count. +#[derive(Clone, Debug, PartialEq)] +pub struct CalculationPreview { + pub row: usize, + pub value: Value, + pub lost: Option, +} + +/// What Calculate Field would write with `expr` into field `field` of `rows` (rows past the end +/// left out), parsed once as [`check_calculation`] reads it: the error is the same. +pub fn preview_calculation( + expr: &str, + ds: &rustgis_data::Dataset, + field: usize, + rows: &[usize], +) -> Result, String> { + let calc = Calculation::parse(expr, ds)?; + let ty = ds.fields.get(field).map(|f| f.ty).ok_or("no field")?; + Ok(rows + .iter() + .filter(|r| **r < ds.features.len()) + .map(|&row| { + let (value, [cut, other]) = written(calc.eval_or_fault(ds, row), ty); + // The error is why the value is null; a cut alone says what it took. + CalculationPreview { row, value, lost: other.or(cut).and_then(Loss::previewed) } + }) + .collect()) +} + /// A Calculate Field expression: the expression language, or, for text it doesn't read, the /// earlier calculator's `a op b` (whose bare field names may hold spaces: `Pop Est * 2`). pub(crate) enum Calculation { @@ -1994,6 +2070,73 @@ mod tests { assert_eq!(v("'a' || 'b'"), Value::Text("ab".into())); } + /// Calculate Field's preview (#2817) is what the run writes in each row, as the field holds + /// it, with what writing it loses; the expression's error is the check's. + #[test] + fn a_calculation_preview_is_what_the_run_writes() { + let fields = vec![ + Field::new("n", FieldType::Double), + Field::new("whole", FieldType::Integer), + Field::new("name", FieldType::Text), + Field::new("day", FieldType::Date), + Field::new("at", FieldType::DateTime), + ]; + let mut ds = Dataset::new("t", GeometryType::None, fields); + for (n, name) in [(2.5, "a"), (1e300, "b"), (-1.5, "c"), (4.0, "d")] { + let at = Value::parse("2026-11-23T10:30:00", FieldType::DateTime); + ds.push(None, vec![Value::Float(n), Value::Int(0), Value::Text(name.into()), Value::Null, at]); + } + let (n, whole, day) = (0, 1, 3); + let preview = |e: &str, field: usize, rows: &[usize]| -> Vec<(usize, Value, Option)> { + let previewed = preview_calculation(e, &ds, field, rows).unwrap_or_else(|e| panic!("{e}")); + previewed.into_iter().map(|p| (p.row, p.value, p.lost)).collect() + }; + // The rows asked for, in their order; a clean result loses nothing. + assert_eq!(preview("n * 2", n, &[0, 3]), vec![(0, Value::Float(5.0), None), (3, Value::Float(8.0), None)]); + // As the field holds it: a fraction into whole numbers, a number past their range. + assert_eq!( + preview("n", whole, &[0, 2]), + vec![(0, Value::Int(2), Some(PreviewLoss::Fraction)), (2, Value::Int(-1), Some(PreviewLoss::Fraction))] + ); + assert_eq!(preview("n", whole, &[1]), vec![(1, Value::Null, Some(PreviewLoss::Range))]); + // Text that isn't a number, an expression's error, a date-time into a date. + assert_eq!(preview("name", whole, &[0]), vec![(0, Value::Null, Some(PreviewLoss::Unheld))]); + assert_eq!(preview("n / 0", n, &[0]), vec![(0, Value::Null, Some(PreviewLoss::Error(rustgis_data::query::Fault::DivisionByZero)))]); + let at = preview("at", day, &[0]); + assert_eq!((at[0].0, at[0].2), (0, Some(PreviewLoss::Time))); + assert!(matches!(at[0].1, Value::Date(_)), "{:?}", at[0].1); + // A null asked for loses nothing. + assert_eq!(preview("null", n, &[0]), vec![(0, Value::Null, None)]); + // No rows, or rows past the end: nothing previewed. + assert_eq!(preview("n", n, &[]), vec![]); + assert_eq!(preview("n", n, &[3, 4, 99]), vec![(3, Value::Float(4.0), None)]); + // An expression that doesn't read: the check's error. + assert_eq!(preview_calculation("nosuch * 2", &ds, n, &[0]), Err(check_calculation("nosuch * 2", &ds).unwrap_err())); + assert!(preview_calculation("n", &ds, 9, &[0]).is_err(), "no such field"); + } + + /// The run's notices still count each loss as before the preview shared their reading: a + /// fraction, a value not read, an error, once each. + #[test] + fn calculate_field_notices_count_what_the_preview_reads() { + let mut ds = Dataset::new("t", GeometryType::None, vec![Field::new("n", FieldType::Double), Field::new("name", FieldType::Text)]); + for (n, name) in [(2.5, "a"), (0.0, "b"), (3.0, "7")] { + ds.push(None, vec![Value::Float(n), Value::Text(name.into())]); + } + let mut losses = WriteLosses::default(); + let calc = Calculation::parse("if(n = 0, 1 / n, n)", &ds).unwrap(); + let written: Vec = (0..3).map(|r| losses.write(r, calc.eval_or_fault(&ds, r), FieldType::Integer)).collect(); + assert_eq!(written, vec![Value::Int(2), Value::Null, Value::Int(3)]); + let calc = Calculation::parse("name", &ds).unwrap(); + assert_eq!(losses.write(0, calc.eval_or_fault(&ds, 0), FieldType::Integer), Value::Null); + let notices: Vec = + losses.notices(NoticeText::term("Calculate Field"), "n", FieldType::Integer).into_iter().map(|(_, t)| t.english()).collect(); + assert_eq!(notices.len(), 3, "{notices:?}"); + assert!(notices[0].contains("1 result lost its fraction"), "{notices:?}"); + assert!(notices[1].contains("is null in 1 row, whose result isn't"), "{notices:?}"); + assert!(notices[2].contains("because of a division by zero (row 2)"), "{notices:?}"); + } + /// A calculation past the expression language's length limit is refused, however the earlier /// calculator would read it: as quoted text, or with a field named like a literal (#2783). #[test] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c0f8871dc9..9d85322b63 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -814,12 +814,29 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { crate::exprcomplete::expr_edit(ui, id, &mut app.dialogs.text, ds, style).labelled_by(input_label.id); // Read once no suggestion is offered: a word still being chosen isn't an error yet. let text = app.dialogs.text.trim(); - let reads = data(app) - .filter(|_| !text.is_empty() && !crate::exprcomplete::offering(ui, id)) - .map(|d| rustgis_engine::cmd::edit::check_calculation(text, d)); - if let Some(Err(e)) = reads { - let t = Tokens::get(ui.ctx()); - ui.label(egui::RichText::new(crate::i18n::fmt("Invalid: {error}", &[("error", &e)])).small().color(t.red)); + // Once it reads, what it would write in the rows Calculate writes first (#2817): the + // first three of the selection, in the order Calculate takes it, else the first three. + let selected = match app.dialogs.table { + Some(_) => &[][..], + None => app.session.active_layer.and_then(|id| app.session.map().layer(id)).map_or(&[][..], |l| &l.selection[..]), + }; + let rows: Vec = if selected.is_empty() { (0..3).collect() } else { selected.iter().take(3).copied().collect() }; + let field = Some(&app.dialogs.a).filter(|a| fields.contains(a)); + let reads = data(app).filter(|_| !text.is_empty() && !crate::exprcomplete::offering(ui, id)).map(|d| { + match field.and_then(|f| d.field_index(f)) { + Some(fi) => rustgis_engine::cmd::edit::preview_calculation(text, d, fi, &rows).map(Some), + None => rustgis_engine::cmd::edit::check_calculation(text, d).map(|()| None), + } + }); + match reads { + Some(Err(e)) => { + let t = Tokens::get(ui.ctx()); + ui.label(egui::RichText::new(crate::i18n::fmt("Invalid: {error}", &[("error", &e)])).small().color(t.red)); + } + Some(Ok(Some(preview))) if !preview.is_empty() => { + ui.label(egui::RichText::new(calculation_preview(&preview)).small()); + } + _ => {} } // A standalone table has no selection: every row. let help = if app.dialogs.table.is_some() { @@ -3125,6 +3142,37 @@ fn calculation_fields(dataset: &rustgis_engine::data::Dataset) -> impl Iterator< dataset.fields.iter().enumerate().filter(|(i, field)| dataset.field_index(&field.name) == Some(*i)).map(|(_, field)| field) } +/// Calculate Field's preview line: each row's value as the field would hold it, shortened to fit +/// the line, with what writing it loses (`Preview: 2 (fraction dropped) · 4`). +fn calculation_preview(rows: &[rustgis_engine::cmd::edit::CalculationPreview]) -> String { + const LONGEST: usize = 40; + let values: Vec = rows + .iter() + .map(|p| { + let mut value = p.value.to_string(); + if let Some((cut, _)) = value.char_indices().nth(LONGEST) { + value.truncate(cut); + value.push('…'); + } + use rustgis_engine::cmd::edit::PreviewLoss; + // In logical order: the line as a whole is put in display form once, below. + let loss = match p.lost { + None => return value, + Some(PreviewLoss::Fraction) => tl_raw!("fraction dropped"), + Some(PreviewLoss::Range) => tl_raw!("past the 64-bit integer range"), + Some(PreviewLoss::NotANumber) => tl_raw!("not a number"), + Some(PreviewLoss::NotFinite) => tl_raw!("not a finite number"), + Some(PreviewLoss::Time) => tl_raw!("time dropped"), + Some(PreviewLoss::Unheld) => tl_raw!("not a value the field holds"), + // The phrases the run's notices give for the same errors. + Some(PreviewLoss::Error(fault)) => tl_raw!(fault.describe()), + }; + crate::i18n::fmt_raw("{value} ({loss})", &[("value", &value), ("loss", loss)]) + }) + .collect(); + crate::i18n::fmt("Preview: {values}", &[("values", &values.join(" · "))]) +} + #[cfg(test)] mod tests { use super::*; @@ -4004,6 +4052,73 @@ mod tests { assert!(h.query_by_label_contains("Invalid:").is_some(), "the error once the list is closed"); } + /// Calculate Field previews what it would write (#2817): the first three rows of a table, as + /// the field holds them, with what writing them loses; nothing for an expression that doesn't + /// read, or while a suggestion is offered. + #[test] + fn calculate_field_previews_the_first_rows_of_a_table() { + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::new(Session::new(rustgis_engine::Project::default())); + app.run("layer.addDataText", json!({"fileName": "pops.csv", "text": "pop,n\n2.5,1\n4,2\n6,3\n8,4\n"})).unwrap(); + let id = app.session.project.tables[0].id; + app.run("ui.dialog", json!({"name": "calculateField", "table": id})).unwrap(); + app.dialogs.a = "pop".into(); + app.dialogs.text = "pop * 2".into(); + let mut h = app_harness(app); + h.run_steps(3); + assert!(h.query_by_label("Preview: 5 · 8 · 12").is_some(), "the first three rows"); + // As the field holds it: a whole-number field drops the fraction, and says so. + h.state_mut().dialogs.a = "n".into(); + h.state_mut().dialogs.text = "pop".into(); + h.run_steps(2); + assert!(h.query_by_label("Preview: 2 (fraction dropped) · 4 · 6").is_some(), "the field's own values"); + // An error in a row is said in place of the value. + h.state_mut().dialogs.text = "1 / (pop - 4)".into(); + h.run_steps(2); + assert!( + h.query_by_label("Preview: 0 (fraction dropped) · (a division by zero) · 0 (fraction dropped)").is_some(), + "the error said in its row" + ); + // An expression that doesn't read: its error, no preview. + h.state_mut().dialogs.text = "nosuch".into(); + h.run_steps(2); + assert!(h.query_by_label_contains("no field named 'nosuch'").is_some()); + assert!(h.query_by_label_contains("Preview:").is_none(), "no preview of what doesn't read"); + // While a suggestion is offered: neither. + h.state_mut().dialogs.text.clear(); + h.ctx.memory_mut(|m| m.request_focus(egui::Id::unique("cf_expression"))); + h.run(); + h.event(egui::Event::Text("po".into())); + h.run(); + assert!(h.query_by_label_contains("Preview:").is_none(), "no preview while a word is chosen"); + } + + /// On a layer, the preview reads the first three selected rows (a selection is kept in the + /// table's order), or the first three rows when none is selected (#2817); an empty layer has + /// no preview. + #[test] + fn calculate_field_previews_the_selected_rows_of_a_layer() { + use egui_kittest::kittest::Queryable; + let point = |v: i64| json!({"type": "Feature", "geometry": {"type": "Point", "coordinates": [v, v]}, "properties": {"v": v}}); + let points = json!({"type": "FeatureCollection", "features": (1..=5).map(point).collect::>()}); + let mut app = RustGisApp::new(Session::new(rustgis_engine::Project::default())); + app.run("layer.addDataText", json!({"fileName": "points.geojson", "text": points.to_string()})).unwrap(); + let id = app.session.active_layer.unwrap(); + app.session.map_mut().layer_mut(id).unwrap().selection = vec![1, 2, 3, 4]; + app.run("ui.dialog", json!({"name": "calculateField"})).unwrap(); + app.dialogs.a = "v".into(); + app.dialogs.text = "v * 10".into(); + let mut h = app_harness(app); + h.run_steps(3); + assert!(h.query_by_label("Preview: 20 · 30 · 40").is_some(), "the first three selected"); + h.state_mut().session.map_mut().layer_mut(id).unwrap().selection.clear(); + h.run_steps(2); + assert!(h.query_by_label("Preview: 10 · 20 · 30").is_some(), "the first three rows"); + h.state_mut().session.map_mut().layer_mut(id).unwrap().dataset.features.clear(); + h.run_steps(2); + assert!(h.query_by_label_contains("Preview:").is_none(), "no rows, no preview"); + } + /// The app in a harness, its fonts installed on the first pass (the dialog draws on the next). fn app_harness(app: RustGisApp) -> egui_kittest::Harness<'static, RustGisApp> { let mut fonts = false; diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index 53a971de2f..2ae61872f2 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -240,7 +240,11 @@ them when it takes no arguments). While the list is open the expression isn't checked: `pop_`, with `pop_est` suggested, is a word still being chosen. It is checked once the list closes (an item taken, Escape, the cursor moved away, the box left, or nothing matching what's typed), and its error shown then if it's still -invalid (`pop_x`: no field named 'pop_x'). +invalid (`pop_x`: no field named 'pop_x'). Once it reads, a line under the box previews what +Calculate Field would write in the first three selected rows, or the first three rows when none is +selected, as the chosen field holds it and the attribute table shows it, with what writing it +loses: `Preview: 2 (fraction dropped) · (a division by zero) · 6`. Only those rows are +evaluated, and nothing changes until **Calculate** is clicked. A `(` typed closes itself, the cursor inside, unless text follows it or it's in a text or a field name; so does a `'` or `"` where a value can start (at the start, after a space, `(`, `,` or an From d7656635d637469aed74184b929ace5822b29bc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 23 Nov 2026 20:08:57 -0500 Subject: [PATCH 2/3] fix(ui): keep line breaks out of the Calculate Field preview and skip rows the layer lacks (#2817) A line break or tab in a text value reads as a space, and a long value stops being written past the cut. A selected row the layer no longer has takes no place among the three. The coercion step returns a named Held struct instead of a positional pair. --- crates/engine/src/cmd/edit.rs | 31 +++++++++++-------- crates/ui-egui/src/dialogs.rs | 57 ++++++++++++++++++++++++++++++----- 2 files changed, 69 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 7a192eecf9..a4110ec14a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -501,17 +501,24 @@ pub enum PreviewLoss { Error(rustgis_data::query::Fault), } -/// A result and the error that made it null, if one did, as a `ty` field holds it, with what -/// that lost: a cut, then the error or, for a null nobody asked for, the value not read. -fn written((v, fault): (Value, Option), ty: FieldType) -> (Value, [Option; 2]) { +/// A result as a field holds it, with what holding it lost. +struct Held { + value: Value, + /// What the coercion to the field's type took. + cut: Option, + /// The error that made it null or, for a null nobody asked for, the value not read. + other: Option, +} + +/// A result and the error that made it null, if one did, as a `ty` field holds it. +fn held((v, fault): (Value, Option), ty: FieldType) -> Held { let asked_null = v.asks_null(); - let (v, cut) = coerce_cut(v, ty); - let cut_loss = (cut != Cut::None).then_some(Loss::Cut(cut)); - let other = match fault.filter(|_| v.is_null()) { + let (value, cut) = coerce_cut(v, ty); + let other = match fault.filter(|_| value.is_null()) { Some(fault) => Some(Loss::Error(fault)), - None => (!asked_null && v.is_null() && cut == Cut::None).then_some(Loss::Unread), + None => (!asked_null && value.is_null() && cut == Cut::None).then_some(Loss::Unread), }; - (v, [cut_loss, other]) + Held { value, cut: (cut != Cut::None).then_some(Loss::Cut(cut)), other } } impl WriteLosses { @@ -529,8 +536,8 @@ impl WriteLosses { /// Row `row`'s result and the error that made it null, if one did, as a `ty` field holds it, /// counting what that lost. pub(crate) fn write(&mut self, row: usize, result: (Value, Option), ty: FieldType) -> Value { - let (v, losses) = written(result, ty); - for loss in losses.into_iter().flatten() { + let Held { value, cut, other } = held(result, ty); + for loss in [cut, other].into_iter().flatten() { if !self.first(row, loss) { continue; } @@ -548,7 +555,7 @@ impl WriteLosses { }, } } - v + value } /// The notices for what writing `field`, of type `ty`, lost, each starting with `by` (the @@ -1661,7 +1668,7 @@ pub fn preview_calculation( .iter() .filter(|r| **r < ds.features.len()) .map(|&row| { - let (value, [cut, other]) = written(calc.eval_or_fault(ds, row), ty); + let Held { value, cut, other } = held(calc.eval_or_fault(ds, row), ty); // The error is why the value is null; a cut alone says what it took. CalculationPreview { row, value, lost: other.or(cut).and_then(Loss::previewed) } }) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9d85322b63..64a4ad6690 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -820,9 +820,14 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { Some(_) => &[][..], None => app.session.active_layer.and_then(|id| app.session.map().layer(id)).map_or(&[][..], |l| &l.selection[..]), }; - let rows: Vec = if selected.is_empty() { (0..3).collect() } else { selected.iter().take(3).copied().collect() }; let field = Some(&app.dialogs.a).filter(|a| fields.contains(a)); let reads = data(app).filter(|_| !text.is_empty() && !crate::exprcomplete::offering(ui, id)).map(|d| { + // A selected row the layer no longer has gets nothing written: it takes no place. + let rows: Vec = if selected.is_empty() { + (0..PREVIEW_ROWS).collect() + } else { + selected.iter().copied().filter(|r| *r < d.features.len()).take(PREVIEW_ROWS).collect() + }; match field.and_then(|f| d.field_index(f)) { Some(fi) => rustgis_engine::cmd::edit::preview_calculation(text, d, fi, &rows).map(Some), None => rustgis_engine::cmd::edit::check_calculation(text, d).map(|()| None), @@ -3142,19 +3147,41 @@ fn calculation_fields(dataset: &rustgis_engine::data::Dataset) -> impl Iterator< dataset.fields.iter().enumerate().filter(|(i, field)| dataset.field_index(&field.name) == Some(*i)).map(|(_, field)| field) } -/// Calculate Field's preview line: each row's value as the field would hold it, shortened to fit -/// the line, with what writing it loses (`Preview: 2 (fraction dropped) · 4`). +/// The rows a Calculate Field preview shows. +const PREVIEW_ROWS: usize = 3; + +/// Calculate Field's preview line: each row's value as the field would hold it, its text cut at +/// forty characters and with no line break of its own, with what writing it loses +/// (`Preview: 2 (fraction dropped) · 4`). The line wraps in the dialog rather than cut a loss off. fn calculation_preview(rows: &[rustgis_engine::cmd::edit::CalculationPreview]) -> String { + use rustgis_engine::cmd::edit::PreviewLoss; + use std::fmt::Write as _; const LONGEST: usize = 40; + /// A value's text on one line, written no further than one character past `LONGEST`. + struct OneLine(String, usize); + impl std::fmt::Write for OneLine { + fn write_str(&mut self, s: &str) -> std::fmt::Result { + for c in s.chars() { + if self.1 > LONGEST { + return Err(std::fmt::Error); + } + self.0.push(if c.is_control() { ' ' } else { c }); + self.1 += 1; + } + Ok(()) + } + } let values: Vec = rows .iter() .map(|p| { - let mut value = p.value.to_string(); + let mut line = OneLine(String::new(), 0); + // An error only stops the writing past the cut. + let _ = write!(line, "{}", p.value); + let mut value = line.0; if let Some((cut, _)) = value.char_indices().nth(LONGEST) { value.truncate(cut); value.push('…'); } - use rustgis_engine::cmd::edit::PreviewLoss; // In logical order: the line as a whole is put in display form once, below. let loss = match p.lost { None => return value, @@ -4094,8 +4121,8 @@ mod tests { } /// On a layer, the preview reads the first three selected rows (a selection is kept in the - /// table's order), or the first three rows when none is selected (#2817); an empty layer has - /// no preview. + /// table's order) the layer has, or the first three rows when none is selected (#2817); an + /// empty layer has no preview. #[test] fn calculate_field_previews_the_selected_rows_of_a_layer() { use egui_kittest::kittest::Queryable; @@ -4111,6 +4138,10 @@ mod tests { let mut h = app_harness(app); h.run_steps(3); assert!(h.query_by_label("Preview: 20 · 30 · 40").is_some(), "the first three selected"); + // A selected row the layer doesn't have gets nothing written, so it takes no place. + h.state_mut().session.map_mut().layer_mut(id).unwrap().selection = vec![9, 2, 3, 4]; + h.run_steps(2); + assert!(h.query_by_label("Preview: 30 · 40 · 50").is_some(), "three rows the layer has"); h.state_mut().session.map_mut().layer_mut(id).unwrap().selection.clear(); h.run_steps(2); assert!(h.query_by_label("Preview: 10 · 20 · 30").is_some(), "the first three rows"); @@ -4119,6 +4150,18 @@ mod tests { assert!(h.query_by_label_contains("Preview:").is_none(), "no rows, no preview"); } + /// A text value in the preview breaks no line (#2817): a line break or tab in it reads as a + /// space, and a long one is cut at forty characters. + #[test] + fn a_calculation_preview_stays_on_one_line() { + use rustgis_engine::cmd::edit::CalculationPreview; + use rustgis_engine::data::Value; + let row = |value: Value| CalculationPreview { row: 0, value, lost: None }; + assert_eq!(super::calculation_preview(&[row(Value::Text("a\nb\tc".into())), row(Value::Int(7))]), "Preview: a b c · 7"); + let long = format!("{}\n{}", "x".repeat(39), "y".repeat(10_000)); + assert_eq!(super::calculation_preview(&[row(Value::Text(long))]), format!("Preview: {} …", "x".repeat(39))); + } + /// The app in a harness, its fonts installed on the first pass (the dialog draws on the next). fn app_harness(app: RustGisApp) -> egui_kittest::Harness<'static, RustGisApp> { let mut fonts = false; From b76f23df5e8cef920797ffea589b7e125aef8583 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 23 Nov 2026 21:00:16 -0500 Subject: [PATCH 3/3] fix(ui): Unicode line separators read as spaces in the Calculate Field preview, and the guide says the layer's checks still run (#2817) The preview's value is what the expression gives for the row as the field holds it; domains, allowed combinations, constraint rules and calculation rules still run when Calculate is clicked. --- crates/ui-egui/src/dialogs.rs | 12 ++++++++---- docs/user-guide/expressions.md | 12 +++++++----- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 64a4ad6690..8833f15b8f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3165,7 +3165,7 @@ fn calculation_preview(rows: &[rustgis_engine::cmd::edit::CalculationPreview]) - if self.1 > LONGEST { return Err(std::fmt::Error); } - self.0.push(if c.is_control() { ' ' } else { c }); + self.0.push(if c.is_control() || matches!(c, '\u{2028}' | '\u{2029}') { ' ' } else { c }); self.1 += 1; } Ok(()) @@ -4150,14 +4150,18 @@ mod tests { assert!(h.query_by_label_contains("Preview:").is_none(), "no rows, no preview"); } - /// A text value in the preview breaks no line (#2817): a line break or tab in it reads as a - /// space, and a long one is cut at forty characters. + /// A text value in the preview breaks no line (#2817): a line break (Unicode's line and + /// paragraph separators too) or tab in it reads as a space, and a long one is cut at forty + /// characters. #[test] fn a_calculation_preview_stays_on_one_line() { use rustgis_engine::cmd::edit::CalculationPreview; use rustgis_engine::data::Value; let row = |value: Value| CalculationPreview { row: 0, value, lost: None }; - assert_eq!(super::calculation_preview(&[row(Value::Text("a\nb\tc".into())), row(Value::Int(7))]), "Preview: a b c · 7"); + assert_eq!( + super::calculation_preview(&[row(Value::Text("a\nb\tc\u{2028}d\u{2029}e".into())), row(Value::Int(7))]), + "Preview: a b c d e · 7" + ); let long = format!("{}\n{}", "x".repeat(39), "y".repeat(10_000)); assert_eq!(super::calculation_preview(&[row(Value::Text(long))]), format!("Preview: {} …", "x".repeat(39))); } diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index 2ae61872f2..32132d97de 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -240,11 +240,13 @@ them when it takes no arguments). While the list is open the expression isn't checked: `pop_`, with `pop_est` suggested, is a word still being chosen. It is checked once the list closes (an item taken, Escape, the cursor moved away, the box left, or nothing matching what's typed), and its error shown then if it's still -invalid (`pop_x`: no field named 'pop_x'). Once it reads, a line under the box previews what -Calculate Field would write in the first three selected rows, or the first three rows when none is -selected, as the chosen field holds it and the attribute table shows it, with what writing it -loses: `Preview: 2 (fraction dropped) · (a division by zero) · 6`. Only those rows are -evaluated, and nothing changes until **Calculate** is clicked. +invalid (`pop_x`: no field named 'pop_x'). Once it reads, a line under the box previews what the +expression gives in the first three selected rows, or the first three rows when none is selected, +as the chosen field holds it and the attribute table shows it, with what writing it loses: +`Preview: 2 (fraction dropped) · (a division by zero) · 6`. Only those rows are evaluated, +and nothing changes until **Calculate** is clicked. The layer's checks (domains, allowed +combinations of values, constraint rules) and its calculation rules still run then, so a value the +preview shows can still be refused. A `(` typed closes itself, the cursor inside, unless text follows it or it's in a text or a field name; so does a `'` or `"` where a value can start (at the start, after a space, `(`, `,` or an