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
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ is out of scope.
- A new background raster command or export, or a tool whose work grows with its input, goes in
the lists in `crates/engine/src/tests.rs` (`cancel_rasters`, `cancel_exports`, `cancel_tools`);
`cancel_rasters` and `cancel_exports` must match the background registries. A read-ahead command
(`reads::prepare`, such as `service.layers`) has no list: add its call to
`long_commands_stop_when_cancelled_while_they_run` by hand.
(`reads::prepare`, such as `service.layers` or `edit.previewShapeConversion`) has no list: add
Comment thread
robmarkcole marked this conversation as resolved.
Resolved
its call to `long_commands_stop_when_cancelled_while_they_run` by hand.
`long_commands_stop_when_cancelled_while_they_run` fails one that never looks at Cancel;
`cancelling_at_each_check_leaves_nothing_behind` cancels each command of the three lists at its
first three checks and its last, and fails one that leaves the project, its undo steps or the
Expand Down
2 changes: 1 addition & 1 deletion crates/assistant/src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ impl ArchiveBatch {
if name != "run_command"
|| !matches!(
args.get("command").and_then(Value::as_str).map(str::trim),
Some("map.reloadTiles" | "map.repairTiles" | "table.statistics")
Some("map.reloadTiles" | "map.repairTiles" | "table.statistics" | "edit.previewShapeConversion")
)
{
return None;
Expand Down
31 changes: 31 additions & 0 deletions crates/assistant/src/relay/archive_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -607,3 +607,34 @@ fn archive_batch_resumes_same_context_after_validation_failure_or_cancellation()
relay.stop();
}
}

