diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 457003c733..eafc44e84c 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1625,26 +1625,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 { - 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); - } - } - 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 ") - )) - } - } + 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 8f2258725f..4e7b7368d6 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -1098,6 +1098,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`. @@ -1125,11 +1149,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.value(row, field) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 15459ccde4..eef08e7e27 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2230,17 +2230,27 @@ fn traverse(s: &mut Session, p: &Json) -> CmdResult { super::edit::add_feature(s, &json!({"layer": id, "geometry": g})) } +/// 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: &'static 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); } + 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) { // A code its field can't hold as given is refused, not cut to another or left out. let mut pairs: Vec<(Value, String)> = Vec::new(); @@ -2287,7 +2297,7 @@ 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")?; if f.ty != FieldType::Integer { return Err(format!("{} must be an integer field to hold subtype codes", f.name)); @@ -2305,7 +2315,10 @@ 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 &mut defaults { - 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) + { *value = super::edit::held_default(field, value, ty)?; } } @@ -2388,12 +2401,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")?; + 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)?; @@ -2422,11 +2432,8 @@ fn contingent(s: &mut Session, p: &Json) -> CmdResult { .iter() .map(|v| { let n = v.as_str().ok_or("fields are names")?; - 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 { @@ -2549,7 +2556,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)?; @@ -2606,9 +2614,17 @@ 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 { - let fi = l.dataset.field_index(k).ok_or_else(|| format!("no field named '{k}'"))?; + 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)?; defaults.push((l.dataset.fields.get(fi).map(|f| f.name.clone()).unwrap_or_default(), coerced)); @@ -2618,7 +2634,32 @@ 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() { + 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 + }; + 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( + key, + [("layer", layer.into()), ("count", twins.len().to_string().into()), ("template", name.into()), ("names", names)], + ), + 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/diagram.rs b/crates/engine/src/cmd/diagram.rs index 09d31f5c8a..d95dcc758d 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 = l.dataset.field_index(field).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 50c24f0217..b4de95ea8d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -22,7 +22,7 @@ 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.addPoint", "Create Point by Coordinates", "Edit › Features", add_point).inputs(point_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"x": number or degrees text, "y": number or degrees text, "crs"?: coordinate system|"map"|layer name (omitted: longitude/latitude, including degrees text), "layer"?: name|id (otherwise the active loaded point layer, or a new Points layer), "name"?: text (requires a text field named name in an existing layer)}"#), C::new("edit.addFeature", "Create Feature", "Edit › Features", add_feature).inputs(super::design::new_feature_inputs).roles(&[]).effects(crate::policy::Effects::NONE) @@ -31,19 +31,19 @@ pub fn commands() -> Vec { 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) @@ -219,10 +219,30 @@ 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 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: &'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(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)) } /// A table's rows change only while editing is on, as a layer's features do @@ -341,11 +361,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(); @@ -354,20 +374,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!("attributes: {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()), @@ -1094,9 +1110,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 { @@ -1175,12 +1192,17 @@ fn check_layer_dates(s: &Session, id: u32, fi: usize, ty: FieldType) -> Result 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)); @@ -1345,8 +1380,20 @@ 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 + // 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); + // 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 { if fi < f.attrs.len() { @@ -1355,9 +1402,10 @@ 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(|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()); } @@ -1380,6 +1428,28 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { label_gone.push((format!("{}'s {}", c.name, and_list(&gone)), gone.len())); } } + // 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.visible = false; + clauses_gone.push(c.name.clone()); + } + } + let clause_note = (!clauses_gone.is_empty()).then(|| { + 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() { [] => None, [(one, n)] => { @@ -1396,9 +1466,9 @@ 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; a class whose clause would read its twin was turned off above. 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(); @@ -1416,35 +1486,75 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { }); } } - l.labels.repoint_missing_fields(&l.dataset); + // 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 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() => NoticeText::format("field {field}", [("field", f.to_string().into())]), + _ => NoticeText::term("no field"), + }; + 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. - // 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; - 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)) { + 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(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(NoticeText::term("the subtypes")); } if let Some(st) = &mut d.subtypes { + let mut defaults = 0; for sub in &mut st.subtypes { - sub.defaults.retain(|(f, _)| !f.eq_ignore_ascii_case(&removed)); + let before = sub.defaults.len(); + sub.defaults.retain(|(f, _)| !names_removed(f)); + defaults += before - sub.defaults.len(); + } + match defaults { + 0 => {} + 1 => design_gone.push(NoticeText::term("1 subtype default")), + n => design_gone.push(NoticeText::format("{count} subtype defaults", [("count", n.to_string().into())])), } } - d.contingent.retain(|c| !c.fields.iter().any(|f| f.eq_ignore_ascii_case(&removed))); + 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(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()); - // The rules that no longer read without the field are removed, by name, and said below. - let mut dropped: Vec = Vec::new(); - d.rules.retain(|r| { - let reads = !r.field.eq_ignore_ascii_case(&removed) + 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(), - }; - if !reads { - dropped.push(r.name.clone()); - } - reads - }); + } + }; + // The rules that read the field (judged before it went) or no longer read without it are + // removed, by name, and said below. + let keep: Vec = d.rules.iter().zip(&rules_read).map(|(r, read)| !read && reads_on(r)).collect(); + let mut dropped: 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 = dropped.len(); let rules_note = (!dropped.is_empty()).then(|| { dropped.sort(); @@ -1455,13 +1565,19 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { dropped.join(", ") ) }); + let design_note = (!design_gone.is_empty()).then(|| { + 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 // 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)); @@ -1479,7 +1595,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); } @@ -1491,12 +1607,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)); } @@ -1526,8 +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, restart_note].into_iter().flatten() { - s.notify(note, false); + 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_text(note, false); } if let Some(note) = diagram_note { s.notify(note, false); @@ -1540,7 +1670,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( @@ -1555,7 +1685,7 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { && t.water.as_ref().is_some_and(|w| w.layer.eq_ignore_ascii_case(&layer_name)) && let Some(b) = t.block.as_mut() && let Some(bw) = b.water.as_mut() - && bw.field.as_deref().is_some_and(|f| f.eq_ignore_ascii_case(&removed)) + && bw.field.as_deref().is_some_and(names_removed) { let note = match (bw.depth, bw.bed.clone()) { (Some(d), Some(bed)) => { @@ -1584,9 +1714,87 @@ 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). 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(); + 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, 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(NoticeText::term(one)), + n => gone.push(NoticeText::format(many, [("count", n.to_string().into())])), + } + } + 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(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(NoticeText::term("its chart")); + } + if !gone.is_empty() { + 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_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() { @@ -1803,9 +2011,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)?; @@ -1831,12 +2038,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); @@ -2029,6 +2237,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 @@ -2287,6 +2503,840 @@ 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, "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}"); + 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(); + // (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(); + } + l.labels.default.field = stored.into(); + l.labels.enabled = true; + let mut other = l.labels.default.clone(); + other.name = "Other".into(); + // 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(); + 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", + // 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}"); + } + 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, 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("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"]); + } + } + + /// 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("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()); + // 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, 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(); + 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_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 [ + "twins: deleting field Pop removed 2 attribute rule(s) that used it or no longer read: 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:?}"); + } + } + } + + /// 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}"); + } + + /// 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()); + 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"; + 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()); + 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]; + 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, 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 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 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 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()); + // 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[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 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 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 [ + ("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[1].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] + 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()); + } + // 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(); + 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)); + // 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"]})), + ] { + 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. + 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")); + } + + /// 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(); + 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(); + 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()); + // 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 }); + 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'")); + 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 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(); + 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: 2 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:?}"); + } + } + // 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(); + 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, + /// 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:?}"); + } + } + } + + /// 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 + /// 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 class = &s.map().layer(id).unwrap().labels.classes[0]; + let (clause, visible) = (class.where_.clone(), class.visible); + if read { + 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 the class is turned off"), + "{said:?}" + ); + } else { + // Kept: reading another field, or (no twin) no longer reading, as before. + assert_eq!((clause.as_deref(), visible), (Some("pop > 1"), true)); + 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 + /// 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"})), + ("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 and contingent values 'pair'".to_string()), + "{said:?}" + ); + assert!( + said.contains(&"dates: deleting field when removed 1 attribute rule(s) that used it or no longer read: 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 /// 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/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index a670435610..e8f3c89e00 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,22 @@ 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")?; + // 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; + // 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()) + }; 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,6 +810,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 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")?), @@ -804,7 +827,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 = l.dataset.field_index(&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")); } @@ -909,7 +935,13 @@ 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 unless it is the mapping's own as + // stored, isn't read ahead. + if layer.dataset.has_case_twin(name) && layer.size_by.as_ref().is_none_or(|b| b.field != 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; } diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index f0e7c4ab43..19a8bc2b8f 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. @@ -126,28 +127,41 @@ 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")); } - 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) .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 FilledIn { names, twins } = filled_in(ds); + // 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()); - // A layer with more fields than a report takes: the first are filled in, and that is said (#1896). - if all > MAX_ITEMS { - s.notify(format!("{report}: the first {MAX_ITEMS} of the layer's {all} fields are filled in"), false); + // A layer with more fields than a report takes: the first are filled in, and that is + // 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 { + 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); } Ok(answer) }).inputs(layer_inputs).roles(&[]).effects(crate::policy::Effects::NONE) @@ -156,15 +170,22 @@ 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); } (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()})) @@ -172,31 +193,31 @@ 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")); } - 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) .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| { @@ -204,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 }) @@ -277,28 +298,121 @@ 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)) } -/// `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) { + // 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) +} + +/// `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))), + } +} + +/// 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, all of them, left out as report.field refuses them (#1955). + twins: Vec, +} + +/// 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, 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 (mut names, mut twins) = (Vec::new(), Vec::new()); + for f in &ds.fields { + if twin(&f.name) { + twins.push(f.name.clone()); + } else if names.len() < MAX_ITEMS { + names.push(f.name.clone()); + } } + FilledIn { names, twins } +} + +/// 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: NoticeText = twins.iter().take(TWINS_NAMED).map(String::as_str).collect::>().join(", ").into(); + let more = twins.len().saturating_sub(TWINS_NAMED); + 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)], + ) + }) +} + +/// 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())) } -fn toggle(list: &mut Vec, field: String, remove: bool) { - let at = list.iter().position(|x| x.eq_ignore_ascii_case(&field)); +/// Adds `field` to `list`, or removes it: the entry named exactly so, else the first named so +/// ignoring case. +/// 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 { @@ -329,7 +443,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}"), @@ -465,18 +578,24 @@ 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) }; 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 = ds.fields.iter().take(MAX_ITEMS).map(|f| f.name.clone()).collect(); - } + let mut twins = Vec::new(); + 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; + // 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()) { rustgis_data::query::parse(w, ds)?; @@ -484,7 +603,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); @@ -500,7 +619,17 @@ 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); } if let Some(cut) = cut { s.notify(cut, false); @@ -550,9 +679,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 { @@ -574,6 +707,16 @@ 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, 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 let Some(layer) = l + && layer.dataset.field_index(n).is_none() + { + return Err(format!("no field '{n}'")); + } + } Some(Value::String(n)) => r.sort = Some(field(n)?), _ => {} } @@ -623,7 +766,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 }) @@ -1363,6 +1506,18 @@ fn import_layer(input: &impl super::InputSource, p: &Value, r: &mut Report) -> R Ok(()) } +/// 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()) +} + /// 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(); @@ -1388,9 +1543,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)?); @@ -1401,7 +1566,7 @@ fn chart_inputs(input: &super::InputContext<'_>, p: &Value) -> Result 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}'"))?; + // 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); diff --git a/crates/engine/src/geometry_calc.rs b/crates/engine/src/geometry_calc.rs index 8fa17f7fd2..b4dc11cc84 100644 --- a/crates/engine/src/geometry_calc.rs +++ b/crates/engine/src/geometry_calc.rs @@ -57,7 +57,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()); @@ -174,6 +175,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")?; @@ -186,8 +189,8 @@ pub fn run(s: &mut Session, p: &Json) -> CmdResult { let name = s.map().layer(id).map(|l| l.name.clone()).unwrap_or_default(); s.say(rustgis_data::loss::Note::loss( rustgis_data::loss::LossCode::DroppedCalculationResult, - format!("{name}: {unplaced} feature(s) have a place that can't be given in longitude/latitude, so their {property} is left empty in {field}"), + format!("{name}: {unplaced} feature(s) have a place that can't be given in longitude/latitude, so their {property} is left empty in {written}"), )); } - Ok(json!({"rows": rows.len(), "nulls": nulls, "unplaced": unplaced, "field": field})) + Ok(json!({"rows": rows.len(), "nulls": nulls, "unplaced": unplaced, "field": written})) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 43521b021c..488b26d9d2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -822,7 +822,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'; 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(); @@ -6889,17 +6889,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(); @@ -30920,12 +30920,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"]); } diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index f88e00968c..a53fdb60d1 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -3737,6 +3737,14 @@ 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 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. let fallback = match ds.field_index(&self.default.field) { @@ -3744,11 +3752,22 @@ 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; one + // whose text is an expression shows the same text, so it isn't counted. + if gone(&c.field) { + c.field.clone_from(&fallback); + 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); + } } + moved } /// Off, on the first text field that looks like a name, with only its Default class. diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index a888f4c8ed..80dd0409b3 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -124,8 +124,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