diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index 469f842c4f..98b9e9e2ad 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -1616,12 +1616,26 @@ pub fn matches(e: &Expr, ds: &Dataset, row: usize, env: &Env) -> bool { /// Tests a row in a chunk whose first row has `offset` preceding rows in the source. pub(crate) fn eval_in_chunk(e: &Expr, ds: &Dataset, row: usize, offset: usize) -> bool { - let env = Env::default(); - let mut eval = Eval::new(ds, row, &env); + matches_at(e, ds, row, &Env::default(), offset) +} + +/// [`matches`] for a row of `ds` that has `offset` rows before `ds`'s first in its layer, so +/// `@row_number` reads its place there: a chunk of a source, or a copy of one row (#2837). +pub fn matches_at(e: &Expr, ds: &Dataset, row: usize, env: &Env, offset: usize) -> bool { + let mut eval = Eval::new(ds, row, env); eval.row_offset = offset; eval.cond(e) == Some(true) } +/// [`value_or_fault`] at `offset`, as [`matches_at`] reads a row. +pub fn value_or_fault_at(e: &Expr, ds: &Dataset, row: usize, env: &Env, offset: usize) -> (Value, Option) { + let mut eval = Eval::new(ds, row, env); + eval.row_offset = offset; + let v = eval.value(e).into_owned(); + let fault = if v.is_null() { eval.fault.get() } else { None }; + (v, fault) +} + /// The expression's value for one row. pub fn value(e: &Expr, ds: &Dataset, row: usize, env: &Env) -> Value { Eval::new(ds, row, env).value(e).into_owned() @@ -1632,10 +1646,7 @@ pub fn value(e: &Expr, ds: &Dataset, row: usize, env: &Env) -> Value { /// or `CASE` condition only picks the branch, so it isn't the result's. Where several errors /// reach the result, the first one met is given. pub fn value_or_fault(e: &Expr, ds: &Dataset, row: usize, env: &Env) -> (Value, Option) { - let eval = Eval::new(ds, row, env); - let v = eval.value(e).into_owned(); - let fault = if v.is_null() { eval.fault.get() } else { None }; - (v, fault) + value_or_fault_at(e, ds, row, env, 0) } /// Whether a value counts as true: a non-zero number, non-empty text; null is unknown. diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 68b5c3a3ce..ba3130384b 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -242,11 +242,6 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: } } let rows: Vec = changes.iter().filter_map(|c| c.row).collect(); - // What each calculation rule's whole-number field cut: the rule and the field's name. Each - // rule's cuts are said, even when a later rule writes the same field: it may read them. - // With them, per rule, the results its field couldn't hold and those an error made null - // (`WriteLosses`), and its type. - let mut cuts: Vec<(String, String, super::edit::WriteLosses, FieldType)> = Vec::new(); // Parsing against the fields separates a measurement failure from a stale rule. The latter // may still be skipped below, but an ambiguous area must never disable a valid rule. let metadata = rustgis_data::Dataset::new(l.dataset.name.clone(), l.dataset.geometry_type, l.dataset.fields.clone()); @@ -268,43 +263,14 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: return Err(format!("{}: {message}", l.dataset.name)); } // Calculation rules, in order. Those that no longer read, by name, said once the edit is kept. - let mut unread: Vec = Vec::new(); let layer = l.dataset.name.clone(); - for rule in l.design.rules.iter().filter(|r| r.kind == RuleKind::Calculation) { - let Some(fi) = l.dataset.field_index(&rule.field) else { continue }; - let ty = l.dataset.fields.get(fi).map(|f| f.ty).unwrap_or(FieldType::Text); - // A rule that no longer reads (a hand-edited file, one past the length limit from an - // earlier version) is skipped rather than blocking every edit, and said. - let Ok(calc) = super::edit::Calculation::parse(&rule.expression, &metadata) else { - // Said only for an edit with rows: one with none (a deletion) computes nothing anyway. - if !rows.is_empty() { - unread.push(rule.name.clone()); - } - continue; - }; - // Counted as Calculate Field counts them. - // A change set may repeat a row: its losses are counted once. - let mut losses = super::edit::WriteLosses::once_per_row(); - for r in &rows { - let v = losses.write(*r, calc.eval_or_fault(&l.dataset, *r), ty); - if let Some(cell) = l.dataset.features.get_mut(*r).and_then(|f| f.attrs.get_mut(fi)) { - *cell = v; - } - } - let name = l.dataset.fields.get(fi).map(|f| f.name.clone()).unwrap_or_default(); - cuts.push((rule.name.clone(), name, losses, ty)); - } - // Validation. Domains and contingent values are checked on the fields an edit changed (all - // of a new feature's), so a value set before the domain doesn't block unrelated edits. - let constraints: Vec<(String, String, rustgis_data::query::Expr)> = l - .design - .rules - .iter() - .filter(|r| r.kind == RuleKind::Constraint) - .filter_map(|rule| { - rustgis_data::query::parse(&rule.expression, &metadata).ok().map(|e| (rule.name.clone(), rule.expression.clone(), e)) - }) - .collect(); + // What each calculation rule's whole-number field cut: the rule and the field's name. Each + // rule's cuts are said, even when a later rule writes the same field: it may read them. + // With them, per rule, the results its field couldn't hold and those an error made null + // (`WriteLosses`), and its type. + let (cuts, unread) = calculation_rules(&l.design, &mut l.dataset, &metadata, &rows, 0); + // Validation (`refusal`), against each row's state before the first edit. + let constraints = constraint_rules(&l.design, &metadata); let mut original = HashMap::new(); if !l.design.domains.is_empty() || !l.design.contingent.is_empty() { // A row edited more than once still validates against its state before the first edit. @@ -315,35 +281,8 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: } } for r in &rows { - let before = original.get(r).copied().flatten().zip(l.dataset.features.get(*r)); - let touched = |fi: usize| before.is_none_or(|(old, now)| old.attrs.get(fi) != now.attrs.get(fi)); - for d in &l.design.domains { - if let Some(fi) = l.dataset.field_index(&d.field).filter(|fi| touched(*fi)) { - let v = l.dataset.value(*r, fi); - if !d.allows(v) { - return Err(format!("{} isn't allowed in {} (its domain)", v, d.field)); - } - } - } - for c in &l.design.contingent { - let vals: Vec<&Value> = - c.fields.iter().map(|f| l.dataset.field_index(f).map(|fi| l.dataset.value(*r, fi)).unwrap_or(&Value::Null)).collect(); - let any_touched = c.fields.iter().any(|f| l.dataset.field_index(f).is_some_and(touched)); - if !any_touched || vals.iter().all(|v| v.is_null()) { - continue; - } - let ok = c.combos.iter().any(|combo| { - combo.iter().zip(&vals).all(|(want, got)| want.is_null() || got.is_null() || want.to_string() == got.to_string()) - }); - if !ok { - let shown: Vec = vals.iter().map(|v| v.to_string()).collect(); - return Err(format!("{} isn't a valid combination of {} ({})", shown.join(", "), c.fields.join(", "), c.name)); - } - } - for (name, expr, e) in &constraints { - if !rustgis_data::query::eval(e, &l.dataset, *r) { - return Err(format!("the edit breaks the rule {name} ({expr})")); - } + if let Some(refused) = refusal(&l.design, &l.dataset, &constraints, *r, original.get(r).copied().flatten(), 0) { + return Err(refused); } } // Archive and counts. @@ -396,6 +335,111 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: Ok(()) } +/// What each calculation rule of `design` cut, by rule: its name, its field's, what writing its +/// results lost (counted once per row, as Calculate Field counts them) and the field's type. +type RuleCuts = Vec<(String, String, super::edit::WriteLosses, FieldType)>; + +/// Runs `design`'s calculation rules, in order, on `rows` of `ds`, whose first row has `offset` +/// rows before it in the layer (0 but for the Calculate Field preview's one-row copy, #2837): +/// what each cut, and the names of the rules that no longer read against `metadata` (the +/// layer's fields), skipped rather than blocking every edit. +pub(crate) fn calculation_rules( + design: &rustgis_map::design::Design, + ds: &mut rustgis_data::Dataset, + metadata: &rustgis_data::Dataset, + rows: &[usize], + offset: usize, +) -> (RuleCuts, Vec) { + let (mut cuts, mut unread) = (Vec::new(), Vec::new()); + for rule in design.rules.iter().filter(|r| r.kind == RuleKind::Calculation) { + let Some(fi) = ds.field_index(&rule.field) else { continue }; + let ty = ds.fields.get(fi).map(|f| f.ty).unwrap_or(FieldType::Text); + // A rule that no longer reads (a hand-edited file, one past the length limit from an + // earlier version) is skipped rather than blocking every edit, and said. + let Ok(calc) = super::edit::Calculation::parse(&rule.expression, metadata) else { + // Said only for an edit with rows: one with none (a deletion) computes nothing anyway. + if !rows.is_empty() { + unread.push(rule.name.clone()); + } + continue; + }; + // Counted as Calculate Field counts them. + // A change set may repeat a row: its losses are counted once. + let mut losses = super::edit::WriteLosses::once_per_row(); + for r in rows { + let v = losses.write(*r, calc.eval_or_fault_at(ds, *r, offset), ty); + if let Some(cell) = ds.features.get_mut(*r).and_then(|f| f.attrs.get_mut(fi)) { + *cell = v; + } + } + let name = ds.fields.get(fi).map(|f| f.name.clone()).unwrap_or_default(); + cuts.push((rule.name.clone(), name, losses, ty)); + } + (cuts, unread) +} + +/// `design`'s constraint rules that read against `metadata` (the layer's fields): name, +/// expression as written, and parsed. +pub(crate) fn constraint_rules( + design: &rustgis_map::design::Design, + metadata: &rustgis_data::Dataset, +) -> Vec<(String, String, rustgis_data::query::Expr)> { + design + .rules + .iter() + .filter(|r| r.kind == RuleKind::Constraint) + .filter_map(|rule| { + rustgis_data::query::parse(&rule.expression, metadata).ok().map(|e| (rule.name.clone(), rule.expression.clone(), e)) + }) + .collect() +} + +/// The error an edit of row `r` of `ds` is refused with, by the first of `design`'s checks it +/// breaks: a domain or an allowed combination of values, on the fields the edit changed from +/// `before` (all of a new feature's), so a value set before the domain doesn't block unrelated +/// edits, then the `constraints` ([`constraint_rules`]). `offset` as [`calculation_rules`] reads +/// it. +pub(crate) fn refusal( + design: &rustgis_map::design::Design, + ds: &rustgis_data::Dataset, + constraints: &[(String, String, rustgis_data::query::Expr)], + r: usize, + before: Option<&Feature>, + offset: usize, +) -> Option { + let before = before.zip(ds.features.get(r)); + let touched = |fi: usize| before.is_none_or(|(old, now)| old.attrs.get(fi) != now.attrs.get(fi)); + for d in &design.domains { + if let Some(fi) = ds.field_index(&d.field).filter(|fi| touched(*fi)) { + let v = ds.value(r, fi); + if !d.allows(v) { + return Some(format!("{} isn't allowed in {} (its domain)", v, d.field)); + } + } + } + for c in &design.contingent { + let vals: Vec<&Value> = c.fields.iter().map(|f| ds.field_index(f).map(|fi| ds.value(r, fi)).unwrap_or(&Value::Null)).collect(); + let any_touched = c.fields.iter().any(|f| ds.field_index(f).is_some_and(touched)); + if !any_touched || vals.iter().all(|v| v.is_null()) { + continue; + } + let ok = c + .combos + .iter() + .any(|combo| combo.iter().zip(&vals).all(|(want, got)| want.is_null() || got.is_null() || want.to_string() == got.to_string())); + if !ok { + let shown: Vec = vals.iter().map(|v| v.to_string()).collect(); + return Some(format!("{} isn't a valid combination of {} ({})", shown.join(", "), c.fields.join(", "), c.name)); + } + } + for (name, expr, e) in constraints { + if !rustgis_data::query::matches_at(e, ds, r, &rustgis_data::query::Env::default(), offset) { + return Some(format!("the edit breaks the rule {name} ({expr})")); + } + } + None +} + /// Registers data-design and editing commands, including opt-in exact-coordinate polygon moves. /// Feature edits share `apply` for rules, archives and counts inside the session transaction. pub fn commands() -> Vec { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index a4110ec14a..268ae29ec2 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1645,32 +1645,67 @@ 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. +/// One row of a Calculate Field preview: the value the field would get, what writing it loses, +/// the kind the run's notices count, and the layer's check that would refuse the edit (#2837). #[derive(Clone, Debug, PartialEq)] pub struct CalculationPreview { pub row: usize, pub value: Value, pub lost: Option, + /// What the run would refuse the edit with, when the layer's checks refuse this row: its + /// error, word for word, for the checks the preview runs. An edit whose area reads are + /// ambiguous is refused before them, with that error instead, which the preview doesn't give. + pub refused: 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. +/// left out), parsed once as [`check_calculation`] reads it: the error is the same. With a +/// layer's `design`, each row also says which of its checks would refuse it: its calculation +/// rules, then its domains, allowed combinations and constraint rules, run as an edit runs them +/// (`apply_with`, in `design`) on a copy of that row alone, its value written, which reads +/// `@row_number` as the layer's row. The copy holds that row alone, with the layer's fields and +/// coordinate system: nothing else of the layer is copied. Not previewed: an edit refused because +/// an area it reads is ambiguous, which needs the whole edit's geometry. pub fn preview_calculation( expr: &str, ds: &rustgis_data::Dataset, field: usize, rows: &[usize], + design: Option<&rustgis_map::design::Design>, ) -> Result, String> { + use rustgis_map::design::RuleKind; let calc = Calculation::parse(expr, ds)?; let ty = ds.fields.get(field).map(|f| f.ty).ok_or("no field")?; + // Only these can refuse a row: a layer with calculation rules alone refuses none. + let layer_checks = + design.filter(|d| !d.domains.is_empty() || !d.contingent.is_empty() || d.rules.iter().any(|r| r.kind == RuleKind::Constraint)); + // The layer's fields, which its rules are read against, and its constraint rules: only for a + // layer with checks. + let prepared = layer_checks.map(|d| { + let metadata = rustgis_data::Dataset::new(ds.name.clone(), ds.geometry_type, ds.fields.clone()); + let constraints = super::design::constraint_rules(d, &metadata); + (d, metadata, constraints) + }); + // What the layer's checks would refuse the edit of `row` with, `value` written. + let refusal_of = |row: usize, value: &Value| { + let (d, metadata, constraints) = prepared.as_ref()?; + let before = ds.features.row(row)?.to_feature(); + // Shares the layer's rows (an `Arc`) until `one.features` is replaced on the next line, so + // no row of the layer is copied: keep that replacement before any change to `one`. + let mut one = ds.clone(); + one.features = vec![before.clone()].into(); + one.features.set_value(0, field, value.clone()); + let _ = super::design::calculation_rules(d, &mut one, metadata, &[0], row); + super::design::refusal(d, &one, constraints, 0, Some(&before), row) + }; Ok(rows .iter() .filter(|r| **r < ds.features.len()) .map(|&row| { let Held { value, cut, other } = held(calc.eval_or_fault(ds, row), ty); + let refusal = refusal_of(row, &value); // 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) } + CalculationPreview { row, value, lost: other.or(cut).and_then(Loss::previewed), refused: refusal } }) .collect()) } @@ -1730,8 +1765,20 @@ impl Calculation { /// Row `r`'s result, with the error that made it null, if one did. pub(crate) fn eval_or_fault(&self, ds: &rustgis_data::Dataset, r: usize) -> (Value, Option) { + self.eval_or_fault_at(ds, r, 0) + } + + /// [`Calculation::eval_or_fault`] for a row with `offset` rows before `ds`'s first in its + /// layer ([`rustgis_data::query::value_or_fault_at`]). `Calc` reads no row number, so it takes + /// no offset. + pub(crate) fn eval_or_fault_at( + &self, + ds: &rustgis_data::Dataset, + r: usize, + offset: usize, + ) -> (Value, Option) { match self { - Calculation::Expr(e) => rustgis_data::query::value_or_fault(e, ds, r, &rustgis_data::query::Env::default()), + Calculation::Expr(e) => rustgis_data::query::value_or_fault_at(e, ds, r, &rustgis_data::query::Env::default(), offset), Calculation::Calc(c) => c.eval_or_fault(ds, r), } } @@ -2095,7 +2142,7 @@ mod tests { } 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}")); + let previewed = preview_calculation(e, &ds, field, rows, None).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. @@ -2118,8 +2165,8 @@ mod tests { 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"); + assert_eq!(preview_calculation("nosuch * 2", &ds, n, &[0], None), Err(check_calculation("nosuch * 2", &ds).unwrap_err())); + assert!(preview_calculation("n", &ds, 9, &[0], None).is_err(), "no such field"); } /// The run's notices still count each loss as before the preview shared their reading: a diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 30bdc16be1..05338ab806 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -51640,6 +51640,116 @@ fn calculate_field_bulk_edit_keeps_validation_archive_and_undo() { assert_eq!(values(&s), [V::Int(2), V::Int(2), V::Int(4)]); } +/// Calculate Field's preview refuses a row exactly when Calculate on that row alone is refused, +/// with its error word for word (#2837): a domain, an allowed combination and a constraint rule, +/// checked after the calculation rules (a rule writing a field the domain then refuses), and a rule +/// reading `@row_number`, which the preview's one-row copy reads as the layer's row. A field the +/// calculation doesn't change isn't checked against its domain, so a layer with only such a domain +/// refuses none. +#[test] +fn calculate_field_preview_refuses_what_calculate_refuses() { + let layer = || { + let mut s = Session::new(Project::default()); + let features: Vec = [1, 2, 3] + .map(|n| { + json!({"type": "Feature", "properties": {"n": n, "m": 0, "kind": "a", "legacy": 9}, "geometry": {"type": "Point", "coordinates": [n, 0]}}) + }) + .to_vec(); + let points = json!({"type": "FeatureCollection", "features": features}); + s.run("layer.addDataText", &json!({"fileName": "calc.geojson", "text": points.to_string()})).unwrap(); + // A value set before its domain: not checked while the calculation leaves it alone. + s.run("data.domain", &json!({"layer": "calc", "field": "legacy", "min": 1, "max": 5, "force": true})).unwrap(); + s + }; + // Each case: its check, the expression, and the row index (0 to 2) it refuses, if any. + let cases: Vec<(&str, Value, &str, Option)> = vec![ + ("untouched domain", Value::Null, "n + 10", None), + ("domain", json!({"cmd": "data.domain", "p": {"layer": "calc", "field": "n", "min": 0, "max": 4}}), "n + 2", Some(2)), + ( + "combination", + json!({"cmd": "data.contingentValues", "p": {"layer": "calc", "name": "N by kind", "fields": ["n", "kind"], "combos": [[2, "a"], [4, "a"]]}}), + "n + 1", + Some(1), + ), + ( + "constraint", + json!({"cmd": "data.attributeRule", "p": {"layer": "calc", "name": "Not two", "kind": "constraint", "expression": "n <> 2"}}), + "n + 1", + Some(0), + ), + ( + "row number", + json!({"cmd": "data.attributeRule", "p": {"layer": "calc", "name": "Second", "kind": "constraint", "expression": "@row_number <> 2"}}), + "n", + Some(1), + ), + ]; + for (name, check, expression, refuses) in cases { + let mut s = layer(); + if let Some(cmd) = check["cmd"].as_str() { + s.run(cmd, &check["p"]).unwrap(); + } + let id = s.map().layer_by_name("calc").unwrap().id; + let l = s.map().layer(id).unwrap(); + let n = l.dataset.field_index("n").unwrap(); + let previewed = crate::cmd::edit::preview_calculation(expression, &l.dataset, n, &[0, 1, 2], Some(&l.design)).unwrap(); + let refused: Vec> = previewed.into_iter().map(|p| p.refused).collect(); + let ran: Vec> = (0..3) + .map(|row| { + let mut s = layer(); + if let Some(cmd) = check["cmd"].as_str() { + s.run(cmd, &check["p"]).unwrap(); + } + s.run("select.rows", &json!({"layer": "calc", "rows": [row]})).unwrap(); + s.run("edit.calculateField", &json!({"layer": "calc", "field": "n", "expression": expression})).err() + }) + .collect(); + assert_eq!(refused, ran, "{name}"); + let refused_rows: Vec = (0..3).filter(|r| ran[*r].is_some()).collect(); + assert_eq!(refused_rows, refuses.into_iter().collect::>(), "{name}: the row refused"); + } + // A calculation rule writing a field whose domain then refuses it: checked after the rule. + let mut s = layer(); + s.run("data.domain", &json!({"layer": "calc", "field": "m", "min": 0, "max": 25})).unwrap(); + s.run("data.attributeRule", &json!({"layer": "calc", "name": "Tens", "kind": "calculation", "field": "m", "expression": "n * 10"})) + .unwrap(); + let l = s.map().layer_by_name("calc").unwrap(); + let n = l.dataset.field_index("n").unwrap(); + let previewed = crate::cmd::edit::preview_calculation("n + 1", &l.dataset, n, &[0, 1], Some(&l.design)).unwrap(); + assert_eq!(previewed[0].refused, None, "2 makes 20"); + s.run("select.rows", &json!({"layer": "calc", "rows": [1]})).unwrap(); + let ran = s.run("edit.calculateField", &json!({"layer": "calc", "field": "n", "expression": "n + 1"})).unwrap_err(); + assert_eq!(previewed[1].refused.as_deref(), Some(ran.as_str()), "3 makes 30"); + // A calculation rule reading `@row_number` reads the layer's row in the preview's copy too. + let ruled = || { + let mut s = layer(); + s.run("data.domain", &json!({"layer": "calc", "field": "m", "min": 0, "max": 15})).unwrap(); + s.run( + "data.attributeRule", + &json!({"layer": "calc", "name": "Place", "kind": "calculation", "field": "m", "expression": "@row_number * 10"}), + ) + .unwrap(); + s + }; + let s = ruled(); + let l = s.map().layer_by_name("calc").unwrap(); + let n = l.dataset.field_index("n").unwrap(); + let refused: Vec> = crate::cmd::edit::preview_calculation("n", &l.dataset, n, &[0, 1], Some(&l.design)) + .unwrap() + .into_iter() + .map(|p| p.refused) + .collect(); + let ran: Vec> = (0..2) + .map(|row| { + let mut s = ruled(); + s.run("select.rows", &json!({"layer": "calc", "rows": [row]})).unwrap(); + s.run("edit.calculateField", &json!({"layer": "calc", "field": "n", "expression": "n"})).err() + }) + .collect(); + assert_eq!(refused, ran, "the rule reads the row's place"); + assert_eq!(ran.iter().map(Option::is_some).collect::>(), [false, true], "row 1 makes 10, row 2 makes 20"); +} + /// Calculate Field keeps a decimal result as it is in a decimal field, rather than rounding it to /// the six places its text shows, and says what a whole-number field cuts: a fraction, or a number /// past the 64-bit range (null). Results the field holds give no notice. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 645586301e..b114e1c4a1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -883,10 +883,14 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { let text = app.dialogs.text.trim(); // 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[..]), + // A layer's checks too, which say which rows the edit would be refused for (#2837); + // a standalone table has none. + let layer = match app.dialogs.table { + Some(_) => None, + None => app.session.active_layer.and_then(|id| app.session.map().layer(id)), }; + let selected = layer.map_or(&[][..], |l| &l.selection[..]); + let design = layer.map(|l| &l.design); 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. @@ -896,7 +900,7 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { 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), + Some(fi) => rustgis_engine::cmd::edit::preview_calculation(text, d, fi, &rows, design).map(Some), None => rustgis_engine::cmd::edit::check_calculation(text, d).map(|()| None), } }); @@ -3300,50 +3304,84 @@ fn calculation_fields(dataset: &rustgis_engine::data::Dataset) -> impl Iterator< 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. +/// forty characters and with no line break of its own, with what writing it loses and what the +/// layer's checks would refuse it with, also on one line (`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); + /// A refusal quotes a value and may give a rule's expression: room for both, still one line. + /// Past it, a refusal is cut in its middle (`refusal_line`). + const LONGEST_REFUSAL: usize = 120; + /// Text on one line, written no further than one character past its cut. + struct OneLine { + text: String, + written: usize, + longest: 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 { + if self.written > self.longest { return Err(std::fmt::Error); } - self.0.push(if c.is_control() || matches!(c, '\u{2028}' | '\u{2029}') { ' ' } else { c }); - self.1 += 1; + self.text.push(if c.is_control() || matches!(c, '\u{2028}' | '\u{2029}') { ' ' } else { c }); + self.written += 1; } Ok(()) } } + /// `text` on one line, cut at `longest` characters. + fn one_line(text: impl std::fmt::Display, longest: usize) -> String { + let mut line = OneLine { text: String::new(), written: 0, longest }; + // An error only stops the writing past the cut. + let _ = write!(line, "{text}"); + let mut text = line.text; + if let Some((cut, _)) = text.char_indices().nth(longest) { + text.truncate(cut); + text.push('…'); + } + text + } + /// `why` on one line, a long one cut in its middle: a refusal quotes the value first and names + /// the check that refuses it last, and both stay (#2837). + fn refusal_line(why: &str) -> String { + let line = one_line(why, usize::MAX); + let count = line.chars().count(); + if count <= LONGEST_REFUSAL { + return line; + } + let head = LONGEST_REFUSAL / 3; + let tail = LONGEST_REFUSAL - head - 1; + let start: String = line.chars().take(head).collect(); + let end: String = line.chars().skip(count - tail).collect(); + format!("{start}…{end}") + } let values: Vec = rows .iter() .map(|p| { - 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('…'); - } + let value = one_line(&p.value, LONGEST); // 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"), + let loss = p.lost.map(|lost| match lost { + PreviewLoss::Fraction => tl_raw!("fraction dropped"), + PreviewLoss::Range => tl_raw!("past the 64-bit integer range"), + PreviewLoss::NotANumber => tl_raw!("not a number"), + PreviewLoss::NotFinite => tl_raw!("not a finite number"), + PreviewLoss::Time => tl_raw!("time dropped"), + 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()), + PreviewLoss::Error(fault) => tl_raw!(fault.describe()), + }); + let shown = match loss { + Some(loss) => crate::i18n::fmt_raw("{value} ({loss})", &[("value", &value), ("loss", loss)]), + None => value, }; - crate::i18n::fmt_raw("{value} ({loss})", &[("value", &value), ("loss", loss)]) + // The check that would refuse the edit, in the run's words (#2837). + match &p.refused { + Some(why) => crate::i18n::fmt_raw("{value} (refused: {why})", &[("value", &shown), ("why", &refusal_line(why))]), + None => shown, + } }) .collect(); crate::i18n::fmt("Preview: {values}", &[("values", &values.join(" · "))]) @@ -4340,6 +4378,48 @@ mod tests { assert!(h.query_by_label_contains("Preview:").is_none(), "no rows, no preview"); } + /// On a layer with checks, the preview says which rows the edit would be refused for, in the + /// run's words (#2837): here the field's domain, 0 to 30. + #[test] + fn calculate_field_preview_says_the_rows_a_layers_checks_refuse() { + 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..=3).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(); + app.run("data.domain", json!({"layer": "points", "field": "v", "min": 0, "max": 30})).unwrap(); + app.run("ui.dialog", json!({"name": "calculateField"})).unwrap(); + app.dialogs.a = "v".into(); + app.dialogs.text = "v * 15".into(); + let mut h = app_harness(app); + h.run_steps(3); + assert!(h.query_by_label("Preview: 15 · 30 · 45 (refused: 45 isn't allowed in v (its domain))").is_some(), "the third refused"); + } + + /// A refused row's value is followed by what refuses it, after what writing it loses. + #[test] + fn a_calculation_preview_says_a_refusal_after_a_loss() { + use rustgis_engine::cmd::edit::{CalculationPreview, PreviewLoss}; + use rustgis_engine::data::Value; + let refused = Some("the edit breaks the rule Even (v % 2 = 0)".to_string()); + let rows = [ + CalculationPreview { row: 0, value: Value::Int(2), lost: Some(PreviewLoss::Fraction), refused: refused.clone() }, + CalculationPreview { row: 1, value: Value::Int(4), lost: None, refused: None }, + ]; + assert_eq!( + super::calculation_preview(&rows), + "Preview: 2 (fraction dropped) (refused: the edit breaks the rule Even (v % 2 = 0)) · 4" + ); + // A refusal quoting a value keeps to one line too, and a long one is cut in its middle, so + // the check that refuses it, at its end, stays (#2837). + let quoted = format!("a\nb{} isn't allowed in v (its domain)", "x".repeat(10_000)); + let row = CalculationPreview { row: 0, value: Value::Int(1), lost: None, refused: Some(quoted) }; + let line = super::calculation_preview(&[row]); + assert!(line.starts_with("Preview: 1 (refused: a b"), "{line}"); + assert!(line.ends_with("x isn't allowed in v (its domain))") && line.contains('…'), "{line}"); + assert!(!line.contains('\n') && line.chars().count() < 200, "{line}"); + } + /// 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. @@ -4347,7 +4427,7 @@ mod tests { 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 }; + let row = |value: Value| CalculationPreview { row: 0, value, lost: None, refused: None }; 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" diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index 32132d97de..e8e5cb897b 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -244,9 +244,13 @@ invalid (`pop_x`: no field named 'pop_x'). Once it reads, a line under the box p 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. +and nothing changes until **Calculate** is clicked. On a layer, each previewed row also runs the +layer's calculation rules and checks (domains, allowed combinations of values, constraint rules) as +Calculate would, and a row they would refuse says so in Calculate's words: +`Preview: 15 · 30 · 45 (refused: 45 isn't allowed in v (its domain))`. Calculate refuses the whole +edit when any of its rows is refused, so rows the preview doesn't show can still refuse it. An area +the edit reads that is ambiguous refuses it too, and the preview doesn't say so, even for a row it +shows. 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