From 86b31e3c33b4830ab78a7baac36a5d8dd5700936 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:28:19 -0600 Subject: [PATCH 01/24] fix(engine): table and layer edits by field name pick the exact name before a case-insensitive one (#1955) With fields `Name` and `name` (GeoJSON and CSV readers make such case twins), edit.setValue, edit.deleteField, edit.convertField, edit.calculateField and edit.calculateGeometry given "name" changed `Name`, the first field matching ignoring case, without a word. Commands that change a field's values or the field itself now take the field named exactly, else the only field named so ignoring case, as edit.addFeature already matched attributes (it now shares the rule). A name matching twins but neither exactly is refused and nothing changes. Dataset::field_index is unchanged: expressions, queries and what a layer keeps by a field's name still read the first match ignoring case. What a layer keeps by name (renderer, labels, domains, subtypes, contingent values, rules, diagram, extrusion, marker rotation, size by, water levels) is judged when a field is deleted, or converted to dates, the way it is read: by the first field so named ignoring case. Deleting a twin nothing read leaves all of it; deleting the one it read takes it, said, rather than letting it go on to read the other. Label classes besides Default on the deleted field now say they move to Default's. data.domain and data.subtypes are refused on a field with a case twin, since design applies to whichever comes first. Two deleteField tests named `pop` and `null` to delete the twin a query or symbol expression reads (`Pop`, `Null`); they now name it exactly. --- crates/engine/src/cmd/design.rs | 14 ++ crates/engine/src/cmd/edit.rs | 301 ++++++++++++++++++++++++----- crates/engine/src/geometry_calc.rs | 3 +- crates/engine/src/tests.rs | 14 +- 4 files changed, 280 insertions(+), 52 deletions(-) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index f82365cf2c..1726343628 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -1547,6 +1547,18 @@ fn traverse(s: &mut Session, p: &Json) -> CmdResult { super::edit::add_feature(s, &json!({"layer": id, "geometry": g})) } +/// Refuses `what` on field `name` while another field is named the same but for case: design finds +/// its field by name ignoring case, so it would apply to the first of them whichever was meant +/// (#1955). +fn case_twins_refused(ds: &rustgis_data::Dataset, name: &str, what: &str) -> Result<(), String> { + if ds.fields.iter().filter(|f| f.name.eq_ignore_ascii_case(name)).count() > 1 { + return Err(format!( + "'{name}' has a field named the same but for case, and {what} would apply to whichever comes first: rename one of them first" + )); + } + Ok(()) +} + fn domain(s: &mut Session, p: &Json) -> CmdResult { let id = s.layer_id(p)?; let field = ps(p, "field").ok_or("field is required")?; @@ -1558,6 +1570,7 @@ fn domain(s: &mut Session, p: &Json) -> CmdResult { l.design.domains.retain(|d| !d.field.eq_ignore_ascii_case(&fname)); return Ok(Json::Null); } + case_twins_refused(&l.dataset, &fname, "a domain")?; let kind = if let Some(codes) = p.get("coded").and_then(Json::as_array) { let pairs: Vec<(Value, String)> = codes .iter() @@ -1605,6 +1618,7 @@ fn subtypes(s: &mut Session, p: &Json) -> CmdResult { let l = s.map().layer(id).ok_or("no such layer")?; let fi = l.dataset.field_index(field).ok_or_else(|| format!("no field named '{field}'"))?; let f = l.dataset.fields.get(fi).ok_or("no field")?; + case_twins_refused(&l.dataset, &f.name, "subtypes")?; if f.ty != FieldType::Integer { return Err(format!("{} must be an integer field to hold subtype codes", f.name)); } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e5c6ab6bb1..9fd107dc8a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -115,10 +115,25 @@ fn data_mut(s: &mut Session, t: Target) -> Result<&mut Dataset, String> { } } -/// Field `name`'s index in the data of `t`: the first matching it ignoring case, as expressions -/// and queries find fields. +/// Field `name`'s index in the data of `t` ([`field_in`]). fn field_of(s: &Session, t: Target, name: &str) -> Result { - data(s, t)?.field_index(name).ok_or_else(|| format!("no field named '{name}'")) + field_in(&data(s, t)?.fields, name)?.ok_or_else(|| format!("no field named '{name}'")) +} + +/// The index of the field a command names `name` in `fields`: the field named exactly so, else the +/// only field named so ignoring case, so an edit never lands on a field the caller didn't name +/// (#1955). A name matching more than one field but none exactly is refused. Expressions and +/// queries read fields differently ([`Dataset::field_index`]). +pub(crate) fn field_in(fields: &[Field], name: &str) -> Result, String> { + if let Some(i) = fields.iter().position(|f| f.name == name) { + return Ok(Some(i)); + } + let mut matches = fields.iter().enumerate().filter(|(_, f)| f.name.eq_ignore_ascii_case(name)); + let first = matches.next().map(|(i, _)| i); + if matches.next().is_some() { + return Err(format!("'{name}' matches more than one field: use an exact field name")); + } + Ok(first) } /// A table's rows change only while editing is on, as a layer's features do @@ -203,11 +218,11 @@ struct LeftOut { taken: Vec, } -/// Each field's value in `"attributes"`, by field. A key gives one field: the one named exactly -/// so, else the only field named so ignoring case (ambiguous keys are refused); the keys named -/// exactly go first, so `Name` fills `Name` even when `name` comes first. A key naming no field, -/// or a field another key gives, is left out and said ([`notify_left_out`]). Non-object values -/// other than null are refused before any row is inserted. +/// Each field's value in `"attributes"`, by field. A key gives one field ([`field_in`]: the one +/// named exactly so, else the only field named so ignoring case; ambiguous keys are refused); the +/// keys named exactly go first, so `Name` fills `Name` even when `name` comes first. A key naming +/// no field, or a field another key gives, is left out and said ([`notify_left_out`]). Non-object +/// values other than null are refused before any row is inserted. fn given_attributes<'a>(fields: &[Field], p: &'a Json) -> Result<(Vec>, LeftOut), String> { let mut given = vec![None; fields.len()]; let mut left = LeftOut::default(); @@ -216,20 +231,16 @@ fn given_attributes<'a>(fields: &[Field], p: &'a Json) -> Result<(Vec attributes, Some(_) => return Err("attributes is an object of field names and values".into()), }; - let exact = |k: &str| fields.iter().position(|f| f.name == k); - for (k, v) in attributes.iter().filter(|(k, _)| exact(k).is_some()) { - match exact(k).and_then(|i| given.get_mut(i)) { - Some(slot @ None) => *slot = Some(v), - _ => left.taken.push(k.clone()), - } - } - for (k, v) in attributes.iter().filter(|(k, _)| exact(k).is_none()) { - let mut matches = fields.iter().enumerate().filter(|(_, f)| f.name.eq_ignore_ascii_case(k)); - let first = matches.next().map(|(i, _)| i); - if matches.next().is_some() { - return Err(format!("attribute '{k}' matches more than one field: use an exact field name")); - } - match first.map(|i| given.get_mut(i)) { + let mut keys = Vec::with_capacity(attributes.len()); + for (k, v) in attributes { + let i = field_in(fields, k).map_err(|e| format!("attribute {e}"))?; + let inexact = !i.and_then(|i| fields.get(i)).is_some_and(|f| f.name == *k); + keys.push((inexact, k, v, i)); + } + // Stable: the keys named exactly first, each kind in the order given. + keys.sort_by_key(|(inexact, ..)| *inexact); + for (_, k, v, i) in keys { + match i.map(|i| given.get_mut(i)) { None => left.no_field.push(k.clone()), Some(Some(slot @ None)) => *slot = Some(v), Some(_) => left.taken.push(k.clone()), @@ -841,10 +852,14 @@ fn check_layer_dates(s: &Session, id: u32, fi: usize, ty: FieldType) -> Result CmdResult { .collect(); // A Default class still as the layer made it loses nothing by starting again: that restart isn't said. let default_untouched = l.labels.default == rustgis_map::LabelClass::default_for(&l.dataset); + // What the layer keeps by a field's name (renderer, labels, design, diagram…) is read from the + // first field so named ignoring case ([`Dataset::field_index`]), so a name read the deleted + // field when it names it in any case and no field before it is named the same but for case. + // A name that read a twin left keeps it; one that read the deleted field would go on to read + // the twin, so it goes too (#1955). + let read = !l.dataset.fields.iter().take(fi).any(|f| f.name.eq_ignore_ascii_case(&name)); + let names_removed = |f: &str| read && f.eq_ignore_ascii_case(&name); let removed = l.dataset.fields.remove(fi).name; for f in &mut l.dataset.features { if fi < f.attrs.len() { @@ -1023,7 +1045,7 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { // (Classes by an expression that read until now go the same way.) let unread = read_before && l.renderer.expression().is_some_and(|e| rustgis_data::query::parse_fields(e, &l.dataset).is_err()); let mut single = None; - if unread || l.renderer.field().is_some_and(|f| f.eq_ignore_ascii_case(&removed)) { + if unread || l.renderer.field().is_some_and(names_removed) { l.renderer = rustgis_map::Renderer::Single(l.renderer.base_symbol()); single = Some(l.name.clone()); } @@ -1064,7 +1086,7 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { // no features, which go on to the next class: it is kept to edit, not dropped with its text // symbol. let mut restart_note = None; - if l.labels.default.field.eq_ignore_ascii_case(&removed) { + if names_removed(&l.labels.default.field) { let by_text = l.labels.default.by.text.as_deref().is_some_and(|t| rustgis_data::query::parse_fields(t, &l.dataset).is_ok()); if by_text { l.labels.default.field.clear(); @@ -1082,25 +1104,45 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { }); } } + // Another class on the deleted field labels with Default's field instead, as + // `repoint_missing_fields` would point it, said; including one whose name would now find a + // twin (#1955). + let fallback = match l.dataset.field_index(&l.labels.default.field) { + Some(_) => l.labels.default.field.clone(), + None => rustgis_map::LabelClass::default_for(&l.dataset).field, + }; + let mut moved = Vec::new(); + for c in &mut l.labels.classes { + let by_text = c.by.text.as_deref().is_some_and(|t| rustgis_data::query::parse_fields(t, &l.dataset).is_ok()); + if names_removed(&c.field) && !by_text { + c.field.clone_from(&fallback); + moved.push(c.name.clone()); + } + } + let moved_note = (!moved.is_empty()).then(|| { + let on = if fallback.is_empty() { "no field".to_string() } else { format!("field {fallback}") }; + let (classes, it) = if moved.len() == 1 { ("class", "it labels") } else { ("classes", "they label") }; + format!("{}: its label {classes} {} labeled the deleted field {removed}, so {it} {on}", l.name, moved.join(", ")) + }); l.labels.repoint_missing_fields(&l.dataset); // A definition query that reads the field was refused above; one that already didn't read is // kept as it is, so its text isn't lost. // Nor its data design: domains, subtypes, contingent values, and rules that used it. let d = &mut l.design; - d.domains.retain(|x| !x.field.eq_ignore_ascii_case(&removed)); - if d.subtypes.as_ref().is_some_and(|st| st.field.eq_ignore_ascii_case(&removed)) { + d.domains.retain(|x| !names_removed(&x.field)); + if d.subtypes.as_ref().is_some_and(|st| names_removed(&st.field)) { d.subtypes = None; } if let Some(st) = &mut d.subtypes { for sub in &mut st.subtypes { - sub.defaults.retain(|(f, _)| !f.eq_ignore_ascii_case(&removed)); + sub.defaults.retain(|(f, _)| !names_removed(f)); } } - d.contingent.retain(|c| !c.fields.iter().any(|f| f.eq_ignore_ascii_case(&removed))); + d.contingent.retain(|c| !c.fields.iter().any(|f| names_removed(f))); let ds = rustgis_data::Dataset::new(l.dataset.name.clone(), l.dataset.geometry_type, l.dataset.fields.clone()); let before = d.rules.len(); d.rules.retain(|r| { - !r.field.eq_ignore_ascii_case(&removed) + !names_removed(&r.field) && match r.kind { rustgis_map::design::RuleKind::Calculation => Calculation::parse(&r.expression, &ds).is_ok(), rustgis_map::design::RuleKind::Constraint => rustgis_data::query::parse_fields(&r.expression, &ds).is_ok(), @@ -1111,9 +1153,9 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { // measured again without it, and a diagram left with no field goes too. Said once. let mut diagram_note = None; if let Some(dg) = &mut l.diagram - && dg.categories.iter().any(|c| c.field.eq_ignore_ascii_case(&removed)) + && dg.categories.iter().any(|c| names_removed(&c.field)) { - dg.categories.retain(|c| !c.field.eq_ignore_ascii_case(&removed)); + dg.categories.retain(|c| !names_removed(&c.field)); if dg.categories.is_empty() { l.diagram = None; diagram_note = Some(format!("{}: its diagram drew only the deleted field {removed}, so it is removed", l.name)); @@ -1131,7 +1173,7 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { if let Some(x) = &mut l.extrusion { let mut what = Vec::new(); for (read, name) in [(&mut x.field, "height"), (&mut x.base_field, "base")] { - if read.as_deref().is_some_and(|f| f.eq_ignore_ascii_case(&removed)) { + if read.as_deref().is_some_and(names_removed) { *read = None; what.push(name); } @@ -1143,12 +1185,12 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { } } let mut rotation_note = None; - if l.marker_rotation.as_ref().is_some_and(|r| r.field.eq_ignore_ascii_case(&removed)) { + if l.marker_rotation.as_ref().is_some_and(|r| names_removed(&r.field)) { l.marker_rotation = None; rotation_note = Some(format!("{}: its markers turned by the deleted field {removed}, so they are no longer turned", l.name)); } let mut size_note = None; - if l.size_by.as_ref().is_some_and(|b| b.field.eq_ignore_ascii_case(&removed)) { + if l.size_by.as_ref().is_some_and(|b| names_removed(&b.field)) { l.size_by = None; size_note = Some(format!("{}: its markers were sized by the deleted field {removed}, so they keep their class sizes", l.name)); } @@ -1178,7 +1220,7 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { Some(format!("{}: its symbol's {} expressions read the deleted field {removed}, so they are removed", l.name, and_list(many))) } }; - for note in [extrusion_note, rotation_note, size_note, by_note, label_note, restart_note].into_iter().flatten() { + for note in [extrusion_note, rotation_note, size_note, by_note, label_note, restart_note, moved_note].into_iter().flatten() { s.notify(note, false); } if let Some(note) = diagram_note { @@ -1192,7 +1234,7 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { let layer_name = s.map().layer(id).map(|l| l.name.clone()).unwrap_or_default(); if let Some(w) = s.map_mut().view.terrain.as_mut().and_then(|t| t.water.as_mut()) && w.layer.eq_ignore_ascii_case(&layer_name) - && w.level.as_deref().is_some_and(|f| f.eq_ignore_ascii_case(&removed)) + && w.level.as_deref().is_some_and(names_removed) { w.level = None; s.notify( @@ -1421,9 +1463,8 @@ fn land_table_edit(s: &mut Session, p: &Json, command: &str) -> Option Result<(Dataset, WriteLosses), String> { - let fi = input.field_index(ps(p, "field").ok_or("field is required")?).ok_or("no field")?; +/// cancellation never installs partial output. Writes field `fi`. +fn calculate_table(input: &Dataset, fi: usize, p: &Json) -> Result<(Dataset, WriteLosses), String> { let ty = input.fields.get(fi).map(|f| f.ty).ok_or("no field")?; let expr = ps(p, "expression").map(str::trim).filter(|e| !e.is_empty()).ok_or("expression is required")?; let calc = Calculation::parse(expr, input)?; @@ -1449,12 +1490,13 @@ fn calculate_field(s: &mut Session, p: &Json) -> CmdResult { } let t = write_target(s, p)?; let field = ps(p, "field").ok_or("field is required")?; - let fi = data(s, t)?.field_index(field).ok_or_else(|| format!("no field named '{field}'; use Add Field (edit.addField) first"))?; + let fi = + field_in(&data(s, t)?.fields, field)?.ok_or_else(|| format!("no field named '{field}'; use Add Field (edit.addField) first"))?; let expr = ps(p, "expression").map(str::trim).filter(|e| !e.is_empty()).ok_or("expression is required")?.to_string(); let Target::Layer(id) = t else { editing_on(s)?; let (ty, field) = data(s, t)?.fields.get(fi).map(|f| (f.ty, f.name.clone())).ok_or("no field")?; - let (result, losses) = calculate_table(data(s, t)?, p)?; + let (result, losses) = calculate_table(data(s, t)?, fi, p)?; let n = result.features.len(); data_mut(s, t)?.features = result.features; calculation_notices(s, &field, ty, &losses); @@ -1767,6 +1809,177 @@ mod tests { } } + /// An edit by field name picks the field named exactly so, else the only one named so but + /// for case; a name matching case twins but neither exactly is refused, changing nothing + /// (#1955). On a layer and a standalone table, as the GeoJSON and CSV readers make twins. + #[test] + fn edits_by_field_name_pick_the_exact_field() { + let names = |s: &Session, t: Target| -> Vec { data(s, t).unwrap().fields.iter().map(|f| f.name.clone()).collect() }; + let row = |s: &Session, t: Target| -> Vec { data(s, t).unwrap().features[0].attrs.clone() }; + for table in [false, true] { + let fresh = |fields: &[&str]| { + let mut s = Session::new(crate::Project::default()); + let fields = fields.iter().map(|f| Field::new(*f, FieldType::Text)).collect(); + let mut ds = Dataset::new("twins", GeometryType::None, fields); + let n = ds.fields.len(); + ds.push(None, (0..n).map(|i| Value::Text(format!("2020-01-0{}", i + 1))).collect()); + let target = if table { + json!({"table": s.project.add_table(ds)}) + } else { + let id = s.map_mut().add_dataset(ds); + json!({"layer": id}) + }; + let t = super::target(&s, &target).unwrap(); + (s, target, t) + }; + let with = |target: &Json, extra: Json| { + let mut p = target.clone(); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + p + }; + let date = |d: &str| Value::Text(d.into()); + + // The exact twin is the one changed. + let (mut s, target, t) = fresh(&["Name", "name"]); + s.run("edit.setValue", &with(&target, json!({"row": 0, "field": "name", "value": "CHANGED"}))).unwrap(); + assert_eq!(row(&s, t), [date("2020-01-01"), date("CHANGED")], "setValue, table {table}"); + s.run("edit.calculateField", &with(&target, json!({"field": "name", "expression": "'calc'"}))).unwrap(); + assert_eq!(row(&s, t), [date("2020-01-01"), date("calc")], "calculateField, table {table}"); + let (mut s, target, t) = fresh(&["Name", "name"]); + s.run("edit.convertField", &with(&target, json!({"field": "name", "type": "date"}))).unwrap(); + let types: Vec = data(&s, t).unwrap().fields.iter().map(|f| f.ty).collect(); + assert_eq!(types, [FieldType::Text, FieldType::Date], "convertField, table {table}"); + let (mut s, target, t) = fresh(&["Name", "name"]); + s.run("edit.deleteField", &with(&target, json!({"field": "name"}))).unwrap(); + assert_eq!(names(&s, t), ["Name"], "deleteField, table {table}"); + + // A unique name but for case still finds its field. + let (mut s, target, t) = fresh(&["Name", "other"]); + s.run("edit.setValue", &with(&target, json!({"row": 0, "field": "NAME", "value": "CHANGED"}))).unwrap(); + assert_eq!(row(&s, t), [date("CHANGED"), date("2020-01-02")], "unique setValue, table {table}"); + s.run("edit.calculateField", &with(&target, json!({"field": "NAME", "expression": "'calc'"}))).unwrap(); + assert_eq!(row(&s, t), [date("calc"), date("2020-01-02")], "unique calculateField, table {table}"); + s.run("edit.deleteField", &with(&target, json!({"field": "NAME"}))).unwrap(); + assert_eq!(names(&s, t), ["other"], "unique deleteField, table {table}"); + + // A name matching both twins but neither exactly is refused, and nothing changes. + let (mut s, target, t) = fresh(&["Name", "name"]); + for (command, extra) in [ + ("edit.setValue", json!({"row": 0, "field": "NAME", "value": "CHANGED"})), + ("edit.calculateField", json!({"field": "NAME", "expression": "'calc'"})), + ("edit.convertField", json!({"field": "NAME", "type": "date"})), + ("edit.deleteField", json!({"field": "NAME"})), + ] { + let error = s.run(command, &with(&target, extra)).unwrap_err(); + assert_eq!(error, "'NAME' matches more than one field: use an exact field name", "{command}, table {table}"); + assert_eq!(names(&s, t), ["Name", "name"], "{command}, table {table}"); + assert_eq!(row(&s, t), [date("2020-01-01"), date("2020-01-02")], "{command}, table {table}"); + let types: Vec = data(&s, t).unwrap().fields.iter().map(|f| f.ty).collect(); + assert_eq!(types, [FieldType::Text, FieldType::Text], "{command}, table {table}"); + } + } + } + + /// What a layer keeps by a field's name is read from the first field so named ignoring case, + /// whichever twin's name it stores. Deleting that field takes and says what read it; deleting + /// its twin, which nothing read, leaves all of it and says nothing (#1955). + #[test] + fn deleting_a_case_twin_takes_what_read_it() { + for stored in ["Name", "name"] { + for (deleted, read) in [("name", false), ("Name", true)] { + let mut s = Session::new(crate::Project::default()); + let fields = ["Name", "name", "n"].map(|f| Field::new(f, FieldType::Double)).to_vec(); + let mut ds = Dataset::new("twins", GeometryType::Point, fields); + let at = Geometry::Point(rustgis_data::Coord::new(3.0, 4.0)); + ds.push(Some(at), vec![Value::Float(1.0), Value::Float(2.0), Value::Float(3.0)]); + let id = s.map_mut().add_dataset(ds); + s.run("layer.symbology", &json!({"layer": id, "type": "unique", "field": "n"})).unwrap(); + s.run("layer.diagram", &json!({"layer": id, "kind": "pie", "fields": [stored, "n"]})).unwrap(); + let l = s.map_mut().layer_mut(id).unwrap(); + if let rustgis_map::Renderer::Unique { field, .. } = &mut l.renderer { + *field = stored.into(); + } + l.labels.default.field = stored.into(); + l.labels.enabled = true; + let mut other = l.labels.default.clone(); + other.name = "Other".into(); + l.labels.classes.push(other); + let kind = rustgis_map::design::DomainKind::Range { min: 0.0, max: 10.0 }; + l.design.domains.push(rustgis_map::design::Domain { field: stored.into(), kind }); + let mark = s.notice_mark(); + s.run("edit.deleteField", &json!({"layer": id, "field": deleted})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + let l = s.map().layer(id).unwrap(); + let slices: Vec<&str> = l.diagram.as_ref().unwrap().categories.iter().map(|c| c.field.as_str()).collect(); + let case = format!("'{stored}' stored, '{deleted}' deleted: {said:?}"); + if read { + assert_eq!(l.renderer.field(), None, "{case}"); + assert!(l.design.domains.is_empty(), "{case}"); + assert_eq!(slices, ["n"], "{case}"); + for part in [ + "its classes read the deleted field Name", + "the deleted field Name, so it starts again", + "its label class Other labeled the deleted field Name", + "its diagram drew the deleted field Name", + ] { + assert!(said.iter().any(|n| n.contains(part)), "{part}: {case}"); + } + } else { + assert_eq!(l.renderer.field(), Some(stored), "{case}"); + assert!(l.labels.enabled && l.labels.default.field == stored, "{case}"); + assert_eq!(l.labels.classes.iter().map(|c| c.field.as_str()).collect::>(), [stored], "{case}"); + assert_eq!(l.design.domains.iter().map(|d| d.field.as_str()).collect::>(), [stored], "{case}"); + assert_eq!(slices, [stored, "n"], "{case}"); + assert!(said.iter().all(|n| !n.contains("deleted field")), "{case}"); + } + } + } + } + + /// Converting and calculating geometry into a field named the same as another but for case + /// work on the field named; the design guard follows the field design applies to; and design + /// is refused on twins, which it couldn't tell apart (#1955). + #[test] + fn field_commands_and_case_twins() { + let mut s = Session::new(crate::Project::default()); + let fields = vec![ + Field::new("Name", FieldType::Text), + Field::new("name", FieldType::Text), + Field::new("X", FieldType::Double), + Field::new("x", FieldType::Double), + ]; + let mut ds = Dataset::new("twins", GeometryType::Point, fields); + let text = |t: &str| Value::Text(t.into()); + ds.push( + Some(Geometry::Point(rustgis_data::Coord::new(3.0, 4.0))), + vec![text("a"), text("2020-01-02"), Value::Float(0.0), Value::Float(0.0)], + ); + let id = s.map_mut().add_dataset(ds); + let domains = |s: &Session| -> Vec { s.map().layer(id).unwrap().design.domains.iter().map(|d| d.field.clone()).collect() }; + // A domain stored as "name" applies to `Name`, the first so named: `name` may become + // dates, `Name` may not. + let kind = rustgis_map::design::DomainKind::Coded(vec![(text("a"), "A".into())]); + s.map_mut().layer_mut(id).unwrap().design.domains.push(rustgis_map::design::Domain { field: "name".into(), kind }); + s.run("edit.convertField", &json!({"layer": id, "field": "name", "type": "date"})).unwrap(); + let error = s.run("edit.convertField", &json!({"layer": id, "field": "Name", "type": "date"})).unwrap_err(); + assert!(error.contains("has a domain"), "{error}"); + let types: Vec = s.map().layer(id).unwrap().dataset.fields.iter().map(|f| f.ty).collect(); + assert_eq!(types, [FieldType::Text, FieldType::Date, FieldType::Double, FieldType::Double]); + // Calculate Geometry fills `x`, not `X`. + let p = json!({"layer": id, "field": "x", "property": "x", "unit": "deg", "scope": "all", "overwrite": true}); + s.run("edit.calculateGeometry", &p).unwrap(); + let ds = &s.map().layer(id).unwrap().dataset; + assert_eq!((ds.value(0, 2), ds.value(0, 3)), (&Value::Float(0.0), &Value::Float(3.0))); + // A domain on either twin, by any case, is refused, and nothing changes. + for field in ["X", "x", "NAME"] { + let error = s.run("data.domain", &json!({"layer": id, "field": field, "min": 0, "max": 5})).unwrap_err(); + assert!(error.contains("named the same but for case"), "{field}: {error}"); + assert_eq!(domains(&s), ["name"]); + } + } + /// Not a number is null in a whole-number field, said as such, not past its range; a number /// past the range is null where it's said, and at the range's end elsewhere, as before. #[test] diff --git a/crates/engine/src/geometry_calc.rs b/crates/engine/src/geometry_calc.rs index 4acc1d20bd..dcbbaa5184 100644 --- a/crates/engine/src/geometry_calc.rs +++ b/crates/engine/src/geometry_calc.rs @@ -56,7 +56,8 @@ pub fn run(s: &mut Session, p: &Json) -> CmdResult { }; let field = p.get("field").and_then(Json::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or("field is required")?; let create = p.get("create").and_then(Json::as_bool).unwrap_or(false); - let existing = l.dataset.field_index(field); + // A new field may not match one ignoring case; an existing one is the field named ([`field_in`]). + let existing = if create { l.dataset.field_index(field) } else { crate::cmd::edit::field_in(&l.dataset.fields, field)? }; let ty = if create { if existing.is_some() { return Err("field already exists".into()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a249ec950b..c3566df7e1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4810,17 +4810,17 @@ fn degenerate_geometry_and_deleted_fields() { let l = s.map().layer_by_name("Countries").unwrap(); assert!(l.dataset.field_index("pop_est").is_some() && l.display_filters.len() == 1); s.run("layer.displayFilters", &json!({"layer": "Countries", "filters": []})).unwrap(); - // Two fields named the same but for case: the query reads the first, which deleting `pop` - // removes; it would otherwise go on to read the second without a word. + // Two fields named the same but for case: the query `pop > 1` reads the first, which deleting + // `Pop` removes; it would otherwise go on to read the second without a word. s.run("layer.addDataText", &json!({"fileName": "twins.csv", "text": "lon,lat,Pop,pop\n1,2,5,0\n3,4,0,5\n"})).unwrap(); s.run("layer.definitionQuery", &json!({"layer": "twins", "where": "pop > 1"})).unwrap(); - let e = s.run("edit.deleteField", &json!({"layer": "twins", "field": "pop"})).unwrap_err(); + let e = s.run("edit.deleteField", &json!({"layer": "twins", "field": "Pop"})).unwrap_err(); assert!(e.contains("definition query (pop > 1) uses 'Pop'"), "{e}"); // The same with a field named like a keyword: `null` reads the field `Null` while it exists, - // and would read the other one once it is gone. + // and would read the other one once deleting `Null` removes it. s.run("layer.addDataText", &json!({"fileName": "keywords.csv", "text": "lon,lat,Null,null\n1,2,5,0\n3,4,0,5\n"})).unwrap(); s.run("layer.definitionQuery", &json!({"layer": "keywords", "where": "null = 5"})).unwrap(); - let e = s.run("edit.deleteField", &json!({"layer": "keywords", "field": "null"})).unwrap_err(); + let e = s.run("edit.deleteField", &json!({"layer": "keywords", "field": "Null"})).unwrap_err(); assert!(e.contains("definition query (null = 5) uses 'Null'"), "{e}"); s.run("edit.deleteField", &json!({"layer": "Countries", "field": "pop_est"})).unwrap(); let l = s.map().layer_by_name("Countries").unwrap(); @@ -23902,12 +23902,12 @@ fn deleting_a_field_clears_the_extrusion_marker_rotation_and_symbol_expressions_ s.run("edit.undo", &Value::Null).unwrap(); let got = by(&s, "Cities"); assert_eq!((got.size.as_deref(), got.angle.as_deref()), (Some("turn / 10 + 4"), Some("TURN"))); - // Two fields named the same but for case: `pop` reads the first, which deleting `pop` removes. + // Two fields named the same but for case: `pop` reads the first, which deleting `Pop` removes. // Its text would still parse, reading the second, so it is judged by the field it read. s.run("layer.addDataText", &json!({"fileName": "twins.csv", "text": "lon,lat,Pop,pop\n1,2,5,0\n3,4,0,5\n"})).unwrap(); s.run("layer.symbolBy", &json!({"layer": "twins", "size": "pop * 2"})).unwrap(); let mark = s.notice_mark(); - s.run("edit.deleteField", &json!({"layer": "twins", "field": "pop"})).unwrap(); + s.run("edit.deleteField", &json!({"layer": "twins", "field": "Pop"})).unwrap(); assert_eq!(by(&s, "twins").size, None); assert_eq!(about(&s, mark, "expression"), ["twins: its symbol's size expression read the deleted field Pop, so it is removed"]); } From 6a7cadcb4280fdb0af5dec3c3d40188bac2fa46a Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:02:37 -0600 Subject: [PATCH 02/24] fix(engine): refuse design on case-twin fields and say which label classes a deleted twin moves (#1955) data.attributeRule (calculation), data.contingentValues and subtype defaults are now refused on a field with a case twin, as domains and subtypes are: design finds its field by name ignoring case, so it would apply to whichever twin comes first. Deleting a field moves every label class on it, including one whose text is an expression, to Default's field through Labeling::repoint_fields, which returns the classes it moved. When a twin is left, which their names would otherwise find, a notice says so. Without a twin nothing changes and nothing new is said. The field lookup for commands that change a field is now the tools' (rustgis_analysis::find_field), whose refusal names the colliding fields. One helper says whether a stored name reads a field. Calculate Geometry replies with the written field's own name. The field parameter of setValue, deleteField, convertField, calculateField and calculateGeometry tells the Assistant and MCP the exact name is used first and an ambiguous one is refused. --- crates/analysis/src/lib.rs | 4 +- crates/analysis/src/tools.rs | 33 ++++--- crates/engine/src/cmd/design.rs | 3 + crates/engine/src/cmd/edit.rs | 143 ++++++++++++++++++----------- crates/engine/src/geometry_calc.rs | 4 +- crates/engine/src/tests.rs | 2 +- crates/map/src/symbology.rs | 21 ++++- 7 files changed, 133 insertions(+), 77 deletions(-) diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 43579deaa5..c2f3f61a42 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -48,8 +48,8 @@ pub use density::{ pub use parallel::scratch_budget; pub use parameters::StatisticList; pub use tools::{ - SimplifyNotes, TOOLS, find_field_case_insensitive, holds_coordinates, in_its_units, layer_raster_crs, max_buffer_bytes, min_pad, - param_applies, past_pole, points_in, projected_crs, raster_crs, simplify_geometry, zonal_bands, + SimplifyNotes, TOOLS, find_field, find_field_case_insensitive, holds_coordinates, in_its_units, layer_raster_crs, max_buffer_bytes, + min_pad, param_applies, past_pole, points_in, projected_crs, raster_crs, simplify_geometry, zonal_bands, }; use rustgis_data::Dataset; diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index bd5e1e9ca3..78d4ae8929 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1540,25 +1540,24 @@ fn keep_source_crs(out: &mut Dataset, ds: &Dataset, overlay: &Dataset) { /// If multiple fields in `ds.fields` match `name` case-insensitively, returns an error /// detailing the collision rather than silently selecting an arbitrary field. pub fn find_field_case_insensitive(ds: &Dataset, name: &str) -> Result { - if let Some(idx) = ds.fields.iter().position(|f| f.name == name) { - return Ok(idx); - } - let mut matches = Vec::new(); - for (idx, f) in ds.fields.iter().enumerate() { - if f.name.eq_ignore_ascii_case(name) { - matches.push(idx); - } + find_field(&ds.fields, name)?.ok_or_else(|| format!("no field named '{name}'")) +} + +/// The index of the field `name` names in `fields`: the one named exactly so, else the only one +/// named so ignoring case; `None` when none is. A name that matches several fields ignoring case +/// but none exactly is an error naming them, rather than an arbitrary pick. +pub fn find_field(fields: &[Field], name: &str) -> Result, String> { + if let Some(idx) = fields.iter().position(|f| f.name == name) { + return Ok(Some(idx)); } + let matches: Vec<&str> = fields.iter().filter(|f| f.name.eq_ignore_ascii_case(name)).map(|f| f.name.as_str()).collect(); match matches.as_slice() { - [] => Err(format!("no field named '{name}'")), - [only] => Ok(*only), - _ => { - let names: Vec = matches.iter().filter_map(|&i| ds.fields.get(i).map(|f| f.name.clone())).collect(); - Err(format!( - "field name '{name}' is ambiguous: case-insensitive collision between {}", - names.iter().map(|n| format!("'{n}'")).collect::>().join(" and ") - )) - } + [] => Ok(None), + [_] => Ok(fields.iter().position(|f| f.name.eq_ignore_ascii_case(name))), + _ => Err(format!( + "field name '{name}' is ambiguous: case-insensitive collision between {}", + matches.iter().map(|n| format!("'{n}'")).collect::>().join(" and ") + )), } } diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 1726343628..0455b79381 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -1640,6 +1640,7 @@ fn subtypes(s: &mut Session, p: &Json) -> CmdResult { .map(|o| o.iter().map(|(k, v)| (k.clone(), Value::from_json(v))).collect()) .unwrap_or_default(); for (field, value) in &defaults { + case_twins_refused(&l.dataset, field, "a subtype default")?; if let Some(ty) = l.dataset.field_index(field).and_then(|i| l.dataset.fields.get(i)).map(|f| f.ty) && super::edit::non_finite_input(value, ty) { @@ -1725,6 +1726,7 @@ fn attribute_rule(s: &mut Session, p: &Json) -> CmdResult { let field = match kind { RuleKind::Calculation => { let fl = ps(p, "field").ok_or("a calculation rule sets a field")?; + case_twins_refused(&l.dataset, fl, "a calculation rule")?; super::edit::Calculation::parse(&expression, &l.dataset)?; l.dataset .field_index(fl) @@ -1759,6 +1761,7 @@ fn contingent(s: &mut Session, p: &Json) -> CmdResult { .iter() .map(|v| { let n = v.as_str().ok_or("fields are names")?; + case_twins_refused(&l.dataset, n, "contingent values")?; l.dataset .field_index(n) .and_then(|i| l.dataset.fields.get(i)) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9fd107dc8a..f25f38ecff 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -21,26 +21,26 @@ pub fn commands() -> Vec { .when(crate::shape_conversion::need_editing).params(r#"{"preview":result of edit.previewShapeConversion,"confirm":true}"#), C::new("edit.calculateGeometry", "Calculate Geometry", "Attribute Table", crate::geometry_calc::run).roles(&[]).effects(crate::policy::Effects::NONE) .when(super::design::need_editable) - .params(r#"{"layer"?, "field": string, "create": bool, "overwrite": bool, "property": string, "unit": string, "epsg"?: number, "scope": "all"|"selected"}"#), + .params(r#"{"layer"?, "field": string (the exact name first; a name matching several fields only ignoring case is refused), "create": bool, "overwrite": bool, "property": string, "unit": string, "epsg"?: number, "scope": "all"|"selected"}"#), C::new("edit.addFeature", "Create Feature", "Edit › Features", add_feature).inputs(super::design::new_feature_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .when(super::design::need_editable_or_table) .params(r#"{"layer"?, "table"?: name|id (a standalone table: adds a row, without geometry or template), "geometry": GeoJSON geometry (lon/lat; left out for a table), "attributes"?: {field: value}, "template"?: feature template}"#), C::new("edit.delete", "Delete", "Edit › Features", delete).roles(&[]).effects(crate::policy::Effects::NONE).key("Delete").when(super::design::need_editable_selection), C::new("edit.setValue", "Edit Attribute", "Attribute Table", set_value).roles(&[]).effects(crate::policy::Effects::NONE) .when(super::design::need_editable_or_table) - .params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "row": number, "field": string, "value": any}"#), + .params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "row": number, "field": string (the exact name first; a name matching several fields only ignoring case is refused), "value": any}"#), C::new("edit.addField", "Add Field", "Data › Data Design › Fields", add_field).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_layer_or_table) .params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "name": string, "type": "long"|"double"|"text"|"boolean"|"date"|"datetime"}"#), C::new("edit.deleteField", "Delete Field", "Data › Data Design › Fields", delete_field).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_layer_or_table) - .params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "field": string}"#), + .params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "field": string (the exact name first; a name matching several fields only ignoring case is refused)}"#), C::new("edit.convertField", "Convert Field to Dates", "Attribute Table", convert_field).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_layer_or_table) - .params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "field": string, "type": "date"|"datetime", "format"?: "iso" (default)|strftime numeric pattern|"excel1900"|"excel1904", "pivotYear"?: first year of the 100-year window for %y}"#), + .params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "field": string (the exact name first; a name matching several fields only ignoring case is refused), "type": "date"|"datetime", "format"?: "iso" (default)|strftime numeric pattern|"excel1900"|"excel1904", "pivotYear"?: first year of the 100-year window for %y}"#), C::new("edit.calculateField", "Calculate Field", "Attribute Table", calculate_field).roles(&[]).effects(crate::policy::Effects::NONE) .when(super::design::need_editable_or_table) - .params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer: every row), "field": string, "expression": expression (fields, 'text', numbers, + - * / % ^ ||, functions: see the Expressions page)}"#), + .params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer: every row), "field": string (the exact name first; a name matching several fields only ignoring case is refused), "expression": expression (fields, 'text', numbers, + - * / % ^ ||, functions: see the Expressions page)}"#), C::new("edit.addBox", "Add Rotated Box", "Edit › Features", crate::box_edit::add).inputs(crate::box_edit::new_box_inputs).roles(box_roles).effects(crate::policy::Effects::NONE) .when(crate::cmd::design::need_editable).params(r#"{"layer"?: name|id, "box": {"center":[x,y],"width":number,"height":number,"angle":clockwise degrees,"frame"?:{"epsg":number,"width":pixels,"height":pixels,"affine":[x0,xc,xr,y0,yc,yr]}},"attributes"?:{field:value},"template"?:string}"#), C::new("edit.updateBox", "Update Rotated Box", "Edit › Features", crate::box_edit::update).roles(&[crate::ParamRole { key: "box", role: crate::Role::Opaque }]).effects(crate::policy::Effects::NONE) @@ -120,20 +120,19 @@ fn field_of(s: &Session, t: Target, name: &str) -> Result { field_in(&data(s, t)?.fields, name)?.ok_or_else(|| format!("no field named '{name}'")) } -/// The index of the field a command names `name` in `fields`: the field named exactly so, else the -/// only field named so ignoring case, so an edit never lands on a field the caller didn't name -/// (#1955). A name matching more than one field but none exactly is refused. Expressions and -/// queries read fields differently ([`Dataset::field_index`]). -pub(crate) fn field_in(fields: &[Field], name: &str) -> Result, String> { - if let Some(i) = fields.iter().position(|f| f.name == name) { - return Ok(Some(i)); - } - let mut matches = fields.iter().enumerate().filter(|(_, f)| f.name.eq_ignore_ascii_case(name)); - let first = matches.next().map(|(i, _)| i); - if matches.next().is_some() { - return Err(format!("'{name}' matches more than one field: use an exact field name")); - } - Ok(first) +/// The field a command that changes a field's values, or the field itself, names: the field named +/// exactly so, else the only field named so ignoring case, so an edit never lands on a field the +/// caller didn't name (#1955); a name matching several fields but none exactly is refused, naming +/// them. The tools find their fields the same way. What a layer keeps by a field's name, and +/// expressions and queries, read the first field so named ignoring case +/// ([`Dataset::field_index`], [`reads_field`]). +pub(crate) use rustgis_analysis::find_field as field_in; + +/// Whether `name`, a field name a layer keeps (its renderer's, labels', design's…), reads field +/// `fi` of `fields`: as they are read, by the first field so named ignoring case +/// ([`Dataset::field_index`]) (#1955). +pub(crate) fn reads_field(fields: &[Field], fi: usize, name: &str) -> bool { + fields.iter().position(|f| f.name.eq_ignore_ascii_case(name)) == Some(fi) } /// A table's rows change only while editing is on, as a layer's features do @@ -233,7 +232,7 @@ fn given_attributes<'a>(fields: &[Field], p: &'a Json) -> Result<(Vec Result CmdResult { .collect(); // A Default class still as the layer made it loses nothing by starting again: that restart isn't said. let default_untouched = l.labels.default == rustgis_map::LabelClass::default_for(&l.dataset); - // What the layer keeps by a field's name (renderer, labels, design, diagram…) is read from the - // first field so named ignoring case ([`Dataset::field_index`]), so a name read the deleted - // field when it names it in any case and no field before it is named the same but for case. - // A name that read a twin left keeps it; one that read the deleted field would go on to read - // the twin, so it goes too (#1955). - let read = !l.dataset.fields.iter().take(fi).any(|f| f.name.eq_ignore_ascii_case(&name)); + // What the layer keeps by a field's name (renderer, labels, design, diagram…) read the deleted + // field when it names it in any case and the field is the first so named ([`reads_field`]). A + // name that read a twin left keeps it; one that read the deleted field would go on to read the + // twin, so it goes too (#1955). + let read = reads_field(&l.dataset.fields, fi, &name); let names_removed = |f: &str| read && f.eq_ignore_ascii_case(&name); let removed = l.dataset.fields.remove(fi).name; for f in &mut l.dataset.features { @@ -1104,27 +1099,18 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { }); } } - // Another class on the deleted field labels with Default's field instead, as - // `repoint_missing_fields` would point it, said; including one whose name would now find a - // twin (#1955). - let fallback = match l.dataset.field_index(&l.labels.default.field) { - Some(_) => l.labels.default.field.clone(), - None => rustgis_map::LabelClass::default_for(&l.dataset).field, - }; - let mut moved = Vec::new(); - for c in &mut l.labels.classes { - let by_text = c.by.text.as_deref().is_some_and(|t| rustgis_data::query::parse_fields(t, &l.dataset).is_ok()); - if names_removed(&c.field) && !by_text { - c.field.clone_from(&fallback); - moved.push(c.name.clone()); - } - } - let moved_note = (!moved.is_empty()).then(|| { - let on = if fallback.is_empty() { "no field".to_string() } else { format!("field {fallback}") }; + // Another class on the deleted field labels with Default's field instead. Where a field named + // the same but for case is left, which its name would now find, that is said (#1955). + let moved = l.labels.repoint_fields(&l.dataset, names_removed); + let twin_left = l.dataset.field_index(&removed).is_some(); + let moved_note = (twin_left && !moved.is_empty()).then(|| { + let on = match l.labels.classes.iter().find(|c| moved.contains(&c.name)).map(|c| c.field.as_str()) { + Some(f) if !f.is_empty() => format!("field {f}"), + _ => "no field".to_string(), + }; let (classes, it) = if moved.len() == 1 { ("class", "it labels") } else { ("classes", "they label") }; - format!("{}: its label {classes} {} labeled the deleted field {removed}, so {it} {on}", l.name, moved.join(", ")) + format!("{}: its label {classes} {} used the deleted field {removed}, so {it} {on}", l.name, moved.join(", ")) }); - l.labels.repoint_missing_fields(&l.dataset); // A definition query that reads the field was refused above; one that already didn't read is // kept as it is, so its text isn't lost. // Nor its data design: domains, subtypes, contingent values, and rules that used it. @@ -1873,7 +1859,10 @@ mod tests { ("edit.deleteField", json!({"field": "NAME"})), ] { let error = s.run(command, &with(&target, extra)).unwrap_err(); - assert_eq!(error, "'NAME' matches more than one field: use an exact field name", "{command}, table {table}"); + assert_eq!( + error, "field name 'NAME' is ambiguous: case-insensitive collision between 'Name' and 'name'", + "{command}, table {table}" + ); assert_eq!(names(&s, t), ["Name", "name"], "{command}, table {table}"); assert_eq!(row(&s, t), [date("2020-01-01"), date("2020-01-02")], "{command}, table {table}"); let types: Vec = data(&s, t).unwrap().fields.iter().map(|f| f.ty).collect(); @@ -1905,7 +1894,11 @@ mod tests { l.labels.enabled = true; let mut other = l.labels.default.clone(); other.name = "Other".into(); - l.labels.classes.push(other); + // One whose text is an expression that still reads goes the same way. + let mut by_text = other.clone(); + by_text.name = "Expr".into(); + by_text.by.text = Some("n * 2".into()); + l.labels.classes.extend([other, by_text]); let kind = rustgis_map::design::DomainKind::Range { min: 0.0, max: 10.0 }; l.design.domains.push(rustgis_map::design::Domain { field: stored.into(), kind }); let mark = s.notice_mark(); @@ -1921,15 +1914,16 @@ mod tests { for part in [ "its classes read the deleted field Name", "the deleted field Name, so it starts again", - "its label class Other labeled the deleted field Name", + "its label classes Other, Expr used the deleted field Name, so they label field name", "its diagram drew the deleted field Name", ] { assert!(said.iter().any(|n| n.contains(part)), "{part}: {case}"); } + assert_eq!(l.labels.classes.iter().map(|c| c.field.as_str()).collect::>(), ["name", "name"], "{case}"); } else { assert_eq!(l.renderer.field(), Some(stored), "{case}"); assert!(l.labels.enabled && l.labels.default.field == stored, "{case}"); - assert_eq!(l.labels.classes.iter().map(|c| c.field.as_str()).collect::>(), [stored], "{case}"); + assert_eq!(l.labels.classes.iter().map(|c| c.field.as_str()).collect::>(), [stored, stored], "{case}"); assert_eq!(l.design.domains.iter().map(|d| d.field.as_str()).collect::>(), [stored], "{case}"); assert_eq!(slices, [stored, "n"], "{case}"); assert!(said.iter().all(|n| !n.contains("deleted field")), "{case}"); @@ -1980,6 +1974,49 @@ mod tests { } } + /// Design that names a field with a case twin (a calculation rule, contingent values, a subtype + /// default) is refused, as domains are; a label class on a deleted field without a twin moves + /// as before, without a word; Calculate Geometry replies with the field as it is named (#1955). + #[test] + fn case_twins_in_design_labels_and_replies() { + let mut s = Session::new(crate::Project::default()); + let fields = vec![ + Field::new("X", FieldType::Double), + Field::new("x", FieldType::Double), + Field::new("code", FieldType::Integer), + Field::new("Lon", FieldType::Double), + ]; + let mut ds = Dataset::new("twins", GeometryType::Point, fields); + let at = Geometry::Point(rustgis_data::Coord::new(3.0, 4.0)); + ds.push(Some(at), vec![Value::Float(0.0), Value::Float(0.0), Value::Int(1), Value::Float(0.0)]); + let id = s.map_mut().add_dataset(ds); + for (command, p) in [ + ("data.attributeRule", json!({"layer": id, "name": "r", "kind": "calculation", "field": "x", "expression": "1"})), + ("data.contingentValues", json!({"layer": id, "name": "c", "fields": ["code", "X"], "combos": [[1, 0]]})), + ("data.subtypes", json!({"layer": id, "field": "code", "subtypes": [{"code": 1, "name": "one", "defaults": {"x": 2}}]})), + ] { + let error = s.run(command, &p).unwrap_err(); + assert!(error.contains("named the same but for case"), "{command}: {error}"); + } + let d = &s.map().layer(id).unwrap().design; + assert!(d.rules.is_empty() && d.contingent.is_empty() && d.subtypes.is_none()); + // The reply names the field written as it is named. + let p = json!({"layer": id, "field": "LON", "property": "x", "unit": "deg", "scope": "all", "overwrite": true}); + assert_eq!(s.run("edit.calculateGeometry", &p).unwrap()["field"], "Lon"); + // No twin: a class on the deleted field moves to Default's, as before, without a notice. + let l = s.map_mut().layer_mut(id).unwrap(); + l.labels.default.field = "code".into(); + let mut other = l.labels.default.clone(); + other.name = "Other".into(); + other.field = "Lon".into(); + l.labels.classes.push(other); + let mark = s.notice_mark(); + s.run("edit.deleteField", &json!({"layer": id, "field": "Lon"})).unwrap(); + assert_eq!(s.map().layer(id).unwrap().labels.classes[0].field, "code"); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().all(|n| !n.contains("used the deleted field")), "{said:?}"); + } + /// Not a number is null in a whole-number field, said as such, not past its range; a number /// past the range is null where it's said, and at the range's end elsewhere, as before. #[test] diff --git a/crates/engine/src/geometry_calc.rs b/crates/engine/src/geometry_calc.rs index dcbbaa5184..5594421117 100644 --- a/crates/engine/src/geometry_calc.rs +++ b/crates/engine/src/geometry_calc.rs @@ -153,6 +153,8 @@ pub fn run(s: &mut Session, p: &Json) -> CmdResult { } let l = s.map_mut().layer_mut(id).ok_or("no layer")?; let fi = if create { l.dataset.ensure_field(field, FieldType::Double) } else { existing.ok_or("no field")? }; + // The reply names the field written as it is named, not as it was asked for. + let written = l.dataset.fields.get(fi).map(|f| f.name.clone()).ok_or("no field")?; let mut changes = Vec::with_capacity(values.len()); for (row, value) in values { let f = l.dataset.features.get_mut(row).ok_or("no feature")?; @@ -161,5 +163,5 @@ pub fn run(s: &mut Session, p: &Json) -> CmdResult { changes.push(crate::cmd::design::Change { before: Some(before), row: Some(row) }); } crate::cmd::design::apply(s, id, changes)?; - Ok(json!({"rows": rows.len(), "nulls": nulls, "field": field})) + Ok(json!({"rows": rows.len(), "nulls": nulls, "field": written})) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c3566df7e1..158695134e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -418,7 +418,7 @@ fn a_standalone_table_is_edited_with_the_edit_commands() { let rows = s.project.tables[1].dataset.features.len(); let depth = s.undo_depth(); let err = s.run("edit.addFeature", &json!({"table": "twins", "attributes": {"Name": "A", "NAME": "B"}})).unwrap_err(); - assert!(err.contains("matches more than one field"), "{err}"); + assert!(err.contains("is ambiguous: case-insensitive collision between 'Name' and 'name'"), "{err}"); assert_eq!(s.project.tables[1].dataset.features.len(), rows); assert_eq!(s.undo_depth(), depth); let mark = s.notice_mark(); diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 7d47a92e55..825f966e40 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -3328,6 +3328,13 @@ impl Labeling { /// name-like one when Default's is gone too (a field deleted, a style from another layer, a /// service's fields changed). The class is kept, with its clause and text symbol. pub fn repoint_missing_fields(&mut self, ds: &Dataset) { + self.repoint_fields(ds, |_| false); + } + + /// As [`Labeling::repoint_missing_fields`], and also every class on a field name `gone` says + /// was deleted, even when the name now finds another field (one named the same but for case) + /// or its text is an expression. Returns the names of the classes `gone` moved. + pub fn repoint_fields(&mut self, ds: &Dataset, gone: impl Fn(&str) -> bool) -> Vec { // Default's field, or (it is gone too, cleared by a refresh) the first name-like one, so // a class isn't left on no field. let fallback = match ds.field_index(&self.default.field) { @@ -3335,11 +3342,19 @@ impl Labeling { None => LabelClass::default_for(ds).field, }; // (A class whose text is an expression that still reads keeps its own, which it doesn't - // label from.) + // label from, unless it was deleted.) let by_text = |c: &LabelClass| c.by.text.as_deref().is_some_and(|t| rustgis_data::query::parse_fields(t, ds).is_ok()); - for c in self.classes.iter_mut().filter(|c| ds.field_index(&c.field).is_none() && !by_text(c)) { - c.field.clone_from(&fallback); + let mut moved = Vec::new(); + for c in &mut self.classes { + // A class on a deleted field labels another field now, even if it's named alike. + if gone(&c.field) { + c.field.clone_from(&fallback); + moved.push(c.name.clone()); + } else if ds.field_index(&c.field).is_none() && !by_text(c) { + c.field.clone_from(&fallback); + } } + moved } /// Off, on the first text field that looks like a name, with only its Default class. From d8025e451b7f3adb4210703aed2828b6798cab04 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:42:02 -0600 Subject: [PATCH 03/24] fix(engine): keep fields by name the way they're read, and say what deleting a field takes (#1955) The field lookup rules live in rustgis-data beside field_index: find_field (the exact name, else the only one ignoring case; one pass; an ambiguous name is refused naming both fields and asking for the exact one), Dataset::reads_field and Dataset::has_case_twin. The tools and the edit commands use them. What a layer keeps by a field's name is read from the first field so named ignoring case. Every place that stores one now goes through one helper that refuses a name with case twins, saying the first would be used: data design (domains, subtypes and their defaults, calculation rules, contingent values, template defaults, relationships), diagrams, size by field, report fields and interpolation. Deleting a field says what its data design lost, with counts and names, and which label classes now label Default's field, twin or not (this was silent before). A class whose text is an expression shows the same text, so it isn't named. A text field with subtype defaults or a calculation rule on it isn't converted to dates either. --- crates/analysis/src/lib.rs | 4 +- crates/analysis/src/tools.rs | 20 +-- crates/data/src/lib.rs | 43 +++++- crates/engine/src/cmd/design.rs | 52 +++----- crates/engine/src/cmd/diagram.rs | 2 +- crates/engine/src/cmd/edit.rs | 207 +++++++++++++++++++++++------ crates/engine/src/cmd/layer.rs | 2 +- crates/engine/src/cmd/report.rs | 2 +- crates/engine/src/cmd/workflows.rs | 2 +- crates/engine/src/tests.rs | 2 +- crates/map/src/symbology.rs | 10 +- 11 files changed, 248 insertions(+), 98 deletions(-) diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index c2f3f61a42..43579deaa5 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -48,8 +48,8 @@ pub use density::{ pub use parallel::scratch_budget; pub use parameters::StatisticList; pub use tools::{ - SimplifyNotes, TOOLS, find_field, find_field_case_insensitive, holds_coordinates, in_its_units, layer_raster_crs, max_buffer_bytes, - min_pad, param_applies, past_pole, points_in, projected_crs, raster_crs, simplify_geometry, zonal_bands, + SimplifyNotes, TOOLS, find_field_case_insensitive, holds_coordinates, in_its_units, layer_raster_crs, max_buffer_bytes, min_pad, + param_applies, past_pole, points_in, projected_crs, raster_crs, simplify_geometry, zonal_bands, }; use rustgis_data::Dataset; diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 78d4ae8929..5df3695b25 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1540,25 +1540,7 @@ fn keep_source_crs(out: &mut Dataset, ds: &Dataset, overlay: &Dataset) { /// If multiple fields in `ds.fields` match `name` case-insensitively, returns an error /// detailing the collision rather than silently selecting an arbitrary field. pub fn find_field_case_insensitive(ds: &Dataset, name: &str) -> Result { - find_field(&ds.fields, name)?.ok_or_else(|| format!("no field named '{name}'")) -} - -/// The index of the field `name` names in `fields`: the one named exactly so, else the only one -/// named so ignoring case; `None` when none is. A name that matches several fields ignoring case -/// but none exactly is an error naming them, rather than an arbitrary pick. -pub fn find_field(fields: &[Field], name: &str) -> Result, String> { - if let Some(idx) = fields.iter().position(|f| f.name == name) { - return Ok(Some(idx)); - } - let matches: Vec<&str> = fields.iter().filter(|f| f.name.eq_ignore_ascii_case(name)).map(|f| f.name.as_str()).collect(); - match matches.as_slice() { - [] => Ok(None), - [_] => Ok(fields.iter().position(|f| f.name.eq_ignore_ascii_case(name))), - _ => Err(format!( - "field name '{name}' is ambiguous: case-insensitive collision between {}", - matches.iter().map(|n| format!("'{n}'")).collect::>().join(" and ") - )), - } + ds.find_field(name)?.ok_or_else(|| format!("no field named '{name}'")) } /// Union of polygons; rings are oriented first because the overlay infers its fill rule from diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index ca574655f8..9823c26892 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -665,6 +665,30 @@ pub fn export_error(ds: &Dataset, crs: raster::Crs) -> Option { ds.crs.and_then(|from| raster::planetary::export_error(from, crs)).map(|e| format!("{}: {e}", ds.name)) } +/// The index of the field `name` names in `fields`, for a command that changes a field (its +/// values, or the field itself) or a tool: the field named exactly so, else the only field named +/// so ignoring case; `None` when none is. A name matching several fields ignoring case but none +/// exactly is an error naming them, rather than an arbitrary pick (#1955). +pub fn find_field(fields: &[Field], name: &str) -> std::result::Result, String> { + let mut alike = Vec::new(); + for (i, f) in fields.iter().enumerate() { + if f.name == name { + return Ok(Some(i)); + } + if f.name.eq_ignore_ascii_case(name) { + alike.push(i); + } + } + match alike.as_slice() { + [] => Ok(None), + [only] => Ok(Some(*only)), + _ => Err(format!( + "field name '{name}' is ambiguous: case-insensitive collision between {}; use an exact field name", + alike.iter().filter_map(|i| fields.get(*i)).map(|f| format!("'{}'", f.name)).collect::>().join(" and ") + )), + } +} + impl Dataset { /// Marks the dataset as having lost the Z or M values of `features` features (none: nothing) /// and says so in `report`. @@ -690,11 +714,28 @@ impl Dataset { } } - /// Index of a field by case-insensitive name. + /// Index of a field by case-insensitive name: the first so named. Expressions, queries and + /// what a layer keeps by a field's name (its renderer's, labels', design's…) read fields so. pub fn field_index(&self, name: &str) -> Option { self.fields.iter().position(|f| f.name.eq_ignore_ascii_case(name)) } + /// The field a command that changes a field names ([`find_field`]). + pub fn find_field(&self, name: &str) -> std::result::Result, String> { + find_field(&self.fields, name) + } + + /// Whether `name`, read as [`Dataset::field_index`] reads it, reads field `fi`. + pub fn reads_field(&self, fi: usize, name: &str) -> bool { + self.field_index(name) == Some(fi) + } + + /// Whether more than one field is named `name` ignoring case: then what is kept by that name + /// reads the first of them ([`Dataset::field_index`]), whichever was meant. + pub fn has_case_twin(&self, name: &str) -> bool { + self.fields.iter().filter(|f| f.name.eq_ignore_ascii_case(name)).nth(1).is_some() + } + /// Value of `field` for feature `row` (Null when out of range). pub fn value(&self, row: usize, field: usize) -> &Value { self.features.get(row).and_then(|f| f.attrs.get(field)).unwrap_or(&Value::Null) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 0455b79381..d6e2f05ea4 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -1547,30 +1547,27 @@ fn traverse(s: &mut Session, p: &Json) -> CmdResult { super::edit::add_feature(s, &json!({"layer": id, "geometry": g})) } -/// Refuses `what` on field `name` while another field is named the same but for case: design finds -/// its field by name ignoring case, so it would apply to the first of them whichever was meant -/// (#1955). -fn case_twins_refused(ds: &rustgis_data::Dataset, name: &str, what: &str) -> Result<(), String> { - if ds.fields.iter().filter(|f| f.name.eq_ignore_ascii_case(name)).count() > 1 { - return Err(format!( - "'{name}' has a field named the same but for case, and {what} would apply to whichever comes first: rename one of them first" - )); - } - Ok(()) +/// The field design names `name` ([`super::edit::kept_field`]): design reads its field by name, +/// the first so named ignoring case, so a name with case twins is refused. Every design command +/// finds its fields through this (#1955). +fn design_field(ds: &rustgis_data::Dataset, name: &str, what: &str) -> Result { + super::edit::kept_field(ds, name, what)?.ok_or_else(|| format!("no field named '{name}'")) } fn domain(s: &mut Session, p: &Json) -> CmdResult { let id = s.layer_id(p)?; let field = ps(p, "field").ok_or("field is required")?; let l = s.map().layer(id).ok_or("no such layer")?; - let fi = l.dataset.field_index(field).ok_or_else(|| format!("no field named '{field}'"))?; - let (fname, ty) = l.dataset.fields.get(fi).map(|f| (f.name.clone(), f.ty)).ok_or("no field")?; if b(p, "clear").unwrap_or(false) { + // Clearing takes off whatever domain the name reads, twins or not. + let fi = l.dataset.field_index(field).ok_or_else(|| format!("no field named '{field}'"))?; + let fname = l.dataset.fields.get(fi).map(|f| f.name.clone()).ok_or("no field")?; let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; l.design.domains.retain(|d| !d.field.eq_ignore_ascii_case(&fname)); return Ok(Json::Null); } - case_twins_refused(&l.dataset, &fname, "a domain")?; + let fi = design_field(&l.dataset, field, "a domain")?; + let (fname, ty) = l.dataset.fields.get(fi).map(|f| (f.name.clone(), f.ty)).ok_or("no field")?; let kind = if let Some(codes) = p.get("coded").and_then(Json::as_array) { let pairs: Vec<(Value, String)> = codes .iter() @@ -1616,9 +1613,8 @@ fn subtypes(s: &mut Session, p: &Json) -> CmdResult { } let field = ps(p, "field").ok_or("field is required")?; let l = s.map().layer(id).ok_or("no such layer")?; - let fi = l.dataset.field_index(field).ok_or_else(|| format!("no field named '{field}'"))?; + let fi = design_field(&l.dataset, field, "subtypes")?; let f = l.dataset.fields.get(fi).ok_or("no field")?; - case_twins_refused(&l.dataset, &f.name, "subtypes")?; if f.ty != FieldType::Integer { return Err(format!("{} must be an integer field to hold subtype codes", f.name)); } @@ -1640,8 +1636,9 @@ fn subtypes(s: &mut Session, p: &Json) -> CmdResult { .map(|o| o.iter().map(|(k, v)| (k.clone(), Value::from_json(v))).collect()) .unwrap_or_default(); for (field, value) in &defaults { - case_twins_refused(&l.dataset, field, "a subtype default")?; - if let Some(ty) = l.dataset.field_index(field).and_then(|i| l.dataset.fields.get(i)).map(|f| f.ty) + // (A default for a field the layer doesn't have is kept, as before.) + if let Some(ty) = + super::edit::kept_field(&l.dataset, field, "a subtype default")?.and_then(|i| l.dataset.fields.get(i)).map(|f| f.ty) && super::edit::non_finite_input(value, ty) { return Err(format!("field '{field}' requires a finite number")); @@ -1726,13 +1723,9 @@ fn attribute_rule(s: &mut Session, p: &Json) -> CmdResult { let field = match kind { RuleKind::Calculation => { let fl = ps(p, "field").ok_or("a calculation rule sets a field")?; - case_twins_refused(&l.dataset, fl, "a calculation rule")?; + let fi = design_field(&l.dataset, fl, "a calculation rule")?; super::edit::Calculation::parse(&expression, &l.dataset)?; - l.dataset - .field_index(fl) - .and_then(|i| l.dataset.fields.get(i)) - .map(|f| f.name.clone()) - .ok_or_else(|| format!("no field named '{fl}'"))? + l.dataset.fields.get(fi).map(|f| f.name.clone()).ok_or("no field")? } RuleKind::Constraint => { rustgis_data::query::parse(&expression, &l.dataset)?; @@ -1761,12 +1754,8 @@ fn contingent(s: &mut Session, p: &Json) -> CmdResult { .iter() .map(|v| { let n = v.as_str().ok_or("fields are names")?; - case_twins_refused(&l.dataset, n, "contingent values")?; - l.dataset - .field_index(n) - .and_then(|i| l.dataset.fields.get(i)) - .map(|f| (f.name.clone(), f.ty)) - .ok_or_else(|| format!("no field named '{n}'")) + let fi = design_field(&l.dataset, n, "contingent values")?; + l.dataset.fields.get(fi).map(|f| (f.name.clone(), f.ty)).ok_or_else(|| "no field".to_string()) }) .collect::>()?; if fields.len() < 2 { @@ -1888,7 +1877,8 @@ fn relate(s: &mut Session, p: &Json) -> CmdResult { } let field_of = |layer: &str, key: &str| -> Result<(String, String), String> { let l = s.map().layer_by_name(layer).filter(|l| !l.is_raster()).ok_or_else(|| format!("no layer '{layer}'"))?; - let f = l.dataset.field_index(key).and_then(|i| l.dataset.fields.get(i)).ok_or_else(|| format!("{layer} has no field '{key}'"))?; + let fi = super::edit::kept_field(&l.dataset, key, "a relationship")?.ok_or_else(|| format!("{layer} has no field '{key}'"))?; + let f = l.dataset.fields.get(fi).ok_or_else(|| format!("{layer} has no field '{key}'"))?; Ok((l.name.clone(), f.name.clone())) }; let [origin_name, destination_name] = relationship_names(p)?; @@ -1947,7 +1937,7 @@ fn template(s: &mut Session, p: &Json) -> CmdResult { let mut defaults = Vec::new(); if let Some(o) = p.get("defaults").and_then(Json::as_object) { for (k, v) in o { - let fi = l.dataset.field_index(k).ok_or_else(|| format!("no field named '{k}'"))?; + let fi = design_field(&l.dataset, k, "a template default")?; let ty = l.dataset.fields.get(fi).map(|f| f.ty).unwrap_or(FieldType::Text); let value = Value::from_json(v); if super::edit::non_finite_input(&value, ty) { diff --git a/crates/engine/src/cmd/diagram.rs b/crates/engine/src/cmd/diagram.rs index e596abaa23..4ff43c2190 100644 --- a/crates/engine/src/cmd/diagram.rs +++ b/crates/engine/src/cmd/diagram.rs @@ -153,7 +153,7 @@ fn set(s: &mut Session, p: &Value) -> CmdResult { } // Every field must be there, and hold numbers. for (field, _) in &asked { - let fi = l.dataset.field_index(field).ok_or_else(|| format!("no field named '{field}'"))?; + let fi = super::edit::kept_field(&l.dataset, field, "a diagram")?.ok_or_else(|| format!("no field named '{field}'"))?; if !l.dataset.fields.get(fi).is_some_and(|fd| fd.ty.is_numeric()) { return Err(format!("'{field}' is not a numeric field")); } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index f25f38ecff..3d81101e2d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -120,19 +120,24 @@ fn field_of(s: &Session, t: Target, name: &str) -> Result { field_in(&data(s, t)?.fields, name)?.ok_or_else(|| format!("no field named '{name}'")) } -/// The field a command that changes a field's values, or the field itself, names: the field named -/// exactly so, else the only field named so ignoring case, so an edit never lands on a field the -/// caller didn't name (#1955); a name matching several fields but none exactly is refused, naming -/// them. The tools find their fields the same way. What a layer keeps by a field's name, and -/// expressions and queries, read the first field so named ignoring case -/// ([`Dataset::field_index`], [`reads_field`]). -pub(crate) use rustgis_analysis::find_field as field_in; - -/// Whether `name`, a field name a layer keeps (its renderer's, labels', design's…), reads field -/// `fi` of `fields`: as they are read, by the first field so named ignoring case -/// ([`Dataset::field_index`]) (#1955). -pub(crate) fn reads_field(fields: &[Field], fi: usize, name: &str) -> bool { - fields.iter().position(|f| f.name.eq_ignore_ascii_case(name)) == Some(fi) +/// The field a command that changes a field's values, or the field itself, names +/// ([`rustgis_data::find_field`]): an edit never lands on a field the caller didn't name (#1955). +/// What a layer keeps by a field's name is read otherwise ([`kept_field`]). +pub(crate) use rustgis_data::find_field as field_in; + +/// The field `what`, kept by a field's name (design, a diagram, a size, a report…), will read for +/// `name`: the first field so named ignoring case ([`Dataset::field_index`]). Refused when the layer +/// has more than one field so named, even if one is named exactly so, since it would read the +/// first of them whichever was meant (#1955). +pub(crate) fn kept_field(ds: &Dataset, name: &str, what: &str) -> Result, String> { + if ds.has_case_twin(name) { + let twins: Vec = ds.fields.iter().filter(|f| f.name.eq_ignore_ascii_case(name)).map(|f| format!("'{}'", f.name)).collect(); + return Err(format!( + "'{name}' names {} ignoring case, and {what} reads its field by name ignoring case, so it would use the first: rename one of them first", + twins.join(" and ") + )); + } + Ok(ds.field_index(name)) } /// A table's rows change only while editing is on, as a layer's features do @@ -851,13 +856,17 @@ fn check_layer_dates(s: &Session, id: u32, fi: usize, ty: FieldType) -> Result CmdResult { // A Default class still as the layer made it loses nothing by starting again: that restart isn't said. let default_untouched = l.labels.default == rustgis_map::LabelClass::default_for(&l.dataset); // What the layer keeps by a field's name (renderer, labels, design, diagram…) read the deleted - // field when it names it in any case and the field is the first so named ([`reads_field`]). A - // name that read a twin left keeps it; one that read the deleted field would go on to read the - // twin, so it goes too (#1955). - let read = reads_field(&l.dataset.fields, fi, &name); + // field when it names it in any case and the field is the first so named + // ([`Dataset::reads_field`]). A name that read a twin left keeps it; one that read the deleted + // field would go on to read the twin, so it goes too (#1955). + let read = l.dataset.reads_field(fi, &name); let names_removed = |f: &str| read && f.eq_ignore_ascii_case(&name); let removed = l.dataset.fields.remove(fi).name; for f in &mut l.dataset.features { @@ -1099,11 +1108,10 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { }); } } - // Another class on the deleted field labels with Default's field instead. Where a field named - // the same but for case is left, which its name would now find, that is said (#1955). + // Another class on the deleted field labels with Default's field instead, said (#1955). One + // whose text is an expression shows the same text either way. let moved = l.labels.repoint_fields(&l.dataset, names_removed); - let twin_left = l.dataset.field_index(&removed).is_some(); - let moved_note = (twin_left && !moved.is_empty()).then(|| { + let moved_note = (!moved.is_empty()).then(|| { let on = match l.labels.classes.iter().find(|c| moved.contains(&c.name)).map(|c| c.field.as_str()) { Some(f) if !f.is_empty() => format!("field {f}"), _ => "no field".to_string(), @@ -1113,28 +1121,62 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { }); // A definition query that reads the field was refused above; one that already didn't read is // kept as it is, so its text isn't lost. - // Nor its data design: domains, subtypes, contingent values, and rules that used it. + // Nor its data design: domains, subtypes, subtype defaults, contingent values, and rules that + // used it, said once with what went (#1955). let d = &mut l.design; + let mut design_gone = Vec::new(); + let domains = d.domains.len(); d.domains.retain(|x| !names_removed(&x.field)); + match domains - d.domains.len() { + 0 => {} + 1 => design_gone.push("its domain".to_string()), + n => design_gone.push(format!("{n} domains")), + } if d.subtypes.as_ref().is_some_and(|st| names_removed(&st.field)) { d.subtypes = None; + design_gone.push("the subtypes".into()); } if let Some(st) = &mut d.subtypes { + let mut defaults = 0; for sub in &mut st.subtypes { + let before = sub.defaults.len(); sub.defaults.retain(|(f, _)| !names_removed(f)); + defaults += before - sub.defaults.len(); + } + match defaults { + 0 => {} + 1 => design_gone.push("1 subtype default".into()), + n => design_gone.push(format!("{n} subtype defaults")), } } + let quoted = |names: Vec| names.iter().map(|n| format!("'{n}'")).collect::>().join(", "); + let contingent: Vec = + d.contingent.iter().filter(|c| c.fields.iter().any(|f| names_removed(f))).map(|c| c.name.clone()).collect(); d.contingent.retain(|c| !c.fields.iter().any(|f| names_removed(f))); + if !contingent.is_empty() { + design_gone.push(format!("contingent values {}", quoted(contingent))); + } let ds = rustgis_data::Dataset::new(l.dataset.name.clone(), l.dataset.geometry_type, l.dataset.fields.clone()); - let before = d.rules.len(); - d.rules.retain(|r| { + let reads_on = |r: &rustgis_map::design::AttributeRule| { !names_removed(&r.field) && match r.kind { rustgis_map::design::RuleKind::Calculation => Calculation::parse(&r.expression, &ds).is_ok(), rustgis_map::design::RuleKind::Constraint => rustgis_data::query::parse_fields(&r.expression, &ds).is_ok(), } + }; + let rules: Vec = d.rules.iter().filter(|r| !reads_on(r)).map(|r| r.name.clone()).collect(); + d.rules.retain(reads_on); + let removed_rules = rules.len(); + if !rules.is_empty() { + design_gone.push(format!("attribute {} {}", if rules.len() == 1 { "rule" } else { "rules" }, quoted(rules))); + } + let design_note = (!design_gone.is_empty()).then(|| { + format!( + "{}: its data design used the deleted field {removed}, so it loses {}", + l.name, + and_list(&design_gone.iter().map(String::as_str).collect::>()) + ) }); - let removed_rules = before - d.rules.len(); // Nor its diagram: the field's slice or bar goes, the range of sums a scaled size grows over is // measured again without it, and a diagram left with no field goes too. Said once. let mut diagram_note = None; @@ -1206,7 +1248,8 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { Some(format!("{}: its symbol's {} expressions read the deleted field {removed}, so they are removed", l.name, and_list(many))) } }; - for note in [extrusion_note, rotation_note, size_note, by_note, label_note, restart_note, moved_note].into_iter().flatten() { + for note in [extrusion_note, rotation_note, size_note, by_note, label_note, restart_note, moved_note, design_note].into_iter().flatten() + { s.notify(note, false); } if let Some(note) = diagram_note { @@ -1860,7 +1903,7 @@ mod tests { ] { let error = s.run(command, &with(&target, extra)).unwrap_err(); assert_eq!( - error, "field name 'NAME' is ambiguous: case-insensitive collision between 'Name' and 'name'", + error, "field name 'NAME' is ambiguous: case-insensitive collision between 'Name' and 'name'; use an exact field name", "{command}, table {table}" ); assert_eq!(names(&s, t), ["Name", "name"], "{command}, table {table}"); @@ -1885,8 +1928,16 @@ mod tests { ds.push(Some(at), vec![Value::Float(1.0), Value::Float(2.0), Value::Float(3.0)]); let id = s.map_mut().add_dataset(ds); s.run("layer.symbology", &json!({"layer": id, "type": "unique", "field": "n"})).unwrap(); - s.run("layer.diagram", &json!({"layer": id, "kind": "pie", "fields": [stored, "n"]})).unwrap(); + // (layer.diagram refuses a twin's name now: the slice is put there as a project + // from before would have it.) + s.run("layer.diagram", &json!({"layer": id, "kind": "pie", "fields": ["n"]})).unwrap(); let l = s.map_mut().layer_mut(id).unwrap(); + if let Some(dg) = &mut l.diagram + && let Some(mut slice) = dg.categories.first().cloned() + { + slice.field = stored.into(); + dg.categories.insert(0, slice); + } if let rustgis_map::Renderer::Unique { field, .. } = &mut l.renderer { *field = stored.into(); } @@ -1914,8 +1965,10 @@ mod tests { for part in [ "its classes read the deleted field Name", "the deleted field Name, so it starts again", - "its label classes Other, Expr used the deleted field Name, so they label field name", + // Expr's text comes from its expression, which still reads: not said. + "its label class Other used the deleted field Name, so it labels field name", "its diagram drew the deleted field Name", + "its data design used the deleted field Name, so it loses its domain", ] { assert!(said.iter().any(|n| n.contains(part)), "{part}: {case}"); } @@ -1969,7 +2022,10 @@ mod tests { // A domain on either twin, by any case, is refused, and nothing changes. for field in ["X", "x", "NAME"] { let error = s.run("data.domain", &json!({"layer": id, "field": field, "min": 0, "max": 5})).unwrap_err(); - assert!(error.contains("named the same but for case"), "{field}: {error}"); + assert!( + error.contains("ignoring case, and a domain reads its field by name ignoring case, so it would use the first"), + "{field}: {error}" + ); assert_eq!(domains(&s), ["name"]); } } @@ -1996,14 +2052,14 @@ mod tests { ("data.subtypes", json!({"layer": id, "field": "code", "subtypes": [{"code": 1, "name": "one", "defaults": {"x": 2}}]})), ] { let error = s.run(command, &p).unwrap_err(); - assert!(error.contains("named the same but for case"), "{command}: {error}"); + assert!(error.contains("so it would use the first: rename one of them first"), "{command}: {error}"); } let d = &s.map().layer(id).unwrap().design; assert!(d.rules.is_empty() && d.contingent.is_empty() && d.subtypes.is_none()); // The reply names the field written as it is named. let p = json!({"layer": id, "field": "LON", "property": "x", "unit": "deg", "scope": "all", "overwrite": true}); assert_eq!(s.run("edit.calculateGeometry", &p).unwrap()["field"], "Lon"); - // No twin: a class on the deleted field moves to Default's, as before, without a notice. + // No twin: a class on the deleted field moves to Default's, as before, and now says so. let l = s.map_mut().layer_mut(id).unwrap(); l.labels.default.field = "code".into(); let mut other = l.labels.default.clone(); @@ -2014,7 +2070,84 @@ mod tests { s.run("edit.deleteField", &json!({"layer": id, "field": "Lon"})).unwrap(); assert_eq!(s.map().layer(id).unwrap().labels.classes[0].field, "code"); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - assert!(said.iter().all(|n| !n.contains("used the deleted field")), "{said:?}"); + assert_eq!(said, ["twins: its label class Other used the deleted field Lon, so it labels field code"]); + } + + /// What a layer keeps by a field's name (a diagram, a size, a report, an interpolation) is + /// refused on a field with a case twin; a text field with subtype defaults or a calculation rule + /// on it doesn't become dates; deleting a field says what its data design lost; and an + /// ambiguous attribute names the fields and asks for the exact one (#1955). + #[test] + fn kept_fields_refuse_case_twins_and_deletions_say_what_went() { + let mut s = Session::new(crate::Project::default()); + let fields = vec![ + Field::new("X", FieldType::Double), + Field::new("x", FieldType::Double), + Field::new("code", FieldType::Integer), + Field::new("n", FieldType::Double), + ]; + let mut ds = Dataset::new("twins", GeometryType::Point, fields); + for (i, at) in [(1.0, 1.0), (2.0, 3.0), (4.0, 2.0)].into_iter().enumerate() { + let v = Value::Float(i as f64 + 1.0); + ds.push(Some(Geometry::Point(rustgis_data::Coord::new(at.0, at.1))), vec![v.clone(), v.clone(), Value::Int(1), v]); + } + let id = s.map_mut().add_dataset(ds); + s.run("layer.symbology", &json!({"layer": id, "type": "unique", "field": "code"})).unwrap(); + s.run("report.new", &json!({"layer": "twins", "name": "R", "fields": ["code"]})).unwrap(); + for (command, p) in [ + ("layer.diagram", json!({"layer": id, "kind": "pie", "fields": ["x", "n"]})), + ("layer.sizeBy", json!({"layer": id, "field": "X"})), + ("analysis.interpolate", json!({"layer": id, "field": "x"})), + ("report.field", json!({"field": "x"})), + ] { + let error = s.run(command, &p).unwrap_err(); + assert!( + error.contains("'x' names 'X' and 'x' ignoring case") || error.contains("'X' names 'X' and 'x' ignoring case"), + "{command}: {error}" + ); + } + let l = s.map().layer(id).unwrap(); + assert!(l.diagram.is_none() && l.size_by.is_none()); + + let mut s = Session::new(crate::Project::default()); + let fields = + vec![Field::new("when", FieldType::Text), Field::new("other", FieldType::Text), Field::new("code", FieldType::Integer)]; + let mut ds = Dataset::new("dates", GeometryType::Point, fields); + let text = |t: &str| Value::Text(t.into()); + ds.push(Some(Geometry::Point(rustgis_data::Coord::new(1.0, 1.0))), vec![text("2020-01-01"), text("b"), Value::Int(1)]); + let id = s.map_mut().add_dataset(ds); + let convert = json!({"layer": id, "field": "when", "type": "date"}); + let rule = json!({"layer": id, "name": "r", "kind": "calculation", "field": "when", "expression": "'2020-01-01'"}); + // A calculation rule writing the field keeps it text. + s.run("data.attributeRule", &rule).unwrap(); + assert!(s.run("edit.convertField", &convert).unwrap_err().contains("calculation rule")); + s.run("data.attributeRule", &json!({"layer": id, "name": "r", "remove": true})).unwrap(); + // So does a subtype default for it. + let subtypes = json!({"layer": id, "field": "code", "symbolize": false, "subtypes": [{"code": 1, "name": "one", "defaults": {"when": "2020-01-01"}}]}); + s.run("data.subtypes", &subtypes).unwrap(); + assert!(s.run("edit.convertField", &convert).unwrap_err().contains("subtype defaults")); + // Deleting it says what the design lost. + s.run("data.attributeRule", &rule).unwrap(); + s.run("data.domain", &json!({"layer": id, "field": "when", "coded": [["2020-01-01", "day"]]})).unwrap(); + s.run("data.contingentValues", &json!({"layer": id, "name": "pair", "fields": ["when", "other"], "combos": [["2020-01-01", "b"]]})) + .unwrap(); + let mark = s.notice_mark(); + let reply = s.run("edit.deleteField", &json!({"layer": id, "field": "when"})).unwrap(); + assert_eq!(reply["rulesRemoved"], 1); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!( + said.contains(&"dates: its data design used the deleted field when, so it loses its domain, 1 subtype default, contingent values 'pair' and attribute rule 'r'".to_string()), + "{said:?}" + ); + let d = &s.map().layer(id).unwrap().design; + assert!(d.domains.is_empty() && d.contingent.is_empty() && d.rules.is_empty()); + assert!(d.subtypes.as_ref().is_some_and(|st| st.subtypes.iter().all(|x| x.defaults.is_empty()))); + + // An ambiguous attribute names both fields and asks for the exact name. + let fields = vec![Field::new("Name", FieldType::Text), Field::new("name", FieldType::Text)]; + let table = s.project.add_table(Dataset::new("t", GeometryType::None, fields)); + let error = s.run("edit.addFeature", &json!({"table": table, "attributes": {"NAME": "a"}})).unwrap_err(); + assert!(error.contains("between 'Name' and 'name'; use an exact field name"), "{error}"); } /// Not a number is null in a whole-number field, said as such, not past its range; a number diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 90eb2987f5..5dd9bf12f3 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -786,7 +786,7 @@ fn size_by(s: &mut Session, p: &Value) -> CmdResult { "size by field goes with Unique Values or Graduated Colors; a single symbol sized by a field is Proportional Symbols".into() ); } - let fi = l.dataset.field_index(&field).ok_or_else(|| format!("no field named '{field}'"))?; + let fi = super::edit::kept_field(&l.dataset, &field, "a size by field")?.ok_or_else(|| format!("no field named '{field}'"))?; if !l.dataset.fields.get(fi).is_some_and(|fd| fd.ty.is_numeric()) { return Err(format!("'{field}' is not a numeric field")); } diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index bfa3f00cef..e4d11e1892 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -277,7 +277,7 @@ fn field_of(input: &impl super::InputSource, p: &Value, key: &str) -> Result<(us let i = index_input(input, p)?; let name = ps(p, key).ok_or_else(|| format!("{key} is required"))?; let l = layer_of_input(input, i)?; - let fi = l.dataset.field_index(name).ok_or_else(|| format!("'{}' has no field '{name}'", l.name))?; + let fi = super::edit::kept_field(&l.dataset, name, "a report")?.ok_or_else(|| format!("'{}' has no field '{name}'", l.name))?; let field = l.dataset.fields.get(fi).map(|f| f.name.clone()).ok_or("no such field")?; Ok((i, field)) } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 9ab7e4db64..7a65cbfabe 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1549,7 +1549,7 @@ fn interpolate(s: &mut Session, p: &Value) -> CmdResult { fn interpolate_work(s: &Session, p: &Value) -> Result { let ds = feature_ds(s, p)?; let field = ps(p, "field").ok_or("field is required")?; - let fi = ds.field_index(field).ok_or_else(|| format!("no field named '{field}'"))?; + let fi = super::edit::kept_field(ds, field, "the interpolation")?.ok_or_else(|| format!("no field named '{field}'"))?; let name = out_name(p, format!("{}_{field}_idw", ds.name))?; // Features without a place or a number are left out, and said (by kind, with a count). let (mut no_point, mut no_value) = (0usize, 0usize); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 158695134e..d92babe50d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -418,7 +418,7 @@ fn a_standalone_table_is_edited_with_the_edit_commands() { let rows = s.project.tables[1].dataset.features.len(); let depth = s.undo_depth(); let err = s.run("edit.addFeature", &json!({"table": "twins", "attributes": {"Name": "A", "NAME": "B"}})).unwrap_err(); - assert!(err.contains("is ambiguous: case-insensitive collision between 'Name' and 'name'"), "{err}"); + assert!(err.contains("is ambiguous: case-insensitive collision between 'Name' and 'name'; use an exact field name"), "{err}"); assert_eq!(s.project.tables[1].dataset.features.len(), rows); assert_eq!(s.undo_depth(), depth); let mark = s.notice_mark(); diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 825f966e40..da51e830f1 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -3333,7 +3333,8 @@ impl Labeling { /// As [`Labeling::repoint_missing_fields`], and also every class on a field name `gone` says /// was deleted, even when the name now finds another field (one named the same but for case) - /// or its text is an expression. Returns the names of the classes `gone` moved. + /// or its text is an expression. Returns the names of the classes `gone` moved whose text came + /// from their field (an expression's text doesn't change). pub fn repoint_fields(&mut self, ds: &Dataset, gone: impl Fn(&str) -> bool) -> Vec { // Default's field, or (it is gone too, cleared by a refresh) the first name-like one, so // a class isn't left on no field. @@ -3346,10 +3347,13 @@ impl Labeling { let by_text = |c: &LabelClass| c.by.text.as_deref().is_some_and(|t| rustgis_data::query::parse_fields(t, ds).is_ok()); let mut moved = Vec::new(); for c in &mut self.classes { - // A class on a deleted field labels another field now, even if it's named alike. + // A class on a deleted field labels another field now, even if it's named alike; one + // whose text is an expression shows the same text, so it isn't counted. if gone(&c.field) { c.field.clone_from(&fallback); - moved.push(c.name.clone()); + if !by_text(c) { + moved.push(c.name.clone()); + } } else if ds.field_index(&c.field).is_none() && !by_text(c) { c.field.clone_from(&fallback); } From 5e4ec068de678cec4ace53481771178c096ccdef Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:44:59 -0600 Subject: [PATCH 04/24] fix(engine): deleting a case twin takes the rules and class expression that read it (#1955) --- crates/engine/src/cmd/edit.rs | 76 +++++++++++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9883384111..d705c238cf 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1046,6 +1046,19 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { return Err(format!("the layer is bound to the time slider by '{name}': unbind it first")); } let read_before = l.renderer.expression().is_some_and(|e| rustgis_data::query::parse_fields(e, &l.dataset).is_ok()); + // The renderer's classes by an expression, and the attribute rules, that read the field, found + // while it is there: one that read it would otherwise go on to read a field named the same but + // for case, without a word (#1955). + let expression_read = l.renderer.expression().is_some_and(needs); + let rules_read: Vec = l + .design + .rules + .iter() + .map(|r| match r.kind { + rustgis_map::design::RuleKind::Calculation => Calculation::parse(&r.expression, &l.dataset).is_ok_and(|c| c.reads_field(fi)), + rustgis_map::design::RuleKind::Constraint => needs(&r.expression), + }) + .collect(); // The symbol's expressions by feature that read the field, found while it is there (#2081). let by = &l.symbol_by; let by_read = [&by.size, &by.fill, &by.stroke, &by.stroke_width, &by.angle].map(|t| t.as_deref().is_some_and(needs)); @@ -1070,7 +1083,8 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { } // Nothing may keep referring to the deleted field. // (Classes by an expression that read until now go the same way.) - let unread = read_before && l.renderer.expression().is_some_and(|e| rustgis_data::query::parse_fields(e, &l.dataset).is_err()); + let unread = expression_read + || read_before && l.renderer.expression().is_some_and(|e| rustgis_data::query::parse_fields(e, &l.dataset).is_err()); let mut single = None; if unread || l.renderer.field().is_some_and(names_removed) { l.renderer = rustgis_map::Renderer::Single(l.renderer.base_symbol()); @@ -1187,8 +1201,10 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { rustgis_map::design::RuleKind::Constraint => rustgis_data::query::parse_fields(&r.expression, &ds).is_ok(), } }; - let rules: Vec = d.rules.iter().filter(|r| !reads_on(r)).map(|r| r.name.clone()).collect(); - d.rules.retain(reads_on); + let keep: Vec = d.rules.iter().zip(&rules_read).map(|(r, read)| !read && reads_on(r)).collect(); + let rules: Vec = d.rules.iter().zip(&keep).filter(|(_, keep)| !**keep).map(|(r, _)| r.name.clone()).collect(); + let mut kept = keep.iter(); + d.rules.retain(|_| kept.next().copied().unwrap_or(true)); let removed_rules = rules.len(); if !rules.is_empty() { design_gone.push(format!("attribute {} {}", if rules.len() == 1 { "rule" } else { "rules" }, quoted(rules))); @@ -1648,6 +1664,14 @@ impl Calculation { } } + /// Whether it reads field `fi` (by its index in the dataset it was parsed against). + pub(crate) fn reads_field(&self, fi: usize) -> bool { + match self { + Calculation::Expr(e) => rustgis_data::query::reads_field(e, fi), + Calculation::Calc(c) => [Some(&c.a), c.b.as_ref()].into_iter().flatten().any(|t| matches!(t, Term::Field(i) if *i == fi)), + } + } + #[cfg(test)] pub(crate) fn eval(&self, ds: &rustgis_data::Dataset, r: usize) -> Value { self.eval_or_fault(ds, r).0 @@ -2097,6 +2121,52 @@ mod tests { assert_eq!(said, ["twins: its label class Other used the deleted field Lon, so it labels field code"]); } + /// An attribute rule or the renderer's class expression that read a deleted field is removed and + /// said, judged by the field it read before the deletion: with fields `Pop` and `pop`, `pop` + /// reads `Pop`, and deleting `Pop` would otherwise leave it reading `pop` (#1955). One that + /// read another field is kept, and nothing is said. + #[test] + fn a_deleted_case_twin_takes_the_rules_and_classes_that_read_it() { + for (fields, deleted, read) in [(["Pop", "pop", "n"], "Pop", true), (["Pop", "a", "n"], "a", false)] { + let mut s = Session::new(crate::Project::default()); + let mut ds = Dataset::new("twins", GeometryType::Point, fields.map(|f| Field::new(f, FieldType::Double)).to_vec()); + ds.push( + Some(Geometry::Point(rustgis_data::Coord::new(3.0, 4.0))), + vec![Value::Float(5.0), Value::Float(0.0), Value::Float(1.0)], + ); + let id = s.map_mut().add_dataset(ds); + s.run("data.attributeRule", &json!({"layer": id, "name": "big", "kind": "constraint", "field": "n", "expression": "pop > 1"})) + .unwrap(); + s.run( + "data.attributeRule", + &json!({"layer": id, "name": "twice", "kind": "calculation", "field": "n", "expression": "pop * 2"}), + ) + .unwrap(); + s.run("layer.symbology", &json!({"layer": id, "type": "unique", "expression": "pop * 2"})).unwrap(); + let mark = s.notice_mark(); + let reply = s.run("edit.deleteField", &json!({"layer": id, "field": deleted})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + let l = s.map().layer(id).unwrap(); + let rules: Vec<&str> = l.design.rules.iter().map(|r| r.name.as_str()).collect(); + if read { + assert_eq!(reply["rulesRemoved"], 2, "{said:?}"); + assert!(rules.is_empty(), "{rules:?}"); + assert_eq!(l.renderer.expression(), None); + for part in [ + "its data design used the deleted field Pop, so it loses attribute rules 'big', 'twice'", + "its classes read the deleted field Pop, so it is drawn with a single symbol", + ] { + assert!(said.iter().any(|n| n.contains(part)), "{part}: {said:?}"); + } + } else { + assert_eq!(reply["rulesRemoved"], 0, "{said:?}"); + assert_eq!(rules, ["big", "twice"]); + assert_eq!(l.renderer.expression(), Some("pop * 2")); + assert!(said.iter().all(|n| !n.contains("deleted field")), "{said:?}"); + } + } + } + /// What a layer keeps by a field's name (a diagram, a size, a report, an interpolation) is /// refused on a field with a case twin; a text field with subtype defaults or a calculation rule /// on it doesn't become dates; deleting a field says what its data design lost; and an From a988ff6bfbdc76ff7c57e4a422f02479b794d475 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:44:59 -0600 Subject: [PATCH 05/24] fix(engine): interpolation takes the exact field name before a case-insensitive one (#1955) --- crates/engine/src/cmd/edit.rs | 33 ++++++++++++++++++++++++++++-- crates/engine/src/cmd/workflows.rs | 4 +++- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index d705c238cf..a3b92d0ce9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -2167,7 +2167,37 @@ mod tests { } } - /// What a layer keeps by a field's name (a diagram, a size, a report, an interpolation) is + /// Interpolation reads its field once and keeps no name, so it takes the field named exactly, + /// else the only one so named ignoring case; a name matching twins but neither exactly is + /// refused (#1955). + #[test] + fn interpolation_takes_the_exact_field() { + let mut s = Session::new(crate::Project::default()); + let fields = ["Val", "val", "Other"].map(|f| Field::new(f, FieldType::Double)).to_vec(); + let mut ds = Dataset::new("twins", GeometryType::Point, fields); + for at in [(1.0, 1.0), (2.0, 3.0), (4.0, 2.0)] { + ds.push( + Some(Geometry::Point(rustgis_data::Coord::new(at.0, at.1))), + vec![Value::Float(1.0), Value::Float(7.0), Value::Float(4.0)], + ); + } + let id = s.map_mut().add_dataset(ds); + let surface = |s: &mut Session, field: &str| -> Result<(f32, f32), String> { + let r = s.run("analysis.interpolate", &json!({"layer": id, "field": field, "cellSize": 0.5}))?; + let layer = r["layer"].as_u64().and_then(|l| u32::try_from(l).ok()).ok_or("no layer")?; + let raster = s.map().layer(layer).and_then(|l| l.raster.as_ref()).and_then(|r| r.data.clone()).ok_or("no raster")?; + let band = raster.bands.first().ok_or("no band")?; + let finite = || band.data.iter().copied().filter(|v| v.is_finite()); + Ok((finite().fold(f32::INFINITY, f32::min), finite().fold(f32::NEG_INFINITY, f32::max))) + }; + assert_eq!(surface(&mut s, "val"), Ok((7.0, 7.0))); + assert_eq!(surface(&mut s, "Val"), Ok((1.0, 1.0))); + assert_eq!(surface(&mut s, "OTHER"), Ok((4.0, 4.0))); + let error = surface(&mut s, "VAL").unwrap_err(); + assert!(error.contains("is ambiguous: case-insensitive collision between 'Val' and 'val'"), "{error}"); + } + + /// What a layer keeps by a field's name (a diagram, a size, a report) is /// refused on a field with a case twin; a text field with subtype defaults or a calculation rule /// on it doesn't become dates; deleting a field says what its data design lost; and an /// ambiguous attribute names the fields and asks for the exact one (#1955). @@ -2191,7 +2221,6 @@ mod tests { for (command, p) in [ ("layer.diagram", json!({"layer": id, "kind": "pie", "fields": ["x", "n"]})), ("layer.sizeBy", json!({"layer": id, "field": "X"})), - ("analysis.interpolate", json!({"layer": id, "field": "x"})), ("report.field", json!({"field": "x"})), ] { let error = s.run(command, &p).unwrap_err(); diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index fd89515705..af6e72a226 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1562,7 +1562,9 @@ fn interpolate(s: &mut Session, p: &Value) -> CmdResult { fn interpolate_work(s: &Session, p: &Value) -> Result { let ds = feature_ds(s, p)?; let field = ps(p, "field").ok_or("field is required")?; - let fi = super::edit::kept_field(ds, field, "the interpolation")?.ok_or_else(|| format!("no field named '{field}'"))?; + // Read once, not kept by name: the field named exactly, else the only one so named ignoring + // case (an ambiguous name is refused). + let fi = super::edit::field_in(&ds.fields, field)?.ok_or_else(|| format!("no field named '{field}'"))?; let name = out_name(p, format!("{}_{field}_idw", ds.name))?; // Features without a place or a number are left out, and said (by kind, with a count). let (mut no_point, mut no_value) = (0usize, 0usize); From ef155e2c7c7af7d195d972d34594f0ac67121de7 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:44:59 -0600 Subject: [PATCH 06/24] fix(engine): suggest a way out RustGIS has when refusing a case-twin field (#1955) --- crates/engine/src/cmd/edit.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index a3b92d0ce9..1216c22bc5 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -134,7 +134,7 @@ pub(crate) fn kept_field(ds: &Dataset, name: &str, what: &str) -> Result = ds.fields.iter().filter(|f| f.name.eq_ignore_ascii_case(name)).map(|f| format!("'{}'", f.name)).collect(); return Err(format!( - "'{name}' names {} ignoring case, and {what} reads its field by name ignoring case, so it would use the first: rename one of them first", + "'{name}' names {} ignoring case, and {what} reads its field by name ignoring case, so it would use the first: copy the first into a field of another name (Add Field, then Calculate Field) and delete it, or rename one in the source data", twins.join(" and ") )); } @@ -2100,7 +2100,7 @@ mod tests { ("data.subtypes", json!({"layer": id, "field": "code", "subtypes": [{"code": 1, "name": "one", "defaults": {"x": 2}}]})), ] { let error = s.run(command, &p).unwrap_err(); - assert!(error.contains("so it would use the first: rename one of them first"), "{command}: {error}"); + assert!(error.contains("so it would use the first: copy the first into a field of another name (Add Field, then Calculate Field) and delete it, or rename one in the source data"), "{command}: {error}"); } let d = &s.map().layer(id).unwrap().design; assert!(d.rules.is_empty() && d.contingent.is_empty() && d.subtypes.is_none()); From 702dbe341eff0f3512f7474b59bc1ccb23266d58 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:44:59 -0600 Subject: [PATCH 07/24] docs: say what keeps a field from converting to dates (#1955) --- docs/user-guide/analysis.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index b998ad5342..1e4741b90e 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -98,8 +98,10 @@ that it cannot keep. Text that doesn't match becomes empty, and a notice counts those rows and shows the first few; undo brings the text back. Digits past the microsecond are rounded to it, and a notice counts those. A field with text and none of it a date is refused and stays text. A field with -a domain, subtypes or contingent values, or one a definition query or display filter would no -longer read as dates (comparing it with a number), is refused. +a domain, subtypes, a subtype default, contingent values or a calculation rule, or one a +definition query or display filter would no longer read as dates (comparing it with a number), +is refused. Design names its field ignoring case, so with two fields named the same but for case +it belongs to the first of them. #### Editing a standalone table From 1b50f5b545dc9c02920ab39de7e49a50d1b4ae29 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:44:13 -0600 Subject: [PATCH 08/24] fix(engine): a report removes an entry stored with a case twin's name and never takes one (#1955) --- crates/engine/src/cmd/edit.rs | 43 +++++++++++++++++++++++++++ crates/engine/src/cmd/report.rs | 51 ++++++++++++++++++++++++--------- 2 files changed, 81 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 1216c22bc5..8c51380348 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -2197,6 +2197,49 @@ mod tests { assert!(error.contains("is ambiguous: case-insensitive collision between 'Val' and 'val'"), "{error}"); } + /// A report never takes a case twin's name: report.field, report.new (given or filled in) and + /// report.autofill refuse it. One stored already (by an older project) can still be removed, + /// matched against what is stored (#1955). + #[test] + fn a_reports_twin_names_are_refused_but_can_be_removed() { + let mut s = Session::new(crate::Project::default()); + let fields = ["Name", "name", "code"].map(|f| Field::new(f, FieldType::Double)).to_vec(); + let mut ds = Dataset::new("twins", GeometryType::Point, fields); + ds.push(Some(Geometry::Point(rustgis_data::Coord::new(3.0, 4.0))), vec![Value::Float(1.0), Value::Float(2.0), Value::Float(3.0)]); + s.map_mut().add_dataset(ds); + let twin = "ignoring case, and a report reads its field by name ignoring case"; + for (command, p) in [ + ("report.new", json!({"layer": "twins", "name": "A", "fields": ["name"]})), + ("report.new", json!({"layer": "twins", "name": "B"})), + ] { + let error = s.run(command, &p).unwrap_err(); + assert!(error.contains(twin), "{command} {p}: {error}"); + } + assert!(s.project.reports.is_empty()); + s.run("report.new", &json!({"layer": "twins", "name": "R", "fields": ["code"]})).unwrap(); + for (command, p) in [("report.field", json!({"report": "R", "field": "name"})), ("report.autofill", json!({"report": "R"}))] { + let error = s.run(command, &p).unwrap_err(); + assert!(error.contains(twin), "{command}: {error}"); + } + assert_eq!(s.project.reports[0].fields, ["code"]); + // Entries an older project stored with a twin's name: removed by it. + let r = &mut s.project.reports[0]; + r.fields.push("name".into()); + r.groups.push("name".into()); + r.stats.push(rustgis_map::report::Stat { field: "name".into(), kind: rustgis_map::report::StatKind::Sum }); + s.run("report.field", &json!({"report": "R", "field": "name", "remove": true})).unwrap(); + s.run("report.group", &json!({"report": "R", "field": "name", "remove": true})).unwrap(); + s.run("report.statistics", &json!({"report": "R", "field": "name", "kind": "sum", "remove": true})).unwrap(); + let r = &s.project.reports[0]; + assert!(r.fields == ["code"] && r.groups.is_empty() && r.stats.is_empty(), "{:?} {:?} {}", r.fields, r.groups, r.stats.len()); + // Without twins, a report fills itself in as before. + let clean = Dataset::new("clean", GeometryType::Point, vec![Field::new("a", FieldType::Double)]); + s.map_mut().add_dataset(clean); + s.run("report.new", &json!({"layer": "clean", "name": "C"})).unwrap(); + s.run("report.autofill", &json!({"report": "C"})).unwrap(); + assert_eq!(s.project.reports[1].fields, ["a"]); + } + /// What a layer keeps by a field's name (a diagram, a size, a report) is /// refused on a field with a case twin; a text field with subtype defaults or a calculation rule /// on it doesn't become dates; deleting a field says what its data design lost; and an diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index e4d11e1892..46ce995f23 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -126,9 +126,9 @@ pub fn commands() -> Vec { .params(r#"{"report"?, "index": section number}"#), // Data. C::new("report.field", "Field", "Data › Data Design", |s, p| { - let (i, field) = field_of(s, p, "field")?; - let r = s.project.reports.get_mut(i).ok_or("no report")?; let remove = b(p, "remove").unwrap_or(false); + let (i, field) = if remove { stored(s, p)? } else { field_of(s, p, "field")? }; + let r = s.project.reports.get_mut(i).ok_or("no report")?; if !remove && r.fields.len() >= MAX_ITEMS && !r.fields.iter().any(|f| f.eq_ignore_ascii_case(&field)) { return Err(format!("a report lists at most {MAX_ITEMS} fields")); } @@ -139,9 +139,9 @@ pub fn commands() -> Vec { .params(r#"{"report"?, "field": name, "remove"?: bool}"#), C::new("report.autofill", "Autofill Fields", "Data › Data Design", |s, p| { let i = index(s, p)?; - let fields = &layer_of(s, i)?.dataset.fields; - let all = fields.len(); - let names = fields.iter().take(MAX_ITEMS).map(|f| f.name.clone()).collect::>(); + let ds = &layer_of(s, i)?.dataset; + let all = ds.fields.len(); + let names = filled_in(ds)?; let r = s.project.reports.get_mut(i).ok_or("no report")?; r.fields = names; let (answer, report) = (json!({"fields": r.fields}), r.name.clone()); @@ -156,10 +156,16 @@ pub fn commands() -> Vec { C::new("report.statistics", "Statistics", "Data › Data Design", |s, p| { let kind = ps(p, "kind").unwrap_or("sum"); let kind = StatKind::from_code(kind).ok_or_else(|| format!("unknown statistic '{kind}'"))?; - let (i, field) = field_of(s, p, "field")?; + let remove = b(p, "remove").unwrap_or(false); + let (i, field) = if remove { stored(s, p)? } else { field_of(s, p, "field")? }; let r = s.project.reports.get_mut(i).ok_or("no report")?; - let at = r.stats.iter().position(|x| x.field.eq_ignore_ascii_case(&field) && x.kind == kind); - match (at, b(p, "remove").unwrap_or(false)) { + // The one named exactly so first, as `toggle` finds a field. + let at = r + .stats + .iter() + .position(|x| x.kind == kind && x.field == field) + .or_else(|| r.stats.iter().position(|x| x.kind == kind && x.field.eq_ignore_ascii_case(&field))); + match (at, remove) { (Some(k), true) => { r.stats.remove(k); } @@ -172,9 +178,9 @@ pub fn commands() -> Vec { .when(need_report) .params(r#"{"report"?, "field": name, "kind"?: "count"|"sum"|"mean"|"min"|"max", "remove"?: bool}"#), C::new("report.group", "Group", "Data › Data Design", |s, p| { - let (i, field) = field_of(s, p, "field")?; - let r = s.project.reports.get_mut(i).ok_or("no report")?; let remove = b(p, "remove").unwrap_or(false); + let (i, field) = if remove { stored(s, p)? } else { field_of(s, p, "field")? }; + let r = s.project.reports.get_mut(i).ok_or("no report")?; if !remove && r.groups.len() >= MAX_GROUPS && !r.groups.iter().any(|g| g.eq_ignore_ascii_case(&field)) { return Err(format!("reports group by at most {MAX_GROUPS} fields")); } @@ -290,8 +296,26 @@ fn optional_field(input: &impl super::InputSource, p: &Value) -> Result<(usize, } } +/// The first [`MAX_ITEMS`] of a layer's fields, to fill a report with: refused, as report.field +/// refuses one, when one of them has a case twin (#1955). +fn filled_in(ds: &rustgis_data::Dataset) -> Result, String> { + let names: Vec = ds.fields.iter().take(MAX_ITEMS).map(|f| f.name.clone()).collect(); + for n in &names { + super::edit::kept_field(ds, n, "a report")?; + } + Ok(names) +} + +/// The report and the field name given, to remove an entry it stored: matched against what is +/// stored, not refused for a case twin, so an entry naming one can still be removed (#1955). +fn stored(input: &impl super::InputSource, p: &Value) -> Result<(usize, String), String> { + Ok((index_input(input, p)?, ps(p, "field").ok_or("field is required")?.to_string())) +} + +/// Adds `field` to `list`, or removes it: the entry named exactly so, else the first named so +/// ignoring case. fn toggle(list: &mut Vec, field: String, remove: bool) { - let at = list.iter().position(|x| x.eq_ignore_ascii_case(&field)); + let at = list.iter().position(|x| *x == field).or_else(|| list.iter().position(|x| x.eq_ignore_ascii_case(&field))); match (at, remove) { (Some(k), true) => { list.remove(k); @@ -465,7 +489,8 @@ fn new_report(s: &mut Session, p: &Value) -> CmdResult { let mut out = Vec::new(); for v in given { let n = v.as_str().ok_or_else(|| format!("{key} are field names"))?; - let fi = ds.field_index(n).ok_or_else(|| format!("'{}' has no field '{n}'", layer.name))?; + // As report.field takes one: a twin's name is refused (#1955). + let fi = super::edit::kept_field(ds, n, "a report")?.ok_or_else(|| format!("'{}' has no field '{n}'", layer.name))?; out.extend(ds.fields.get(fi).map(|f| f.name.clone())); } Ok(out) @@ -475,7 +500,7 @@ fn new_report(s: &mut Session, p: &Value) -> CmdResult { let all = ds.fields.len(); let first_of = r.fields.is_empty() && all > MAX_ITEMS; if r.fields.is_empty() { - r.fields = ds.fields.iter().take(MAX_ITEMS).map(|f| f.name.clone()).collect(); + r.fields = filled_in(ds)?; } r.groups = fields_of("groups", "a report groups by", MAX_GROUPS)?; if let Some(w) = ps(p, "where").map(str::trim).filter(|w| !w.is_empty()) { From e5b8d13a1b278c3b35c7cb6878b75004b2fb3eba Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:44:13 -0600 Subject: [PATCH 09/24] fix(engine): size by field and diagrams set again keep the twin field they read (#1955) --- crates/engine/src/cmd/diagram.rs | 8 +++++-- crates/engine/src/cmd/edit.rs | 40 ++++++++++++++++++++++++++++++++ crates/engine/src/cmd/layer.rs | 14 +++++++++-- 3 files changed, 58 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/diagram.rs b/crates/engine/src/cmd/diagram.rs index 4ff43c2190..8c67a30064 100644 --- a/crates/engine/src/cmd/diagram.rs +++ b/crates/engine/src/cmd/diagram.rs @@ -151,9 +151,13 @@ fn set(s: &mut Session, p: &Value) -> CmdResult { if l.is_streamed() && matches!(size, Asked::Scaled(..)) { return Err("a size scaled by the sum needs all of a streamed layer: layer.loadAll first, or a fixed size".into()); } - // Every field must be there, and hold numbers. + // Every field must be there, and hold numbers. A name with a case twin is refused unless the + // diagram already draws it, as set again over its own fields (#1955). + let current: Vec = l.diagram.as_ref().map(|d| d.categories.iter().map(|c| c.field.clone()).collect()).unwrap_or_default(); for (field, _) in &asked { - let fi = super::edit::kept_field(&l.dataset, field, "a diagram")?.ok_or_else(|| format!("no field named '{field}'"))?; + let fi = + if current.contains(field) { l.dataset.field_index(field) } else { super::edit::kept_field(&l.dataset, field, "a diagram")? } + .ok_or_else(|| format!("no field named '{field}'"))?; if !l.dataset.fields.get(fi).is_some_and(|fd| fd.ty.is_numeric()) { return Err(format!("'{field}' is not a numeric field")); } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 8c51380348..5a7530ead3 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -2240,6 +2240,46 @@ mod tests { assert_eq!(s.project.reports[1].fields, ["a"]); } + /// A size by field or diagram set again over the field it already reads keeps reading it, twin + /// or not; a twin's name newly given is refused (#1955). + #[test] + fn a_mapping_set_again_keeps_its_twin_field() { + let mut s = Session::new(crate::Project::default()); + let fields = ["X", "x", "n", "code"].map(|f| Field::new(f, FieldType::Double)).to_vec(); + let mut ds = Dataset::new("twins", GeometryType::Point, fields); + for (i, at) in [(1.0, 1.0), (2.0, 3.0), (4.0, 2.0)].into_iter().enumerate() { + let v = Value::Float(i as f64 + 1.0); + ds.push(Some(Geometry::Point(rustgis_data::Coord::new(at.0, at.1))), vec![v.clone(), v.clone(), v.clone(), Value::Float(1.0)]); + } + let id = s.map_mut().add_dataset(ds); + s.run("layer.symbology", &json!({"layer": id, "type": "unique", "field": "code"})).unwrap(); + s.run("layer.sizeBy", &json!({"layer": id, "field": "n"})).unwrap(); + s.run("layer.diagram", &json!({"layer": id, "kind": "pie", "fields": ["n"]})).unwrap(); + // As an older project stored them: on the twin name `x`. + let l = s.map_mut().layer_mut(id).unwrap(); + if let Some(b) = &mut l.size_by { + b.field = "x".into(); + } + if let Some(d) = &mut l.diagram { + d.categories.iter_mut().for_each(|c| c.field = "x".into()); + } + s.run("layer.sizeBy", &json!({"layer": id, "min": 2, "max": 9})).unwrap(); + s.run("layer.diagram", &json!({"layer": id, "kind": "bar", "fields": ["x"]})).unwrap(); + let l = s.map().layer(id).unwrap(); + assert_eq!(l.size_by.as_ref().map(|b| (b.min, b.max)), Some((2.0, 9.0))); + assert_eq!(l.diagram.as_ref().map(|d| d.categories.len()), Some(1)); + // A twin's name newly given: refused. + for (command, p) in [ + ("layer.sizeBy", json!({"layer": id, "field": "X"})), + ("layer.diagram", json!({"layer": id, "kind": "pie", "fields": ["n", "X"]})), + ] { + let error = s.run(command, &p).unwrap_err(); + assert!(error.contains("names 'X' and 'x' ignoring case"), "{command}: {error}"); + } + // Read ahead: not for a twin's name. + assert!(crate::cmd::layer::size_by_ahead(&s, &json!({"layer": id, "field": "X"})).is_none()); + } + /// What a layer keeps by a field's name (a diagram, a size, a report) is /// refused on a field with a case twin; a text field with subtype defaults or a calculation rule /// on it doesn't become dates; deleting a field says what its data design lost; and an diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 92016fe45f..d0f310e578 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -789,6 +789,8 @@ fn size_by(s: &mut Session, p: &Value) -> CmdResult { if l.geometry_type() != GeometryType::Point || l.graphics { return Err("this works on point layers".into()); } + // A field given; else the mapping's own, which keeps the field it reads. + let given = field.is_some(); let field = match field { Some(field) => field, None => Some(l.size_by.as_ref().map(|b| b.field.clone()).ok_or("give a field: the layer has no size mapping to change")?), @@ -802,7 +804,10 @@ fn size_by(s: &mut Session, p: &Value) -> CmdResult { "size by field goes with Unique Values or Graduated Colors; a single symbol sized by a field is Proportional Symbols".into() ); } - let fi = super::edit::kept_field(&l.dataset, &field, "a size by field")?.ok_or_else(|| format!("no field named '{field}'"))?; + // A name given with a case twin is refused; the mapping's own, already there, goes on reading + // the field it reads (#1955). + let fi = if given { super::edit::kept_field(&l.dataset, &field, "a size by field")? } else { l.dataset.field_index(&field) } + .ok_or_else(|| format!("no field named '{field}'"))?; if !l.dataset.fields.get(fi).is_some_and(|fd| fd.ty.is_numeric()) { return Err(format!("'{field}' is not a numeric field")); } @@ -901,7 +906,12 @@ fn size_range(dataset: &Dataset, field: usize) -> Result, Str pub(crate) fn size_by_ahead(s: &Session, p: &Value) -> Option { let id = s.layer_id(p).ok()?; let layer = s.map().layer(id)?; - let field = layer.dataset.field_index(ps(p, "field")?)?; + let name = ps(p, "field")?; + // A name with a case twin, which layer.sizeBy refuses, isn't read ahead. + if layer.dataset.has_case_twin(name) { + return None; + } + let field = layer.dataset.field_index(name)?; if !rustgis_map::symbol_by::SizeBy::applies_to(layer) || layer.is_streamed() || !layer.dataset.fields.get(field)?.ty.is_numeric() { return None; } From 70108c0eea3b9a0b554425eab69a6bd69a944cdd Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:44:13 -0600 Subject: [PATCH 10/24] fix(engine): deleting a field removes the label class clauses that read it, said (#1955) --- crates/engine/src/cmd/edit.rs | 69 ++++++++++++++++++++++++++++++++++- 1 file changed, 67 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 5a7530ead3..42d81265a6 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1067,6 +1067,10 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { .chain(&l.labels.classes) .map(|c| [&c.by.text, &c.by.size, &c.by.color, &c.by.angle].map(|t| t.as_deref().is_some_and(needs))) .collect(); + // And the label classes' clauses that read it: one that still parses without it would go on to + // read a field named the same but for case (#1955). + let clause_read: Vec = + std::iter::once(&l.labels.default).chain(&l.labels.classes).map(|c| c.where_.as_deref().is_some_and(needs)).collect(); // A Default class still as the layer made it loses nothing by starting again: that restart isn't said. let default_untouched = l.labels.default == rustgis_map::LabelClass::default_for(&l.dataset); // What the layer keeps by a field's name (renderer, labels, design, diagram…) read the deleted @@ -1109,6 +1113,25 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { label_gone.push((format!("{}'s {}", c.name, and_list(&gone)), gone.len())); } } + // A clause that read it and would now read a field named the same but for case is removed, so + // the class takes the features the earlier ones leave, as with no clause; said once, naming the + // classes. One that no longer reads is kept to edit, taking no features, as before. + let mut clauses_gone = Vec::new(); + let classes = std::iter::once(&mut l.labels.default).chain(l.labels.classes.iter_mut()); + for (c, read) in classes.zip(&clause_read) { + if *read && c.where_.as_deref().is_some_and(|w| rustgis_data::query::parse_fields(w, &l.dataset).is_ok()) { + c.where_ = None; + clauses_gone.push(c.name.clone()); + } + } + let clause_note = (!clauses_gone.is_empty()).then(|| { + let (classes, they) = if clauses_gone.len() == 1 { ("class", "it is") } else { ("classes", "they are") }; + format!( + "{}: the clause of its label {classes} {} read the deleted field {removed}, so {they} removed", + l.name, + clauses_gone.join(", ") + ) + }); let label_note = match label_gone.as_slice() { [] => None, [(one, n)] => { @@ -1125,7 +1148,7 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { // said; by a text expression that still reads, Default only loses the field. Another class on // it labels with Default's field instead. A class clause naming it no longer reads, and takes // no features, which go on to the next class: it is kept to edit, not dropped with its text - // symbol. + // symbol; one that would read its twin was removed above. let mut restart_note = None; if names_removed(&l.labels.default.field) { let by_text = l.labels.default.by.text.as_deref().is_some_and(|t| rustgis_data::query::parse_fields(t, &l.dataset).is_ok()); @@ -1287,7 +1310,9 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { Some(format!("{}: its symbol's {} expressions read the deleted field {removed}, so they are removed", l.name, and_list(many))) } }; - for note in [extrusion_note, rotation_note, size_note, by_note, label_note, restart_note, moved_note, design_note].into_iter().flatten() + for note in [extrusion_note, rotation_note, size_note, by_note, label_note, clause_note, restart_note, moved_note, design_note] + .into_iter() + .flatten() { s.notify(note, false); } @@ -2280,6 +2305,46 @@ mod tests { assert!(crate::cmd::layer::size_by_ahead(&s, &json!({"layer": id, "field": "X"})).is_none()); } + /// Deleting a field removes the label class clauses that read it and would go on to read its + /// twin, said: with fields `Pop` and `pop`, `pop > 1` reads `Pop`, and deleting `Pop` would + /// otherwise leave it reading `pop`. A clause that read another field is kept, and nothing is + /// said; one on a deleted field without a twin stays, no longer reading, as before (#1955). + #[test] + fn a_deleted_field_takes_the_label_clauses_that_read_it() { + for (fields, deleted, read) in + [(["Pop", "pop", "n"], "Pop", true), (["Pop", "a", "n"], "a", false), (["Pop", "a", "n"], "Pop", false)] + { + let mut s = Session::new(crate::Project::default()); + let mut ds = Dataset::new("twins", GeometryType::Point, fields.map(|f| Field::new(f, FieldType::Double)).to_vec()); + ds.push( + Some(Geometry::Point(rustgis_data::Coord::new(3.0, 4.0))), + vec![Value::Float(5.0), Value::Float(0.0), Value::Float(1.0)], + ); + let id = s.map_mut().add_dataset(ds); + let l = s.map_mut().layer_mut(id).unwrap(); + l.labels.default.field = "n".into(); + let mut big = l.labels.default.clone(); + big.name = "Big".into(); + big.where_ = Some("pop > 1".into()); + l.labels.classes.push(big); + let mark = s.notice_mark(); + s.run("edit.deleteField", &json!({"layer": id, "field": deleted})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + let clause = s.map().layer(id).unwrap().labels.classes[0].where_.clone(); + if read { + assert_eq!(clause, None); + assert!( + said.iter().any(|n| n == "twins: the clause of its label class Big read the deleted field Pop, so it is removed"), + "{said:?}" + ); + } else { + // Kept: reading another field, or (no twin) no longer reading, as before. + assert_eq!(clause.as_deref(), Some("pop > 1")); + assert!(said.iter().all(|n| !n.contains("clause")), "{said:?}"); + } + } + } + /// What a layer keeps by a field's name (a diagram, a size, a report) is /// refused on a field with a case twin; a text field with subtype defaults or a calculation rule /// on it doesn't become dates; deleting a field says what its data design lost; and an From 9b838bc2ce1b19e3ef7d17aa8ba249e6e88b55ab Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:03:07 -0600 Subject: [PATCH 11/24] fix(engine): a report filled in leaves out case twins and says which, rather than refusing (#1955) --- crates/engine/src/cmd/edit.rs | 41 +++++++++++++++++----------- crates/engine/src/cmd/report.rs | 47 ++++++++++++++++++++++----------- 2 files changed, 57 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 42d81265a6..725c0c063a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -2222,9 +2222,9 @@ mod tests { assert!(error.contains("is ambiguous: case-insensitive collision between 'Val' and 'val'"), "{error}"); } - /// A report never takes a case twin's name: report.field, report.new (given or filled in) and - /// report.autofill refuse it. One stored already (by an older project) can still be removed, - /// matched against what is stored (#1955). + /// A report never takes a case twin's name: report.field and report.new refuse one given, and + /// report.new and report.autofill filling a report in leave twins out, said. One stored already + /// (by an older project) can still be removed, matched against what is stored (#1955). #[test] fn a_reports_twin_names_are_refused_but_can_be_removed() { let mut s = Session::new(crate::Project::default()); @@ -2233,19 +2233,26 @@ mod tests { ds.push(Some(Geometry::Point(rustgis_data::Coord::new(3.0, 4.0))), vec![Value::Float(1.0), Value::Float(2.0), Value::Float(3.0)]); s.map_mut().add_dataset(ds); let twin = "ignoring case, and a report reads its field by name ignoring case"; - for (command, p) in [ - ("report.new", json!({"layer": "twins", "name": "A", "fields": ["name"]})), - ("report.new", json!({"layer": "twins", "name": "B"})), - ] { - let error = s.run(command, &p).unwrap_err(); - assert!(error.contains(twin), "{command} {p}: {error}"); - } + let error = s.run("report.new", &json!({"layer": "twins", "name": "A", "fields": ["name"]})).unwrap_err(); + assert!(error.contains(twin), "{error}"); assert!(s.project.reports.is_empty()); - s.run("report.new", &json!({"layer": "twins", "name": "R", "fields": ["code"]})).unwrap(); - for (command, p) in [("report.field", json!({"report": "R", "field": "name"})), ("report.autofill", json!({"report": "R"}))] { - let error = s.run(command, &p).unwrap_err(); - assert!(error.contains(twin), "{command}: {error}"); - } + let left_out = |report: &str| { + format!( + "{report}: fields named the same but for case are left out (Name, name): a report reads its field by name ignoring case, so it would use the first" + ) + }; + // Filled in: the twins left out, and said. + let mark = s.notice_mark(); + s.run("report.new", &json!({"layer": "twins", "name": "R"})).unwrap(); + assert_eq!(s.project.reports[0].fields, ["code"]); + assert!(s.notices_since(mark).iter().any(|n| n.text == left_out("R")), "{:?}", s.notices_since(mark)); + s.project.reports[0].fields.clear(); + let mark = s.notice_mark(); + s.run("report.autofill", &json!({"report": "R"})).unwrap(); + assert_eq!(s.project.reports[0].fields, ["code"]); + assert!(s.notices_since(mark).iter().any(|n| n.text == left_out("R")), "{:?}", s.notices_since(mark)); + let error = s.run("report.field", &json!({"report": "R", "field": "name"})).unwrap_err(); + assert!(error.contains(twin), "{error}"); assert_eq!(s.project.reports[0].fields, ["code"]); // Entries an older project stored with a twin's name: removed by it. let r = &mut s.project.reports[0]; @@ -2257,12 +2264,14 @@ mod tests { s.run("report.statistics", &json!({"report": "R", "field": "name", "kind": "sum", "remove": true})).unwrap(); let r = &s.project.reports[0]; assert!(r.fields == ["code"] && r.groups.is_empty() && r.stats.is_empty(), "{:?} {:?} {}", r.fields, r.groups, r.stats.len()); - // Without twins, a report fills itself in as before. + // Without twins, a report fills itself in as before, and says nothing of twins. let clean = Dataset::new("clean", GeometryType::Point, vec![Field::new("a", FieldType::Double)]); s.map_mut().add_dataset(clean); + let mark = s.notice_mark(); s.run("report.new", &json!({"layer": "clean", "name": "C"})).unwrap(); s.run("report.autofill", &json!({"report": "C"})).unwrap(); assert_eq!(s.project.reports[1].fields, ["a"]); + assert!(s.notices_since(mark).iter().all(|n| !n.text.contains("same but for case")), "{:?}", s.notices_since(mark)); } /// A size by field or diagram set again over the field it already reads keeps reading it, twin diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 46ce995f23..7c7a95ba32 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -140,8 +140,8 @@ pub fn commands() -> Vec { C::new("report.autofill", "Autofill Fields", "Data › Data Design", |s, p| { let i = index(s, p)?; let ds = &layer_of(s, i)?.dataset; - let all = ds.fields.len(); - let names = filled_in(ds)?; + let (names, twins) = filled_in(ds); + let all = ds.fields.len() - twins.len(); let r = s.project.reports.get_mut(i).ok_or("no report")?; r.fields = names; let (answer, report) = (json!({"fields": r.fields}), r.name.clone()); @@ -149,6 +149,9 @@ pub fn commands() -> Vec { if all > MAX_ITEMS { s.notify(format!("{report}: the first {MAX_ITEMS} of the layer's {all} fields are filled in"), false); } + if let Some(note) = twins_left_out(&report, &twins) { + s.notify(note, false); + } Ok(answer) }).inputs(layer_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_report) @@ -296,14 +299,21 @@ fn optional_field(input: &impl super::InputSource, p: &Value) -> Result<(usize, } } -/// The first [`MAX_ITEMS`] of a layer's fields, to fill a report with: refused, as report.field -/// refuses one, when one of them has a case twin (#1955). -fn filled_in(ds: &rustgis_data::Dataset) -> Result, String> { - let names: Vec = ds.fields.iter().take(MAX_ITEMS).map(|f| f.name.clone()).collect(); - for n in &names { - super::edit::kept_field(ds, n, "a report")?; - } - Ok(names) +/// The first [`MAX_ITEMS`] of a layer's fields, to fill a report with, and the fields left out +/// for having a case twin, which report.field refuses (#1955). +fn filled_in(ds: &rustgis_data::Dataset) -> (Vec, Vec) { + let (twins, names): (Vec<_>, Vec<_>) = ds.fields.iter().map(|f| f.name.clone()).partition(|n| ds.has_case_twin(n)); + (names.into_iter().take(MAX_ITEMS).collect(), twins) +} + +/// The notice for the fields [`filled_in`] left out of report `report`, if any. +fn twins_left_out(report: &str, twins: &[String]) -> Option { + (!twins.is_empty()).then(|| { + format!( + "{report}: fields named the same but for case are left out ({}): a report reads its field by name ignoring case, so it would use the first", + twins.join(", ") + ) + }) } /// The report and the field name given, to remove an entry it stored: matched against what is @@ -497,11 +507,15 @@ fn new_report(s: &mut Session, p: &Value) -> CmdResult { }; r.fields = fields_of("fields", "a report lists", MAX_ITEMS)?; // The layer's fields when none are given: the first of a wide layer, and that is said. - let all = ds.fields.len(); - let first_of = r.fields.is_empty() && all > MAX_ITEMS; - if r.fields.is_empty() { - r.fields = filled_in(ds)?; - } + let mut twins = Vec::new(); + let mut all = ds.fields.len(); + let first_of = r.fields.is_empty() && { + let names; + (names, twins) = filled_in(ds); + all -= twins.len(); + r.fields = names; + all > MAX_ITEMS + }; r.groups = fields_of("groups", "a report groups by", MAX_GROUPS)?; if let Some(w) = ps(p, "where").map(str::trim).filter(|w| !w.is_empty()) { rustgis_data::query::parse(w, ds)?; @@ -527,6 +541,9 @@ fn new_report(s: &mut Session, p: &Value) -> CmdResult { if first_of { s.notify(format!("{name}: the report lists the first {MAX_ITEMS} of the layer's {all} fields"), false); } + if let Some(note) = twins_left_out(&name, &twins) { + s.notify(note, false); + } if let Some(cut) = cut { s.notify(cut, false); } From 33ea900a97749029088b8af7004866ae928cdeee Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:03:08 -0600 Subject: [PATCH 12/24] fix(engine): size by field takes its own twin field back from the Symbology pane (#1955) --- crates/engine/src/cmd/edit.rs | 9 +++++++-- crates/engine/src/cmd/layer.rs | 10 ++++++---- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 725c0c063a..55372362cc 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -2297,6 +2297,9 @@ mod tests { if let Some(d) = &mut l.diagram { d.categories.iter_mut().for_each(|c| c.field = "x".into()); } + // The Symbology pane sends the mapping's own field back with it (which is then stored as + // the field it reads is named), and a change of range alone sends none. + s.run("layer.sizeBy", &json!({"layer": id, "field": "x", "min": 3, "max": 8})).unwrap(); s.run("layer.sizeBy", &json!({"layer": id, "min": 2, "max": 9})).unwrap(); s.run("layer.diagram", &json!({"layer": id, "kind": "bar", "fields": ["x"]})).unwrap(); let l = s.map().layer(id).unwrap(); @@ -2304,13 +2307,15 @@ mod tests { assert_eq!(l.diagram.as_ref().map(|d| d.categories.len()), Some(1)); // A twin's name newly given: refused. for (command, p) in [ - ("layer.sizeBy", json!({"layer": id, "field": "X"})), + // (The mapping now stores `X`, the name of the field it reads.) + ("layer.sizeBy", json!({"layer": id, "field": "x"})), ("layer.diagram", json!({"layer": id, "kind": "pie", "fields": ["n", "X"]})), ] { let error = s.run(command, &p).unwrap_err(); assert!(error.contains("names 'X' and 'x' ignoring case"), "{command}: {error}"); } - // Read ahead: not for a twin's name. + // Read ahead: not for a twin's name newly given (nor the mapping's own, whose range it has). + assert!(crate::cmd::layer::size_by_ahead(&s, &json!({"layer": id, "field": "x"})).is_none()); assert!(crate::cmd::layer::size_by_ahead(&s, &json!({"layer": id, "field": "X"})).is_none()); } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index d0f310e578..927b78de6f 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -789,8 +789,9 @@ fn size_by(s: &mut Session, p: &Value) -> CmdResult { if l.geometry_type() != GeometryType::Point || l.graphics { return Err("this works on point layers".into()); } - // A field given; else the mapping's own, which keeps the field it reads. - let given = field.is_some(); + // A field given other than the mapping's own (which the Symbology pane sends back unchanged); + // else the mapping's own, which keeps the field it reads. + let given = matches!(&field, Some(Some(f)) if l.size_by.as_ref().is_none_or(|b| b.field != *f)); let field = match field { Some(field) => field, None => Some(l.size_by.as_ref().map(|b| b.field.clone()).ok_or("give a field: the layer has no size mapping to change")?), @@ -907,8 +908,9 @@ pub(crate) fn size_by_ahead(s: &Session, p: &Value) -> Option Date: Fri, 20 Nov 2026 10:03:08 -0600 Subject: [PATCH 13/24] docs(engine): Convert Field's doc comment says what design refuses it (#1955) --- crates/engine/src/cmd/edit.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 55372362cc..0be98bc07a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -802,9 +802,10 @@ fn add_field(s: &mut Session, p: &Json) -> CmdResult { /// `2026-03-05T14:30:00+02:00`, or with a space for the `T`). A date field /// also takes a date-time at midnight without a zone. Values that aren't dates become null, said /// with their count and the first few, and undo brings them back; digits past the microsecond are -/// rounded off, and said. A field with text and none of it a date is refused and stays text. Refused while a data design -/// (domain, subtype, contingent values) names the field or a definition query or display filter -/// would stop reading with it. Layer and table conversions run on the desktop worker +/// rounded off, and said. A field with text and none of it a date is refused and stays text. +/// Refused while a data design (a domain, subtypes, a subtype default, contingent values or a +/// calculation rule) names the field, judged by the field the name reads (the first so named +/// ignoring case), or a definition query or display filter would stop reading with it. Layer and table conversions run on the desktop worker /// ([`table_ahead`]), with progress and Cancel; a layer read in place is refused as every /// `edit.*` command is. The shared rows' first copy cannot be interrupted. fn convert_field(s: &mut Session, p: &Json) -> CmdResult { From a05cb6237e3837291bef914c82d9392468af2e9e Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:00:54 -0600 Subject: [PATCH 14/24] fix(engine): a report filled in finds case twins in one pass and names at most 20 (#1955) --- crates/engine/src/cmd/edit.rs | 20 ++++++++++++ crates/engine/src/cmd/report.rs | 55 ++++++++++++++++++++++++--------- 2 files changed, 61 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 0be98bc07a..ade8570dfa 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -2275,6 +2275,26 @@ mod tests { assert!(s.notices_since(mark).iter().all(|n| !n.text.contains("same but for case")), "{:?}", s.notices_since(mark)); } + /// A report filled in from a layer with many twins names the first 20 it leaves out and counts + /// the rest (#1955). + #[test] + fn a_reports_twins_left_out_are_named_up_to_a_limit() { + let mut s = Session::new(crate::Project::default()); + let mut fields: Vec = + (0..25).flat_map(|i| [format!("T{i}"), format!("t{i}")]).map(|n| Field::new(&n, FieldType::Double)).collect(); + fields.push(Field::new("code", FieldType::Double)); + s.map_mut().add_dataset(Dataset::new("twins", GeometryType::Point, fields)); + let mark = s.notice_mark(); + s.run("report.new", &json!({"layer": "twins", "name": "R"})).unwrap(); + assert_eq!(s.project.reports[0].fields, ["code"]); + let named: Vec = (0..10).flat_map(|i| [format!("T{i}"), format!("t{i}")]).collect(); + let notice = format!( + "R: fields named the same but for case are left out ({}, and 30 more): a report reads its field by name ignoring case, so it would use the first", + named.join(", ") + ); + assert!(s.notices_since(mark).iter().any(|n| n.text == notice), "{:?}", s.notices_since(mark)); + } + /// A size by field or diagram set again over the field it already reads keeps reading it, twin /// or not; a twin's name newly given is refused (#1955). #[test] diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 7c7a95ba32..625441ba68 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -140,8 +140,7 @@ pub fn commands() -> Vec { C::new("report.autofill", "Autofill Fields", "Data › Data Design", |s, p| { let i = index(s, p)?; let ds = &layer_of(s, i)?.dataset; - let (names, twins) = filled_in(ds); - let all = ds.fields.len() - twins.len(); + let FilledIn { names, twins, clean: all } = filled_in(ds); let r = s.project.reports.get_mut(i).ok_or("no report")?; r.fields = names; let (answer, report) = (json!({"fields": r.fields}), r.name.clone()); @@ -299,19 +298,48 @@ fn optional_field(input: &impl super::InputSource, p: &Value) -> Result<(usize, } } -/// The first [`MAX_ITEMS`] of a layer's fields, to fill a report with, and the fields left out -/// for having a case twin, which report.field refuses (#1955). -fn filled_in(ds: &rustgis_data::Dataset) -> (Vec, Vec) { - let (twins, names): (Vec<_>, Vec<_>) = ds.fields.iter().map(|f| f.name.clone()).partition(|n| ds.has_case_twin(n)); - (names.into_iter().take(MAX_ITEMS).collect(), twins) +/// A layer's fields to fill a report with ([`filled_in`]). +struct FilledIn { + /// The first [`MAX_ITEMS`] fields without a case twin. + names: Vec, + /// The fields with a case twin among those looked at before the report was full, left out as + /// report.field refuses them (#1955). + twins: Vec, + /// How many of the layer's fields have no case twin. + clean: usize, } -/// The notice for the fields [`filled_in`] left out of report `report`, if any. +/// The most twins a notice names; the rest are counted. +const TWINS_NAMED: usize = 20; + +/// The first [`MAX_ITEMS`] of a layer's fields without a case twin, in one pass over the fields to +/// find twins (their names in lower case) and one to pick, which stops once the report is full. +fn filled_in(ds: &rustgis_data::Dataset) -> FilledIn { + let mut named: HashMap = HashMap::with_capacity(ds.fields.len()); + for f in &ds.fields { + *named.entry(f.name.to_ascii_lowercase()).or_default() += 1; + } + let twin = |n: &str| named.get(&n.to_ascii_lowercase()).is_some_and(|c| *c > 1); + let clean = named.values().filter(|c| **c == 1).count(); + let (mut names, mut twins) = (Vec::new(), Vec::new()); + for f in &ds.fields { + if names.len() >= MAX_ITEMS { + break; + } + if twin(&f.name) { twins.push(f.name.clone()) } else { names.push(f.name.clone()) } + } + FilledIn { names, twins, clean } +} + +/// The notice for the fields [`filled_in`] left out of report `report`, if any: the first +/// [`TWINS_NAMED`] named, the rest counted. fn twins_left_out(report: &str, twins: &[String]) -> Option { (!twins.is_empty()).then(|| { + let shown = twins.iter().take(TWINS_NAMED).map(String::as_str).collect::>().join(", "); + let more = twins.len().saturating_sub(TWINS_NAMED); + let tail = if more > 0 { format!(", and {more} more") } else { String::new() }; format!( - "{report}: fields named the same but for case are left out ({}): a report reads its field by name ignoring case, so it would use the first", - twins.join(", ") + "{report}: fields named the same but for case are left out ({shown}{tail}): a report reads its field by name ignoring case, so it would use the first" ) }) } @@ -510,10 +538,9 @@ fn new_report(s: &mut Session, p: &Value) -> CmdResult { let mut twins = Vec::new(); let mut all = ds.fields.len(); let first_of = r.fields.is_empty() && { - let names; - (names, twins) = filled_in(ds); - all -= twins.len(); - r.fields = names; + let filled = filled_in(ds); + (twins, all) = (filled.twins, filled.clean); + r.fields = filled.names; all > MAX_ITEMS }; r.groups = fields_of("groups", "a report groups by", MAX_GROUPS)?; From 7ff076c2f47b560a3bd18ad797f3614c4242644b Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:16:01 -0600 Subject: [PATCH 15/24] fix(engine): a report filled in says every twin it leaves out and what the limit cut, and removing what it lacks is refused (#1955) --- crates/engine/src/cmd/edit.rs | 36 +++++++++++++++++++++++++++ crates/engine/src/cmd/report.rs | 44 ++++++++++++++++++--------------- 2 files changed, 60 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ade8570dfa..67fc6299d8 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -2295,6 +2295,42 @@ mod tests { assert!(s.notices_since(mark).iter().any(|n| n.text == notice), "{:?}", s.notices_since(mark)); } + /// A layer of 64 fields without twins and `Pop`, `pop`: the report lists the 64, says it lists + /// the first 64 of the layer's 66, and that the twins are left out. Removing an entry the report + /// doesn't hold is an error naming it (#1955). + #[test] + fn a_full_report_says_both_what_it_cut_and_its_twins() { + let mut s = Session::new(crate::Project::default()); + let mut fields: Vec = (0..64).map(|i| Field::new(format!("f{i}"), FieldType::Double)).collect(); + fields.extend(["Pop", "pop"].map(|n| Field::new(n, FieldType::Double))); + s.map_mut().add_dataset(Dataset::new("wide", GeometryType::Point, fields)); + let mark = s.notice_mark(); + s.run("report.new", &json!({"layer": "wide", "name": "R"})).unwrap(); + assert_eq!(s.project.reports[0].fields.len(), 64); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|n| n == "R: the report lists the first 64 of the layer's 66 fields"), "{said:?}"); + assert!(said.iter().any(|n| n.starts_with("R: fields named the same but for case are left out (Pop, pop)")), "{said:?}"); + let mark = s.notice_mark(); + s.run("report.autofill", &json!({"report": "R"})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|n| n == "R: the first 64 of the layer's 66 fields are filled in"), "{said:?}"); + assert!(said.iter().any(|n| n.contains("(Pop, pop)")), "{said:?}"); + // Nothing to remove: refused, naming it; there to remove: removed. + for (command, extra, error) in [ + ("report.field", json!({}), "the report has no field 'nope'"), + ("report.group", json!({}), "the report has no group 'nope'"), + ("report.statistics", json!({"kind": "sum"}), "the report has no sum statistic of 'nope'"), + ] { + let mut p = json!({"report": "R", "field": "nope", "remove": true}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + assert_eq!(s.run(command, &p).unwrap_err(), error); + } + s.run("report.field", &json!({"report": "R", "field": "f0", "remove": true})).unwrap(); + assert_eq!(s.project.reports[0].fields.len(), 63); + } + /// A size by field or diagram set again over the field it already reads keeps reading it, twin /// or not; a twin's name newly given is refused (#1955). #[test] diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 625441ba68..9459129f36 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -132,7 +132,7 @@ pub fn commands() -> Vec { if !remove && r.fields.len() >= MAX_ITEMS && !r.fields.iter().any(|f| f.eq_ignore_ascii_case(&field)) { return Err(format!("a report lists at most {MAX_ITEMS} fields")); } - toggle(&mut r.fields, field, remove); + toggle(&mut r.fields, field, remove, "field")?; Ok(json!({"fields": r.fields})) }).inputs(layer_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_report) @@ -140,12 +140,15 @@ pub fn commands() -> Vec { C::new("report.autofill", "Autofill Fields", "Data › Data Design", |s, p| { let i = index(s, p)?; let ds = &layer_of(s, i)?.dataset; - let FilledIn { names, twins, clean: all } = filled_in(ds); + let all = ds.fields.len(); + let FilledIn { names, twins } = filled_in(ds); + let full = names.len() >= MAX_ITEMS && all > MAX_ITEMS; let r = s.project.reports.get_mut(i).ok_or("no report")?; r.fields = names; let (answer, report) = (json!({"fields": r.fields}), r.name.clone()); - // A layer with more fields than a report takes: the first are filled in, and that is said (#1896). - if all > MAX_ITEMS { + // A layer with more fields than a report takes: the first are filled in, and that is + // said (#1896), with the layer's own count of fields. + if full { s.notify(format!("{report}: the first {MAX_ITEMS} of the layer's {all} fields are filled in"), false); } if let Some(note) = twins_left_out(&report, &twins) { @@ -173,6 +176,7 @@ pub fn commands() -> Vec { } (None, false) if r.stats.len() < MAX_ITEMS => r.stats.push(Stat { field, kind }), (None, false) => return Err("the report has too many statistics".into()), + (None, true) => return Err(format!("the report has no {} statistic of '{field}'", kind.label().to_lowercase())), _ => {} } Ok(json!({"stats": r.stats.len()})) @@ -186,7 +190,7 @@ pub fn commands() -> Vec { if !remove && r.groups.len() >= MAX_GROUPS && !r.groups.iter().any(|g| g.eq_ignore_ascii_case(&field)) { return Err(format!("reports group by at most {MAX_GROUPS} fields")); } - toggle(&mut r.groups, field, remove); + toggle(&mut r.groups, field, remove, "group")?; Ok(json!({"groups": r.groups})) }).inputs(layer_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_report) @@ -302,33 +306,30 @@ fn optional_field(input: &impl super::InputSource, p: &Value) -> Result<(usize, struct FilledIn { /// The first [`MAX_ITEMS`] fields without a case twin. names: Vec, - /// The fields with a case twin among those looked at before the report was full, left out as - /// report.field refuses them (#1955). + /// The fields with a case twin, all of them, left out as report.field refuses them (#1955). twins: Vec, - /// How many of the layer's fields have no case twin. - clean: usize, } /// The most twins a notice names; the rest are counted. const TWINS_NAMED: usize = 20; -/// The first [`MAX_ITEMS`] of a layer's fields without a case twin, in one pass over the fields to -/// find twins (their names in lower case) and one to pick, which stops once the report is full. +/// The first [`MAX_ITEMS`] of a layer's fields without a case twin, and every field with one: in +/// one pass over the fields to find twins (their names in lower case), and one to pick. fn filled_in(ds: &rustgis_data::Dataset) -> FilledIn { let mut named: HashMap = HashMap::with_capacity(ds.fields.len()); for f in &ds.fields { *named.entry(f.name.to_ascii_lowercase()).or_default() += 1; } let twin = |n: &str| named.get(&n.to_ascii_lowercase()).is_some_and(|c| *c > 1); - let clean = named.values().filter(|c| **c == 1).count(); let (mut names, mut twins) = (Vec::new(), Vec::new()); for f in &ds.fields { - if names.len() >= MAX_ITEMS { - break; + if twin(&f.name) { + twins.push(f.name.clone()); + } else if names.len() < MAX_ITEMS { + names.push(f.name.clone()); } - if twin(&f.name) { twins.push(f.name.clone()) } else { names.push(f.name.clone()) } } - FilledIn { names, twins, clean } + FilledIn { names, twins } } /// The notice for the fields [`filled_in`] left out of report `report`, if any: the first @@ -352,15 +353,18 @@ fn stored(input: &impl super::InputSource, p: &Value) -> Result<(usize, String), /// Adds `field` to `list`, or removes it: the entry named exactly so, else the first named so /// ignoring case. -fn toggle(list: &mut Vec, field: String, remove: bool) { +/// Removing one the list doesn't hold is an error naming it, `what` saying which list. +fn toggle(list: &mut Vec, field: String, remove: bool, what: &str) -> Result<(), String> { let at = list.iter().position(|x| *x == field).or_else(|| list.iter().position(|x| x.eq_ignore_ascii_case(&field))); match (at, remove) { (Some(k), true) => { list.remove(k); } + (None, true) => return Err(format!("the report has no {what} '{field}'")), (None, false) if list.len() < MAX_ITEMS => list.push(field), _ => {} } + Ok(()) } fn add_section(s: &mut Session, p: &Value, sec: Section) -> CmdResult { @@ -536,12 +540,12 @@ fn new_report(s: &mut Session, p: &Value) -> CmdResult { r.fields = fields_of("fields", "a report lists", MAX_ITEMS)?; // The layer's fields when none are given: the first of a wide layer, and that is said. let mut twins = Vec::new(); - let mut all = ds.fields.len(); + let all = ds.fields.len(); let first_of = r.fields.is_empty() && { let filled = filled_in(ds); - (twins, all) = (filled.twins, filled.clean); + twins = filled.twins; r.fields = filled.names; - all > MAX_ITEMS + r.fields.len() >= MAX_ITEMS && all > MAX_ITEMS }; r.groups = fields_of("groups", "a report groups by", MAX_GROUPS)?; if let Some(w) = ps(p, "where").map(str::trim).filter(|w| !w.is_empty()) { From bf844411c312a33a5f5301683b6cf41d4d49b0f6 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:16:02 -0600 Subject: [PATCH 16/24] fix(engine): size by field takes a name that reads the field its mapping reads (#1955) --- crates/engine/src/cmd/edit.rs | 8 +++++--- crates/engine/src/cmd/layer.rs | 10 ++++++---- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 67fc6299d8..44e597d8ef 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -2362,16 +2362,18 @@ mod tests { let l = s.map().layer(id).unwrap(); assert_eq!(l.size_by.as_ref().map(|b| (b.min, b.max)), Some((2.0, 9.0))); assert_eq!(l.diagram.as_ref().map(|d| d.categories.len()), Some(1)); - // A twin's name newly given: refused. + // Given in either spelling, a twin's name reads the field the mapping reads (`X`): taken. + s.run("layer.sizeBy", &json!({"layer": id, "field": "x", "min": 2, "max": 9})).unwrap(); + // A twin's name newly given, the mapping on another field: refused. + s.run("layer.sizeBy", &json!({"layer": id, "field": "n"})).unwrap(); for (command, p) in [ - // (The mapping now stores `X`, the name of the field it reads.) ("layer.sizeBy", json!({"layer": id, "field": "x"})), ("layer.diagram", json!({"layer": id, "kind": "pie", "fields": ["n", "X"]})), ] { let error = s.run(command, &p).unwrap_err(); assert!(error.contains("names 'X' and 'x' ignoring case"), "{command}: {error}"); } - // Read ahead: not for a twin's name newly given (nor the mapping's own, whose range it has). + // Read ahead: not for a twin's name newly given. assert!(crate::cmd::layer::size_by_ahead(&s, &json!({"layer": id, "field": "x"})).is_none()); assert!(crate::cmd::layer::size_by_ahead(&s, &json!({"layer": id, "field": "X"})).is_none()); } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 927b78de6f..b918f2a8bf 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -789,9 +789,10 @@ fn size_by(s: &mut Session, p: &Value) -> CmdResult { if l.geometry_type() != GeometryType::Point || l.graphics { return Err("this works on point layers".into()); } - // A field given other than the mapping's own (which the Symbology pane sends back unchanged); - // else the mapping's own, which keeps the field it reads. - let given = matches!(&field, Some(Some(f)) if l.size_by.as_ref().is_none_or(|b| b.field != *f)); + // A field given other than the one the mapping reads (which the Symbology pane sends back, + // in any spelling); else the mapping's own, which keeps the field it reads. + let reads = |name: &str| l.dataset.field_index(name); + let given = matches!(&field, Some(Some(f)) if l.size_by.as_ref().is_none_or(|b| reads(&b.field) != reads(f))); let field = match field { Some(field) => field, None => Some(l.size_by.as_ref().map(|b| b.field.clone()).ok_or("give a field: the layer has no size mapping to change")?), @@ -910,7 +911,8 @@ pub(crate) fn size_by_ahead(s: &Session, p: &Value) -> Option Date: Fri, 20 Nov 2026 19:16:03 -0600 Subject: [PATCH 17/24] fix(engine): a label class whose clause would read a deleted field's twin is turned off, not made catch-all (#1955) --- crates/engine/src/cmd/edit.rs | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 44e597d8ef..4ab103e1b8 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1114,21 +1114,21 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { label_gone.push((format!("{}'s {}", c.name, and_list(&gone)), gone.len())); } } - // A clause that read it and would now read a field named the same but for case is removed, so - // the class takes the features the earlier ones leave, as with no clause; said once, naming the - // classes. One that no longer reads is kept to edit, taking no features, as before. + // A class whose clause read it and would now read a field named the same but for case is + // turned off, so it labels nothing, as a class whose clause no longer reads labels nothing; its + // clause is kept to edit. Said once, naming the classes. let mut clauses_gone = Vec::new(); let classes = std::iter::once(&mut l.labels.default).chain(l.labels.classes.iter_mut()); for (c, read) in classes.zip(&clause_read) { if *read && c.where_.as_deref().is_some_and(|w| rustgis_data::query::parse_fields(w, &l.dataset).is_ok()) { - c.where_ = None; + c.visible = false; clauses_gone.push(c.name.clone()); } } let clause_note = (!clauses_gone.is_empty()).then(|| { - let (classes, they) = if clauses_gone.len() == 1 { ("class", "it is") } else { ("classes", "they are") }; + let (classes, they) = if clauses_gone.len() == 1 { ("class", "the class is") } else { ("classes", "the classes are") }; format!( - "{}: the clause of its label {classes} {} read the deleted field {removed}, so {they} removed", + "{}: the clause of its label {classes} {} read the deleted field {removed}, so {they} turned off", l.name, clauses_gone.join(", ") ) @@ -1149,7 +1149,7 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { // said; by a text expression that still reads, Default only loses the field. Another class on // it labels with Default's field instead. A class clause naming it no longer reads, and takes // no features, which go on to the next class: it is kept to edit, not dropped with its text - // symbol; one that would read its twin was removed above. + // symbol; a class whose clause would read its twin was turned off above. let mut restart_note = None; if names_removed(&l.labels.default.field) { let by_text = l.labels.default.by.text.as_deref().is_some_and(|t| rustgis_data::query::parse_fields(t, &l.dataset).is_ok()); @@ -2403,16 +2403,18 @@ mod tests { let mark = s.notice_mark(); s.run("edit.deleteField", &json!({"layer": id, "field": deleted})).unwrap(); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - let clause = s.map().layer(id).unwrap().labels.classes[0].where_.clone(); + let class = &s.map().layer(id).unwrap().labels.classes[0]; + let (clause, visible) = (class.where_.clone(), class.visible); if read { - assert_eq!(clause, None); + assert_eq!((clause.as_deref(), visible), (Some("pop > 1"), false)); assert!( - said.iter().any(|n| n == "twins: the clause of its label class Big read the deleted field Pop, so it is removed"), + said.iter() + .any(|n| n == "twins: the clause of its label class Big read the deleted field Pop, so the class is turned off"), "{said:?}" ); } else { // Kept: reading another field, or (no twin) no longer reading, as before. - assert_eq!(clause.as_deref(), Some("pop > 1")); + assert_eq!((clause.as_deref(), visible), (Some("pop > 1"), true)); assert!(said.iter().all(|n| !n.contains("clause")), "{said:?}"); } } From 23257da2b19cf85c8513032cdb2e00c68be66990 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:31:56 -0600 Subject: [PATCH 18/24] fix(engine): settings kept by a field's name take a case twin only as stored, and deleting a twin drops what reports named it by (#1955) --- crates/engine/src/cmd/edit.rs | 153 ++++++++++++++++++++++++++++++-- crates/engine/src/cmd/layer.rs | 28 +++--- crates/engine/src/cmd/report.rs | 23 +++-- 3 files changed, 178 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9f1d42078e..4af222dbbd 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1390,6 +1390,8 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { // ([`Dataset::reads_field`]). A name that read a twin left keeps it; one that read the deleted // field would go on to read the twin, so it goes too (#1955). let read = l.dataset.reads_field(fi, &name); + // Whether a field named the same but for case is left: what named the deleted one would read it. + let twin_left = read && l.dataset.has_case_twin(&name); let names_removed = |f: &str| read && f.eq_ignore_ascii_case(&name); let removed = l.dataset.fields.remove(fi).name; for f in &mut l.dataset.features { @@ -1691,6 +1693,51 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { if let Some(note) = rules_note { s.notify(note, false); } + // Nor the reports on the layer, when a twin is left that they would go on to read: what they + // named the deleted field by goes, said once a report (#1955). + if twin_left { + let mut report_notes = Vec::new(); + for r in s.project.reports.iter_mut().filter(|r| r.layer.eq_ignore_ascii_case(&layer_name)) { + let mut gone = Vec::new(); + let (fields, groups, stats) = (r.fields.len(), r.groups.len(), r.stats.len()); + r.fields.retain(|f| !names_removed(f)); + r.groups.retain(|f| !names_removed(f)); + r.stats.retain(|x| !names_removed(&x.field)); + for (before, after, what) in + [(fields, r.fields.len(), "field"), (groups, r.groups.len(), "group"), (stats, r.stats.len(), "statistic")] + { + match before.saturating_sub(after) { + 0 => {} + 1 => gone.push(format!("a {what}")), + n => gone.push(format!("{n} {what}s")), + } + } + for (slot, what) in [ + (&mut r.sort, "its sort"), + (&mut r.picture_field, "its picture field"), + (&mut r.attachments_field, "its attachments field"), + ] { + if slot.as_deref().is_some_and(names_removed) { + *slot = None; + gone.push(what.to_string()); + } + } + if r.chart.as_ref().is_some_and(|c| names_removed(&c.category) || c.value.as_deref().is_some_and(names_removed)) { + r.chart = None; + gone.push("its chart".to_string()); + } + if !gone.is_empty() { + report_notes.push(format!( + "{}: it named the deleted field {removed} in {}, so they are removed", + r.name, + and_list(&gone.iter().map(String::as_str).collect::>()) + )); + } + } + for note in report_notes { + s.notify(note, false); + } + } Ok(json!({"rulesRemoved": removed_rules})) } @@ -2790,13 +2837,24 @@ mod tests { /// doesn't hold is an error naming it (#1955). #[test] fn a_full_report_says_both_what_it_cut_and_its_twins() { + let wide = |s: &mut Session, clean: usize, name: &str| { + let mut fields: Vec = (0..clean).map(|i| Field::new(format!("f{i}"), FieldType::Double)).collect(); + fields.extend(["Pop", "pop"].map(|n| Field::new(n, FieldType::Double))); + s.map_mut().add_dataset(Dataset::new(name, GeometryType::Point, fields)); + }; let mut s = Session::new(crate::Project::default()); - let mut fields: Vec = (0..64).map(|i| Field::new(format!("f{i}"), FieldType::Double)).collect(); - fields.extend(["Pop", "pop"].map(|n| Field::new(n, FieldType::Double))); - s.map_mut().add_dataset(Dataset::new("wide", GeometryType::Point, fields)); + // 64 fields without twins fit: only the twins are said. + wide(&mut s, 64, "fits"); + let mark = s.notice_mark(); + s.run("report.new", &json!({"layer": "fits", "name": "F"})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().all(|n| !n.contains("the first 64")), "{said:?}"); + assert!(said.iter().any(|n| n.starts_with("F: fields named the same but for case are left out (Pop, pop)")), "{said:?}"); + // 66 without twins don't: both are said, with the count of fields a report may take. + wide(&mut s, 66, "wide"); let mark = s.notice_mark(); s.run("report.new", &json!({"layer": "wide", "name": "R"})).unwrap(); - assert_eq!(s.project.reports[0].fields.len(), 64); + assert_eq!(s.project.reports[1].fields.len(), 64); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert!(said.iter().any(|n| n == "R: the report lists the first 64 of the layer's 66 fields"), "{said:?}"); assert!(said.iter().any(|n| n.starts_with("R: fields named the same but for case are left out (Pop, pop)")), "{said:?}"); @@ -2818,7 +2876,7 @@ mod tests { assert_eq!(s.run(command, &p).unwrap_err(), error); } s.run("report.field", &json!({"report": "R", "field": "f0", "remove": true})).unwrap(); - assert_eq!(s.project.reports[0].fields.len(), 63); + assert_eq!(s.project.reports[1].fields.len(), 63); } /// A size by field or diagram set again over the field it already reads keeps reading it, twin @@ -2852,10 +2910,9 @@ mod tests { let l = s.map().layer(id).unwrap(); assert_eq!(l.size_by.as_ref().map(|b| (b.min, b.max)), Some((2.0, 9.0))); assert_eq!(l.diagram.as_ref().map(|d| d.categories.len()), Some(1)); - // Given in either spelling, a twin's name reads the field the mapping reads (`X`): taken. - s.run("layer.sizeBy", &json!({"layer": id, "field": "x", "min": 2, "max": 9})).unwrap(); - // A twin's name newly given, the mapping on another field: refused. - s.run("layer.sizeBy", &json!({"layer": id, "field": "n"})).unwrap(); + // The mapping is now stored as `X`: `X` again is the same mapping; `x` is a name given, + // which would read `X` whichever was meant: refused. + s.run("layer.sizeBy", &json!({"layer": id, "field": "X", "min": 2, "max": 9})).unwrap(); for (command, p) in [ ("layer.sizeBy", json!({"layer": id, "field": "x"})), ("layer.diagram", json!({"layer": id, "kind": "pie", "fields": ["n", "X"]})), @@ -2866,6 +2923,84 @@ mod tests { // Read ahead: not for a twin's name newly given. assert!(crate::cmd::layer::size_by_ahead(&s, &json!({"layer": id, "field": "x"})).is_none()); assert!(crate::cmd::layer::size_by_ahead(&s, &json!({"layer": id, "field": "X"})).is_none()); + // Without twins, any spelling is the field. + let mut ds = Dataset::new("plain", GeometryType::Point, ["v", "code"].map(|f| Field::new(f, FieldType::Double)).to_vec()); + ds.push(Some(Geometry::Point(rustgis_data::Coord::new(1.0, 1.0))), vec![Value::Float(1.0), Value::Float(1.0)]); + let plain = s.map_mut().add_dataset(ds); + s.run("layer.symbology", &json!({"layer": plain, "type": "unique", "field": "code"})).unwrap(); + s.run("layer.sizeBy", &json!({"layer": plain, "field": "v", "min": 0, "max": 10})).unwrap(); + s.run("layer.sizeBy", &json!({"layer": plain, "field": "V", "min": 0, "max": 10})).unwrap(); + } + + /// Other settings kept by a field's name take a case twin's name only as they store it + /// already: marker rotation, a label class's field and a report's sort refuse it newly given, + /// and a layer without twins is as before (#1955). + #[test] + fn settings_kept_by_name_refuse_a_twin_given_anew() { + let mut s = Session::new(crate::Project::default()); + let mut ds = Dataset::new("twins", GeometryType::Point, ["X", "x", "v", "code"].map(|f| Field::new(f, FieldType::Double)).to_vec()); + ds.push(Some(Geometry::Point(rustgis_data::Coord::new(1.0, 1.0))), vec![Value::Float(1.0); 4]); + let id = s.map_mut().add_dataset(ds); + s.run("report.new", &json!({"layer": "twins", "name": "R", "fields": ["v"]})).unwrap(); + for (command, p) in [ + ("layer.markerRotation", json!({"layer": id, "field": "x"})), + ("labels.field", json!({"layer": id, "field": "x"})), + ("report.new", json!({"layer": "twins", "name": "S", "fields": ["v"], "sort": "x"})), + ("report.update", json!({"report": "R", "sort": "X"})), + ] { + let error = s.run(command, &p).unwrap_err(); + assert!(error.contains("names 'X' and 'x' ignoring case"), "{command}: {error}"); + } + // As stored already (an older project): set again, kept. + let l = s.map_mut().layer_mut(id).unwrap(); + l.marker_rotation = Some(rustgis_map::MarkerRotation { field: "x".into(), counterclockwise: false }); + l.labels.default.field = "x".into(); + s.project.reports[0].sort = Some("x".into()); + s.run("layer.markerRotation", &json!({"layer": id, "field": "x", "counterclockwise": true})).unwrap(); + s.run("labels.field", &json!({"layer": id, "field": "x"})).unwrap(); + s.run("report.update", &json!({"report": "R", "sort": "x"})).unwrap(); + // Without twins, as before. + s.run("layer.markerRotation", &json!({"layer": id, "field": "V"})).unwrap(); + s.run("labels.field", &json!({"layer": id, "field": "V"})).unwrap(); + s.run("report.update", &json!({"report": "R", "sort": "V"})).unwrap(); + assert_eq!(s.project.reports[0].sort.as_deref(), Some("v")); + } + + /// Deleting the first of two twins a report on the layer named (fields, groups, statistics, + /// sort, chart, picture and attachments) removes what named it, said once a report, as it would + /// read the other twin; deleting the second twin, which nothing read, or a field without a + /// twin, leaves the report as it was (#1955). + #[test] + fn deleting_a_field_takes_what_reports_named_it_by() { + for (fields, deleted, read) in + [(["Pop", "pop", "n"], "Pop", true), (["Pop", "pop", "n"], "pop", false), (["Pop", "a", "n"], "Pop", false)] + { + let mut s = Session::new(crate::Project::default()); + let mut ds = Dataset::new("twins", GeometryType::Point, fields.map(|f| Field::new(f, FieldType::Double)).to_vec()); + ds.push(Some(Geometry::Point(rustgis_data::Coord::new(1.0, 1.0))), vec![Value::Float(1.0); 3]); + s.map_mut().add_dataset(ds); + s.run("report.new", &json!({"layer": "twins", "name": "R", "fields": ["n"]})).unwrap(); + let r = &mut s.project.reports[0]; + r.fields.push("Pop".into()); + r.groups.push("Pop".into()); + r.stats.push(rustgis_map::report::Stat { field: "Pop".into(), kind: rustgis_map::report::StatKind::Sum }); + r.sort = Some("Pop".into()); + r.chart = Some(rustgis_map::report::ReportChart { category: "n".into(), value: Some("Pop".into()) }); + let mark = s.notice_mark(); + s.run("edit.deleteField", &json!({"layer": "twins", "field": deleted})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + let r = &s.project.reports[0]; + if read { + assert!(r.fields == ["n"] && r.groups.is_empty() && r.stats.is_empty() && r.sort.is_none() && r.chart.is_none()); + assert!( + said.iter().any(|n| n == "R: it named the deleted field Pop in a field, a group, a statistic, its sort and its chart, so they are removed"), + "{said:?}" + ); + } else { + assert!(r.fields == ["n", "Pop"] && r.groups.len() == 1 && r.stats.len() == 1 && r.sort.is_some() && r.chart.is_some()); + assert!(said.iter().all(|n| !n.starts_with("R:")), "{said:?}"); + } + } } /// Deleting a field removes the label class clauses that read it and would go on to read its diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 35233bb4dc..ae563b0ef7 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -370,7 +370,11 @@ pub fn commands() -> Vec { return Err("this works on point layers".into()); } if let Some(f) = &field { - let fi = l.dataset.field_index(f).ok_or_else(|| format!("no field named '{f}'"))?; + // The field it turns by already, as stored, or one named anew (a case twin's + // name refused, as it would read the first twin; #1955). + let own = l.marker_rotation.as_ref().is_some_and(|r| r.field == *f); + let fi = if own { l.dataset.field_index(f) } else { super::edit::kept_field(&l.dataset, f, "marker rotation")? } + .ok_or_else(|| format!("no field named '{f}'"))?; if !l.dataset.fields.get(fi).is_some_and(|fd| fd.ty.is_numeric()) { return Err(format!("'{f}' is not a numeric field")); } @@ -515,7 +519,12 @@ pub fn commands() -> Vec { C::new("labels.field", "Label Field", "Labeling › Label Class", |s, p| { let name = s_req(p, "field")?.to_string(); let id = s.layer_id(p)?; - let fname = s.map().layer(id).and_then(|l| l.dataset.field_index(&name).and_then(|i| l.dataset.fields.get(i)).map(|f| f.name.clone())); + let l = s.map().layer(id).ok_or("no such layer")?; + // A field a class labels with already, as stored, or one named anew (a case twin's name + // refused, as it would read the first twin; #1955). + let own = std::iter::once(&l.labels.default).chain(&l.labels.classes).any(|c| c.field == name); + let fi = if own { l.dataset.field_index(&name) } else { super::edit::kept_field(&l.dataset, &name, "a label class")? }; + let fname = fi.and_then(|i| l.dataset.fields.get(i)).map(|f| f.name.clone()); let fname = fname.ok_or_else(|| format!("no field named '{name}'"))?; super::labels::with_labels(s, p, |labels| { super::labels::class_in(labels, p)?.field = fname; @@ -791,10 +800,10 @@ fn size_by(s: &mut Session, p: &Value) -> CmdResult { if l.geometry_type() != GeometryType::Point || l.graphics { return Err("this works on point layers".into()); } - // A field given other than the one the mapping reads (which the Symbology pane sends back, - // in any spelling); else the mapping's own, which keeps the field it reads. - let reads = |name: &str| l.dataset.field_index(name); - let given = matches!(&field, Some(Some(f)) if l.size_by.as_ref().is_none_or(|b| reads(&b.field) != reads(f))); + // A field given other than the mapping's own name, spelled as it is stored (which the + // Symbology pane sends back); else the mapping's own, which keeps the field it reads. Another + // spelling is a name given: with a case twin it is refused, as it would read the first twin. + let given = matches!(&field, Some(Some(f)) if l.size_by.as_ref().is_none_or(|b| b.field != *f)); let field = match field { Some(field) => field, None => Some(l.size_by.as_ref().map(|b| b.field.clone()).ok_or("give a field: the layer has no size mapping to change")?), @@ -917,10 +926,9 @@ pub(crate) fn size_by_ahead(s: &Session, p: &Value) -> Option Vec { C::new("report.autofill", "Autofill Fields", "Data › Data Design", |s, p| { let i = index(s, p)?; let ds = &layer_of(s, i)?.dataset; - let all = ds.fields.len(); let FilledIn { names, twins } = filled_in(ds); - let full = names.len() >= MAX_ITEMS && all > MAX_ITEMS; + // The fields a report may take: all but the twins. + let all = ds.fields.len() - twins.len(); + let full = all > MAX_ITEMS; let r = s.project.reports.get_mut(i).ok_or("no report")?; r.fields = names; let (answer, report) = (json!({"fields": r.fields}), r.name.clone()); @@ -540,12 +541,14 @@ fn new_report(s: &mut Session, p: &Value) -> CmdResult { r.fields = fields_of("fields", "a report lists", MAX_ITEMS)?; // The layer's fields when none are given: the first of a wide layer, and that is said. let mut twins = Vec::new(); - let all = ds.fields.len(); + let mut all = ds.fields.len(); let first_of = r.fields.is_empty() && { let filled = filled_in(ds); twins = filled.twins; r.fields = filled.names; - r.fields.len() >= MAX_ITEMS && all > MAX_ITEMS + // The fields a report may take: all but the twins. + all -= twins.len(); + all > MAX_ITEMS }; r.groups = fields_of("groups", "a report groups by", MAX_GROUPS)?; if let Some(w) = ps(p, "where").map(str::trim).filter(|w| !w.is_empty()) { @@ -554,7 +557,7 @@ fn new_report(s: &mut Session, p: &Value) -> CmdResult { } r.selected_only = b(p, "selectedOnly").unwrap_or(false); if let Some(sort) = ps(p, "sort") { - let fi = ds.field_index(sort).ok_or_else(|| format!("'{}' has no field '{sort}'", layer.name))?; + let fi = super::edit::kept_field(ds, sort, "a report")?.ok_or_else(|| format!("'{}' has no field '{sort}'", layer.name))?; r.sort = ds.fields.get(fi).map(|f| f.name.clone()); } r.descending = b(p, "descending").unwrap_or(false); @@ -623,9 +626,13 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { } // Everything is checked against the (possibly new) layer before the report changes. let l = find_layer(s, &r.layer); + // A field named anew: a case twin's name is refused, as a report reads the first twin (#1955). let field = |n: &str| -> Result { let ds = &l.ok_or("the report's layer isn't in the project")?.dataset; - ds.field_index(n).and_then(|fi| ds.fields.get(fi)).map(|f| f.name.clone()).ok_or_else(|| format!("no field '{n}'")) + super::edit::kept_field(ds, n, "a report")? + .and_then(|fi| ds.fields.get(fi)) + .map(|f| f.name.clone()) + .ok_or_else(|| format!("no field '{n}'")) }; let mut cut = None; if let Some(n) = new_name { @@ -647,6 +654,8 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { } match p.get("sort") { Some(Value::Null) => r.sort = None, + // Its own sort set again, as stored, stays. + Some(Value::String(n)) if r.sort.as_deref() == Some(n.as_str()) => {} Some(Value::String(n)) => r.sort = Some(field(n)?), _ => {} } @@ -696,7 +705,7 @@ fn subreport(s: &mut Session, p: &Value) -> CmdResult { let mut fields = Vec::new(); for v in given { let n = v.as_str().ok_or("fields are field names")?; - let fi = ds.field_index(n).ok_or_else(|| format!("'{other}' has no field '{n}'"))?; + let fi = super::edit::kept_field(ds, n, "a subreport")?.ok_or_else(|| format!("'{other}' has no field '{n}'"))?; fields.extend(ds.fields.get(fi).map(|f| f.name.clone())); } add_section(s, &json!({"report": i}), Section::Subreport { relationship: name, fields }) From c2b395956a6a58c57c333af15b0df5c1cb00c7db Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:36:19 -0600 Subject: [PATCH 19/24] fix(engine): deleting a twin changes only the reports that read its layer, and its notices are translatable (#1955) --- crates/engine/src/cmd/design.rs | 2 +- crates/engine/src/cmd/edit.rs | 175 ++++++++++++++++++++++++-------- crates/engine/src/cmd/report.rs | 30 ++++-- 3 files changed, 156 insertions(+), 51 deletions(-) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 44b201fa14..ab24eb2b38 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2233,7 +2233,7 @@ fn traverse(s: &mut Session, p: &Json) -> CmdResult { /// The field design names `name` ([`super::edit::kept_field`]): design reads its field by name, /// the first so named ignoring case, so a name with case twins is refused. Every design command /// finds its fields through this (#1955). -fn design_field(ds: &rustgis_data::Dataset, name: &str, what: &str) -> Result { +fn design_field(ds: &rustgis_data::Dataset, name: &str, what: &'static str) -> Result { super::edit::kept_field(ds, name, what)?.ok_or_else(|| format!("no field named '{name}'")) } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 4af222dbbd..bfb85349b8 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -233,13 +233,14 @@ pub(crate) use rustgis_data::find_field as field_in; /// `name`: the first field so named ignoring case ([`Dataset::field_index`]). Refused when the layer /// has more than one field so named, even if one is named exactly so, since it would read the /// first of them whichever was meant (#1955). -pub(crate) fn kept_field(ds: &Dataset, name: &str, what: &str) -> Result, String> { +pub(crate) fn kept_field(ds: &Dataset, name: &str, what: &'static str) -> Result, String> { if ds.has_case_twin(name) { let twins: Vec = ds.fields.iter().filter(|f| f.name.eq_ignore_ascii_case(name)).map(|f| format!("'{}'", f.name)).collect(); - return Err(format!( - "'{name}' names {} ignoring case, and {what} reads its field by name ignoring case, so it would use the first: copy the first into a field of another name (Add Field, then Calculate Field) and delete it, or rename one in the source data", - twins.join(" and ") - )); + return Err(NoticeText::format( + "'{name}' names {twins} ignoring case, and {what} reads its field by name ignoring case, so it would use the first: copy the first into a field of another name (Add Field, then Calculate Field) and delete it, or rename one in the source data", + [("name", name.to_string().into()), ("twins", twins.join(" and ").into()), ("what", NoticeText::term(what))], + ) + .english()); } Ok(ds.field_index(name)) } @@ -1439,11 +1440,14 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { } } let clause_note = (!clauses_gone.is_empty()).then(|| { - let (classes, they) = if clauses_gone.len() == 1 { ("class", "the class is") } else { ("classes", "the classes are") }; - format!( - "{}: the clause of its label {classes} {} read the deleted field {removed}, so {they} turned off", - l.name, - clauses_gone.join(", ") + let key = if clauses_gone.len() == 1 { + "{layer}: the clause of its label class {classes} read the deleted field {field}, so the class is turned off" + } else { + "{layer}: the clause of its label classes {classes} read the deleted field {field}, so the classes are turned off" + }; + NoticeText::format( + key, + [("layer", l.name.clone().into()), ("classes", clauses_gone.join(", ").into()), ("field", removed.clone().into())], ) }); let label_note = match label_gone.as_slice() { @@ -1487,11 +1491,18 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { let moved = l.labels.repoint_fields(&l.dataset, names_removed); let moved_note = (!moved.is_empty()).then(|| { let on = match l.labels.classes.iter().find(|c| moved.contains(&c.name)).map(|c| c.field.as_str()) { - Some(f) if !f.is_empty() => format!("field {f}"), - _ => "no field".to_string(), + Some(f) if !f.is_empty() => NoticeText::format("field {field}", [("field", f.to_string().into())]), + _ => NoticeText::term("no field"), }; - let (classes, it) = if moved.len() == 1 { ("class", "it labels") } else { ("classes", "they label") }; - format!("{}: its label {classes} {} used the deleted field {removed}, so {it} {on}", l.name, moved.join(", ")) + let key = if moved.len() == 1 { + "{layer}: its label class {classes} used the deleted field {field}, so it labels {on}" + } else { + "{layer}: its label classes {classes} used the deleted field {field}, so they label {on}" + }; + NoticeText::format( + key, + [("layer", l.name.clone().into()), ("classes", moved.join(", ").into()), ("field", removed.clone().into()), ("on", on)], + ) }); // A definition query that reads the field was refused above; one that already didn't read is // kept as it is, so its text isn't lost. @@ -1503,12 +1514,12 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { d.domains.retain(|x| !names_removed(&x.field)); match domains - d.domains.len() { 0 => {} - 1 => design_gone.push("its domain".to_string()), - n => design_gone.push(format!("{n} domains")), + 1 => design_gone.push(NoticeText::term("its domain")), + n => design_gone.push(NoticeText::format("{count} domains", [("count", n.to_string().into())])), } if d.subtypes.as_ref().is_some_and(|st| names_removed(&st.field)) { d.subtypes = None; - design_gone.push("the subtypes".into()); + design_gone.push(NoticeText::term("the subtypes")); } if let Some(st) = &mut d.subtypes { let mut defaults = 0; @@ -1519,8 +1530,8 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { } match defaults { 0 => {} - 1 => design_gone.push("1 subtype default".into()), - n => design_gone.push(format!("{n} subtype defaults")), + 1 => design_gone.push(NoticeText::term("1 subtype default")), + n => design_gone.push(NoticeText::format("{count} subtype defaults", [("count", n.to_string().into())])), } } let quoted = |names: Vec| names.iter().map(|n| format!("'{n}'")).collect::>().join(", "); @@ -1528,7 +1539,7 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { d.contingent.iter().filter(|c| c.fields.iter().any(|f| names_removed(f))).map(|c| c.name.clone()).collect(); d.contingent.retain(|c| !c.fields.iter().any(|f| names_removed(f))); if !contingent.is_empty() { - design_gone.push(format!("contingent values {}", quoted(contingent))); + design_gone.push(NoticeText::format("contingent values {names}", [("names", quoted(contingent).into())])); } let ds = rustgis_data::Dataset::new(l.dataset.name.clone(), l.dataset.geometry_type, l.dataset.fields.clone()); let reads_on = |r: &rustgis_map::design::AttributeRule| { @@ -1555,10 +1566,9 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { ) }); let design_note = (!design_gone.is_empty()).then(|| { - format!( - "{}: its data design used the deleted field {removed}, so it loses {}", - l.name, - and_list(&design_gone.iter().map(String::as_str).collect::>()) + NoticeText::format( + "{layer}: its data design used the deleted field {field}, so it loses {parts}", + [("layer", l.name.clone().into()), ("field", removed.clone().into()), ("parts", and_text(design_gone))], ) }); // Nor its diagram: the field's slice or bar goes, the range of sums a scaled size grows over is @@ -1632,11 +1642,22 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { Some(format!("{}: its symbol's {} expressions read the deleted field {removed}, so they are removed", l.name, and_list(many))) } }; - for note in [extrusion_note, rotation_note, size_note, by_note, label_note, clause_note, restart_note, moved_note, design_note] - .into_iter() - .flatten() + let plain = |note: Option| note.map(NoticeText::from); + for note in [ + plain(extrusion_note), + plain(rotation_note), + plain(size_note), + plain(by_note), + plain(label_note), + clause_note, + plain(restart_note), + moved_note, + design_note, + ] + .into_iter() + .flatten() { - s.notify(note, false); + s.notify_text(note, false); } if let Some(note) = diagram_note { s.notify(note, false); @@ -1694,22 +1715,47 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { s.notify(note, false); } // Nor the reports on the layer, when a twin is left that they would go on to read: what they - // named the deleted field by goes, said once a report (#1955). + // named the deleted field by goes, said once a report (#1955). Only a report that reads this + // layer ([`super::report::names_layer`]); one whose layer name another map has too may be + // meant for that layer, which still has the field: kept as it is, and said. if twin_left { let mut report_notes = Vec::new(); - for r in s.project.reports.iter_mut().filter(|r| r.layer.eq_ignore_ascii_case(&layer_name)) { + let reads: Vec<(bool, bool)> = s + .project + .reports + .iter() + .map(|r| (super::report::names_layer(s, &r.layer, id), super::report::named_elsewhere(s, &r.layer))) + .collect(); + for (r, (ours, elsewhere)) in s.project.reports.iter_mut().zip(reads) { + if !ours { + continue; + } + if elsewhere { + let names = r.fields.iter().chain(&r.groups).chain(r.stats.iter().map(|x| &x.field)).any(|f| names_removed(f)) + || [&r.sort, &r.picture_field, &r.attachments_field].into_iter().any(|f| f.as_deref().is_some_and(names_removed)) + || r.chart.as_ref().is_some_and(|c| names_removed(&c.category) || c.value.as_deref().is_some_and(names_removed)); + if names { + report_notes.push(NoticeText::format( + "{report}: it names the deleted field {field}, which on this map it would read as its twin; another map has a layer named {layer} too, so the report is kept as it is", + [("report", r.name.clone().into()), ("field", removed.clone().into()), ("layer", r.layer.clone().into())], + )); + } + continue; + } let mut gone = Vec::new(); let (fields, groups, stats) = (r.fields.len(), r.groups.len(), r.stats.len()); r.fields.retain(|f| !names_removed(f)); r.groups.retain(|f| !names_removed(f)); r.stats.retain(|x| !names_removed(&x.field)); - for (before, after, what) in - [(fields, r.fields.len(), "field"), (groups, r.groups.len(), "group"), (stats, r.stats.len(), "statistic")] - { + for (before, after, one, many) in [ + (fields, r.fields.len(), "a field", "{count} fields"), + (groups, r.groups.len(), "a group", "{count} groups"), + (stats, r.stats.len(), "a statistic", "{count} statistics"), + ] { match before.saturating_sub(after) { 0 => {} - 1 => gone.push(format!("a {what}")), - n => gone.push(format!("{n} {what}s")), + 1 => gone.push(NoticeText::term(one)), + n => gone.push(NoticeText::format(many, [("count", n.to_string().into())])), } } for (slot, what) in [ @@ -1719,28 +1765,36 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { ] { if slot.as_deref().is_some_and(names_removed) { *slot = None; - gone.push(what.to_string()); + gone.push(NoticeText::term(what)); } } if r.chart.as_ref().is_some_and(|c| names_removed(&c.category) || c.value.as_deref().is_some_and(names_removed)) { r.chart = None; - gone.push("its chart".to_string()); + gone.push(NoticeText::term("its chart")); } if !gone.is_empty() { - report_notes.push(format!( - "{}: it named the deleted field {removed} in {}, so they are removed", - r.name, - and_list(&gone.iter().map(String::as_str).collect::>()) + report_notes.push(NoticeText::format( + "{report}: it named the deleted field {field} in {parts}, so they are removed", + [("report", r.name.clone().into()), ("field", removed.clone().into()), ("parts", and_text(gone))], )); } } for note in report_notes { - s.notify(note, false); + s.notify_text(note, false); } } Ok(json!({"rulesRemoved": removed_rules})) } +/// [`and_list`] of translatable parts: `a`, `a and b`, `a, b and c`. +fn and_text(mut parts: Vec) -> NoticeText { + match parts.pop() { + None => String::new().into(), + Some(last) if parts.is_empty() => last, + Some(last) => NoticeText::format("{rest} and {last}", [("rest", NoticeText::list(parts)), ("last", last)]), + } +} + /// `a`, `a and b`, `a, b and c`. fn and_list(parts: &[&str]) -> String { match parts.split_last() { @@ -3003,6 +3057,43 @@ mod tests { } } + /// A report whose layer name another map has too may be meant for that map's layer, which still + /// has the field: deleting the first twin here keeps the report as it is, and says so; a report + /// on another layer is left alone (#1955). + #[test] + fn deleting_a_twin_keeps_a_report_another_map_may_read() { + let mut s = Session::new(crate::Project::default()); + let twins = |name: &str, fields: &[&str]| { + let mut ds = Dataset::new(name, GeometryType::Point, fields.iter().map(|f| Field::new(*f, FieldType::Double)).collect()); + ds.push(Some(Geometry::Point(rustgis_data::Coord::new(1.0, 1.0))), vec![Value::Float(1.0); fields.len()]); + ds + }; + s.map_mut().add_dataset(twins("twins", &["Pop", "pop", "n"])); + s.map_mut().add_dataset(twins("other", &["Pop", "n"])); + for (report, layer) in [("R", "twins"), ("O", "other")] { + s.run("report.new", &json!({"layer": layer, "name": report, "fields": ["n"]})).unwrap(); + } + for r in &mut s.project.reports { + r.fields.push("Pop".into()); + r.sort = Some("Pop".into()); + } + s.run("map.new", &json!({"name": "Second"})).unwrap(); + s.map_mut().add_dataset(twins("twins", &["Pop", "n"])); + s.run("map.activate", &json!({"name": "Map"})).unwrap(); + let mark = s.notice_mark(); + s.run("edit.deleteField", &json!({"layer": "twins", "field": "Pop"})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + for r in &s.project.reports { + assert!(r.fields == ["n", "Pop"] && r.sort.as_deref() == Some("Pop"), "{}: {:?}", r.name, r.fields); + } + assert!( + said.iter().any(|n| n + == "R: it names the deleted field Pop, which on this map it would read as its twin; another map has a layer named twins too, so the report is kept as it is"), + "{said:?}" + ); + assert!(said.iter().all(|n| !n.starts_with("O:")), "{said:?}"); + } + /// Deleting a field removes the label class clauses that read it and would go on to read its /// twin, said: with fields `Pop` and `pop`, `pop > 1` reads `Pop`, and deleting `Pop` would /// otherwise leave it reading `pop`. A clause that read another field is kept, and nothing is diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index f0fe5dc511..f90f728d9e 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -10,6 +10,7 @@ use rustgis_map::symbology::fmt_num; use serde_json::{Value, json}; use super::{b, f, ps}; +use crate::notice_text::NoticeText; use crate::{CmdResult, CommandSpec as C, Session}; /// Report files and report templates: JSON with these extensions. @@ -153,7 +154,7 @@ pub fn commands() -> Vec { s.notify(format!("{report}: the first {MAX_ITEMS} of the layer's {all} fields are filled in"), false); } if let Some(note) = twins_left_out(&report, &twins) { - s.notify(note, false); + s.notify_text(note, false); } Ok(answer) }).inputs(layer_inputs).roles(&[]).effects(crate::policy::Effects::NONE) @@ -335,13 +336,15 @@ fn filled_in(ds: &rustgis_data::Dataset) -> FilledIn { /// The notice for the fields [`filled_in`] left out of report `report`, if any: the first /// [`TWINS_NAMED`] named, the rest counted. -fn twins_left_out(report: &str, twins: &[String]) -> Option { +fn twins_left_out(report: &str, twins: &[String]) -> Option { (!twins.is_empty()).then(|| { - let shown = twins.iter().take(TWINS_NAMED).map(String::as_str).collect::>().join(", "); + let shown: NoticeText = twins.iter().take(TWINS_NAMED).map(String::as_str).collect::>().join(", ").into(); let more = twins.len().saturating_sub(TWINS_NAMED); - let tail = if more > 0 { format!(", and {more} more") } else { String::new() }; - format!( - "{report}: fields named the same but for case are left out ({shown}{tail}): a report reads its field by name ignoring case, so it would use the first" + let shown = + if more > 0 { NoticeText::format("{names}, and {count} more", [("names", shown), ("count", more.to_string().into())]) } else { shown }; + NoticeText::format( + "{report}: fields named the same but for case are left out ({names}): a report reads its field by name ignoring case, so it would use the first", + [("report", report.to_string().into()), ("names", shown)], ) }) } @@ -396,7 +399,6 @@ struct Fitted { impl Fitted { /// Publishes only completed changes, with literal report names and translated operation text. fn notify(self, s: &mut Session, name: &str, when: &'static str) { - use crate::notice_text::NoticeText; for (n, key) in [ (self.fields, "{name}: {n} report column(s) missing from the layer removed {when}"), (self.groups, "{name}: {n} report grouping field(s) missing from the layer removed {when}"), @@ -576,7 +578,7 @@ fn new_report(s: &mut Session, p: &Value) -> CmdResult { s.notify(format!("{name}: the report lists the first {MAX_ITEMS} of the layer's {all} fields"), false); } if let Some(note) = twins_left_out(&name, &twins) { - s.notify(note, false); + s.notify_text(note, false); } if let Some(cut) = cut { s.notify(cut, false); @@ -1376,6 +1378,18 @@ fn import_layer(input: &impl super::InputSource, p: &Value, r: &mut Report) -> R } /// Finds a literal feature layer active-map first, then in project order. +/// Whether a report naming layer `name` reads layer `id` of the active map, resolved as +/// [`find_layer_map`] resolves it: a same-named layer of another map is another layer. +pub(super) fn names_layer(s: &Session, name: &str, id: u32) -> bool { + find_layer_map(s, name).is_some_and(|(map, layer)| std::ptr::eq(map, s.map()) && layer.id == id) +} + +/// Whether a map other than the active one has a layer named `name`, which a report naming it +/// reads while that map is active. +pub(super) fn named_elsewhere(s: &Session, name: &str) -> bool { + s.project.maps.iter().filter(|m| !std::ptr::eq(*m, s.map())).any(|m| m.layer_by_name(name).is_some()) +} + fn find_layer_map<'a>(input: &'a impl super::InputSource, name: &str) -> Option<(&'a rustgis_map::Map, &'a Layer)> { let context = input.input_context(); let s = &context; From 74e415efe4b9e7860dfe93cb26ec18c157b79bf8 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:18:12 -0600 Subject: [PATCH 20/24] fix(engine): a stored twin name is kept only by its own label class or report field, and the report count says what it counts (#1955) --- crates/engine/src/cmd/edit.rs | 40 ++++++++++++++- crates/engine/src/cmd/layer.rs | 8 +-- crates/engine/src/cmd/report.rs | 88 +++++++++++++++++++++++++++------ 3 files changed, 115 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index bfb85349b8..329efe0d11 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -2910,12 +2910,12 @@ mod tests { s.run("report.new", &json!({"layer": "wide", "name": "R"})).unwrap(); assert_eq!(s.project.reports[1].fields.len(), 64); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - assert!(said.iter().any(|n| n == "R: the report lists the first 64 of the layer's 66 fields"), "{said:?}"); + assert!(said.iter().any(|n| n == "R: the report lists the first 64 of the layer's 66 fields without a case twin"), "{said:?}"); assert!(said.iter().any(|n| n.starts_with("R: fields named the same but for case are left out (Pop, pop)")), "{said:?}"); let mark = s.notice_mark(); s.run("report.autofill", &json!({"report": "R"})).unwrap(); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - assert!(said.iter().any(|n| n == "R: the first 64 of the layer's 66 fields are filled in"), "{said:?}"); + assert!(said.iter().any(|n| n == "R: the first 64 of the layer's 66 fields without a case twin are filled in"), "{said:?}"); assert!(said.iter().any(|n| n.contains("(Pop, pop)")), "{said:?}"); // Nothing to remove: refused, naming it; there to remove: removed. for (command, extra, error) in [ @@ -3020,6 +3020,42 @@ mod tests { assert_eq!(s.project.reports[0].sort.as_deref(), Some("v")); } + /// A twin's name a setting stores already is kept only by that setting: a label class's own, + /// not another class's, and a report's own chart, picture and attachments fields; a twin's + /// name given anew is refused (#1955). + #[test] + fn a_stored_twin_name_is_kept_only_by_its_own_setting() { + let mut s = Session::new(crate::Project::default()); + let mut ds = Dataset::new("twins", GeometryType::Point, ["X", "x", "v"].map(|f| Field::new(f, FieldType::Double)).to_vec()); + ds.push(Some(Geometry::Point(rustgis_data::Coord::new(1.0, 1.0))), vec![Value::Float(1.0); 3]); + let id = s.map_mut().add_dataset(ds); + s.run("labels.class.add", &json!({"layer": id, "name": "A"})).unwrap(); + s.run("labels.class.add", &json!({"layer": id, "name": "B"})).unwrap(); + s.run("report.new", &json!({"layer": "twins", "name": "R", "fields": ["v"]})).unwrap(); + // As an older project stored them. + let l = s.map_mut().layer_mut(id).unwrap(); + l.labels.class_mut("A").unwrap().field = "x".into(); + let r = &mut s.project.reports[0]; + (r.picture_field, r.attachments_field) = (Some("x".into()), Some("x".into())); + r.chart = Some(rustgis_map::report::ReportChart { category: "x".into(), value: Some("x".into()) }); + let twin = |error: String| assert!(error.contains("names 'X' and 'x' ignoring case"), "{error}"); + // Another class's stored name is a name given anew to B. + twin(s.run("labels.field", &json!({"layer": id, "class": "B", "field": "x"})).unwrap_err()); + s.run("labels.field", &json!({"layer": id, "class": "A", "field": "x"})).unwrap(); + // The report's own, sent again as stored: kept. + s.run("report.dynamicPicture", &json!({"report": "R", "field": "x"})).unwrap(); + s.run("report.attachments", &json!({"report": "R", "field": "x"})).unwrap(); + s.run("report.chart", &json!({"report": "R", "category": "x", "value": "x"})).unwrap(); + let r = &s.project.reports[0]; + assert_eq!((r.picture_field.as_deref(), r.attachments_field.as_deref()), (Some("x"), Some("x"))); + assert_eq!(r.chart.as_ref().map(|c| (c.category.as_str(), c.value.as_deref())), Some(("x", Some("x")))); + // The other twin's name, given anew: refused. + twin(s.run("report.dynamicPicture", &json!({"report": "R", "field": "X"})).unwrap_err()); + twin(s.run("report.attachments", &json!({"report": "R", "field": "X"})).unwrap_err()); + twin(s.run("report.chart", &json!({"report": "R", "category": "X"})).unwrap_err()); + twin(s.run("report.chart", &json!({"report": "R", "category": "x", "value": "X"})).unwrap_err()); + } + /// Deleting the first of two twins a report on the layer named (fields, groups, statistics, /// sort, chart, picture and attachments) removes what named it, said once a report, as it would /// read the other twin; deleting the second twin, which nothing read, or a field without a diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index ae563b0ef7..36d56c4e91 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -520,9 +520,11 @@ pub fn commands() -> Vec { let name = s_req(p, "field")?.to_string(); let id = s.layer_id(p)?; let l = s.map().layer(id).ok_or("no such layer")?; - // A field a class labels with already, as stored, or one named anew (a case twin's name - // refused, as it would read the first twin; #1955). - let own = std::iter::once(&l.labels.default).chain(&l.labels.classes).any(|c| c.field == name); + // The field the class labels with already, as stored, or one named anew (a case twin's + // name refused, as it would read the first twin; #1955). Only the class given: another + // class's stored name is a name given anew to this one. + let mut probe = l.labels.clone(); + let own = super::labels::class_in(&mut probe, p)?.field == name; let fi = if own { l.dataset.field_index(&name) } else { super::edit::kept_field(&l.dataset, &name, "a label class")? }; let fname = fi.and_then(|i| l.dataset.fields.get(i)).map(|f| f.name.clone()); let fname = fname.ok_or_else(|| format!("no field named '{name}'"))?; diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index f90f728d9e..a48693dc06 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -149,9 +149,16 @@ pub fn commands() -> Vec { r.fields = names; let (answer, report) = (json!({"fields": r.fields}), r.name.clone()); // A layer with more fields than a report takes: the first are filled in, and that is - // said (#1896), with the layer's own count of fields. + // said (#1896), with the count of the layer's fields a report may take (those without + // a case twin, which are said apart). if full { - s.notify(format!("{report}: the first {MAX_ITEMS} of the layer's {all} fields are filled in"), false); + let key = if twins.is_empty() { + "{report}: the first {count} of the layer's {all} fields are filled in" + } else { + "{report}: the first {count} of the layer's {all} fields without a case twin are filled in" + }; + let args = [("report", report.clone().into()), ("count", MAX_ITEMS.to_string().into()), ("all", all.to_string().into())]; + s.notify_text(NoticeText::format(key, args), false); } if let Some(note) = twins_left_out(&report, &twins) { s.notify_text(note, false); @@ -198,19 +205,19 @@ pub fn commands() -> Vec { .when(need_report) .params(r#"{"report"?, "field": name, "remove"?: bool}"#), C::new("report.attachments", "Attachments", "Data › Data Design", |s, p| { - let (i, field) = optional_field(s, p)?; + let (i, field) = optional_field(s, p, own_attachments)?; let r = s.project.reports.get_mut(i).ok_or("no report")?; r.attachments_field = field; Ok(json!({"field": r.attachments_field})) - }).inputs(optional_inputs).roles(&[]).effects(crate::policy::Effects::NONE) + }).inputs(attachments_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_report) .params(r#"{"report"?, "field": name of a field listing each record's attachments (paths separated by ';')|null}"#), C::new("report.dynamicPicture", "Dynamic Picture", "Data › Data Design", |s, p| { - let (i, field) = optional_field(s, p)?; + let (i, field) = optional_field(s, p, own_picture)?; let r = s.project.reports.get_mut(i).ok_or("no report")?; r.picture_field = field; Ok(json!({"field": r.picture_field})) - }).inputs(optional_inputs).roles(&[]).effects(crate::policy::Effects::NONE) + }).inputs(picture_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_report) .params(r#"{"report"?, "field": name of a field holding a picture path or base64 PNG/JPEG|null}"#), C::new("report.chart", "Chart Frame", "Data › Data Design", |s, p| { @@ -218,9 +225,9 @@ pub fn commands() -> Vec { let chart = match p.get("category") { None | Some(Value::Null) => None, Some(_) => { - let (_, category) = field_of(s, p, "category")?; + let (_, category) = own_field_of(s, p, "category", own_category)?; let value = match ps(p, "value") { - Some(_) => Some(field_of(s, p, "value")?.1), + Some(_) => Some(own_field_of(s, p, "value", own_value)?.1), None => None, }; Some(ReportChart { category, value }) @@ -296,11 +303,43 @@ fn field_of(input: &impl super::InputSource, p: &Value, key: &str) -> Result<(us Ok((i, field)) } -/// `field` as a field of the report's layer, or `None` for null/absent. -fn optional_field(input: &impl super::InputSource, p: &Value) -> Result<(usize, Option), String> { +/// What a report stores already for a command's field ([`own_field_of`]). +type Own = fn(&Report) -> Option<&str>; + +fn own_attachments(r: &Report) -> Option<&str> { + r.attachments_field.as_deref() +} + +fn own_picture(r: &Report) -> Option<&str> { + r.picture_field.as_deref() +} + +fn own_category(r: &Report) -> Option<&str> { + r.chart.as_ref().map(|c| c.category.as_str()) +} + +fn own_value(r: &Report) -> Option<&str> { + r.chart.as_ref().and_then(|c| c.value.as_deref()) +} + +/// [`field_of`], except that the name the report stores already for it (`own`), given again as +/// stored, is kept as it is: a case twin's name an older project stored can be set again, as +/// report.update's sort can; a twin's name given anew is refused (#1955). +fn own_field_of(input: &impl super::InputSource, p: &Value, key: &str, own: Own) -> Result<(usize, String), String> { + let i = index_input(input, p)?; + let name = ps(p, key).ok_or_else(|| format!("{key} is required"))?; + let context = input.input_context(); + if context.project.reports.get(i).and_then(own) == Some(name) { + return Ok((i, name.to_string())); + } + field_of(input, p, key) +} + +/// `field` as a field of the report's layer ([`own_field_of`]), or `None` for null/absent. +fn optional_field(input: &impl super::InputSource, p: &Value, own: Own) -> Result<(usize, Option), String> { match p.get("field") { None | Some(Value::Null) => Ok((index_input(input, p)?, None)), - Some(_) => field_of(input, p, "field").map(|(i, f)| (i, Some(f))), + Some(_) => own_field_of(input, p, "field", own).map(|(i, f)| (i, Some(f))), } } @@ -575,7 +614,14 @@ fn new_report(s: &mut Session, p: &Value) -> CmdResult { let i = s.project.reports.len() - 1; s.active_report = Some(i); if first_of { - s.notify(format!("{name}: the report lists the first {MAX_ITEMS} of the layer's {all} fields"), false); + // Counting the fields a report may take: those without a case twin, said apart. + let key = if twins.is_empty() { + "{report}: the report lists the first {count} of the layer's {all} fields" + } else { + "{report}: the report lists the first {count} of the layer's {all} fields without a case twin" + }; + let args = [("report", name.clone().into()), ("count", MAX_ITEMS.to_string().into()), ("all", all.to_string().into())]; + s.notify_text(NoticeText::format(key, args), false); } if let Some(note) = twins_left_out(&name, &twins) { s.notify_text(note, false); @@ -1377,7 +1423,6 @@ fn import_layer(input: &impl super::InputSource, p: &Value, r: &mut Report) -> R Ok(()) } -/// Finds a literal feature layer active-map first, then in project order. /// Whether a report naming layer `name` reads layer `id` of the active map, resolved as /// [`find_layer_map`] resolves it: a same-named layer of another map is another layer. pub(super) fn names_layer(s: &Session, name: &str, id: u32) -> bool { @@ -1390,6 +1435,7 @@ pub(super) fn named_elsewhere(s: &Session, name: &str) -> bool { s.project.maps.iter().filter(|m| !std::ptr::eq(*m, s.map())).any(|m| m.layer_by_name(name).is_some()) } +/// Finds a literal feature layer active-map first, then in project order. fn find_layer_map<'a>(input: &'a impl super::InputSource, name: &str) -> Option<(&'a rustgis_map::Map, &'a Layer)> { let context = input.input_context(); let s = &context; @@ -1414,9 +1460,19 @@ fn layer_inputs(input: &super::InputContext<'_>, p: &Value) -> Result, p: &Value) -> Result { + optional_inputs(input, p, own_attachments) +} + +/// [`optional_inputs`] of report.dynamicPicture. +fn picture_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { + optional_inputs(input, p, own_picture) +} + /// Binds a field-dependent layer only when an optional field is actually supplied. -fn optional_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { - let (i, field) = optional_field(input, p)?; +fn optional_inputs(input: &super::InputContext<'_>, p: &Value, own: Own) -> Result { + let (i, field) = optional_field(input, p, own)?; let mut inputs = if field.is_some() { owning_inputs(input, layer_of_input(input, i)?) } else { super::Inputs::layers(std::iter::empty()) }; inputs.extend(object_inputs(input, p)?); @@ -1427,7 +1483,7 @@ fn chart_inputs(input: &super::InputContext<'_>, p: &Value) -> Result Date: Sat, 28 Nov 2026 18:44:18 -0600 Subject: [PATCH 21/24] fix(engine): a stored twin name set again must still be a field, and a label class keeps it as stored (#1955) --- crates/engine/src/cmd/edit.rs | 15 +++++++++++++++ crates/engine/src/cmd/layer.rs | 8 ++++++-- crates/engine/src/cmd/report.rs | 5 +++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 329efe0d11..172504fe66 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -3042,6 +3042,7 @@ mod tests { // Another class's stored name is a name given anew to B. twin(s.run("labels.field", &json!({"layer": id, "class": "B", "field": "x"})).unwrap_err()); s.run("labels.field", &json!({"layer": id, "class": "A", "field": "x"})).unwrap(); + assert_eq!(s.map().layer(id).unwrap().labels.class("A").map(|c| c.field.as_str()), Some("x"), "kept as stored"); // The report's own, sent again as stored: kept. s.run("report.dynamicPicture", &json!({"report": "R", "field": "x"})).unwrap(); s.run("report.attachments", &json!({"report": "R", "field": "x"})).unwrap(); @@ -3054,6 +3055,20 @@ mod tests { twin(s.run("report.attachments", &json!({"report": "R", "field": "X"})).unwrap_err()); twin(s.run("report.chart", &json!({"report": "R", "category": "X"})).unwrap_err()); twin(s.run("report.chart", &json!({"report": "R", "category": "x", "value": "X"})).unwrap_err()); + // A stored name the layer no longer has: refused, as before. + let r = &mut s.project.reports[0]; + (r.picture_field, r.attachments_field) = (Some("gone".into()), Some("gone".into())); + r.chart = Some(rustgis_map::report::ReportChart { category: "gone".into(), value: None }); + for (command, p) in [ + ("report.dynamicPicture", json!({"report": "R", "field": "gone"})), + ("report.attachments", json!({"report": "R", "field": "gone"})), + ("report.chart", json!({"report": "R", "category": "gone"})), + ] { + let error = s.run(command, &p).unwrap_err(); + assert!(error.contains("has no field 'gone'"), "{command}: {error}"); + } + s.map_mut().layer_mut(id).unwrap().labels.class_mut("A").unwrap().field = "gone".into(); + assert!(s.run("labels.field", &json!({"layer": id, "class": "A", "field": "gone"})).unwrap_err().contains("no field named 'gone'")); } /// Deleting the first of two twins a report on the layer named (fields, groups, statistics, diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 36d56c4e91..8cbb0827de 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -525,8 +525,12 @@ pub fn commands() -> Vec { // class's stored name is a name given anew to this one. let mut probe = l.labels.clone(); let own = super::labels::class_in(&mut probe, p)?.field == name; - let fi = if own { l.dataset.field_index(&name) } else { super::edit::kept_field(&l.dataset, &name, "a label class")? }; - let fname = fi.and_then(|i| l.dataset.fields.get(i)).map(|f| f.name.clone()); + // Its own stays as stored (a field of the layer still), not respelled as the first twin. + let fname = if own { + l.dataset.field_index(&name).map(|_| name.clone()) + } else { + super::edit::kept_field(&l.dataset, &name, "a label class")?.and_then(|i| l.dataset.fields.get(i)).map(|f| f.name.clone()) + }; let fname = fname.ok_or_else(|| format!("no field named '{name}'"))?; super::labels::with_labels(s, p, |labels| { super::labels::class_in(labels, p)?.field = fname; diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index a48693dc06..10da4455e6 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -330,6 +330,11 @@ fn own_field_of(input: &impl super::InputSource, p: &Value, key: &str, own: Own) let name = ps(p, key).ok_or_else(|| format!("{key} is required"))?; let context = input.input_context(); if context.project.reports.get(i).and_then(own) == Some(name) { + // Still a field of the layer: only the twin refusal is skipped. + let l = layer_of_input(input, i)?; + if l.dataset.field_index(name).is_none() { + return Err(format!("'{}' has no field '{name}'", l.name)); + } return Ok((i, name.to_string())); } field_of(input, p, key) From 20681c0f560719c9ddc8c1e2b0dc647bd028a6b3 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:42:56 -0600 Subject: [PATCH 22/24] fix(engine): a template leaves out twin defaults and says which, and a stored sort must still be a field (#1955) --- crates/engine/src/cmd/design.rs | 20 +++++++++++++++- crates/engine/src/cmd/edit.rs | 42 ++++++++++++++++++++++++++++++++- crates/engine/src/cmd/layer.rs | 8 +++++-- crates/engine/src/cmd/report.rs | 9 +++++-- 4 files changed, 73 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index ab24eb2b38..a20fff41ff 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2614,8 +2614,16 @@ fn template(s: &mut Session, p: &Json) -> CmdResult { return if l.design.templates.len() == before { Err(format!("no template '{name}'")) } else { Ok(Json::Null) }; } let mut defaults = Vec::new(); + // A field with a case twin is left out, and said: a default reads its field by name ignoring + // case, so it would fill the first twin. From Selection sends every field of the feature it + // copies, so refusing would refuse the whole template (#1955). + let mut twins = Vec::new(); if let Some(o) = p.get("defaults").and_then(Json::as_object) { for (k, v) in o { + if l.dataset.has_case_twin(k) { + twins.push(k.clone()); + continue; + } let fi = design_field(&l.dataset, k, "a template default")?; let ty = l.dataset.fields.get(fi).map(|f| f.ty).unwrap_or(FieldType::Text); let coerced = super::edit::held_default(k, &Value::from_json(v), ty)?; @@ -2626,7 +2634,17 @@ fn template(s: &mut Session, p: &Json) -> CmdResult { let description = super::within("description", "a template's description", ps(p, "description").unwrap_or(""), 500)?; l.design.templates.retain(|t| !t.name.eq_ignore_ascii_case(&name)); l.design.templates.push(FeatureTemplate { name: name.clone(), description, defaults }); - Ok(json!({"template": name, "templates": l.design.templates.len()})) + let (answer, layer) = (json!({"template": name, "templates": l.design.templates.len()}), l.name.clone()); + if !twins.is_empty() { + s.notify_text( + crate::notice_text::NoticeText::format( + "{layer}: fields named the same but for case are left out of template {template} ({names}): a template default reads its field by name ignoring case, so it would fill the first", + [("layer", layer.into()), ("template", name.into()), ("names", twins.join(", ").into())], + ), + false, + ); + } + Ok(answer) } /// The nearest vertex, line end or edge of a visible feature layer within the snapping tolerance. diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 172504fe66..a4f93a9a24 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -3055,7 +3055,7 @@ mod tests { twin(s.run("report.attachments", &json!({"report": "R", "field": "X"})).unwrap_err()); twin(s.run("report.chart", &json!({"report": "R", "category": "X"})).unwrap_err()); twin(s.run("report.chart", &json!({"report": "R", "category": "x", "value": "X"})).unwrap_err()); - // A stored name the layer no longer has: refused, as before. + // A stored name the layer no longer has: refused, and left as it is. let r = &mut s.project.reports[0]; (r.picture_field, r.attachments_field) = (Some("gone".into()), Some("gone".into())); r.chart = Some(rustgis_map::report::ReportChart { category: "gone".into(), value: None }); @@ -3069,6 +3069,46 @@ mod tests { } s.map_mut().layer_mut(id).unwrap().labels.class_mut("A").unwrap().field = "gone".into(); assert!(s.run("labels.field", &json!({"layer": id, "class": "A", "field": "gone"})).unwrap_err().contains("no field named 'gone'")); + s.project.reports[0].sort = Some("gone".into()); + assert!(s.run("report.update", &json!({"report": "R", "sort": "gone"})).unwrap_err().contains("no field 'gone'")); + let r = &s.project.reports[0]; + assert_eq!( + (r.picture_field.as_deref(), r.attachments_field.as_deref(), r.sort.as_deref()), + (Some("gone"), Some("gone"), Some("gone")) + ); + assert_eq!(r.chart.as_ref().map(|c| c.category.as_str()), Some("gone")); + assert_eq!(s.map().layer(id).unwrap().labels.class("A").map(|c| c.field.as_str()), Some("gone")); + // Without a twin, a class's own name sent in another case is spelled as the field is. + s.map_mut().layer_mut(id).unwrap().labels.class_mut("A").unwrap().field = "V".into(); + s.run("labels.field", &json!({"layer": id, "class": "A", "field": "V"})).unwrap(); + assert_eq!(s.map().layer(id).unwrap().labels.class("A").map(|c| c.field.as_str()), Some("v")); + } + + /// A template's defaults leave out the fields with a case twin, and say which, rather than + /// refusing the template (From Selection sends every field); without twins, all are kept and + /// nothing is said (#1955). + #[test] + fn a_template_leaves_out_twin_defaults() { + for (fields, twins) in [(["Pop", "pop", "n"], true), (["Pop", "a", "n"], false)] { + let mut s = Session::new(crate::Project::default()); + let ds = Dataset::new("t", GeometryType::Point, fields.map(|f| Field::new(f, FieldType::Double)).to_vec()); + let id = s.map_mut().add_dataset(ds); + let defaults: serde_json::Map = fields.iter().map(|f| (f.to_string(), json!(1))).collect(); + let mark = s.notice_mark(); + s.run("edit.template", &json!({"layer": id, "name": "T", "defaults": defaults})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + let kept: Vec = s.map().layer(id).unwrap().design.templates[0].defaults.iter().map(|(f, _)| f.clone()).collect(); + if twins { + assert_eq!(kept, ["n"]); + assert!( + said.iter().any(|n| n.starts_with("t: fields named the same but for case are left out of template T (Pop, pop)")), + "{said:?}" + ); + } else { + assert_eq!(kept.len(), 3, "{kept:?}"); + assert!(said.iter().all(|n| !n.contains("left out of template")), "{said:?}"); + } + } } /// Deleting the first of two twins a report on the layer named (fields, groups, statistics, diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 8cbb0827de..29da6b0eb1 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -525,9 +525,13 @@ pub fn commands() -> Vec { // class's stored name is a name given anew to this one. let mut probe = l.labels.clone(); let own = super::labels::class_in(&mut probe, p)?.field == name; - // Its own stays as stored (a field of the layer still), not respelled as the first twin. - let fname = if own { + // Its own, with a case twin, stays as stored (a field of the layer still), not respelled + // as the first twin; without one, it is spelled as the field is. + let spelled = |i: usize| l.dataset.fields.get(i).map(|f| f.name.clone()); + let fname = if own && l.dataset.has_case_twin(&name) { l.dataset.field_index(&name).map(|_| name.clone()) + } else if own { + l.dataset.field_index(&name).and_then(spelled) } else { super::edit::kept_field(&l.dataset, &name, "a label class")?.and_then(|i| l.dataset.fields.get(i)).map(|f| f.name.clone()) }; diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 10da4455e6..811130cc79 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -707,8 +707,13 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { } match p.get("sort") { Some(Value::Null) => r.sort = None, - // Its own sort set again, as stored, stays. - Some(Value::String(n)) if r.sort.as_deref() == Some(n.as_str()) => {} + // Its own sort set again, as stored, stays, a field of the layer still: only the twin + // refusal is skipped. + Some(Value::String(n)) if r.sort.as_deref() == Some(n.as_str()) => { + if l.ok_or("the report's layer isn't in the project")?.dataset.field_index(n).is_none() { + return Err(format!("no field '{n}'")); + } + } Some(Value::String(n)) => r.sort = Some(field(n)?), _ => {} } From b1ad647e7627628b4ab8565856889bc00dd42121 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:50:26 -0600 Subject: [PATCH 23/24] fix(engine): the template notice counts its twins and names the first 20, and a report without its layer keeps its sort (#1955) --- crates/engine/src/cmd/design.rs | 16 +++++++++++++--- crates/engine/src/cmd/edit.rs | 21 ++++++++++++++++++++- crates/engine/src/cmd/report.rs | 5 ++++- 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index a20fff41ff..f06b542f7a 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2636,10 +2636,20 @@ fn template(s: &mut Session, p: &Json) -> CmdResult { l.design.templates.push(FeatureTemplate { name: name.clone(), description, defaults }); let (answer, layer) = (json!({"template": name, "templates": l.design.templates.len()}), l.name.clone()); if !twins.is_empty() { + use crate::notice_text::NoticeText; + // The first ones named, the rest counted, as a report's twins are. + const NAMED: usize = 20; + let shown: NoticeText = twins.iter().take(NAMED).map(String::as_str).collect::>().join(", ").into(); + let more = twins.len().saturating_sub(NAMED); + let names = if more > 0 { + NoticeText::format("{names}, and {count} more", [("names", shown), ("count", more.to_string().into())]) + } else { + shown + }; s.notify_text( - crate::notice_text::NoticeText::format( - "{layer}: fields named the same but for case are left out of template {template} ({names}): a template default reads its field by name ignoring case, so it would fill the first", - [("layer", layer.into()), ("template", name.into()), ("names", twins.join(", ").into())], + NoticeText::format( + "{layer}: {count} fields named the same but for case are left out of template {template} ({names}): a template default reads its field by name ignoring case, so it would fill the first", + [("layer", layer.into()), ("count", twins.len().to_string().into()), ("template", name.into()), ("names", names)], ), false, ); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index a4f93a9a24..875d2e4df2 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -3078,6 +3078,10 @@ mod tests { ); assert_eq!(r.chart.as_ref().map(|c| c.category.as_str()), Some("gone")); assert_eq!(s.map().layer(id).unwrap().labels.class("A").map(|c| c.field.as_str()), Some("gone")); + // Without its layer, a report's stored sort set again with another change is left as it is. + s.project.reports[0].layer = "missing".into(); + s.run("report.update", &json!({"report": "R", "name": "R2", "sort": "gone"})).unwrap(); + assert_eq!((s.project.reports[0].name.as_str(), s.project.reports[0].sort.as_deref()), ("R2", Some("gone"))); // Without a twin, a class's own name sent in another case is spelled as the field is. s.map_mut().layer_mut(id).unwrap().labels.class_mut("A").unwrap().field = "V".into(); s.run("labels.field", &json!({"layer": id, "class": "A", "field": "V"})).unwrap(); @@ -3101,7 +3105,7 @@ mod tests { if twins { assert_eq!(kept, ["n"]); assert!( - said.iter().any(|n| n.starts_with("t: fields named the same but for case are left out of template T (Pop, pop)")), + said.iter().any(|n| n.starts_with("t: 2 fields named the same but for case are left out of template T (Pop, pop)")), "{said:?}" ); } else { @@ -3109,6 +3113,21 @@ mod tests { assert!(said.iter().all(|n| !n.contains("left out of template")), "{said:?}"); } } + // Many twins: the first named, the rest counted. + let mut s = Session::new(crate::Project::default()); + let names: Vec = (0..25).flat_map(|i| [format!("T{i}"), format!("t{i}")]).collect(); + let ds = Dataset::new("t", GeometryType::Point, names.iter().map(|f| Field::new(f, FieldType::Double)).collect()); + let id = s.map_mut().add_dataset(ds); + let defaults: serde_json::Map = names.iter().map(|f| (f.clone(), json!(1))).collect(); + let mark = s.notice_mark(); + s.run("edit.template", &json!({"layer": id, "name": "T", "defaults": defaults})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!( + said.iter() + .any(|n| n.starts_with("t: 50 fields named the same but for case are left out of template T (") + && n.contains(", and 30 more)")), + "{said:?}" + ); } /// Deleting the first of two twins a report on the layer named (fields, groups, statistics, diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 811130cc79..515147e23e 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -709,8 +709,11 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { Some(Value::Null) => r.sort = None, // Its own sort set again, as stored, stays, a field of the layer still: only the twin // refusal is skipped. + // (Without its layer, as before, it is left as it is.) Some(Value::String(n)) if r.sort.as_deref() == Some(n.as_str()) => { - if l.ok_or("the report's layer isn't in the project")?.dataset.field_index(n).is_none() { + if let Some(layer) = l + && layer.dataset.field_index(n).is_none() + { return Err(format!("no field '{n}'")); } } From 5686b7a1ed9a0251b46e9c7451a2410629604ffb Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 30 Nov 2026 09:53:09 -0600 Subject: [PATCH 24/24] fix(engine): the template twins notice is singular for one field (#1955) --- crates/engine/src/cmd/design.rs | 7 ++++++- crates/engine/src/cmd/edit.rs | 11 +++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index f06b542f7a..eef08e7e27 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2646,9 +2646,14 @@ fn template(s: &mut Session, p: &Json) -> CmdResult { } else { shown }; + let key = if twins.len() == 1 { + "{layer}: {count} field named the same as another but for case is left out of template {template} ({names}): a template default reads its field by name ignoring case, so it would fill the first" + } else { + "{layer}: {count} fields named the same but for case are left out of template {template} ({names}): a template default reads its field by name ignoring case, so it would fill the first" + }; s.notify_text( NoticeText::format( - "{layer}: {count} fields named the same but for case are left out of template {template} ({names}): a template default reads its field by name ignoring case, so it would fill the first", + key, [("layer", layer.into()), ("count", twins.len().to_string().into()), ("template", name.into()), ("names", names)], ), false, diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 875d2e4df2..b4de95ea8d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -3113,6 +3113,17 @@ mod tests { assert!(said.iter().all(|n| !n.contains("left out of template")), "{said:?}"); } } + // One twin key given (the other twin left out of the defaults): said in the singular. + let mut s = Session::new(crate::Project::default()); + let ds = Dataset::new("t", GeometryType::Point, ["Pop", "pop", "n"].map(|f| Field::new(f, FieldType::Double)).to_vec()); + let id = s.map_mut().add_dataset(ds); + let mark = s.notice_mark(); + s.run("edit.template", &json!({"layer": id, "name": "T", "defaults": {"POP": 1, "n": 1}})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!( + said.iter().any(|n| n.starts_with("t: 1 field named the same as another but for case is left out of template T (POP)")), + "{said:?}" + ); // Many twins: the first named, the rest counted. let mut s = Session::new(crate::Project::default()); let names: Vec = (0..25).flat_map(|i| [format!("T{i}"), format!("t{i}")]).collect();