From 64a174b178b726e561f444a090b41124fc19bd1e Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 00:30:52 -0300 Subject: [PATCH 1/4] fix(labels): labels.move takes a row and names the label it moved (#3391) read_features gives each row's feature id (_id) beside _row. labels.move takes "row" as well as "feature" (one of them), answers with the feature's id and its label text, and says when the definition query or the label class's where leaves the feature out. Co-Authored-By: Claude Opus 5.5 --- crates/assistant/src/tests.rs | 3 ++ crates/assistant/src/tools.rs | 6 ++-- crates/engine/command-surface.txt | 2 +- crates/engine/src/cmd/labels.rs | 59 ++++++++++++++++++++++++++++--- crates/engine/src/tests.rs | 58 ++++++++++++++++++++++++++++++ docs/user-guide/cartography.md | 4 +++ 6 files changed, 125 insertions(+), 7 deletions(-) diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index 20e811e291..496a7b6d60 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -762,6 +762,9 @@ fn geoprocessing_and_reading_data() { run_tool_call(&mut s, &t("read_features", json!({"layer": "Cities", "order_by": "seen DESC", "limit": 1}))).unwrap_or_default(); let v: Value = serde_json::from_str(&latest).unwrap_or(Value::Null); assert_eq!(v["rows"][0]["_row"], json!(1), "{latest}"); + // Its id too, which labels.move takes (#3391). + let fid = s.map().layer_by_name("Cities").unwrap().dataset.features[1].id; + assert_eq!(v["rows"][0]["_id"], json!(fid), "{latest}"); assert!(run_tool_call(&mut s, &t("read_features", json!({"layer": "Cities", "fields": ["nope"]}))).is_err()); assert!(run_tool_call(&mut s, &t("read_features", json!({"layer": "Cities", "fields": [1, null]}))).is_err()); let cmds = run_tool_call(&mut s, &t("search_commands", json!({"query": "basemap"}))).unwrap_or_default(); diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index bb824f2bff..4e577b600c 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -113,7 +113,7 @@ pub fn defs() -> Vec { }, ToolDef { name: "read_features", - description: "Read a vector layer's or a standalone table's attribute rows, optionally only those matching a where clause (SQL-like: pop_max > 1000000 AND continent = 'Asia'). Give layer or table. Returns the number matching and up to `limit` rows, each with its row number (_row; a layer's for select.rows) and a layer's location (_lon, _lat).", + description: "Read a vector layer's or a standalone table's attribute rows, optionally only those matching a where clause (SQL-like: pop_max > 1000000 AND continent = 'Asia'). Give layer or table. Returns the number matching and up to `limit` rows, each with its row number (_row: what select.rows and the edit commands take), its feature id (_id: what labels.move takes) and a layer's location (_lon, _lat).", schema: json!({ "type": "object", "properties": { @@ -1273,7 +1273,7 @@ fn row_source<'a>(s: &'a Session, a: &Value) -> Result, String> { /// `read_features`: the rows of a layer or standalone table ([`row_source`]) that match `where` and /// `selected`, ordered by `order_by`, as `{layer | table, total, matched, rows}`. Only the first -/// `limit` rows are returned, each with its `_row`, the chosen `fields` and a layer feature's +/// `limit` rows are returned, each with its `_row` and `_id`, the chosen `fields` and a layer feature's /// `_lon`/`_lat`. fn read_features(s: &Session, a: &Value) -> Result { let src = row_source(s, a)?; @@ -1341,6 +1341,8 @@ fn read_features(s: &Session, a: &Value) -> Result { let f = ds.features.get(r)?; let mut o = serde_json::Map::new(); o.insert("_row".into(), json!(r)); + // Its id, which labels.move takes (#3391); a row moves with a sort or an edit. + o.insert("_id".into(), json!(f.id)); // Where it is (its extent's centre, in longitude/latitude), for zooming or going to it. // Left out where it isn't a place (`point` gives only finite ones). if let Some(c) = f.geometry.as_ref().and_then(|g| lonlat.point(g.extent().center())) { diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 93d273fd1c..a1c69950ab 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -206,7 +206,7 @@ labels.enable layer? on? labels.field layer? class? field labels.fonts search? labels.lock on? -labels.move layer? class? feature to +labels.move layer? class? feature? row? to labels.pause on? labels.placement layer? class? position? to? side? offset? repeat? lineOffset? otherPositions? fit? abbreviations? showAll? weight? clearance? removeDuplicates? callout? guide? labels.resetMoved layer? class? all? diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 9423ae2684..9a6dca54f5 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -434,7 +434,22 @@ pub fn commands() -> Vec { ), // Labels moved by hand (the Move Label tool, as QGIS's): kept by their feature's id. C::new("labels.move", "Move Label", "Labeling › Label Placement", |s, p| { - let feature = p.get("feature").and_then(Value::as_u64).ok_or("feature is a feature's id")?; + // By its id (what a move is kept by) or its row (as read_features gives it, #3391). + let given = |k: &str| p.get(k).filter(|v| !v.is_null()); + let by_id = given("feature").map(|v| v.as_u64().ok_or("feature is a feature's id")).transpose()?; + let row = given("row") + .map(|v| v.as_u64().and_then(|r| usize::try_from(r).ok()).ok_or("row is a row number, as read_features gives it")) + .transpose()?; + let feature = match (by_id, row) { + (Some(_), Some(_)) => return Err("give feature (a feature's id) or row, not both".into()), + (None, None) => return Err("feature is a feature's id, or row a row number (as read_features gives it)".into()), + (Some(f), None) => f, + (None, Some(r)) => s + .layer_id(p) + .ok() + .and_then(|id| s.map().layer(id)?.dataset.features.get(r).map(|f| f.id)) + .ok_or_else(|| format!("row {r} is not one of the layer's loaded rows"))?, + }; let to = match p.get("to") { None => return Err("to is [x, y] (longitude, latitude), or null to put it back".into()), Some(Value::Null) => None, @@ -457,7 +472,7 @@ pub fn commands() -> Vec { .filter(|l| l.labels.in_order().any(|c| c.moved.len() >= rustgis_map::symbology::MAX_MOVED_LABELS)) .map(|l| l.dataset.features.iter().map(|f| f.id).collect()); let mut pruned = 0usize; - let r = with_labels(s, p, |labels| { + with_labels(s, p, |labels| { let c = class_in(labels, p)?; if let Some(live) = &live && c.moved.len() >= rustgis_map::symbology::MAX_MOVED_LABELS @@ -489,13 +504,17 @@ pub fn commands() -> Vec { false, ); } + let (label, hidden) = moved_label(s, p, feature); + if let Some(why) = hidden.filter(|_| to.is_some()) { + s.notify(format!("feature {feature} isn't drawn ({why}); its label is moved but won't show"), false); + } // Locked, the labels are locked again where they are placed next (`with_labels`: the // moves changed), as the one moved may not have been placed when the lock was taken. - Ok(r) + Ok(json!({"feature": feature, "label": label})) }).roles(&[]).effects(crate::policy::Effects::NONE) .inputs(super::Inputs::single_layer) .when(need_feature_layer) - .params(r#"{"layer"?, "class"?: name (none: the Default class), "feature": the feature's id, "to": [x, y] (longitude, latitude: where the label's text is centred) | null (back where its class puts it)}"#), + .params(r#"{"layer"?, "class"?: name (none: the Default class), "feature"?: the feature's id (read_features's _id), "row"?: its row (read_features's _row; one of feature or row), "to": [x, y] (longitude, latitude: where the label's text is centred) | null (back where its class puts it); answers with the feature's id and its label (its class's field's value), and says when the definition query or the class's where leaves the feature out}"#), C::new("labels.resetMoved", "Reset Moved", "Labeling › Label Placement", |s, p| { let all = match p.get("all") { None | Some(Value::Null) => false, @@ -727,6 +746,38 @@ pub(crate) fn with_class(s: &mut Session, p: &Value, f: impl FnOnce(&mut LabelCl }) } +/// For a label moved (#3391): its text, as its class's field gives it (null where the feature isn't +/// loaded or has none), and why the map doesn't draw the feature there, if it doesn't. +fn moved_label(s: &Session, p: &Value, feature: u64) -> (Option, Option) { + let Some(l) = s.layer_id(p).ok().and_then(|id| s.map().layer(id)) else { return (None, None) }; + let ds = &l.dataset; + let Some(row) = ds.features.iter().position(|f| f.id == feature) else { return (None, None) }; + let class = match class_param(p, "class") { + Ok(Some(n)) => l.labels.class(n), + _ => Some(&l.labels.default), + }; + let label = class + .and_then(|c| ds.fields.iter().position(|f| f.name == c.field)) + .and_then(|fi| ds.features.get(row)?.attrs.get(fi)) + .filter(|v| !matches!(v, Attr::Null)) + .map(ToString::to_string); + let env = rustgis_data::query::Env::default(); + // A definition query that doesn't read draws every feature (`Layer::query_rows`). + let query = rustgis_data::rows::Query::compile(l.definition_query.as_deref(), ds).ok(); + let why = if query.is_some_and(|q| q.is_filtered() && !q.matches(ds, row, &env)) { + Some("the definition query leaves it out".to_string()) + } else { + class.and_then(|c| match c.query(ds) { + None => Some(format!("label class {}'s where doesn't read", c.name)), + Some(Some(e)) if !rustgis_data::query::matches(&e, ds, row, &env) => { + Some(format!("label class {}'s where leaves it out", c.name)) + } + Some(_) => None, + }) + }; + (label, why) +} + /// The label class `p` names (`"class"`; Default when none). pub(crate) fn class_in<'a>(labels: &'a mut Labeling, p: &Value) -> Result<&'a mut LabelClass, String> { match class_param(p, "class")? { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 13d763f9ca..a1378c0801 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9284,6 +9284,64 @@ fn labels_take_a_font_by_family_name() { assert!(s.run("labels.fonts", &json!({})).unwrap()["fonts"].is_array()); } +/// `labels.move` takes a row, as `read_features` gives it, or a feature's id, not both; it answers +/// with the feature moved and its label, and says when the map doesn't draw it there (#3391). +#[test] +fn labels_move_takes_a_row_names_the_label_and_says_when_hidden() { + let mut s = world(); + let id = s.map().layer_by_name("Cities").unwrap().id; + let l = s.map().layer(id).unwrap(); + let field = l.labels.default.field.clone(); + let fi = l.dataset.fields.iter().position(|f| f.name == field).unwrap(); + let f = &l.dataset.features[3]; + let (fid, name) = (f.id, f.attrs[fi].to_string()); + assert_ne!(fid, 3, "the row and the id differ"); + let others = format!("\"{field}\" <> '{}'", name.replace('\'', "''")); + let moved = |s: &Session| s.map().layer(id).unwrap().labels.default.moved.clone(); + let hidden = |s: &Session, mark| s.notices_since(mark).iter().any(|n: &crate::Notice| n.text.contains("isn't drawn")); + let mark = s.notice_mark(); + let r = s.run("labels.move", &json!({"layer": id, "row": 3, "to": [1, 2]})).unwrap(); + assert_eq!(r, json!({"feature": fid, "label": name})); + assert_eq!(moved(&s), vec![rustgis_map::symbology::MovedLabel { id: fid, at: [1.0, 2.0] }]); + assert!(!hidden(&s, mark), "drawn: no notice"); + // By its id, the same answer. + let r = s.run("labels.move", &json!({"layer": id, "feature": fid, "to": [1, 3]})).unwrap(); + assert_eq!(r, json!({"feature": fid, "label": name})); + // Both, neither, or a row that isn't one: refused, nothing changed. + for bad in [ + json!({"row": 3, "feature": fid, "to": [1, 1]}), + json!({"to": [1, 1]}), + json!({"row": 1_000_000, "to": [1, 1]}), + json!({"row": -1, "to": [1, 1]}), + ] { + let mut p = bad.clone(); + p["layer"] = json!(id); + assert!(s.run("labels.move", &p).is_err(), "{bad}"); + } + assert_eq!(moved(&s)[0].at, [1.0, 3.0]); + // Left out by the definition query: moved, and said. + s.run("layer.definitionQuery", &json!({"layer": id, "where": others})).unwrap(); + let mark = s.notice_mark(); + s.run("labels.move", &json!({"layer": id, "row": 3, "to": [1, 4]})).unwrap(); + let said = format!("feature {fid} isn't drawn (the definition query leaves it out); its label is moved but won't show"); + assert!(s.notices_since(mark).iter().any(|n| n.text == said), "{:?}", s.notices_since(mark)); + assert_eq!(moved(&s)[0].at, [1.0, 4.0], "kept"); + s.run("layer.definitionQuery", &json!({"layer": id, "where": ""})).unwrap(); + // Left out by its label class's where. + s.run("labels.class.add", &json!({"layer": id, "name": "Others", "where": others})).unwrap(); + let mark = s.notice_mark(); + s.run("labels.move", &json!({"layer": id, "class": "Others", "row": 3, "to": [1, 5]})).unwrap(); + assert!( + s.notices_since(mark).iter().any(|n| n.text.contains("(label class Others's where leaves it out)")), + "{:?}", + s.notices_since(mark) + ); + // Put back: nothing to say. + let mark = s.notice_mark(); + s.run("labels.move", &json!({"layer": id, "class": "Others", "row": 3, "to": null})).unwrap(); + assert!(!hidden(&s, mark)); +} + /// A streamed window cannot discard saved moves for off-window features to make space at the cap. #[test] fn moved_labels_preserve_off_window_features_at_the_cap() { diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index cff652028c..393d62a7fb 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -724,6 +724,10 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: anything else pans the map; Esc leaves the tool (`labels.move={"layer": "Cities", "feature": 12, "to": [2.5, 49.1]}`; `"to": null` puts it back; `labels.resetMoved={"layer": "Cities", "all": true}`). + The command names the feature by its id (`_id` in the assistant's `read_features`) or by its + row (`"row": 230`, the `_row` it gives), not both, and answers with the id and the label's text + (`{"feature": 231, "label": "Bogota"}`), so a wrong feature shows at once; a feature the + definition query or the class's `where` leaves out is said not to be drawn. Deleting a feature removes its saved move; Undo restores it. Service refresh and Repair Data Source reset saved moves and old label locks because replacement data can reuse feature ids, with a counted notice and undo restoration. Opening a project, importing a map or styles, or adding a layer file From 9fe74b6d58f9d53e765118e62e1fe617c3be7672 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 01:10:31 -0300 Subject: [PATCH 2/4] fix(labels): keep read_features' own keys and give labels.move's expression text A field named _row, _id, _lon or _lat no longer replaces read_features' key of that name; it is given as field:. labels.move answers with the text a class's text expression gives, as the map draws it, before the field's value. Co-Authored-By: Claude Opus 5.5 --- crates/assistant/src/tests.rs | 10 ++++++++++ crates/assistant/src/tools.rs | 10 ++++++++-- crates/engine/src/cmd/labels.rs | 22 ++++++++++++++-------- crates/engine/src/tests.rs | 8 ++++++++ 4 files changed, 40 insertions(+), 10 deletions(-) diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index 496a7b6d60..4d8e54bc62 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -765,6 +765,16 @@ fn geoprocessing_and_reading_data() { // Its id too, which labels.move takes (#3391). let fid = s.map().layer_by_name("Cities").unwrap().dataset.features[1].id; assert_eq!(v["rows"][0]["_id"], json!(fid), "{latest}"); + // A field named like one of those keys doesn't replace it: it is given as field:. + for f in ["_id", "_row"] { + s.run("edit.addField", &json!({"layer": "Cities", "name": f, "type": "integer"})).unwrap(); + s.run("edit.setValue", &json!({"layer": "Cities", "row": 1, "field": f, "value": 999})).unwrap(); + } + let named = + run_tool_call(&mut s, &t("read_features", json!({"layer": "Cities", "order_by": "seen DESC", "limit": 1}))).unwrap_or_default(); + let v: Value = serde_json::from_str(&named).unwrap_or(Value::Null); + assert_eq!((&v["rows"][0]["_row"], &v["rows"][0]["_id"]), (&json!(1), &json!(fid)), "{named}"); + assert_eq!((&v["rows"][0]["field:_id"], &v["rows"][0]["field:_row"]), (&json!(999), &json!(999)), "{named}"); assert!(run_tool_call(&mut s, &t("read_features", json!({"layer": "Cities", "fields": ["nope"]}))).is_err()); assert!(run_tool_call(&mut s, &t("read_features", json!({"layer": "Cities", "fields": [1, null]}))).is_err()); let cmds = run_tool_call(&mut s, &t("search_commands", json!({"query": "basemap"}))).unwrap_or_default(); diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 4e577b600c..f3a7616724 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -113,7 +113,7 @@ pub fn defs() -> Vec { }, ToolDef { name: "read_features", - description: "Read a vector layer's or a standalone table's attribute rows, optionally only those matching a where clause (SQL-like: pop_max > 1000000 AND continent = 'Asia'). Give layer or table. Returns the number matching and up to `limit` rows, each with its row number (_row: what select.rows and the edit commands take), its feature id (_id: what labels.move takes) and a layer's location (_lon, _lat).", + description: "Read a vector layer's or a standalone table's attribute rows, optionally only those matching a where clause (SQL-like: pop_max > 1000000 AND continent = 'Asia'). Give layer or table. Returns the number matching and up to `limit` rows, each with its row number (_row: what select.rows and the edit commands take), its feature id (_id: what labels.move takes) and a layer's location (_lon, _lat); a field named like one of these is given as field:.", schema: json!({ "type": "object", "properties": { @@ -1359,7 +1359,13 @@ fn read_features(s: &Session, a: &Value) -> Result { rustgis_engine::data::Value::Text(t) => json!(clip(t, 200)), d @ (rustgis_engine::data::Value::Date(_) | rustgis_engine::data::Value::DateTime(_)) => json!(d.to_string()), }; - o.insert(field.name.clone(), v); + // A field named like one of the keys above doesn't replace it (#3391). + let key = if ["_row", "_id", "_lon", "_lat"].contains(&field.name.as_str()) { + format!("field:{}", field.name) + } else { + field.name.clone() + }; + o.insert(key, v); } Some(Value::Object(o)) }) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 9a6dca54f5..75c9ba7da6 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -514,7 +514,7 @@ pub fn commands() -> Vec { }).roles(&[]).effects(crate::policy::Effects::NONE) .inputs(super::Inputs::single_layer) .when(need_feature_layer) - .params(r#"{"layer"?, "class"?: name (none: the Default class), "feature"?: the feature's id (read_features's _id), "row"?: its row (read_features's _row; one of feature or row), "to": [x, y] (longitude, latitude: where the label's text is centred) | null (back where its class puts it); answers with the feature's id and its label (its class's field's value), and says when the definition query or the class's where leaves the feature out}"#), + .params(r#"{"layer"?, "class"?: name (none: the Default class), "feature"?: the feature's id (read_features's _id), "row"?: its row (read_features's _row; one of feature or row), "to": [x, y] (longitude, latitude: where the label's text is centred) | null (back where its class puts it); answers with the feature's id and its label's text (its class's text expression, else its field), and says when the definition query or the class's where leaves the feature out}"#), C::new("labels.resetMoved", "Reset Moved", "Labeling › Label Placement", |s, p| { let all = match p.get("all") { None | Some(Value::Null) => false, @@ -746,8 +746,9 @@ pub(crate) fn with_class(s: &mut Session, p: &Value, f: impl FnOnce(&mut LabelCl }) } -/// For a label moved (#3391): its text, as its class's field gives it (null where the feature isn't -/// loaded or has none), and why the map doesn't draw the feature there, if it doesn't. +/// For a label moved (#3391): its text, as its class's text expression or field gives it (null +/// where the feature isn't loaded or has none), and why the map doesn't draw the feature there, +/// if it doesn't. fn moved_label(s: &Session, p: &Value, feature: u64) -> (Option, Option) { let Some(l) = s.layer_id(p).ok().and_then(|id| s.map().layer(id)) else { return (None, None) }; let ds = &l.dataset; @@ -756,11 +757,16 @@ fn moved_label(s: &Session, p: &Value, feature: u64) -> (Option, Option< Ok(Some(n)) => l.labels.class(n), _ => Some(&l.labels.default), }; - let label = class - .and_then(|c| ds.fields.iter().position(|f| f.name == c.field)) - .and_then(|fi| ds.features.get(row)?.attrs.get(fi)) - .filter(|v| !matches!(v, Attr::Null)) - .map(ToString::to_string); + // As the map draws it (and `convert` takes it): a text expression first, else the field. + let by_text = class.and_then(|c| rustgis_map::label_by::LabelExprs::new(&c.by, ds, Some(s.map().scale()))).filter(|e| e.has_text()); + let label = match by_text.and_then(|e| e.text(ds, row)) { + Some(text) => text, + None => class + .and_then(|c| ds.fields.iter().position(|f| f.name == c.field)) + .and_then(|fi| ds.features.get(row)?.attrs.get(fi)) + .filter(|v| !matches!(v, Attr::Null)) + .map(ToString::to_string), + }; let env = rustgis_data::query::Env::default(); // A definition query that doesn't read draws every feature (`Layer::query_rows`). let query = rustgis_data::rows::Query::compile(l.definition_query.as_deref(), ds).ok(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a1378c0801..faa11f0e5c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9340,6 +9340,14 @@ fn labels_move_takes_a_row_names_the_label_and_says_when_hidden() { let mark = s.notice_mark(); s.run("labels.move", &json!({"layer": id, "class": "Others", "row": 3, "to": null})).unwrap(); assert!(!hidden(&s, mark)); + // Labels by a text expression: the text the map shows, not the field's value. + s.run("labels.by", &json!({"layer": id, "text": format!("\"{field}\" || '!'")})).unwrap(); + let r = s.run("labels.move", &json!({"layer": id, "row": 3, "to": [1, 6]})).unwrap(); + assert_eq!(r["label"], json!(format!("{name}!"))); + // One giving no text there: no label. + s.run("labels.by", &json!({"layer": id, "text": "' '"})).unwrap(); + let r = s.run("labels.move", &json!({"layer": id, "row": 3, "to": [1, 7]})).unwrap(); + assert_eq!(r["label"], Value::Null); } /// A streamed window cannot discard saved moves for off-window features to make space at the cap. From a55c6bf005c1201eed9ed92acbd48dd1be63db7d Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 01:43:14 -0300 Subject: [PATCH 3/4] fix(labels): read rows through accessors; keep a field: field's value labels.move and read_features read the layer's rows through Features' accessors (row, rows, value). A field renamed to field: in read_features takes another field: prefix while that name is a field too, so neither value is lost. Co-Authored-By: Claude Opus 5.5 --- crates/assistant/src/tests.rs | 5 +++++ crates/assistant/src/tools.rs | 19 +++++++++++-------- crates/engine/src/cmd/labels.rs | 8 ++++---- 3 files changed, 20 insertions(+), 12 deletions(-) diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index 4d8e54bc62..7efbdb9a1b 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -775,6 +775,11 @@ fn geoprocessing_and_reading_data() { let v: Value = serde_json::from_str(&named).unwrap_or(Value::Null); assert_eq!((&v["rows"][0]["_row"], &v["rows"][0]["_id"]), (&json!(1), &json!(fid)), "{named}"); assert_eq!((&v["rows"][0]["field:_id"], &v["rows"][0]["field:_row"]), (&json!(999), &json!(999)), "{named}"); + // Nor does one take the key of a field literally named field:: each value is kept. + s.run("layer.addDataText", &json!({"fileName": "clash.csv", "text": "_id,field:_id\na,b\n"})).unwrap(); + let both = run_tool_call(&mut s, &t("read_features", json!({"table": "clash"}))).unwrap_or_default(); + let v: Value = serde_json::from_str(&both).unwrap_or(Value::Null); + assert_eq!((&v["rows"][0]["field:_id"], &v["rows"][0]["field:field:_id"]), (&json!("b"), &json!("a")), "{both}"); assert!(run_tool_call(&mut s, &t("read_features", json!({"layer": "Cities", "fields": ["nope"]}))).is_err()); assert!(run_tool_call(&mut s, &t("read_features", json!({"layer": "Cities", "fields": [1, null]}))).is_err()); let cmds = run_tool_call(&mut s, &t("search_commands", json!({"query": "basemap"}))).unwrap_or_default(); diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index f3a7616724..06da31c122 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -113,7 +113,7 @@ pub fn defs() -> Vec { }, ToolDef { name: "read_features", - description: "Read a vector layer's or a standalone table's attribute rows, optionally only those matching a where clause (SQL-like: pop_max > 1000000 AND continent = 'Asia'). Give layer or table. Returns the number matching and up to `limit` rows, each with its row number (_row: what select.rows and the edit commands take), its feature id (_id: what labels.move takes) and a layer's location (_lon, _lat); a field named like one of these is given as field:.", + description: "Read a vector layer's or a standalone table's attribute rows, optionally only those matching a where clause (SQL-like: pop_max > 1000000 AND continent = 'Asia'). Give layer or table. Returns the number matching and up to `limit` rows, each with its row number (_row: what select.rows and the edit commands take), its feature id (_id: what labels.move takes) and a layer's location (_lon, _lat); a field named like one of these is given as field: (field:field: where that is a field's name too).", schema: json!({ "type": "object", "properties": { @@ -1342,7 +1342,7 @@ fn read_features(s: &Session, a: &Value) -> Result { let mut o = serde_json::Map::new(); o.insert("_row".into(), json!(r)); // Its id, which labels.move takes (#3391); a row moves with a sort or an edit. - o.insert("_id".into(), json!(f.id)); + o.insert("_id".into(), json!(ds.features.row(r).map(|f| f.id()))); // Where it is (its extent's centre, in longitude/latitude), for zooming or going to it. // Left out where it isn't a place (`point` gives only finite ones). if let Some(c) = f.geometry.as_ref().and_then(|g| lonlat.point(g.extent().center())) { @@ -1359,12 +1359,15 @@ fn read_features(s: &Session, a: &Value) -> Result { rustgis_engine::data::Value::Text(t) => json!(clip(t, 200)), d @ (rustgis_engine::data::Value::Date(_) | rustgis_engine::data::Value::DateTime(_)) => json!(d.to_string()), }; - // A field named like one of the keys above doesn't replace it (#3391). - let key = if ["_row", "_id", "_lon", "_lat"].contains(&field.name.as_str()) { - format!("field:{}", field.name) - } else { - field.name.clone() - }; + // A field named like one of the keys above doesn't replace it (#3391), nor takes the + // key of a field literally named field:. + let mut key = field.name.clone(); + if ["_row", "_id", "_lon", "_lat"].contains(&key.as_str()) { + key = format!("field:{key}"); + while ds.fields.iter().any(|f| f.name == key) { + key = format!("field:{key}"); + } + } o.insert(key, v); } Some(Value::Object(o)) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 75c9ba7da6..602b190f42 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -447,7 +447,7 @@ pub fn commands() -> Vec { (None, Some(r)) => s .layer_id(p) .ok() - .and_then(|id| s.map().layer(id)?.dataset.features.get(r).map(|f| f.id)) + .and_then(|id| s.map().layer(id)?.dataset.features.row(r).map(|f| f.id())) .ok_or_else(|| format!("row {r} is not one of the layer's loaded rows"))?, }; let to = match p.get("to") { @@ -752,7 +752,7 @@ pub(crate) fn with_class(s: &mut Session, p: &Value, f: impl FnOnce(&mut LabelCl fn moved_label(s: &Session, p: &Value, feature: u64) -> (Option, Option) { let Some(l) = s.layer_id(p).ok().and_then(|id| s.map().layer(id)) else { return (None, None) }; let ds = &l.dataset; - let Some(row) = ds.features.iter().position(|f| f.id == feature) else { return (None, None) }; + let Some(row) = ds.features.rows().position(|f| f.id() == feature) else { return (None, None) }; let class = match class_param(p, "class") { Ok(Some(n)) => l.labels.class(n), _ => Some(&l.labels.default), @@ -763,8 +763,8 @@ fn moved_label(s: &Session, p: &Value, feature: u64) -> (Option, Option< Some(text) => text, None => class .and_then(|c| ds.fields.iter().position(|f| f.name == c.field)) - .and_then(|fi| ds.features.get(row)?.attrs.get(fi)) - .filter(|v| !matches!(v, Attr::Null)) + .map(|fi| ds.features.value(row, fi)) + .filter(|v| !v.is_null()) .map(ToString::to_string), }; let env = rustgis_data::query::Env::default(); From 1d803fa444221c6ab64f425ddba51a9f19d2bcbb Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 02:03:02 -0300 Subject: [PATCH 4/4] fix(labels): read a class's where at the map's scale in labels.move's notice A label class's where that reads @map_scale is checked at the map's scale, as the map draws it, so labels.move no longer says a drawn label won't show. A label hidden by its class's where is said as a label that won't show, not as a feature that isn't drawn. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/labels.rs | 18 ++++++++++-------- crates/engine/src/tests.rs | 11 +++++++++-- docs/user-guide/cartography.md | 2 +- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 602b190f42..cb49f27aac 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -505,8 +505,8 @@ pub fn commands() -> Vec { ); } let (label, hidden) = moved_label(s, p, feature); - if let Some(why) = hidden.filter(|_| to.is_some()) { - s.notify(format!("feature {feature} isn't drawn ({why}); its label is moved but won't show"), false); + if let Some(said) = hidden.filter(|_| to.is_some()) { + s.notify(said, false); } // Locked, the labels are locked again where they are placed next (`with_labels`: the // moves changed), as the one moved may not have been placed when the lock was taken. @@ -747,8 +747,7 @@ pub(crate) fn with_class(s: &mut Session, p: &Value, f: impl FnOnce(&mut LabelCl } /// For a label moved (#3391): its text, as its class's text expression or field gives it (null -/// where the feature isn't loaded or has none), and why the map doesn't draw the feature there, -/// if it doesn't. +/// where the feature isn't loaded or has none), and a notice when the map doesn't draw it there. fn moved_label(s: &Session, p: &Value, feature: u64) -> (Option, Option) { let Some(l) = s.layer_id(p).ok().and_then(|id| s.map().layer(id)) else { return (None, None) }; let ds = &l.dataset; @@ -771,12 +770,15 @@ fn moved_label(s: &Session, p: &Value, feature: u64) -> (Option, Option< // A definition query that doesn't read draws every feature (`Layer::query_rows`). let query = rustgis_data::rows::Query::compile(l.definition_query.as_deref(), ds).ok(); let why = if query.is_some_and(|q| q.is_filtered() && !q.matches(ds, row, &env)) { - Some("the definition query leaves it out".to_string()) + Some(format!("feature {feature} isn't drawn (the definition query leaves it out); its label is moved but won't show")) } else { + // The class's where hides its label only: the feature, and other classes' labels, still draw. + let hidden = |why: String| format!("the label of feature {feature} won't show ({why}); it is moved all the same"); class.and_then(|c| match c.query(ds) { - None => Some(format!("label class {}'s where doesn't read", c.name)), - Some(Some(e)) if !rustgis_data::query::matches(&e, ds, row, &env) => { - Some(format!("label class {}'s where leaves it out", c.name)) + None => Some(hidden(format!("label class {}'s where doesn't read", c.name))), + // At the map's scale, as `LabelMatcher` reads it (`@map_scale`). + Some(Some(e)) if !rustgis_data::query::matches(&e, ds, row, &env.at_scale(Some(s.map().scale()))) => { + Some(hidden(format!("label class {}'s where leaves it out", c.name))) } Some(_) => None, }) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index faa11f0e5c..a3152fd3c7 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9298,7 +9298,7 @@ fn labels_move_takes_a_row_names_the_label_and_says_when_hidden() { assert_ne!(fid, 3, "the row and the id differ"); let others = format!("\"{field}\" <> '{}'", name.replace('\'', "''")); let moved = |s: &Session| s.map().layer(id).unwrap().labels.default.moved.clone(); - let hidden = |s: &Session, mark| s.notices_since(mark).iter().any(|n: &crate::Notice| n.text.contains("isn't drawn")); + let hidden = |s: &Session, mark| s.notices_since(mark).iter().any(|n: &crate::Notice| n.text.contains("won't show")); let mark = s.notice_mark(); let r = s.run("labels.move", &json!({"layer": id, "row": 3, "to": [1, 2]})).unwrap(); assert_eq!(r, json!({"feature": fid, "label": name})); @@ -9332,7 +9332,8 @@ fn labels_move_takes_a_row_names_the_label_and_says_when_hidden() { let mark = s.notice_mark(); s.run("labels.move", &json!({"layer": id, "class": "Others", "row": 3, "to": [1, 5]})).unwrap(); assert!( - s.notices_since(mark).iter().any(|n| n.text.contains("(label class Others's where leaves it out)")), + s.notices_since(mark).iter().any(|n| n.text + == format!("the label of feature {fid} won't show (label class Others's where leaves it out); it is moved all the same")), "{:?}", s.notices_since(mark) ); @@ -9340,6 +9341,12 @@ fn labels_move_takes_a_row_names_the_label_and_says_when_hidden() { let mark = s.notice_mark(); s.run("labels.move", &json!({"layer": id, "class": "Others", "row": 3, "to": null})).unwrap(); assert!(!hidden(&s, mark)); + // A where reading the map's scale is read at it: drawn at 1:5000, nothing said. + s.run("map.goToXY", &json!({"lon": 0, "lat": 0, "scale": 5000})).unwrap(); + s.run("labels.class.add", &json!({"layer": id, "name": "Near", "where": "@map_scale > 1000"})).unwrap(); + let mark = s.notice_mark(); + s.run("labels.move", &json!({"layer": id, "class": "Near", "row": 3, "to": [1, 5]})).unwrap(); + assert!(!hidden(&s, mark), "{:?}", s.notices_since(mark)); // Labels by a text expression: the text the map shows, not the field's value. s.run("labels.by", &json!({"layer": id, "text": format!("\"{field}\" || '!'")})).unwrap(); let r = s.run("labels.move", &json!({"layer": id, "row": 3, "to": [1, 6]})).unwrap(); diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 393d62a7fb..e6e944f4b5 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -727,7 +727,7 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: The command names the feature by its id (`_id` in the assistant's `read_features`) or by its row (`"row": 230`, the `_row` it gives), not both, and answers with the id and the label's text (`{"feature": 231, "label": "Bogota"}`), so a wrong feature shows at once; a feature the - definition query or the class's `where` leaves out is said not to be drawn. + definition query or the class's `where` leaves out is said to have a label that won't show. Deleting a feature removes its saved move; Undo restores it. Service refresh and Repair Data Source reset saved moves and old label locks because replacement data can reuse feature ids, with a counted notice and undo restoration. Opening a project, importing a map or styles, or adding a layer file