Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions crates/assistant/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,24 @@ 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}");
// A field named like one of those keys doesn't replace it: it is given as field:<name>.
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}");
// Nor does one take the key of a field literally named field:<name>: 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();
Expand Down
17 changes: 14 additions & 3 deletions crates/assistant/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ pub fn defs() -> Vec<ToolDef> {
},
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); a field named like one of these is given as field:<name> (field:field:<name> where that is a field's name too).",
schema: json!({
"type": "object",
"properties": {
Expand Down Expand Up @@ -1273,7 +1273,7 @@ fn row_source<'a>(s: &'a Session, a: &Value) -> Result<RowSource<'a>, 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<Value, String> {
let src = row_source(s, a)?;
Expand Down Expand Up @@ -1341,6 +1341,8 @@ fn read_features(s: &Session, a: &Value) -> Result<Value, String> {
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!(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())) {
Expand All @@ -1357,7 +1359,16 @@ fn read_features(s: &Session, a: &Value) -> Result<Value, String> {
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), nor takes the
// key of a field literally named field:<name>.
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))
})
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down
67 changes: 63 additions & 4 deletions crates/engine/src/cmd/labels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,22 @@ pub fn commands() -> Vec<C> {
),
// 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.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") {
None => return Err("to is [x, y] (longitude, latitude), or null to put it back".into()),
Some(Value::Null) => None,
Expand All @@ -457,7 +472,7 @@ pub fn commands() -> Vec<C> {
.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
Expand Down Expand Up @@ -489,13 +504,17 @@ pub fn commands() -> Vec<C> {
false,
);
}
let (label, hidden) = moved_label(s, p, feature);
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.
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'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,
Expand Down Expand Up @@ -727,6 +746,46 @@ 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 a notice when the map doesn't draw it there.
fn moved_label(s: &Session, p: &Value, feature: u64) -> (Option<String>, Option<String>) {
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.rows().position(|f| f.id() == feature) else { return (None, None) };
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let class = match class_param(p, "class") {
Ok(Some(n)) => l.labels.class(n),
_ => Some(&l.labels.default),
};
// 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))
.map(|fi| ds.features.value(row, fi))
.filter(|v| !v.is_null())
.map(ToString::to_string),
};
let env = rustgis_data::query::Env::default();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// 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)) {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
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(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,
})
};
(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")? {
Expand Down
73 changes: 73 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9284,6 +9284,79 @@ 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("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}));
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
== 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)
);
// 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 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();
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.
#[test]
fn moved_labels_preserve_off_window_features_at_the_cap() {
Expand Down
4 changes: 4 additions & 0 deletions docs/user-guide/cartography.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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
Expand Down
Loading