From 375d750096e28fa9e230e97148a69f0d8125ec1a Mon Sep 17 00:00:00 2001 From: lillith <35337584+0xlillith@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:15:39 +0100 Subject: [PATCH] Drawing: edit sheet sketches through shared commands (#7082) Add an explicitly owned sheet entry, typed create/edit/inspect/cancel commands, and reuse the existing rectangle/line/point implementations through the W38.0 store and R2 atomic solver boundary. Preserve source parameters and model active state; restore the sheet entry through drawing undo/redo and checkpoints. Eight new command tests pass. Across the selected original and new engine groups: 479 unique passed, zero failed, two pre-existing ignored. Native engine check, strict Clippy and wasm pass. Source-hashed CI-profile artifact reused for all runtime checks. Full repository and native/browser UI acceptance remain pending; this is a command subset, not all sketch tools or complete W38a. No kernel, format, dependency, shared catalog or CI changes. The pending locale delta needs main's existing #6448 loader on the drawings receiver. Original Cam store tests and commits retained; no competing store or parent claim. --- .../pending/drawing-sheet-sketch-editor.json | 8 + crates/engine/src/cmd/drawing_sketch.rs | 187 ++++++++++++ crates/engine/src/cmd/drawing_tests.rs | 280 ++++++++++++++++++ crates/engine/src/cmd/edit.rs | 4 +- crates/engine/src/cmd/mod.rs | 21 +- crates/engine/src/cmd/sketch.rs | 39 ++- crates/engine/src/cmd/sketch_create.rs | 16 +- crates/engine/src/cmd/sketch_store.rs | 60 ++++ crates/engine/src/lib.rs | 72 ++++- crates/engine/src/schema/drawing_sketch.rs | 57 ++++ crates/engine/src/schema/mod.rs | 1 + crates/ui-egui/src/agent_chat/tests.rs | 1 + docs/drawing-sheet-sketches.md | 95 ++++-- 13 files changed, 804 insertions(+), 37 deletions(-) create mode 100644 assets/locales/pending/drawing-sheet-sketch-editor.json create mode 100644 crates/engine/src/cmd/drawing_sketch.rs create mode 100644 crates/engine/src/schema/drawing_sketch.rs diff --git a/assets/locales/pending/drawing-sheet-sketch-editor.json b/assets/locales/pending/drawing-sheet-sketch-editor.json new file mode 100644 index 000000000..9adcde6f4 --- /dev/null +++ b/assets/locales/pending/drawing-sheet-sketch-editor.json @@ -0,0 +1,8 @@ +{ + "en": { + "cmd.drawing.sketch.create": "Create Sheet Sketch", + "cmd.drawing.sketch.edit": "Edit Sheet Sketch", + "cmd.drawing.sketch.inspect": "Inspect Sheet Sketch", + "cmd.sketch.cancel": "Cancel Sketch" + } +} diff --git a/crates/engine/src/cmd/drawing_sketch.rs b/crates/engine/src/cmd/drawing_sketch.rs new file mode 100644 index 000000000..e11770498 --- /dev/null +++ b/crates/engine/src/cmd/drawing_sketch.rs @@ -0,0 +1,187 @@ +//! Sheet-owned sketch lifecycle on the embedded drawing receiver (W38a). +//! Geometry tools reuse cmd::sketch and cmd::sketch_store; there is no second sketcher. +use super::{CommandSpec, sketch_store}; +use crate::params::bad; +use crate::schema::{drawing_sketch as contract, output_schema_for}; +use crate::{Result, Session, SheetSketchEdit}; +use serde::de::DeserializeOwned; +use serde_json::Value; +use solidcraft_doc::drawing::SheetSketch; +use solidcraft_doc::ids::{self, IdSource}; +use solidcraft_sketch::Sketch; +use std::sync::Arc; + +pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("drawing.sketch.create", "Create Sheet Sketch", crate::checked!("drawing.sketch.create", contract::CREATE, create)) + .in_drawing().doc_only().icon("sketch") + .contract(&contract::CREATE).output(output_schema_for::) + .params("owner: exact sheet id in the open drawing; name?: text. Creates and enters one sheet sketch in paper XY millimetres; one drawing undo step."), + CommandSpec::new("drawing.sketch.edit", "Edit Sheet Sketch", crate::checked!("drawing.sketch.edit", contract::EDIT, edit)) + .in_drawing().doc_only().noundo().icon("sketch") + .contract(&contract::EDIT).output(output_schema_for::) + .params("sketch: exact encoded sketch id in the open drawing. Enters that sheet sketch without changing its data or the source design."), + CommandSpec::new("drawing.sketch.inspect", "Inspect Sheet Sketch", crate::checked!("drawing.sketch.inspect", contract::INSPECT, inspect)) + .in_drawing().doc_only().noundo().icon("inspect") + .contract(&contract::INSPECT).output(output_schema_for::) + .params("sketch?: exact encoded id, else the active sheet sketch. Reports resolved paper-mm points and local entity ids without adopting the solution."), + +]; + +fn parsed(cmd: &str, p: &Value) -> Result { + T::deserialize(p).map_err(|e| bad(cmd, e.to_string())) +} +fn id(cmd: &str, text: &str) -> Result { + ids::decode(text).ok_or_else(|| bad(cmd, "an exact encoded drawing object id is required")) +} +fn no_entry(s: &Session, cmd: &str) -> Result<()> { + if s.active_sheet_sketch.is_some() { + return Err(bad(cmd, "finish or cancel the sheet sketch before entering another")); + } + Ok(()) +} + +fn create(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.sketch.create"; + let p: contract::Create = parsed(cmd, p)?; + no_entry(s, cmd)?; + let owner = s.drawing(cmd)?.clone(); + owner.validate().map_err(|e| bad(cmd, e.to_string()))?; + let sheet = id(cmd, &p.owner)?; + if !owner.sheets.iter().any(|record| record.id == sheet) { + return Err(bad(cmd, "the open drawing has no such sheet")); + } + let name = p.name.unwrap_or_else(|| "Sheet sketch".into()); + // Any object id held by drawing undo/redo must not name a new sketch either. + let retired: std::collections::BTreeSet = s + .undo + .iter() + .chain(&s.redo) + .filter_map(|step| step.doc.drawing(owner.id)) + .flat_map(|drawing| { + std::iter::once(drawing.id) + .chain(drawing.sources.iter().map(|record| record.id)) + .chain(drawing.sheets.iter().map(|record| record.id)) + .chain(drawing.sketches.iter().map(|record| record.id)) + }) + .collect(); + let mut source = IdSource::from_entropy(); + let mut fresh = None; + for _ in 0..64 { + let next = owner.allocate_id(&mut source)?; + if !retired.contains(&next) { + fresh = Some(next); + break; + } + } + let sketch = fresh.ok_or_else(|| bad(cmd, "could not allocate an unused sheet sketch id"))?; + s.edit_drawing(cmd, |drawing| { + drawing.sketches.push(Arc::new(SheetSketch { id: sketch, sheet, name, sketch: Sketch::new() })); + Ok(()) + })?; + s.active_sheet_sketch = Some(Arc::new(SheetSketchEdit { drawing: owner.id, sheet, sketch, original: None })); + s.selection.clear(); + reading(s, sketch, cmd) +} + +fn edit(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.sketch.edit"; + let p: contract::Edit = parsed(cmd, p)?; + let sketch = id(cmd, &p.sketch)?; + let owner = s.drawing(cmd)?.clone(); + if let Some(entry) = &s.active_sheet_sketch { + if entry.drawing == owner.id && entry.sketch == sketch { + return reading(s, sketch, cmd); // keep the original cancel boundary + } + return Err(bad(cmd, "finish or cancel the sheet sketch before entering another")); + } + let solved = s.doc.solve_sheet_sketch(owner.id, sketch)?; + let original = owner.sheet_sketch(sketch).cloned().ok_or_else(|| bad(cmd, "the open drawing has no such sketch"))?; + s.active_sheet_sketch = Some(Arc::new(SheetSketchEdit { drawing: owner.id, sheet: solved.sheet, sketch, original: Some(original) })); + s.selection.clear(); + s.revision += 1; + reading(s, sketch, cmd) +} + +fn inspect(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.sketch.inspect"; + let p: contract::Inspect = parsed(cmd, p)?; + let sketch = match p.sketch { + Some(text) => id(cmd, &text)?, + None => sketch_store::sheet_target(s, &Value::Null, cmd)?.sketch, + }; + reading(s, sketch, cmd) +} + +fn reading(s: &Session, sketch: u64, cmd: &str) -> Result { + let owner = s.drawing(cmd)?; + let solved = s.doc.solve_sheet_sketch(owner.id, sketch)?; + let record = owner.sheet_sketch(sketch).ok_or_else(|| bad(cmd, "the open drawing has no such sketch"))?; + let reading = contract::Reading { + drawing: ids::encode(owner.id), + sheet: ids::encode(solved.sheet), + sketch: ids::encode(sketch), + name: record.name.clone(), + editing: s + .active_sheet_sketch + .as_ref() + .is_some_and(|active| active.drawing == owner.id && active.sheet == solved.sheet && active.sketch == sketch), + solved: solved.report.keeps_orientation(), + dof: solved.report.dof, + points: solved + .sketch + .points + .iter() + .map(|point| contract::Point { id: point.id.clone(), at: [point.pos.x, point.pos.y], fixed: point.fixed }) + .collect(), + curves: solved.sketch.curves.iter().map(|curve| curve.id.clone()).collect(), + constraints: solved.sketch.constraints.iter().map(|constraint| constraint.id.clone()).collect(), + }; + serde_json::to_value(reading).map_err(|e| bad(cmd, e.to_string())) +} + +pub(super) fn finish(s: &mut Session, p: &Value) -> Result { + let _: contract::Empty = parsed("sketch.finish", p)?; + let entry = sketch_store::sheet_target(s, &Value::Null, "sketch.finish")?; + let mut result = reading(s, entry.sketch, "sketch.finish")?; + s.active_sheet_sketch = None; + s.selection.clear(); + s.revision += 1; + if let Some(object) = result.as_object_mut() { + object.insert("editing".into(), Value::Bool(false)); + } + Ok(result) +} + +pub(super) fn cancel(s: &mut Session, p: &Value) -> Result { + let cmd = "sketch.cancel"; + let _: contract::Empty = parsed(cmd, p)?; + let entry = sketch_store::sheet_target(s, &Value::Null, cmd)?; + let removed = entry.original.is_none(); + s.edit_drawing(cmd, |drawing| { + let at = drawing + .sketches + .iter() + .position(|record| record.id == entry.sketch) + .ok_or_else(|| bad(cmd, "the edited sheet sketch no longer exists"))?; + match &entry.original { + Some(original) => { + let slot = drawing.sketches.get_mut(at).ok_or_else(|| bad(cmd, "the sheet sketch changed while cancelling"))?; + *slot = original.clone(); + } + None => { + drawing.sketches.remove(at); + } + } + Ok(()) + })?; + s.active_sheet_sketch = None; + s.selection.clear(); + s.revision += 1; + serde_json::to_value(contract::Cancelled { + drawing: ids::encode(entry.drawing), + sheet: ids::encode(entry.sheet), + sketch: ids::encode(entry.sketch), + removed, + }) + .map_err(|e| bad(cmd, e.to_string())) +} diff --git a/crates/engine/src/cmd/drawing_tests.rs b/crates/engine/src/cmd/drawing_tests.rs index 3f7af19b0..6a246c25d 100644 --- a/crates/engine/src/cmd/drawing_tests.rs +++ b/crates/engine/src/cmd/drawing_tests.rs @@ -533,3 +533,283 @@ fn receiver_store_callback_failure_preserves_model_drawings_and_history() { assert_eq!((s.undo.len(), s.redo.len(), s.evaluations), history); assert!(sketch_store::read(&s.doc, id).unwrap().resolve_point("not_committed").is_none()); } + +// W38a R4: exercise real commands and Session history, not an alternative sketcher. +fn sheet_editor() -> (Session, u64, u64, Value) { + let mut s = design(); + s.doc_mut().units = "in".into(); + let drawing = run(&mut s, "drawing.create", json!({"name": "Paper", "units": "in"})); + let owner = drawing["sheets"][0]["id"].clone(); + let made = run(&mut s, "drawing.sketch.create", json!({"owner": owner, "name": "Detail"})); + let d = ids::decode(made["drawing"].as_str().unwrap()).unwrap(); + let sk = ids::decode(made["sketch"].as_str().unwrap()).unwrap(); + (s, d, sk, made) +} + +#[test] +fn sheet_editor_existing_tools_make_paper_geometry_without_evaluating_the_model() { + use solidcraft_geom::Vec2; + let (mut s, d, sk, made) = sheet_editor(); + let source = s.doc.clone(); + let model = s.model.state(); + let count = s.evaluations; + let steps = s.undo.len(); + assert!(s.active_sketch.is_none(), "a sheet id is never a model active_sketch"); + assert_eq!(s.active_sheet_sketch.as_ref().unwrap().sketch, sk); + let rectangle = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [15,10], "p1": [55,30]})); + assert_eq!(rectangle["created"]["curves"].as_array().unwrap().len(), 4); + let record = s.doc.drawing(d).unwrap().sheet_sketch(sk).unwrap(); + assert_eq!(record.sketch.curves.len(), 4); + for at in [[15.0, 10.0], [55.0, 10.0], [55.0, 30.0], [15.0, 30.0]] { + assert!(record.sketch.points.iter().any(|p| p.pos.dist(Vec2::new(at[0], at[1])) < 1e-8)); + } + run(&mut s, "sketch.line", json!({"points": [[70,10],[100,50]]})); + let record = s.doc.drawing(d).unwrap().sheet_sketch(sk).unwrap(); + assert_eq!(record.sketch.curves.len(), 5); + assert_eq!(s.undo.len(), steps + 2); + assert_eq!(s.undo.last().unwrap().part, Some(d)); + assert_eq!((s.evaluations, &s.doc.features, &s.doc.params), (count, &source.features, &source.params)); + assert!(Arc::ptr_eq(&model, &s.model.state())); + let inspected = run(&mut s, "drawing.sketch.inspect", json!({})); + assert_eq!(inspected["sketch"], made["sketch"]); + assert_eq!(inspected["curves"].as_array().unwrap().len(), 5); + assert_eq!(s.undo.len(), steps + 2, "inspection adds no step"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.drawing(d).unwrap().sheet_sketch(sk).unwrap().sketch.curves.len(), 4); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc.drawing(d).unwrap().sheet_sketch(sk).unwrap().sketch.curves.len(), 5); + assert_eq!(s.evaluations, count); +} + +#[test] +fn sheet_editor_point_and_line_expressions_keep_paper_defaults_and_read_only_source() { + let (mut s, d, sk, _) = sheet_editor(); + s.doc_mut().set_param("Inset", "1", Some("in"), None).unwrap(); + s.doc_mut().set_param("Angle", "90", Some("deg"), None).unwrap(); + let original = s.doc.clone(); + let count = s.evaluations; + run(&mut s, "sketch.point", json!({"point": ["Inset + 5", "2"], "id": "driven"})); + run(&mut s, "sketch.line", json!({"points": [["Inset", "5"], ["Inset + 10", "5"]]})); + let sketch = &s.doc.drawing(d).unwrap().sheet_sketch(sk).unwrap().sketch; + let point = &sketch.points[sketch.resolve_point("driven").unwrap()]; + assert!((point.pos.x - 30.4).abs() < 1e-9); + assert_eq!(point.pos.y, 2.0); + assert_eq!(point.exprs.as_ref().unwrap().x.as_deref(), Some("Inset + 5")); + assert!(sketch.points.iter().any(|p| (p.pos.x - 25.4).abs() < 1e-9 && p.pos.y == 5.0)); + assert!(sketch.points.iter().any(|p| (p.pos.x - 35.4).abs() < 1e-9 && p.pos.y == 5.0)); + assert_eq!((&s.doc.params, &s.doc.features), (&original.params, &original.features)); + for point in [json!(["Missing", 0]), json!(["Angle", 0]), json!(["1 / 0", 0])] { + let before = s.doc.clone(); + let entry = s.active_sheet_sketch.clone(); + let history = (s.undo.len(), s.redo.len()); + refused(&mut s, "sketch.point", json!({"point": point})); + assert!(Arc::ptr_eq(&before, &s.doc)); + assert_eq!(s.active_sheet_sketch, entry); + assert_eq!((s.undo.len(), s.redo.len()), history); + } + assert_eq!(s.evaluations, count); +} + +#[test] +fn sheet_editor_finish_cancel_and_their_undo_preserve_the_correct_entry() { + let (mut s, d, sk, made) = sheet_editor(); + let count = s.evaluations; + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [15,10], "p1": [55,30]})); + let finished = s.doc.drawing(d).unwrap().sheet_sketch(sk).unwrap().clone(); + assert_eq!(run(&mut s, "sketch.finish", json!({}))["editing"], false); + assert!(s.active_sheet_sketch.is_none()); + run(&mut s, "drawing.sketch.edit", json!({"sketch": made["sketch"]})); + run(&mut s, "sketch.point", json!({"point": [90,60], "id": "temporary"})); + let edited = s.doc.drawing(d).unwrap().sheet_sketch(sk).unwrap().clone(); + // Re-entering the same sketch must not move the cancellation boundary. + run(&mut s, "drawing.sketch.edit", json!({"sketch": made["sketch"]})); + assert_eq!(run(&mut s, "sketch.cancel", json!({}))["removed"], false); + assert!(Arc::ptr_eq(&finished, s.doc.drawing(d).unwrap().sheet_sketch(sk).unwrap())); + assert!(s.active_sheet_sketch.is_none()); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.drawing(d).unwrap().sheet_sketch(sk).unwrap().sketch, edited.sketch); + assert_eq!(s.active_sheet_sketch.as_ref().unwrap().sketch, sk); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc.drawing(d).unwrap().sheet_sketch(sk).unwrap().sketch, finished.sketch); + assert!(s.active_sheet_sketch.is_none()); + let sheet = made["sheet"].clone(); + let new = run(&mut s, "drawing.sketch.create", json!({"owner": sheet})); + let new_id = ids::decode(new["sketch"].as_str().unwrap()).unwrap(); + run(&mut s, "sketch.point", json!({"point": [5,7]})); + assert_eq!(run(&mut s, "sketch.cancel", json!({}))["removed"], true); + assert!(s.doc.drawing(d).unwrap().sheet_sketch(new_id).is_none()); + assert_eq!(s.doc.drawing(d).unwrap().sheet_sketch(sk).unwrap().sketch, finished.sketch); + run(&mut s, "edit.undo", json!({})); + assert!(s.doc.drawing(d).unwrap().sheet_sketch(new_id).is_some()); + run(&mut s, "edit.redo", json!({})); + assert!(s.doc.drawing(d).unwrap().sheet_sketch(new_id).is_none()); + assert!(s.active_sheet_sketch.is_none()); + assert_eq!(s.evaluations, count); +} + +#[test] +fn sheet_editor_checkpoint_scratch_and_reopen_keep_owners_separate() { + let (mut s, d, sk, made) = sheet_editor(); + let count = s.evaluations; + let checkpoint = run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].clone(); + let before = s.doc.clone(); + let mut scratch = s.scratch(); + run(&mut scratch, "sketch.rectangle.two_point", json!({"p0": [15,10], "p1": [55,30]})); + assert!(Arc::ptr_eq(&before, &s.doc)); + assert!(s.doc.drawing(d).unwrap().sheet_sketch(sk).unwrap().sketch.curves.is_empty()); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [15,10], "p1": [55,30]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": checkpoint})); + assert!(s.doc.drawing(d).unwrap().sheet_sketch(sk).unwrap().sketch.curves.is_empty()); + assert_eq!(s.active_sheet_sketch.as_ref().unwrap().sketch, sk); + run(&mut s, "sketch.line", json!({"points": [[15,10],[55,30]]})); + run(&mut s, "sketch.finish", json!({})); + let saved = s.doc.to_json(); + let document = solidcraft_doc::Document::from_json(&saved).unwrap(); + let mut reopened = Session::new(document); + assert!(reopened.active_sheet_sketch.is_none()); + run(&mut reopened, "drawing.open", json!({"drawing": made["drawing"]})); + run(&mut reopened, "drawing.sketch.edit", json!({"sketch": made["sketch"]})); + let result = run(&mut reopened, "drawing.sketch.inspect", json!({})); + assert_eq!(result["curves"].as_array().unwrap().len(), 1); + assert_eq!(reopened.doc.to_json(), saved); + assert_eq!(s.evaluations, count); +} + +#[test] +fn sheet_editor_rejects_cross_targets_model_tools_and_source_mutation() { + let (mut s, d, sk, made) = sheet_editor(); + let before = s.doc.clone(); + let entry = s.active_sheet_sketch.clone(); + let state = s.model.state(); + let history = (s.undo.len(), s.redo.len(), s.evaluations); + let model = s.doc.features[0].id; + assert_ne!(model, sk); + for (command, params) in [ + ("sketch.point", json!({"sketch": model, "point": [2,3]})), + ("sketch.point", json!({"sketch": -1, "point": [2,3]})), + ("sketch.point", json!({"sketch": 1.5, "point": [2,3]})), + ("sketch.line", json!({"points": ["vertex:1,2,3",[4,5]]})), + ("sketch.dimension", json!({"entities": [], "value": "Forbidden = 3"})), + ("sketch.project", json!({"refs": []})), + ("sketch.create", json!({"plane": "XY"})), + ("drawing.close", json!({})), + ("drawing.open", json!({"drawing": made["drawing"]})), + ("drawing.delete", json!({"drawing": made["drawing"]})), + ("drawing.sketch.create", json!({"owner": made["sheet"]})), + ] { + refused(&mut s, command, params); + assert!(Arc::ptr_eq(&s.doc, &before), "{command}"); + assert_eq!(s.active_sheet_sketch, entry, "{command}"); + assert_eq!((s.undo.len(), s.redo.len(), s.evaluations), history, "{command}"); + } + let result = super::super::sketch_store::edit_sheet(&mut s, &json!({}), "test", |_sketch, doc| { + doc.name = "Forbidden mutation".into(); + Ok(()) + }); + assert!(result.unwrap_err().to_string().contains("cannot change the source design")); + assert!(Arc::ptr_eq(&s.doc, &before) && Arc::ptr_eq(&s.model.state(), &state)); + assert_eq!(s.open_drawing, Some(d)); +} + +#[test] +fn sheet_editor_new_commands_validate_hostile_inputs_and_declare_schemas() { + let mut s = design(); + let drawing = run(&mut s, "drawing.create", json!({})); + let before = s.doc.clone(); + let history = (s.undo.len(), s.redo.len(), s.evaluations); + for params in [ + json!({}), + json!({"owner": 1}), + json!({"owner": "not-an-id"}), + json!({"owner": drawing["id"]}), + json!({"owner": drawing["sheets"][0]["id"], "name": " "}), + json!({"owner": drawing["sheets"][0]["id"], "name": "X".repeat(257)}), + json!({"owner": drawing["sheets"][0]["id"], "unexpected": true}), + json!([]), + ] { + refused(&mut s, "drawing.sketch.create", params); + assert!(Arc::ptr_eq(&s.doc, &before)); + assert!(s.active_sheet_sketch.is_none()); + assert_eq!((s.undo.len(), s.redo.len(), s.evaluations), history); + } + for command in ["drawing.sketch.create", "drawing.sketch.edit", "drawing.sketch.inspect", "sketch.cancel"] { + let spec = find_command(command).unwrap(); + assert!(spec.contract.is_some() && spec.output.is_some(), "{command}"); + } + s.param_check = crate::schema::ParamCheck::Strict; + let made = run(&mut s, "drawing.sketch.create", json!({"owner": drawing["sheets"][0]["id"]})); + assert!(made["editing"].as_bool().unwrap()); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "drawing.sketch.edit", json!({"sketch": made["sketch"]})); + run(&mut s, "sketch.cancel", json!({})); +} + +#[test] +fn sheet_editor_same_numeric_id_in_two_drawings_and_model_never_retargets_geometry() { + use solidcraft_doc::drawing::SheetSketch; + use solidcraft_sketch::Sketch; + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Model"})); + let id = s.active_sketch.unwrap(); + run(&mut s, "sketch.line", json!({"points": [[0,0],[40,0]]})); + run(&mut s, "sketch.finish", json!({})); + let model = s.doc.sketch(id).unwrap().clone(); + run(&mut s, "drawing.create", json!({"name": "First"})); + s.edit_drawing("test", |drawing| { + drawing.sketches.push(Arc::new(SheetSketch { id, sheet: drawing.sheets[0].id, name: "Same id".into(), sketch: Sketch::new() })); + Ok(()) + }) + .unwrap(); + let first = open_one(&s); + let mut second = (*first).clone(); + second.id = first.allocate_id(&mut IdSource::seeded(7082)).unwrap(); + second.name = "Second".into(); + let second_id = second.id; + s.doc_mut().put_drawing(Arc::new(second)); + let second = s.doc.drawing(second_id).unwrap().clone(); + let count = s.evaluations; + run(&mut s, "drawing.sketch.edit", json!({"sketch": ids::encode(id)})); + run(&mut s, "sketch.point", json!({"sketch": id, "point": [15,10], "id": "first_point"})); + assert_eq!(s.doc.sketch(id).unwrap(), &model); + assert!(Arc::ptr_eq(s.doc.drawing(second_id).unwrap(), &second)); + run(&mut s, "sketch.finish", json!({})); + let first_edited = s.doc.drawing(first.id).unwrap().clone(); + run(&mut s, "drawing.open", the(second_id)); + run(&mut s, "drawing.sketch.edit", json!({"sketch": ids::encode(id)})); + run(&mut s, "sketch.point", json!({"point": [50,20], "id": "second_point"})); + assert_eq!(s.doc.sketch(id).unwrap(), &model); + assert!(Arc::ptr_eq(s.doc.drawing(first.id).unwrap(), &first_edited)); + assert!(s.doc.drawing(second_id).unwrap().sheet_sketch(id).unwrap().sketch.resolve_point("first_point").is_none()); + run(&mut s, "edit.undo", json!({})); + assert!(s.doc.drawing(second_id).unwrap().sheet_sketch(id).unwrap().sketch.resolve_point("second_point").is_none()); + assert!(Arc::ptr_eq(s.doc.drawing(first.id).unwrap(), &first_edited)); + assert_eq!(s.evaluations, count); +} + +#[test] +fn sheet_editor_commands_and_refusals_do_not_evaluate_a_stale_model() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + let model_sketch = s.active_sketch.unwrap(); + let line = run(&mut s, "sketch.line", json!({"points": [[0,0],[40,0]]}))["curves"][0].as_str().unwrap().to_string(); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.box", json!({"length": 5,"width": 5,"height": 5})); + run(&mut s, "sketch.edit", json!({"sketch": model_sketch})); + run(&mut s, "sketch.drag", json!({"entity": format!("{line}.end"), "from": [40,0], "to": [45,3], "live": true})); + assert!(s.model.is_stale(), "the fixture includes an unfinished model gesture"); + let model = s.model.state(); + let count = s.evaluations; + let drawing = run(&mut s, "drawing.create", json!({})); + run(&mut s, "drawing.sketch.create", json!({"owner": drawing["sheets"][0]["id"]})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [15,10], "p1": [55,30]})); + run(&mut s, "drawing.sketch.inspect", json!({})); + refused(&mut s, "solid.box", json!({"length": 3,"width": 3,"height": 3})); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.redo", json!({})); + run(&mut s, "sketch.finish", json!({})); + assert!(s.model.is_stale()); + assert!(Arc::ptr_eq(&model, &s.model.state())); + assert_eq!(s.evaluations, count); + assert_eq!(s.active_sketch, Some(model_sketch), "model active state was not overwritten"); +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index d5f01b117..13ada72b5 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -114,13 +114,15 @@ fn nothing(s: &Session, what: &str) -> EngineError { fn go_to(s: &mut Session, snap: Snapshot) -> Snapshot { let was = Snapshot { part: snap.part, ..Snapshot::of(s, &snap.label) }; let snap = match snap.part { - Some(id) => Snapshot { doc: drawing_from(&s.doc, &snap.doc, id), ..was.clone() }, + Some(id) => Snapshot { doc: drawing_from(&s.doc, &snap.doc, id), active_sheet_sketch: snap.active_sheet_sketch.clone(), ..was.clone() }, None => Snapshot { doc: drawings_from(snap.doc, &s.doc), ..snap }, }; let same = Arc::ptr_eq(&s.doc, &snap.doc); let moved = s.active_sketch != snap.active_sketch || s.pending_moves != snap.pending_moves; s.doc = snap.doc; s.active_sketch = snap.active_sketch; + s.active_sheet_sketch = snap.active_sheet_sketch; + s.prune_sheet_sketch_edit(); s.pending_moves = snap.pending_moves; s.selection.clear(); // A new document is evaluated by `execute`, and a drawing's change evaluates nothing. diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 423f0fbf7..8db367a56 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -32,6 +32,7 @@ mod construct; mod delete; mod diagnostics; mod drawing; +mod drawing_sketch; mod edit; mod face; mod features; @@ -111,6 +112,8 @@ pub type SchemaFn = fn() -> schemars::Schema; pub enum Part { Model, Drawing, + /// A shared sketch tool: model or the explicitly active sheet sketch. + Sketch, Any, } @@ -227,12 +230,23 @@ impl CommandSpec { self.part = Part::Drawing; self } + /// Uses the shared sketch tool on its active model or explicit sheet receiver. + pub const fn in_sketch_part(mut self) -> Self { + self.part = Part::Sketch; + self + } /// Whether the command can run in `s` now: on the part open, and enabled. The one check /// running a command, running it inside another and listing it make. pub fn allowed(&self, s: &Session) -> std::result::Result<(), String> { + if s.active_sheet_sketch.is_some() && matches!(self.id, "drawing.create" | "drawing.open" | "drawing.close" | "drawing.delete") { + return Err("finish or cancel the sheet sketch before switching drawings".into()); + } match (self.part, s.open_drawing.is_some()) { (Part::Model, true) => Err("a drawing is open: close it to change the model (drawing.close)".into()), (Part::Drawing, false) => Err("open a drawing first (drawing.open, or drawing.create)".into()), + (Part::Sketch, true) if !s.active_sheet_sketch.as_ref().is_some_and(|entry| Some(entry.drawing) == s.open_drawing) => { + Err("a drawing is open: enter a sheet sketch first (drawing.sketch.create or drawing.sketch.edit)".into()) + } _ => (self.enabled)(s), } } @@ -279,7 +293,11 @@ pub fn always(_: &Session) -> std::result::Result<(), String> { } pub fn in_sketch(s: &Session) -> std::result::Result<(), String> { - if s.active_sketch.is_some() { Ok(()) } else { Err("no sketch is being edited (Create Sketch or Edit Sketch first)".into()) } + let active = match s.open_drawing { + Some(drawing) => s.active_sheet_sketch.as_ref().is_some_and(|entry| entry.drawing == drawing), + None => s.active_sketch.is_some(), + }; + if active { Ok(()) } else { Err("no sketch is being edited (Create Sketch or Edit Sketch first)".into()) } } /// The mirror of [`in_sketch`], for a command that acts on bodies and has nothing to offer the @@ -338,6 +356,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(view_navigation::COMMANDS.iter()); v.extend(view_dxf::COMMANDS.iter()); v.extend(drawing::COMMANDS.iter()); + v.extend(drawing_sketch::COMMANDS.iter()); v.extend(diagnostics::COMMANDS.iter()); v.extend(render::COMMANDS.iter()); v diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 66720d0c0..5669b1e8a 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -32,8 +32,13 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("sketch") .params("plane: XY|XZ|YZ | construction plane name or id | {origin?: [x,y,z] numbers in mm, default [0,0,0] (not an expression), x_dir, y_dir} | {face: [world x,y,z], body?: exact world body, index?: face index, path?: complete occurrence ids, fixed?: bool}; new face attachments require a unique certified source (a flat face of a sheet metal body attaches to its panel instead, in the flat pattern's coordinates), fixed:true explicitly freezes the selected plane; offset?: expr, flip?: bool | \"x\" | \"y\" (not on a face: sketch the plane from its other side, so the normal and the default extrude direction are reversed; a half turn about the plane's own x or y axis, true picks the one keeping the sketch's y axis upward; offset still moves along the unflipped normal), project_edges?: bool, name?"), CommandSpec::new("sketch.edit", "Edit Sketch", edit_sketch).noundo().icon("sketch").params("sketch: id or name"), - CommandSpec::new("sketch.finish", "Finish Sketch", finish_sketch).at("SKETCH", "FINISH SKETCH").icon("finish").enabled(in_sketch).noundo(), + CommandSpec::new("sketch.finish", "Finish Sketch", finish_sketch).in_sketch_part().at("SKETCH", "FINISH SKETCH").icon("finish").enabled(in_sketch).noundo(), + CommandSpec::new("sketch.cancel", "Cancel Sketch", crate::checked!("sketch.cancel", crate::schema::drawing_sketch::EMPTY, super::drawing_sketch::cancel)) + .in_drawing().doc_only().icon("close").enabled(in_sketch) + .contract(&crate::schema::drawing_sketch::EMPTY).output(crate::schema::output_schema_for::) + .params("Restore the active sheet sketch to its entry geometry (or remove a new sketch), close editing and record the change in drawing undo. Does not change other drawing data or the source model."), CommandSpec::new("sketch.line", "Line", draw_line) + .in_sketch_part() .at("SKETCH", "CREATE") .icon("line") .key("L") @@ -43,6 +48,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .enabled(in_sketch) .params(concat!("command: sketch creation command, params: object, dimensions: object of role to numeric or expression value; creates geometry and all driving dimensions atomically in one undo step", created_doc!())), CommandSpec::new("sketch.rectangle.two_point", "2-Point Rectangle", rect_two_point) + .in_sketch_part() .at("SKETCH", "CREATE") .icon("rect") .key("R") @@ -114,7 +120,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("slot_overall") .enabled(in_sketch) .params(concat!("p0, p1: overall ends, width", connect_doc!(), created_doc!())), - CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them), id?", connect_doc!(), created_doc!())), + CommandSpec::new("sketch.point", "Point", draw_point).in_sketch_part().at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them), id?", connect_doc!(), created_doc!())), CommandSpec::new("sketch.dimension", "Sketch Dimension", dimension).at("SKETCH", "CREATE").icon("dimension").key("D").enabled(in_sketch).params( "entities: [refs], type?: auto|distance|horizontal|vertical|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override), or `name = expression` (e.g. \"width = 40\"), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them is the distance between them, above or below them horizontal, beside them vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled", ), @@ -217,6 +223,9 @@ pub(super) fn edit( strict: bool, f: impl FnOnce(&mut Sketch, &mut solidcraft_doc::Document) -> Result, ) -> Result<(T, Value)> { + if s.open_drawing.is_some() { + return sketch_store::edit_sheet(s, p, cmd, f); + } let id = sketch_store::target(s, p, cmd)?; let (out, rep) = edit_solved(s, id, strict, Analysis::Freedom, |sk, doc| Ok((f(sk, doc)?, Left::Unsolved)))?; Ok((out, rep.map(|rep| report_json(&rep)).unwrap_or(Value::Null))) @@ -427,10 +436,14 @@ impl PArg { } pub(super) fn parg(sk: &mut Sketch, doc: &solidcraft_doc::Document, v: &Value, cmd: &str) -> Result { + parg_in(sk, doc, v, cmd, false) +} + +fn parg_in(sk: &mut Sketch, doc: &solidcraft_doc::Document, v: &Value, cmd: &str, paper: bool) -> Result { if let Some(p) = vec2(v) { return Ok(PArg::At(p)); } - if let Some((at, exprs)) = expr_point(doc, v, cmd)? { + if let Some((at, exprs)) = expr_point_in(doc, v, cmd, paper)? { return Ok(match exprs { Some(exprs) => PArg::Ref(add_placed_point(sk, at, exprs, None)?, at), None => PArg::At(at), @@ -459,13 +472,13 @@ const POINT_MUST: &str = "a point's coordinates must be numbers or expressions o /// A point given as `[x, y]` with a coordinate typed as text: where it is now and, when a /// coordinate names a parameter, the expressions that place it (none: a plain point). -pub(super) fn expr_point(doc: &solidcraft_doc::Document, v: &Value, cmd: &str) -> Result)>> { +fn expr_point_in(doc: &solidcraft_doc::Document, v: &Value, cmd: &str, paper: bool) -> Result)>> { let Some([x, y]) = v.as_array().map(Vec::as_slice) else { return Ok(None) }; if !x.is_string() && !y.is_string() { return Ok(None); } - let (px, ex) = super::sketch_create::text_number(doc, x, cmd, "point x", POINT_MUST, false)?; - let (py, ey) = super::sketch_create::text_number(doc, y, cmd, "point y", POINT_MUST, false)?; + let (px, ex) = super::sketch_create::text_number_in(doc, x, cmd, "point x", POINT_MUST, false, paper)?; + let (py, ey) = super::sketch_create::text_number_in(doc, y, cmd, "point y", POINT_MUST, false, paper)?; let exprs = (ex.is_some() || ey.is_some()).then_some(PointExprs { x: ex, y: ey }); Ok(Some((Vec2::new(px, py), exprs))) } @@ -775,6 +788,9 @@ fn edit_sketch(s: &mut Session, p: &Value) -> Result { } fn finish_sketch(s: &mut Session, _p: &Value) -> Result { + if s.open_drawing.is_some() { + return super::drawing_sketch::finish(s, _p); + } let id = s.active_sketch.take(); s.revision += 1; let profiles = id.and_then(|i| s.model.state().sketch(i).map(|ss| ss.profiles.len())).unwrap_or(0); @@ -786,7 +802,11 @@ fn finish_sketch(s: &mut Session, _p: &Value) -> Result { fn draw_line(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.line"; - let p = &super::sketch_project::snap_points(s, p, cmd)?; + let paper = s.open_drawing.is_some(); + // Model projections and automatic model-reference snaps are not sheet tools. + // Plain coordinates/local ids still use the existing parser below; unsupported + // reference forms fail there without creating a link or falling back to a model. + let p = &if paper { p.clone() } else { super::sketch_project::snap_points(s, p, cmd)? }; let list = p.get("points").and_then(Value::as_array).cloned().ok_or_else(|| bad(cmd, "`points` must be a list"))?; if list.len() < 2 || list.len() > 10_000 { return Err(bad(cmd, "a line needs 2 or more points")); @@ -795,7 +815,7 @@ fn draw_line(s: &mut Session, p: &Value) -> Result { let infer = bool_(p, "infer").unwrap_or(false); let ids = string_list(p, "ids"); let ((curves, cons), info) = draw(s, p, cmd, |sk, doc| { - let args: Vec = list.iter().map(|v| parg(sk, doc, v, cmd)).collect::>()?; + let args: Vec = list.iter().map(|v| parg_in(sk, doc, v, cmd, paper)).collect::>()?; let n = args.len(); let segs = if closed { n } else { n - 1 }; let mut pts: Vec> = args.iter().map(PArg::idx).collect(); @@ -1369,9 +1389,10 @@ fn slot_overall(s: &mut Session, p: &Value) -> Result { fn draw_point(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.point"; + let paper = s.open_drawing.is_some(); let id = str_(p, "id").map(str::to_string); let ((pid, cons), info) = edit(s, p, cmd, false, |sk, doc| { - let i = match expr_point(doc, p.get("point").unwrap_or(&Value::Null), cmd)? { + let i = match expr_point_in(doc, p.get("point").unwrap_or(&Value::Null), cmd, paper)? { Some((at, Some(exprs))) => add_placed_point(sk, at, exprs, id.as_deref())?, Some((at, None)) => sk.add_point(at, id.as_deref())?, None => sk.add_point(req_vec2(cmd, p, "point")?, id.as_deref())?, diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index ce28c4d9b..1ddc88f1a 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -168,6 +168,20 @@ const AT_MUST: &str = "`at` must be the baseline start [x, y], each a number or /// to. Returns the value (mm or radians) and the expression kept. Anything else is refused with /// `must`. pub(super) fn text_number(doc: &solidcraft_doc::Document, v: &Value, cmd: &str, key: &str, must: &str, angle: bool) -> Result<(f64, Option)> { + text_number_in(doc, v, cmd, key, must, angle, false) +} + +/// Shared numeric parsing with explicit paper defaults. The source parameter +/// evaluator still sees the original design and its own parameter units. +pub(super) fn text_number_in( + doc: &solidcraft_doc::Document, + v: &Value, + cmd: &str, + key: &str, + must: &str, + angle: bool, + paper: bool, +) -> Result<(f64, Option)> { use solidcraft_doc::expr::{self, Kind}; let kind = if angle { Kind::Angle } else { Kind::Length }; match v { @@ -176,7 +190,7 @@ pub(super) fn text_number(doc: &solidcraft_doc::Document, v: &Value, cmd: &str, Ok((if angle { x.to_radians() } else { x }, None)) } Value::String(e) if !e.trim().is_empty() && e.len() <= 4096 => { - let e = doc.with_design_unit(e.trim(), kind); + let e = if paper { e.trim().to_string() } else { doc.with_design_unit(e.trim(), kind) }; match doc.eval(&e, kind) { Ok(x) => { let x = crate::params::finite(x).ok_or_else(|| bad(cmd, must))?; diff --git a/crates/engine/src/cmd/sketch_store.rs b/crates/engine/src/cmd/sketch_store.rs index aa131ac9f..a4e2967e4 100644 --- a/crates/engine/src/cmd/sketch_store.rs +++ b/crates/engine/src/cmd/sketch_store.rs @@ -66,6 +66,66 @@ pub(super) fn checked(sk: &Sketch) -> Result<()> { Ok(()) } +/// The exact active sheet target, checked before a shared tool reads or edits it. +/// A number/string can confirm that target; it never selects a model or another sheet. +pub(super) fn sheet_target(s: &Session, p: &Value, cmd: &str) -> Result> { + let entry = s.active_sheet_sketch.as_ref().ok_or_else(|| bad(cmd, "no sheet sketch is being edited"))?; + if s.open_drawing != Some(entry.drawing) { + return Err(bad(cmd, "the edited sketch does not belong to the open drawing")); + } + let mut owners = s.doc.drawings.iter().filter(|drawing| drawing.id == entry.drawing); + let owner = owners.next().ok_or_else(|| bad(cmd, "the edited drawing no longer exists"))?; + if owners.next().is_some() { + return Err(bad(cmd, "the edited drawing id is ambiguous")); + } + owner.validate().map_err(|e| bad(cmd, e.to_string()))?; + let record = owner.sheet_sketch(entry.sketch).ok_or_else(|| bad(cmd, "the edited sheet sketch no longer exists"))?; + if record.sheet != entry.sheet { + return Err(bad(cmd, "the edited sketch's owning sheet changed")); + } + if let Some(given) = p.get("sketch").filter(|value| !value.is_null()) { + let target = match given { + Value::Number(number) => number.as_u64(), + Value::String(text) => solidcraft_doc::ids::decode(text), + _ => None, + } + .ok_or_else(|| bad(cmd, "a sheet sketch target must be its exact id"))?; + if target != entry.sketch { + return Err(bad(cmd, "finish or cancel before selecting a different sheet sketch")); + } + } + Ok(entry.clone()) +} + +/// Apply an existing geometry tool through R2. The legacy callback may read its +/// Document, but any attempted source mutation is refused before publication. +/// This is the sheet receiver of this store, not a second store or solver. +pub(super) fn edit_sheet( + s: &mut Session, + p: &Value, + cmd: &str, + change: impl FnOnce(&mut Sketch, &mut Document) -> Result, +) -> Result<(T, Value)> { + let entry = sheet_target(s, p, cmd)?; + let mut candidate = s.doc.solve_sheet_sketch(entry.drawing, entry.sketch)?.sketch; + let mut source = (*s.doc).clone(); + let out = change(&mut candidate, &mut source)?; + if source != *s.doc { + return Err(bad(cmd, "a sheet sketch cannot change the source design or its parameters")); + } + let (_, solved) = source.edit_sheet_sketch(entry.drawing, entry.sketch, |sketch| { + *sketch = candidate; + Ok(()) + })?; + if solved.sheet != entry.sheet { + return Err(bad(cmd, "the edited sketch's owning sheet changed")); + } + if source != *s.doc { + s.doc = std::sync::Arc::new(source); + } + Ok((out, super::sketch::report_json(&solved.report))) +} + #[cfg(test)] mod tests { use serde_json::{Value, json}; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f46c8c115..d640dc386 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -157,12 +157,24 @@ struct BodyRename { new: String, } +/// A sheet-sketch editing entry. Its owner is never a model feature id. +/// Original geometry is only the cancel boundary; Session keeps the one undo history. +#[derive(Clone, Debug, PartialEq)] +pub struct SheetSketchEdit { + pub drawing: u64, + pub sheet: u64, + pub sketch: u64, + pub(crate) original: Option>, +} + /// One undo step. #[derive(Clone, Debug)] pub struct Snapshot { pub label: String, pub doc: Arc, pub active_sketch: Option, + /// Explicitly owned sheet edit, independent of the model sketch being edited. + pub active_sheet_sketch: Option>, pub pending_moves: std::collections::BTreeMap, /// The part of the design the step changed: a drawing (by id), or the model and the list of /// drawings (`None`). Undo and redo go through one part's steps (`edit.undo`). @@ -173,7 +185,14 @@ impl Snapshot { /// The session as it is now, as a step of the model, under `label`: the one place a step is /// taken. pub fn of(s: &Session, label: &str) -> Snapshot { - Snapshot { label: label.to_string(), doc: s.doc.clone(), active_sketch: s.active_sketch, pending_moves: s.pending_moves.clone(), part: None } + Snapshot { + label: label.to_string(), + doc: s.doc.clone(), + active_sketch: s.active_sketch, + active_sheet_sketch: s.active_sheet_sketch.clone(), + pending_moves: s.pending_moves.clone(), + part: None, + } } } @@ -254,6 +273,8 @@ pub struct Session { pub redo: Vec, /// Sketch feature being edited (sketch mode). pub active_sketch: Option, + /// Explicitly owned sheet edit, independent of the model sketch being edited. + pub active_sheet_sketch: Option>, /// The drawing open (by id): drawing commands change it, and the model's wait until it is /// closed ([`cmd::Part`]). pub open_drawing: Option, @@ -341,6 +362,8 @@ pub(crate) struct Checkpoint { pub id: u64, pub doc: Arc, pub active_sketch: Option, + /// Explicitly owned sheet edit, independent of the model sketch being edited. + pub active_sheet_sketch: Option>, pub open_drawing: Option, pub pending_moves: std::collections::BTreeMap, pub undo: Vec, @@ -430,6 +453,7 @@ impl Session { undo: Vec::new(), redo: Vec::new(), active_sketch: None, + active_sheet_sketch: None, open_drawing: None, selection: Vec::new(), path: None, @@ -546,6 +570,20 @@ impl Session { Ok(()) } + /// An undo or document replacement cannot leave an edit aimed at another owner. + pub(crate) fn prune_sheet_sketch_edit(&mut self) { + if self.active_sheet_sketch.as_ref().is_some_and(|entry| { + self.open_drawing != Some(entry.drawing) + || self + .doc + .drawing(entry.drawing) + .and_then(|drawing| drawing.sheet_sketch(entry.sketch)) + .is_none_or(|record| record.sheet != entry.sheet) + }) { + self.active_sheet_sketch = None; + } + } + /// The design as a file holds it: the document with what is hidden in it. pub fn design(&self) -> std::borrow::Cow<'_, Document> { if self.visibility.is_empty() { @@ -687,6 +725,7 @@ impl Session { } self.revision += 1; self.prune_occurrence_state(); + self.prune_sheet_sketch_edit(); // Joints follow the geometry their origins snap to. if !self.doc.assembly.joints.is_empty() { cmd::joints::resolve(self); @@ -827,12 +866,19 @@ impl Session { let host_viewport = self.render_viewport.clone(); let host_jobs = self.render_jobs.host.clone(); let live = spec.live.filter(|_| params.get("live").and_then(Value::as_bool) == Some(true)); - if live.is_none() && spec.reads_model && self.model.is_stale() { + // A disabled model command must not evaluate a stale model merely because + // it was tried from a drawing. Shared sheet tools read only drawing data. + if self.open_drawing.is_some() { + spec.allowed(self).map_err(|why| EngineError::Disabled(spec.id.to_string(), why))?; + } + let reads_model = spec.reads_model && !(self.open_drawing.is_some() && spec.part == cmd::Part::Sketch); + if live.is_none() && reads_model && self.model.is_stale() { self.refresh(); } spec.allowed(self).map_err(|why| EngineError::Disabled(spec.id.to_string(), why))?; let open_drawing = self.open_drawing; - let before = Snapshot { part: open_drawing.filter(|_| spec.part == cmd::Part::Drawing), ..Snapshot::of(self, spec.label) }; + let before = + Snapshot { part: open_drawing.filter(|_| matches!(spec.part, cmd::Part::Drawing | cmd::Part::Sketch)), ..Snapshot::of(self, spec.label) }; let null = Value::Object(Default::default()); let params = if params.is_null() { &null } else { params }; let given = params; @@ -870,6 +916,7 @@ impl Session { // Commands that only read leave no trace (the journal keeps what a replay needs). let changed = !Arc::ptr_eq(&self.doc, &before.doc) || self.active_sketch != before.active_sketch + || self.active_sheet_sketch != before.active_sheet_sketch || self.pending_moves != before.pending_moves || self.open_drawing != open_drawing || spec.id.starts_with("select."); @@ -902,6 +949,7 @@ impl Session { } Err(e) => { self.open_drawing = open_drawing; + self.active_sheet_sketch = before.active_sheet_sketch.clone(); if changed || self.pending_moves != before.pending_moves { self.doc = before.doc; self.active_sketch = before.active_sketch; @@ -923,6 +971,18 @@ impl Session { return v; } let Some(out) = v.as_object_mut() else { return v }; + if self.open_drawing.is_some() { + if let Some(entry) = + self.active_sheet_sketch.as_ref().or(before.active_sheet_sketch.as_ref()).filter(|entry| self.open_drawing == Some(entry.drawing)) + { + let current = self.doc.drawing(entry.drawing).and_then(|drawing| drawing.sheet_sketch(entry.sketch)); + if let Some(after) = current.filter(|record| record.sheet == entry.sheet) { + let previous = before.doc.drawing(entry.drawing).and_then(|drawing| drawing.sheet_sketch(entry.sketch)); + out.insert("created".into(), cmd::sketch_created(previous.map(|record| &record.sketch), &after.sketch)); + } + } + return v; // never fall back to the model after a sheet cancellation + } let named = match params.get("sketch") { Some(Value::Number(n)) => self.doc.find_feature(&n.to_string()).map(|f| f.id), Some(Value::String(x)) => self.doc.find_feature(x).map(|f| f.id), @@ -944,6 +1004,7 @@ impl Session { id, doc: self.doc.clone(), active_sketch: self.active_sketch, + active_sheet_sketch: self.active_sheet_sketch.clone(), open_drawing: self.open_drawing, undo: self.undo.clone(), pending_moves: self.pending_moves.clone(), @@ -963,11 +1024,13 @@ impl Session { let before = Snapshot::of(self, ""); self.doc = c.doc; self.active_sketch = c.active_sketch; + self.active_sheet_sketch = c.active_sheet_sketch; self.open_drawing = c.open_drawing; self.pending_moves = c.pending_moves; self.undo = c.undo; self.redo = c.redo; self.selection.clear(); + self.prune_sheet_sketch_edit(); if self.render_only_change(&before) { self.refresh_render(&before.doc); } else if !Arc::ptr_eq(&self.doc, &before.doc) || self.active_sketch != before.active_sketch || self.pending_moves != before.pending_moves { @@ -992,6 +1055,7 @@ impl Session { undo: Vec::new(), redo: Vec::new(), active_sketch: self.active_sketch, + active_sheet_sketch: self.active_sheet_sketch.clone(), open_drawing: self.open_drawing, selection: self.selection.clone(), path: None, @@ -1061,6 +1125,8 @@ impl Session { } self.redo = computed.redo; self.active_sketch = computed.active_sketch; + self.active_sheet_sketch = computed.active_sheet_sketch; + self.open_drawing = computed.open_drawing; self.selection = computed.selection; self.revision = computed.revision; self.invalidate_view(previous_revision); diff --git a/crates/engine/src/schema/drawing_sketch.rs b/crates/engine/src/schema/drawing_sketch.rs new file mode 100644 index 000000000..84f246d3c --- /dev/null +++ b/crates/engine/src/schema/drawing_sketch.rs @@ -0,0 +1,57 @@ +//! Input/output contracts for the first sheet-sketch command lifecycle. +use super::TypedContract; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Create { + /// Exact sheet id in the open drawing, as returned by drawing.inspect. + pub owner: String, + pub name: Option, +} +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Edit { + pub sketch: String, +} +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Inspect { + pub sketch: Option, +} +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Empty {} + +#[derive(Serialize, JsonSchema)] +pub struct Point { + pub id: String, + pub at: [f64; 2], + pub fixed: bool, +} +#[derive(Serialize, JsonSchema)] +pub struct Reading { + pub drawing: String, + pub sheet: String, + pub sketch: String, + pub name: String, + pub editing: bool, + pub solved: bool, + pub dof: usize, + pub points: Vec, + pub curves: Vec, + pub constraints: Vec, +} +#[derive(Serialize, JsonSchema)] +pub struct Cancelled { + pub drawing: String, + pub sheet: String, + pub sketch: String, + pub removed: bool, +} + +pub static CREATE: TypedContract = TypedContract::new(); +pub static EDIT: TypedContract = TypedContract::new(); +pub static INSPECT: TypedContract = TypedContract::new(); +pub static EMPTY: TypedContract = TypedContract::new(); diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 266d5fa87..369122093 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -46,6 +46,7 @@ mod types; mod tests; // The contracts, by command file. +pub mod drawing_sketch; pub mod features; pub mod inspect; diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index d2db1ffcc..fafef3bd3 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -174,6 +174,7 @@ fn merging_finds_the_turns_start_when_the_history_was_trimmed() { label: String::new(), doc: d.clone(), active_sketch: None, + active_sheet_sketch: None, pending_moves: Default::default(), part: None, }; diff --git a/docs/drawing-sheet-sketches.md b/docs/drawing-sheet-sketches.md index c5a85ebea..f09d78035 100644 --- a/docs/drawing-sheet-sketches.md +++ b/docs/drawing-sheet-sketches.md @@ -1,10 +1,10 @@ -# Drawing-owned sheet sketches: records and atomic edits +# Drawing-owned sheet sketches: records, solving and command lifecycle -R1 of [W38a #7082][issue] stores sheet-sketch records; R2 resolves their source -references and applies candidate edits through the existing solver. Both build -on the embedded-drawing K3b/K4-prime receiver in [#3891][storage], not the -superseded separate-file drawing session. These library interfaces do not yet -enable sketch commands, an interactive editor or complete W38a. +These increments of [W38a #7082][issue] build on the embedded-drawing K3b/K4-prime +receiver in [#3891][storage], not the superseded separate-file session. R1 adds +records, R2 read-only solving and atomic edits, R3 composes the shared store, +and R4 connects a bounded command lifecycle. This is not the complete native or +browser Drawing UI, all-tools parity, or completed W38a. ## Stored meaning @@ -149,12 +149,11 @@ source cycles, unrelated errors and no-op Arc identity. They exercise the actual shared evaluator and solver. Actual executed results belong in the PR, not this design note. -The command/store increment still depends on W38.0 #6336 and the real K session -interfaces. It must route reads/edits to the resolved-state boundary above and -supply drawing-owned dimension bindings, create/edit/finish/cancel, drawing-local -undo/redo and checkpoints, hostile command handling, reopening after live edits -and UI/native/browser parity. The -record-only container checks above are not that end-to-end acceptance. W38d's later +R3/R4 compose the actual W38.0 #6336 store with the embedded K session and route +a first set of sheet commands through R2, including entry, finish/cancel and +history. Drawing-owned dimension definitions, the remaining tools, cached live +presentation and native/browser UI parity still need implementation and acceptance. +The record-only container checks above do not qualify all those editing paths. W38d's later saved-fill integration must retain outer-plus-holes identity after edits. W38b/c/e and source-edge projection remain with their existing owners. @@ -166,8 +165,8 @@ and source-edge projection remain with their existing owners. The existing W38.0 store from CamWight's #6336, revision `07984653`, is now composed with this embedded K receiver. This is a source-compatible port of the same `cmd::sketch_store`, not another store or a replacement main-target PR. -Its original module, including its routing scan and null/exact-number tests, -is unchanged. The calls present on this receiver go through `target`, `active`, +R3 retained the original module, including its routing scan and null/exact-number +tests; R4 extends that same module with the explicitly owned sheet adapter. The calls present on this receiver go through `target`, `active`, `read`, `write`, `update` and `checked` as in the original work. The receiver predates several unrelated main changes. This adaptation does not @@ -178,16 +177,68 @@ MidPoint/standard-part behavior just to make a cherry-pick apply. In particular, shared update transaction. Model-only joint/plane lookups stay explicitly marked. Original author/source references remain in the commit and PR. -This step is deliberately **still model-store routing**, not the sheet receiver. -The drawing part gate remains unchanged; no drawing id is put into +At the R3 checkpoint this was **model-store routing**, not the sheet receiver. +R4 below changes the part gate only for its admitted tools; no drawing id is put into `Session::active_sketch`. Two receiver-specific engine tests exercise model/sheet id collisions, refusal of model sketch commands with a drawing open, successful model editing after closing it, and callback failure without publishing a clone. Their executed results, if available, belong in the PR. -The next change must give an active sketch an explicit owner, route sheet edits -to R2, and preserve model-only command refusals before enabling existing tools. -Drawing-owned dimension definitions, create/edit/finish/cancel, live presentation, -undo/checkpoint restoration and UI acceptance remain incomplete. Integrating this -port is not evidence that #6336 landed on main or that its independent full gate -qualifies the combined receiver. +The R4 command slice below now supplies explicit sheet ownership and R2 routing. +Drawing-owned dimensions, remaining tools, live presentation and UI acceptance +remain incomplete. Integrating this port is not evidence that #6336 landed on +main or that its independent full gate qualifies the combined receiver. + +## R4: exact-owner command lifecycle + +`drawing.sketch.create {owner, name?}` creates and enters a sketch on the exact +encoded sheet id of the open drawing. `drawing.sketch.edit {sketch}` enters an +existing exact encoded id; repeating it on the same sketch preserves the first +cancel boundary. `drawing.sketch.inspect {sketch?}` reports the resolved paper-mm +points, local entity ids and solver state without adopting that solution. + +The existing `sketch.rectangle.two_point`, `sketch.line` and `sketch.point` tools +use the same geometry implementations through the shared store's sheet adapter. +There is no parallel sketcher or alternate model-feature lookup. A separate +session entry names drawing, sheet and sketch explicitly; the model's +`active_sketch` is never assigned a sheet id. An explicit tool target can confirm +that entry, not silently switch to another drawing or a same-numbered feature. +The ordinary model paths of these tools remain available with no drawing open. + +Point and line expressions read the containing design's parameter values, under +R2's declared-source checks. Bare expression values are paper millimetres even +when the model displays inches. The legacy tool callback may read a copy of the +source document, but any attempted mutation of that source is refused before +publication. R2 validates and solves the changed sketch before storing it. + +`sketch.finish` ends sheet editing. `sketch.cancel` restores only that sketch's +entry record, or removes a sketch created in that entry, then leaves editing. +The cancellation is itself one drawing undo step when data changed; Undo restores +the edited record and its active entry, and Redo returns to the cancelled state. +Other sketches, drawing properties, other drawings and model history are not +rolled back. Session checkpoints, scratch previews and restored drawing history +carry the explicit sheet entry. Switching or deleting drawings while it is active +requires Finish or Cancel. These commands must not evaluate a stale model merely +because a model-only operation was attempted from the drawing. + +This first command slice deliberately does **not** enable dimensions that define +parameters, the other sketch geometry/modify/constraint tools, text, patterns, +offsets, clipboard, live drag or model projection paths in Drawing. They remain +explicitly unavailable, not silently redirected to model geometry. New source +bindings, auxiliary payload validation, all-tools parity, cached solved-state +presentation and actual native/browser editor UI acceptance remain subsequent +work. W38d saved-fill association is not enabled by these commands. + +The lifecycle acceptance cases are in the existing engine `cmd/drawing_tests.rs`: +paper rectangle size, source-read-only point/line expressions, failed calls, +finish/cancel and history, checkpoint/scratch/reopen, colliding identifiers across +two drawings and a model sketch, schemas/hostile input, and no stale-model +re-evaluation. Executed results and any remaining failures belong in the PR. + +New command messages are supplied as a pending locale delta, per current project +rules. This pinned K receiver predates the pending-catalog reader; native UI +translation qualification requires the already-merged shared prerequisite #6448 +(`1ceab2ed4c03832f1937e0da98b9c8c50f49aa3e`) to reach `drawings`. The four pending +ids were checked against the current main English catalog and are not duplicates. +This feature does not modify the i18n loader, shared catalogs or CI to bypass that +integration requirement.