#[test]
fn shape_conversion_preview_uses_the_worker_without_implicitly_applying() {
use rustgis_engine::data::{Dataset, GeometryType};
let mut s = Session::new(Project::default());
let id = s.map_mut().add_dataset(Dataset::new("Polygons", GeometryType::Polygon, vec![]));
s.active_layer = Some(id);
s.run("edit.enable", &json!({"on":true})).unwrap();
s.run("edit.addFeature", &json!({"geometry":{"type":"Polygon","coordinates":[[[0.,0.],[0.01,0.],[0.01,0.01],[0.,0.01],[0.,0.]]]}}))
.unwrap();
let depth = s.undo_depth();
let relay = Relay::start(0).unwrap();
let grant = relay.grant(true).unwrap();
let (_, rx) = queue(&relay, &grant, command(1, "edit.previewShapeConversion", json!({"layer":id,"row":0,"kind":"circle"})));
assert_eq!(relay.poll(&mut s), 0);
assert!(rx.try_recv().is_err());
let done = worker(relay.take_archive_read().unwrap());
finish(&relay, &mut s, done);
let answer = reply(&rx);
assert!(answer.get("error").is_none(), "{answer}");
let result = answer.get("result").expect("preview returned no result");
assert_eq!(result["isError"], false, "{answer}");
let text = result["content"][0]["text"].as_str().unwrap();
let proposal: rustgis_engine::shape_conversion::Proposal = serde_json::from_str(text).unwrap();
assert_eq!((proposal.layer, proposal.row), (id, 0));
assert!(matches!(proposal.shape, rustgis_engine::shape_conversion::Shape::Circle(_)));
assert!(proposal.current(&s));
assert_eq!(s.undo_depth(), depth);
assert!(s.circle_spec(id, 0).is_none());
relay.stop();
}
2 changes: 1 addition & 1 deletion crates/engine/src/box_edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult {
remember(s, id, row, b.clone())?;
Ok(json!({"row":row,"box":b}))
}
fn remember(s: &mut Session, id: u32, row: usize, spec: BoxSpec) -> Result<(), String> {
pub(crate) fn remember(s: &mut Session, id: u32, row: usize, spec: BoxSpec) -> Result<(), String> {
let key = Cache::key(s, id, row).ok_or("box source changed")?;
if key.3 == u64::MAX {
return Err("feature IDs have reached their limit; create a fresh layer for boxes".into());
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/circle_edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult {
json!({"row":row,"circle":b,"polygonEdges":b.segments()?,"approximation":"straight edges; tolerance is in construction-grid units before projection"}),
)
}
fn remember(s: &mut Session, id: u32, row: usize, spec: CircleSpec) -> Result<(), String> {
pub(crate) fn remember(s: &mut Session, id: u32, row: usize, spec: CircleSpec) -> Result<(), String> {
let key = Cache::key(s, id, row).ok_or("circle source changed")?;
if key.3 == u64::MAX {
return Err("feature IDs have reached their limit; create a fresh layer for circles".into());
Expand Down
6 changes: 6 additions & 0 deletions crates/engine/src/cmd/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ pub fn commands() -> Vec<C> {
let box_roles: &[crate::ParamRole] =
&[crate::ParamRole { key: "box", role: crate::Role::Opaque }, crate::ParamRole { key: "attributes", role: crate::Role::Opaque }];
vec![
C::new("edit.previewShapeConversion", "Preview Shape Conversion", "Edit › Features", crate::shape_conversion::preview).inputs(crate::shape_conversion::preview_inputs)
.roles(&[crate::ParamRole {key:"frame",role:crate::Role::Opaque}]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view()
.when(crate::cmd::design::need_editable).params(r#"{"layer"?:name|id,"row":number,"featureId"?:number,"kind":"circle|rotatedBox","request"?:number (preview correlation only),"image"?:GeoTIFF layer name|id,"frame"?:construction grid as edit.addBox.box.frame (otherwise Web Mercator)}"#),
C::new("edit.applyShapeConversion", "Apply Shape Conversion", "Edit › Features", crate::shape_conversion::apply).inputs(crate::shape_conversion::apply_inputs)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
.roles(&[crate::ParamRole {key:"preview",role:crate::Role::Opaque}]).effects(crate::policy::Effects::NONE)
.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"}"#),
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/cmd/reads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ pub(crate) fn prepare(s: &mut Session, op: Authorized<CommandOp>, owner: Continu
id if super::edit::table_edit_in_background(id).is_some() => ("Edit Table", super::edit::table_ahead(s, spec.id, params)?, None),
"topology.validate" => ("Error Inspector", super::design::topology_ahead(s, params), None),
"source.syncState" => ("Source File State", super::publish::sync_ahead(s, params), None),
"edit.previewShapeConversion" => ("Preview Shape Conversion", crate::shape_conversion::ahead(s, params), None),
"table.statistics" => ("Column Statistics", super::table_stats::stats_ahead(s, params), None),
_ => return Err("only Add Data, Load All, Repair/Reload Data, Convert To Annotation, models, scripts, tile archives, service listings, topology, Source File State and Column Statistics prepare background work".into()),
Comment thread
robmarkcole marked this conversation as resolved.
Resolved
};
Expand Down
27 changes: 24 additions & 3 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub mod policy;
pub mod prefs;
pub mod project;
mod roles;
pub mod shape_conversion;
pub use peer::Peer;
pub(crate) use roles::{Document, ParamRole, Role};
mod parameters;
Expand Down Expand Up @@ -1183,7 +1184,7 @@ fn edits_features(id: &str) -> bool {
}

impl Session {
/// Marks this thread as the desktop window owner for column statistics. Adapters with a
/// Marks this thread as the desktop window owner for column statistics and shape fitting. Adapters with a
/// window use the prepared read queue; headless adapters leave this disabled.
#[cfg(not(target_arch = "wasm32"))]
pub fn statistics_need_read_ahead(&mut self, enabled: bool) {
Expand Down Expand Up @@ -1787,9 +1788,12 @@ impl Session {
/// the active one; a command that takes a standalone table is checked against the one they
/// name.
fn conditions(&mut self, spec: &CommandSpec, params: &Value) -> (Option<&'static str>, Option<u32>, Option<u32>) {
let named = match params.get("layer") {
// Apply carries its explicit target inside the preview, even when another layer is
// active. Conditions and the streamed-edit preflight must judge that same target.
let layer_params = if spec.id == "edit.applyShapeConversion" { params.get("preview").unwrap_or(params) } else { params };
let named = match layer_params.get("layer") {
Some(serde_json::Value::Array(list)) => list.first().and_then(|v| self.layer_id(&serde_json::json!({"layer": v})).ok()),
Some(_) => self.layer_id(params).ok(),
Some(_) => self.layer_id(layer_params).ok(),
None => None,
};
let active = self.active_layer;
Expand Down Expand Up @@ -1844,6 +1848,22 @@ impl Session {
/// Runs `f` as the command `label`: when it `mutates`, the project is snapshotted for undo
/// and restored if `f` fails or panics.
pub(crate) fn guarded(&mut self, label: &'static str, mutates: bool, f: impl FnOnce(&mut Session) -> CmdResult) -> CmdResult {
self.guarded_inner(label, mutates, true, f)
}

/// An atomic host-call savepoint. The enclosing plugin transaction owns Undo; a guest may
/// handle this call's error and still succeed, so failure must restore its changes here.
pub(crate) fn savepoint(&mut self, label: &'static str, f: impl FnOnce(&mut Session) -> CmdResult) -> CmdResult {
self.guarded_inner(label, true, false, f)
}

fn guarded_inner(
&mut self,
label: &'static str,
mutates: bool,
record_undo: bool,
f: impl FnOnce(&mut Session) -> CmdResult,
) -> CmdResult {
let snapshot = mutates.then(|| self.project.clone());
let construction_snapshot = self.constructions.clone();
let trust = (self.trusted_tasks.clone(), self.trusted_models.clone(), self.trusted_notebooks.clone());
Expand Down Expand Up @@ -1890,6 +1910,7 @@ impl Session {
// [`Session::request_url`]) changed nothing: no undo step, nothing to save yet. The
// session's own flag says so, not the answer, which a plugin's command could forge.
(Ok(_), Some(_)) if std::mem::take(&mut self.request_only) => {}
(Ok(_), Some(_)) if !record_undo => {}
(Ok(_), Some(mut snap)) => {
// A successful script may publish and then remove the layer. Its undo
// snapshot still needs the committed file record, even without a live layer
Expand Down
17 changes: 14 additions & 3 deletions crates/engine/src/policy/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ impl Session {
let CallKind::Command { id, params } = &call.kind else {
return Err("only standalone archive or column-statistics commands can prepare a scoped read".into());
};
if !matches!(id.as_str(), "map.reloadTiles" | "map.repairTiles" | "table.statistics") {
if !matches!(id.as_str(), "map.reloadTiles" | "map.repairTiles" | "table.statistics" | "edit.previewShapeConversion") {
return Err("only standalone archive or column-statistics commands can prepare a scoped read".into());
}
let capture = |s: &mut Session| s.capture_read(id, params);
Expand Down Expand Up @@ -156,15 +156,25 @@ impl Session {
| "service.add"
| "source.syncState"
| "table.statistics"
| "edit.previewShapeConversion"
) && crate::cmd::edit::table_edit_in_background(command).is_none()
{
return Err("only Add Data, Load All, Repair/Reload Data, Convert To Annotation, models, scripts, tile archives, service reads, topology, Source File State and Column Statistics prepare background work".into());
}
let mut params = params.as_object().cloned().ok_or("read parameters must be an object")?;
// Scoped previews retain the raw invocation that was approved. Their admitted owner
// pins the resolved target; landing rechecks that these selectors still name it.
if matches!(
command,
"layer.loadAll" | "layer.reloadData" | "layer.repairSource" | "labels.convert" | "source.syncState" | "table.statistics"
) || (command == "edit.convertField" && params.get("table").is_none_or(Value::is_null))
"layer.loadAll"
| "layer.reloadData"
| "layer.repairSource"
| "labels.convert"
| "source.syncState"
| "table.statistics"
| "edit.previewShapeConversion"
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
) && (command != "edit.previewShapeConversion" || self.policy_user())
|| (command == "edit.convertField" && params.get("table").is_none_or(Value::is_null))
{
let id = self.layer_id(&Value::Object(params.clone()))?;
params.insert("layer".into(), json!(id));
Expand Down Expand Up @@ -941,6 +951,7 @@ impl Session {
};
let result = match txn {
Txn::Own => self.guarded(spec.label, spec.mutates, run),
Txn::Shared if spec.id == "edit.applyShapeConversion" => self.savepoint(spec.label, run),
Txn::Shared => run(self),
};
self.url_completion_landed(spec.id, &params, &result);
Expand Down
Loading
Loading