diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rs index dadd21650..a6dc37956 100644 --- a/crates/engine/src/cmd/browser.rs +++ b/crates/engine/src/cmd/browser.rs @@ -682,6 +682,7 @@ fn redefine_sketch(s: &mut Session, p: &Value) -> Result { && super::sketch::face::anchor(&plane) .is_none_or(|next| next.target != anchor.target || next.component != anchor.component || next.path != anchor.path) { + // design-only: Redefine Sketch Plane edits the design's sketch feature. let sketch = trial.doc_mut().sketch_mut(id)?; if let Some(mut visible) = visible_geometry { let constraints: std::collections::BTreeMap<_, _> = diff --git a/crates/engine/src/cmd/drawing_tests.rs b/crates/engine/src/cmd/drawing_tests.rs index cfc7199db..3f7af19b0 100644 --- a/crates/engine/src/cmd/drawing_tests.rs +++ b/crates/engine/src/cmd/drawing_tests.rs @@ -452,3 +452,84 @@ fn drawing_steps_in_any_order_keep_the_rules() { } } } + +/// The shared model-store port must not make a saved sheet sketch a model feature, +/// even when their numeric ids coincide. Drawing tools are not enabled by this port. +#[test] +fn sheet_records_do_not_redirect_the_shared_model_sketch_store() { + use crate::cmd::sketch_store; + use solidcraft_doc::drawing::SheetSketch; + use solidcraft_geom::Vec2; + use solidcraft_sketch::Sketch; + + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Model sketch"})); + let model_id = s.active_sketch.unwrap(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "drawing.create", json!({"name": "Drawing", "units": "in"})); + let mut ids = IdSource::seeded(6336); + let separate = s.drawing("test").unwrap().allocate_id(&mut ids).unwrap(); + assert!(s.doc.feature(separate).is_none()); + s.edit_drawing("test", |drawing| { + let mut sheet_sketch = Sketch::new(); + sheet_sketch.add_point(Vec2::new(15.0, 10.0), Some("sheet_point"))?; + for id in [model_id, separate] { + drawing.sketches.push(Arc::new(SheetSketch { + id, + sheet: drawing.sheets[0].id, + name: "Sheet sketch".into(), + sketch: sheet_sketch.clone(), + })); + } + Ok(()) + }) + .unwrap(); + let drawing = open_one(&s); + let before = s.doc.clone(); + let history = (s.undo.len(), s.redo.len(), s.evaluations); + let model = sketch_store::read(&s.doc, model_id).unwrap(); + assert_eq!(model.curves.len(), 1); + assert!(model.resolve_point("sheet_point").is_none()); + assert!(sketch_store::read(&s.doc, separate).is_err()); + assert!(sketch_store::target(&s, &json!({"sketch": separate}), "test").is_err()); + for command in ["sketch.edit", "sketch.line", "sketch.export_dxf", "sketch.solve"] { + let error = refused(&mut s, command, json!({"sketch": model_id, "points": [[0, 0], [10, 0]]})); + assert!(error.contains("a drawing is open"), "{command}: {error}"); + assert!(Arc::ptr_eq(&s.doc, &before)); + assert_eq!((s.undo.len(), s.redo.len(), s.evaluations), history); + } + run(&mut s, "drawing.close", json!({})); + run(&mut s, "sketch.edit", json!({"sketch": model_id.to_string()})); + run(&mut s, "sketch.point", json!({"point": [60, 5], "id": "model_point"})); + assert!(sketch_store::read(&s.doc, model_id).unwrap().resolve_point("model_point").is_some()); + assert!(Arc::ptr_eq(s.doc.drawing(drawing.id).unwrap(), &drawing)); + assert!(drawing.sheet_sketch(model_id).unwrap().sketch.resolve_point("model_point").is_none()); +} + +/// Callback refusal inside the existing store never publishes its private clone. +#[test] +fn receiver_store_callback_failure_preserves_model_drawings_and_history() { + use crate::cmd::sketch_store; + use solidcraft_geom::Vec2; + + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + let id = s.active_sketch.unwrap(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "drawing.create", json!({})); + run(&mut s, "drawing.close", json!({})); + let before = s.doc.clone(); + let state = s.model.state(); + let history = (s.undo.len(), s.redo.len(), s.evaluations); + let result: Result<()> = sketch_store::update(&mut s, id, |_, _, sketch| { + sketch.add_point(Vec2::new(15.0, 10.0), Some("not_committed"))?; + Err(bad("test", "refuse after changing the private sketch")) + }); + assert!(result.unwrap_err().to_string().contains("private sketch")); + assert!(Arc::ptr_eq(&s.doc, &before)); + assert!(Arc::ptr_eq(&s.model.state(), &state)); + 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()); +} diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index c7d750fab..e7e6bdc36 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -262,7 +262,7 @@ pub(super) fn feature_sketch(s: &Session, p: &Value, cmd: &str) -> Result { _ => Err(bad(cmd, format!("`{key}` is not a sketch"))), }; } - if let Some(a) = s.active_sketch { + if let Some(a) = super::sketch_store::active(s) { return Ok(a); } let limit = s.doc.marker.unwrap_or(usize::MAX); diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index aecc7cce5..c591e4198 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -213,12 +213,7 @@ fn sketch_json(s: &Session, id: u64) -> Option { } fn sketch_inspect(s: &mut Session, p: &Value) -> Result { - let id = match p.get("sketch") { - Some(Value::Number(n)) => s.doc.find_feature(&n.to_string()).map(|f| f.id), - Some(Value::String(x)) => s.doc.find_feature(x).map(|f| f.id), - _ => s.active_sketch, - } - .ok_or_else(|| bad("sketch.inspect", "no such sketch (and none is active)"))?; + let id = super::sketch_store::target(s, p, "sketch.inspect")?; sketch_json(s, id).ok_or_else(|| EngineError::Other("that sketch is not evaluated (rolled back or not a sketch)".into())) } diff --git a/crates/engine/src/cmd/joints_inspect.rs b/crates/engine/src/cmd/joints_inspect.rs index 87e4caf57..ba4d1980b 100644 --- a/crates/engine/src/cmd/joints_inspect.rs +++ b/crates/engine/src/cmd/joints_inspect.rs @@ -189,6 +189,7 @@ fn face_ref(doc: &Document, name: &str) -> Value { .filter(|(k, _)| k.strip_prefix('s').is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))) .map_or(curve, |(_, c)| c); let found = f.kind.input_sketches().into_iter().find_map(|id| { + // design-only: a joint names a curve of one of the design's sketches. let sk = doc.sketch(id).ok()?; let c = sk.curves.iter().find(|c| c.id == curve)?; let curve_type = serde_json::to_value(&c.kind).ok().and_then(|k| k.get("type").cloned()).unwrap_or(Value::Null); diff --git a/crates/engine/src/cmd/measure_sel.rs b/crates/engine/src/cmd/measure_sel.rs index 8927abb74..a441781f3 100644 --- a/crates/engine/src/cmd/measure_sel.rs +++ b/crates/engine/src/cmd/measure_sel.rs @@ -146,7 +146,7 @@ fn sketch_of<'a>( if let Some(id) = sketch { return st.sketch(id); } - if let Some(ss) = s.active_sketch.and_then(|id| st.sketch(id)).filter(|ss| has(&ss.sketch)) { + if let Some(ss) = super::sketch_store::active(s).and_then(|id| st.sketch(id)).filter(|ss| has(&ss.sketch)) { return Some(ss); } st.sketches.iter().rev().map(|ss| &**ss).find(|ss| has(&ss.sketch)) diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index b659d0eaf..423f0fbf7 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -83,6 +83,7 @@ mod sketch_import; mod sketch_inspect; mod sketch_modify; mod sketch_project; +mod sketch_store; mod surface; mod surface_analysis; mod surface_boundary; diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index ec1ff880d..66720d0c0 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -15,6 +15,7 @@ mod dimensioned; mod drag; #[path = "sketch_face.rs"] pub(super) mod face; +use super::sketch_store; use dimensioned::draw as draw_dimensioned; use drag::drag_entity; @@ -207,23 +208,6 @@ pub static COMMANDS: &[CommandSpec] = &[ // --------------------------------------------------------------------------------------------- // Helpers -/// Resolve the sketch a command acts on: `sketch` param (id or name) or the active sketch. -pub(super) fn target_sketch(s: &Session, p: &Value, cmd: &str) -> Result { - if let Some(v) = p.get("sketch") { - let key = match v { - Value::Number(n) => n.to_string(), - Value::String(x) => x.clone(), - _ => return Err(bad(cmd, "`sketch` must be an id or a name")), - }; - let f = s.doc.find_feature(&key).ok_or_else(|| bad(cmd, format!("no sketch `{key}`")))?; - if !matches!(f.kind, FeatureKind::Sketch { .. }) { - return Err(bad(cmd, format!("`{key}` is not a sketch"))); - } - return Ok(f.id); - } - s.active_sketch.ok_or_else(|| EngineError::Other("no sketch is being edited".into())) -} - /// Edit a sketch: clone it, apply `f`, solve with the document's dimension values and store /// it. With `strict`, an edit that makes the constraints unsolvable is rejected. pub(super) fn edit( @@ -233,7 +217,7 @@ pub(super) fn edit( strict: bool, f: impl FnOnce(&mut Sketch, &mut solidcraft_doc::Document) -> Result, ) -> Result<(T, Value)> { - let id = target_sketch(s, p, cmd)?; + 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))) } @@ -277,7 +261,7 @@ pub(super) fn edit_solved( f: impl FnOnce(&mut Sketch, &mut solidcraft_doc::Document) -> Result<(T, Left)>, ) -> Result<(T, Option)> { let mut doc = (*s.doc).clone(); - let mut sk = doc.sketch(id)?.clone(); + let mut sk = sketch_store::read(&doc, id)?.clone(); super::sketch_project::refresh(s, &doc, id, &mut sk); // The stored sketch is solved for its stored values. let stored = sk.driving_values(); @@ -313,8 +297,8 @@ pub(super) fn edit_solved( Some(settle(strict, rep, &mut sk, unsolved)?) } }; - sk.validate_periodic_splines()?; - *doc.sketch_mut(id)? = sk; + sketch_store::checked(&sk)?; + sketch_store::write(&mut doc, id, sk)?; *s.doc_mut() = doc; Ok((out, rep)) } @@ -1593,7 +1577,7 @@ pub(super) fn redundancy( /// The constraints that already determine constraint `cid` of the target sketch, as /// "id (Name)". fn determined_by(s: &Session, p: &Value, cmd: &str, cid: &str) -> Vec { - let Some(sk) = target_sketch(s, p, cmd).ok().and_then(|id| s.doc.sketch(id).ok()) else { return Vec::new() }; + let Some(sk) = sketch_store::target(s, p, cmd).ok().and_then(|id| sketch_store::read(&s.doc, id).ok()) else { return Vec::new() }; let Some(ci) = sk.constraints.iter().position(|c| c.id == cid) else { return Vec::new() }; solidcraft_sketch::determined_by(sk, ci) .into_iter() @@ -1727,7 +1711,7 @@ fn c_horizontal_vertical(s: &mut Session, p: &Value) -> Result { fn c_coincident(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.constraint.coincident"; // Already tied (e.g. connected when it was drawn there): nothing to add. - let sk = s.doc.sketch(target_sketch(s, p, cmd)?)?; + let sk = sketch_store::read(&s.doc, sketch_store::target(s, p, cmd)?)?; let pt = |k: &str| p.get(k).and_then(Value::as_str).and_then(|r| sk.resolve_point(r)); let line_points = coincident_line_points(sk, p, cmd)?; if let Some((a, b)) = line_points.or_else(|| pt("a").zip(pt("b"))) @@ -2366,7 +2350,7 @@ fn measured(is_angle: bool, v: f64) -> (f64, &'static str) { /// What the dimension just added (the sketch's last constraint) measures on the solved sketch. fn solved_measure(s: &Session, p: &Value, cmd: &str) -> Option<(f64, &'static str)> { - let sk = s.doc.sketch(target_sketch(s, p, cmd).ok()?).ok()?; + let sk = sketch_store::read(&s.doc, sketch_store::target(s, p, cmd).ok()?).ok()?; let k = &sk.constraints.last()?.kind; Some(measured(k.is_angle(), solidcraft_sketch::measure_dimension(sk, k)?)) } @@ -2616,7 +2600,7 @@ fn sketch_delete(s: &mut Session, p: &Value) -> Result { fn move_point(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.move_point"; let to = req_vec2(cmd, p, "to")?; - let id = target_sketch(s, p, cmd)?; + let id = sketch_store::target(s, p, cmd)?; let state = s.model.result(id).map(|r| r.state.clone()); let last = state.as_ref().and_then(|state| state.sketch(id)); let (_, rep) = edit_solved(s, id, false, Analysis::Freedom, |sk, _| { @@ -2642,7 +2626,7 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option to, Some(v) => vec2(v).ok_or_else(|| bad(cmd, "`from` must be a point [x, y]"))?, }; - let id = target_sketch(s, p, cmd)?; + let id = sketch_store::target(s, p, cmd)?; // The sketch's report as last evaluated: a live frame keeps its degrees of freedom. let state = s.model.result(id).map(|r| r.state.clone()); let last = state.as_ref().and_then(|state| state.sketch(id)); @@ -2679,7 +2663,7 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option Result<(Value, Option Result { let cmd = "sketch.drag_end"; - let id = target_sketch(s, p, cmd)?; + let id = sketch_store::target(s, p, cmd)?; let start = s.doc.clone(); let mut constraint = Value::Null; if let Some(c) = p.get("constraint").filter(|c| !c.is_null()) { @@ -2754,8 +2738,8 @@ fn sketch_options(s: &mut Session, p: &Value) -> Result { } let set = |k: &str| bool_(p, k); if keys.iter().all(|k| set(k).is_none()) { - let id = target_sketch(s, p, cmd)?; - return Ok(json!({"options": options_json(&s.doc.sketch(id)?.view)})); + let id = sketch_store::target(s, p, cmd)?; + return Ok(json!({"options": options_json(&sketch_store::read(&s.doc, id)?.view)})); } let (v, info) = edit(s, p, cmd, false, |sk, _| { let v = &mut sk.view; @@ -2781,14 +2765,14 @@ fn sketch_options(s: &mut Session, p: &Value) -> Result { fn chain_cmd(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.chain"; - let id = target_sketch(s, p, cmd)?; - let sk = s.doc.sketch(id)?; + let id = sketch_store::target(s, p, cmd)?; + let sk = sketch_store::read(&s.doc, id)?; let c = curve_ref(sk, p.get("curve"), cmd, "curve")?; Ok(json!({"curves": ids_of(sk, &sk.chain(c))})) } fn solve_cmd(s: &mut Session, p: &Value) -> Result { - let id = target_sketch(s, p, "sketch.solve")?; + let id = sketch_store::target(s, p, "sketch.solve")?; let st = s.model.state(); let ss = st.sketch(id).ok_or_else(|| EngineError::Other("the sketch has not been evaluated".into()))?; Ok(json!({"status": ss.report.status, "dof": ss.report.dof, "failing": ss.report.failing, "profiles": ss.profiles.len()})) diff --git a/crates/engine/src/cmd/sketch_3d.rs b/crates/engine/src/cmd/sketch_3d.rs index d6202511f..7070a8087 100644 --- a/crates/engine/src/cmd/sketch_3d.rs +++ b/crates/engine/src/cmd/sketch_3d.rs @@ -6,7 +6,8 @@ use serde_json::{Value, json}; use solidcraft_geom::Vec3; use solidcraft_sketch::WireSpace; -use super::sketch::{edit, target_sketch}; +use super::sketch::edit; +use super::sketch_store; use super::{CommandSpec, in_sketch}; use crate::params::{bad, req_vec3, vec3}; use crate::{Result, Session}; @@ -45,7 +46,7 @@ fn needs_3d(sk: &solidcraft_sketch::Sketch, cmd: &str) -> Result<()> { /// World command inputs belong to the target sketch's owner, which may differ from the /// active component when a script supplies an explicit sketch. fn inverse_owner_frame(s: &Session, p: &Value, cmd: &str) -> Result { - let id = target_sketch(s, p, cmd)?; + let id = sketch_store::target(s, p, cmd)?; let owner = s.doc.feature(id).map(|f| f.component).ok_or_else(|| bad(cmd, "target sketch is missing"))?; if owner != 0 && owner != s.active_component { if s.doc.occurrences.len() > 100_000 { diff --git a/crates/engine/src/cmd/sketch_clipboard.rs b/crates/engine/src/cmd/sketch_clipboard.rs index a0363bfbc..7d90d5a7a 100644 --- a/crates/engine/src/cmd/sketch_clipboard.rs +++ b/crates/engine/src/cmd/sketch_clipboard.rs @@ -11,7 +11,8 @@ use serde_json::{Value, json}; use solidcraft_geom::{Aabb2, Vec2}; use solidcraft_sketch::{ConstraintKind, CurveKind, LinkKind, LinkSource, Sketch}; -use super::sketch::{edit, target_sketch}; +use super::sketch::edit; +use super::sketch_store; use super::{CommandSpec, in_sketch}; use crate::params::{bad, string_list, vec2}; use crate::{Result, Sel, Session}; @@ -91,12 +92,12 @@ fn text_of(sk: &Sketch, ci: usize) -> Option<&str> { fn copy(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.copy"; - let id = target_sketch(s, p, cmd)?; + let id = sketch_store::target(s, p, cmd)?; let ids = chosen(s, p); if ids.is_empty() { return Err(bad(cmd, "select the sketch curves or points to copy")); } - let sk = s.doc.sketch(id)?; + let sk = sketch_store::read(&s.doc, id)?; let (mut cs, mut ps, mut texts): (Vec, Vec, Vec) = (Vec::new(), Vec::new(), Vec::new()); for e in &ids { if let Some(c) = sk.curve_index(e) { @@ -244,7 +245,7 @@ fn paste(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "params must be an object")); } let Some(clip) = s.sketch_clipboard.clone() else { return Err(bad(cmd, "nothing copied (sketch.copy first)")) }; - let target = target_sketch(s, p, cmd)?; + let target = sketch_store::target(s, p, cmd)?; let positioned = p.get("at").is_some() || p.get("translate").is_some(); let t = if let Some(v) = p.get("at") { vec2(v).ok_or_else(|| bad(cmd, "`at` must be [x, y]"))? - clip.center diff --git a/crates/engine/src/cmd/sketch_constraints.rs b/crates/engine/src/cmd/sketch_constraints.rs index 8ac590467..7d2c24a01 100644 --- a/crates/engine/src/cmd/sketch_constraints.rs +++ b/crates/engine/src/cmd/sketch_constraints.rs @@ -6,6 +6,7 @@ use solidcraft_geom::Vec2; use solidcraft_sketch::{ConstraintKind, CurveKind, Sketch}; use super::sketch::{add_c, constraint_result, dof_now, edit, listed, redundancy, residual_of}; +use super::sketch_store; use super::{CommandSpec, in_sketch}; use crate::params::{bad, num, req_vec2, str_, string_list, vec2}; use crate::{EngineError, Result, Session}; @@ -396,8 +397,8 @@ fn toggle_driven(s: &mut Session, p: &Value) -> Result { })?; if !driven { // Making it driving must not over-constrain: compare with the sketch without it. - let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch"))?; - let mut sk = s.doc.sketch(id)?.clone(); + let id = sketch_store::active(s).ok_or_else(|| bad(cmd, "no sketch"))?; + let mut sk = sketch_store::read(&s.doc, id)?.clone(); if let Some(c) = sk.constraints.iter_mut().find(|c| c.id == cid) { c.driven = true; } @@ -457,12 +458,7 @@ fn anchor(sk: &Sketch, k: &ConstraintKind) -> Option { } fn glyphs(s: &mut Session, p: &Value) -> Result { - let id = match p.get("sketch") { - Some(Value::Number(n)) => n.as_u64(), - Some(Value::String(x)) => s.doc.find_feature(x).map(|f| f.id), - _ => s.active_sketch, - } - .ok_or_else(|| bad("sketch.glyphs", "no such sketch"))?; + let id = sketch_store::target(s, p, "sketch.glyphs")?; let st = s.model.state(); let ss = st.sketch(id).ok_or_else(|| EngineError::Other("that sketch is not evaluated".into()))?; let failing = &ss.report.failing; @@ -496,7 +492,7 @@ fn snap(s: &mut Session, p: &Value) -> Result { let at = req_vec2(cmd, p, "at")?; let from = p.get("from").and_then(vec2); let r = num(p, "radius").filter(|r| *r > 0.0).unwrap_or(1.0); - let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch is being edited"))?; + let id = sketch_store::active(s).ok_or_else(|| bad(cmd, "no sketch is being edited"))?; let st = s.model.state(); let ss = st.sketch(id).ok_or_else(|| EngineError::Other("the sketch is not evaluated".into()))?; let sk = &ss.sketch; diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index b97d7dd4a..ce28c4d9b 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -13,6 +13,7 @@ macro_rules! text_style_doc { } use super::sketch::{add_c, circumcircle, edit, ids_of, mark_construction, req_parg, result, slot}; +use super::sketch_store; use super::{CommandSpec, in_sketch}; use crate::params::{bad, num, req_vec2, str_, string_list}; use crate::{Result, Session}; @@ -262,20 +263,19 @@ fn text(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, AT_MUST)); } let src = text_source(&s.doc, p, cmd, None)?; - let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch is being edited"))?; - let mut doc = (*s.doc).clone(); - let mut sk = doc.sketch(id)?.clone(); - // A text needs nothing outside its sketch (a path is one of its curves). - let geom = sk.text_source_geometry(&src).map_err(|e| bad(cmd, e.to_string()))?; - if geom.is_empty() { - return Err(bad(cmd, "the text makes no outline")); - } - let guide = guide(&mut sk, &src); + let id = sketch_store::active(s).ok_or_else(|| bad(cmd, "no sketch is being edited"))?; let exprs = text_exprs_json(&src); - let l = sk.add_link(LinkKind::Text, src, &geom)?; - let curves = ids_of(&sk, &sk.link_curves(&l)); - *doc.sketch_mut(id)? = sk; - *s.doc_mut() = doc; + let (l, curves, guide) = sketch_store::update(s, id, |_, _, sk| { + // A text needs nothing outside its sketch (a path is one of its curves). + let geom = sk.text_source_geometry(&src).map_err(|e| bad(cmd, e.to_string()))?; + if geom.is_empty() { + return Err(bad(cmd, "the text makes no outline")); + } + let guide = guide(sk, &src); + let l = sk.add_link(LinkKind::Text, src, &geom)?; + let curves = ids_of(sk, &sk.link_curves(&l)); + Ok((l, curves, guide)) + })?; let mut out = json!({"link": l, "curves": curves, "guide": guide}); if let Some(exprs) = exprs { out["exprs"] = exprs; @@ -350,23 +350,20 @@ const MAX_TEXT_EDITS: usize = 1000; fn edit_text(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.edit_text"; - let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch is being edited"))?; - let mut doc = (*s.doc).clone(); - let mut sk = doc.sketch(id)?.clone(); - // The numbers its expressions give now (a parameter may have changed since the sketch was - // last stored); one that cannot be evaluated is left as it was, to be replaced by this edit. - let _ = doc.apply_text_values(&doc.param_values().0, &mut sk); - let out = apply_text_edits(&mut sk, &doc, p)?; - *doc.sketch_mut(id)? = sk; - *s.doc_mut() = doc; - Ok(out) + let id = sketch_store::active(s).ok_or_else(|| bad(cmd, "no sketch is being edited"))?; + sketch_store::update(s, id, |_, doc, sk| { + // The numbers its expressions give now (a parameter may have changed since the sketch was + // last stored); one that cannot be evaluated is left as it was, to be replaced by this edit. + let _ = doc.apply_text_values(&doc.param_values().0, sk); + apply_text_edits(sk, doc, p) + }) } /// One frame of an interactive resize or rotation: the sketch is solved and shown, the /// features after it keep their last result until `sketch.drag_end` evaluates the model. fn edit_text_live(s: &mut Session, p: &Value) -> Result<(Value, Option)> { let cmd = "sketch.edit_text"; - let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch is being edited"))?; + let id = sketch_store::active(s).ok_or_else(|| bad(cmd, "no sketch is being edited"))?; let (out, report) = super::sketch::edit_solved(s, id, false, solidcraft_sketch::Analysis::Full, |sk, doc| { Ok((apply_text_edits(sk, doc, p)?, super::sketch::Left::Unsolved)) })?; diff --git a/crates/engine/src/cmd/sketch_ends.rs b/crates/engine/src/cmd/sketch_ends.rs index 02f8f8bdb..b8ce0f129 100644 --- a/crates/engine/src/cmd/sketch_ends.rs +++ b/crates/engine/src/cmd/sketch_ends.rs @@ -4,7 +4,8 @@ use serde_json::{Value, json}; use solidcraft_sketch::{ConstraintKind, EndReport, EndTouch, Sketch, loose_ends}; -use super::sketch::{add_c, edit, target_sketch}; +use super::sketch::{add_c, edit}; +use super::sketch_store; use super::{CommandSpec, in_sketch}; use crate::params::{bad, string_list}; use crate::{EngineError, Result, Session}; @@ -53,7 +54,7 @@ fn report_json(sk: &Sketch, r: &EndReport) -> Value { } fn loose_ends_cmd(s: &mut Session, p: &Value) -> Result { - let id = target_sketch(s, p, "sketch.loose_ends")?; + let id = sketch_store::target(s, p, "sketch.loose_ends")?; let st = s.model.state(); let ss = st.sketch(id).ok_or_else(|| EngineError::Other("the sketch has not been evaluated".into()))?; Ok(report_json(&ss.sketch, &ss.ends)) diff --git a/crates/engine/src/cmd/sketch_import.rs b/crates/engine/src/cmd/sketch_import.rs index 83632df19..7a74a2478 100644 --- a/crates/engine/src/cmd/sketch_import.rs +++ b/crates/engine/src/cmd/sketch_import.rs @@ -9,6 +9,7 @@ use solidcraft_sketch::{CurveKind, LinkKind, LinkSource, Sketch}; use super::CommandSpec; use super::sketch::{edit, ids_of}; +use super::sketch_store; use crate::params::{bad, num, str_, vec2}; use crate::{EngineError, Result, Session}; @@ -129,12 +130,13 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result { Ok((ids_of(sk, &cs), texts)) })?; // Text becomes sketch text. - let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch"))?; + let id = sketch_store::active(s).ok_or_else(|| bad(cmd, "no sketch"))?; let mut n_text = 0; for t in texts { if let Geom2::Text { text, at, height, angle } = t { + // Not `sketch_store::update`: a text that can't be linked is skipped, not refused. let mut doc = (*s.doc).clone(); - let mut sk = doc.sketch(id)?.clone(); + let mut sk = sketch_store::read(&doc, id)?.clone(); if super::sketch_project::add_link( s, &doc, @@ -145,7 +147,7 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result { ) .is_ok() { - *doc.sketch_mut(id)? = sk; + sketch_store::write(&mut doc, id, sk)?; *s.doc_mut() = doc; n_text += 1; } @@ -164,12 +166,7 @@ fn insert_svg(s: &mut Session, p: &Value) -> Result { fn export_dxf(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.export_dxf"; - let id = match p.get("sketch") { - Some(Value::Number(n)) => n.as_u64(), - Some(Value::String(x)) => s.doc.find_feature(x).map(|f| f.id), - _ => s.active_sketch, - } - .ok_or_else(|| bad(cmd, "no such sketch (and none is active)"))?; + let id = sketch_store::target(s, p, cmd)?; let st = s.model.state(); let ss = st.sketch(id).ok_or_else(|| EngineError::Other("that sketch is not evaluated".into()))?; let sk = &ss.sketch; diff --git a/crates/engine/src/cmd/sketch_inspect.rs b/crates/engine/src/cmd/sketch_inspect.rs index 3222e8fc6..960816564 100644 --- a/crates/engine/src/cmd/sketch_inspect.rs +++ b/crates/engine/src/cmd/sketch_inspect.rs @@ -79,12 +79,7 @@ fn curvature_comb(s: &mut Session, p: &Value) -> Result { let mut combs: Vec<(String, Vec<(Vec3, f64, Vec3)>)> = Vec::new(); let curves = string_list(p, "curves"); if !curves.is_empty() { - let id = match p.get("sketch") { - Some(Value::Number(n)) => n.as_u64(), - Some(Value::String(x)) => s.doc.find_feature(x).map(|f| f.id), - _ => s.active_sketch, - } - .ok_or_else(|| bad(cmd, "no such sketch (and none is active)"))?; + let id = super::sketch_store::target(s, p, cmd)?; let ss = st.sketch(id).ok_or_else(|| EngineError::Other("that sketch is not evaluated".into()))?; for c in curves.iter().take(1000) { let ci = ss.sketch.curve_index(c).ok_or_else(|| bad(cmd, format!("unknown curve `{c}`")))?; @@ -230,12 +225,7 @@ fn minimum_radius(s: &mut Session, p: &Value) -> Result { let mut items: Vec<(String, Option<(f64, Vec3)>)> = Vec::new(); let curves = string_list(p, "curves"); if !curves.is_empty() { - let id = match p.get("sketch") { - Some(Value::Number(n)) => n.as_u64(), - Some(Value::String(x)) => s.doc.find_feature(x).map(|f| f.id), - _ => s.active_sketch, - } - .ok_or_else(|| bad(cmd, "no such sketch (and none is active)"))?; + let id = super::sketch_store::target(s, p, cmd)?; let ss = st.sketch(id).ok_or_else(|| EngineError::Other("that sketch is not evaluated".into()))?; for c in curves.iter().take(1000) { let ci = ss.sketch.curve_index(c).ok_or_else(|| bad(cmd, format!("unknown curve `{c}`")))?; diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index b998d3c4d..46eabc144 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -9,6 +9,7 @@ use solidcraft_geom::Vec2; use solidcraft_sketch::{ConstraintKind, Curve, CurveKind, Shape, Sketch, intersections}; use super::sketch::{add_c, edit, ids_of, solve_current}; +use super::sketch_store; use super::{CommandSpec, in_sketch}; use crate::params::{bad, bool_, expr, num, req_vec2, str_, string_list, vec2, vec2_list}; use crate::{Result, Session}; @@ -1655,7 +1656,7 @@ fn offset(s: &mut Session, p: &Value) -> Result { fn break_offset(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.offset.break"; - let sketch = super::sketch::target_sketch(s, p, cmd)?; + let sketch = sketch_store::target(s, p, cmd)?; let (out, info) = edit(s, p, cmd, true, |sk, doc| { let output = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must name an offset output"))?; let record = sk.freeform_offsets.iter().position(|record| record.output == output); @@ -1675,7 +1676,7 @@ fn break_offset(s: &mut Session, p: &Value) -> Result { if !rep.keeps_orientation() { return Err(bad(cmd, rep.failure(|_| "cannot break an offset with conflicting dimensions".into()))); } - sk.validate_periodic_splines()?; + sketch_store::checked(sk)?; if let Some(association) = sk .offsets .iter() diff --git a/crates/engine/src/cmd/sketch_project.rs b/crates/engine/src/cmd/sketch_project.rs index 07a3ee923..fc7ff212e 100644 --- a/crates/engine/src/cmd/sketch_project.rs +++ b/crates/engine/src/cmd/sketch_project.rs @@ -9,6 +9,7 @@ use solidcraft_doc::{Document, FeatureKind}; use solidcraft_geom::{Plane, Vec3}; use solidcraft_sketch::{ConstraintKind, LinkKind, LinkSource, Sketch}; +use super::sketch_store; use super::{CommandSpec, in_sketch}; use crate::params::{bad, bool_, str_, vec3}; use crate::{EngineError, Result, Session}; @@ -196,7 +197,7 @@ pub(super) fn refresh(s: &Session, doc: &Document, id: u64, sk: &mut Sketch) -> Some(anchor) => solidcraft_doc::project::refresh_face_anchor_links(&doc, &vals, &st, &plane, sk, anchor), None => solidcraft_doc::project::refresh_links(&doc, &vals, &st, &plane, sk), }; - if let Ok(stored) = doc.sketch(id) + if let Ok(stored) = sketch_store::read(&doc, id) && sk.positions_in(stored).is_some() { let mut solved = sk.clone(); @@ -254,19 +255,18 @@ fn run_links(s: &mut Session, p: &Value, cmd: &str, kind: LinkKind) -> Result = refs.iter().map(|v| source(s, v, cmd)).collect::>()?; - let mut doc = (*s.doc).clone(); - let mut sk = doc.sketch(id)?.clone(); - refresh(s, &doc, id, &mut sk); - let mut out = Vec::new(); - for src in sources { - let what = src.describe(); - let l = add_link(s, &doc, id, &mut sk, kind, src).map_err(|e| bad(cmd, format!("{what}: {e}")))?; - out.push(link_json(&sk, &l)); - } - *doc.sketch_mut(id)? = sk; - *s.doc_mut() = doc; + let out = sketch_store::update(s, id, |s, doc, sk| { + refresh(s, doc, id, sk); + let mut out = Vec::new(); + for src in sources { + let what = src.describe(); + let l = add_link(s, doc, id, sk, kind, src).map_err(|e| bad(cmd, format!("{what}: {e}")))?; + out.push(link_json(sk, &l)); + } + Ok(out) + })?; Ok(json!({"links": out})) } @@ -284,18 +284,16 @@ fn include_cmd(s: &mut Session, p: &Value) -> Result { /// Add one link from `src` to the active sketch and report it. fn one_link(s: &mut Session, cmd: &str, kind: LinkKind, src: LinkSource) -> Result { - let id = s.active_sketch.ok_or_else(|| EngineError::Other("no sketch is being edited".into()))?; - let mut doc = (*s.doc).clone(); - let mut sk = doc.sketch(id)?.clone(); - refresh(s, &doc, id, &mut sk); - let what = src.describe(); - let l = add_link(s, &doc, id, &mut sk, kind, src).map_err(|e| bad(cmd, format!("{what}: {e}")))?; - let mut out = link_json(&sk, &l); - let wires: Vec = sk.link_wires(&l).iter().filter_map(|w| sk.wires.get(*w).map(|w| w.id.clone())).collect(); - out["wires"] = json!(wires); - *doc.sketch_mut(id)? = sk; - *s.doc_mut() = doc; - Ok(out) + let id = sketch_store::active(s).ok_or_else(|| EngineError::Other("no sketch is being edited".into()))?; + sketch_store::update(s, id, |s, doc, sk| { + refresh(s, doc, id, sk); + let what = src.describe(); + let l = add_link(s, doc, id, sk, kind, src).map_err(|e| bad(cmd, format!("{what}: {e}")))?; + let mut out = link_json(sk, &l); + let wires: Vec = sk.link_wires(&l).iter().filter_map(|w| sk.wires.get(*w).map(|w| w.id.clone())).collect(); + out["wires"] = json!(wires); + Ok(out) + }) } fn project_to_surface(s: &mut Session, p: &Value) -> Result { @@ -338,7 +336,7 @@ fn spun_profile(s: &mut Session, p: &Value) -> Result { "Y" => (Vec3::ZERO, Vec3::Y), "Z" => (Vec3::ZERO, Vec3::Z), _ => { - let id = s.active_sketch.ok_or_else(|| EngineError::Other("no sketch is being edited".into()))?; + let id = sketch_store::active(s).ok_or_else(|| EngineError::Other("no sketch is being edited".into()))?; let st = s.model.state(); let ss = st.sketch(id).ok_or_else(|| EngineError::Other("the sketch is not evaluated".into()))?; let ci = ss.sketch.curve_index(axis).ok_or_else(|| bad(cmd, format!("unknown curve `{axis}`")))?; @@ -371,48 +369,47 @@ fn fit_section(s: &mut Session, p: &Value) -> Result { if s.model.state().body(&body).is_none() { return Err(bad(cmd, format!("no body `{body}`"))); } - let id = s.active_sketch.ok_or_else(|| EngineError::Other("no sketch is being edited".into()))?; - let mut doc = (*s.doc).clone(); - let mut sk = doc.sketch(id)?.clone(); - let l = add_link(s, &doc, id, &mut sk, LinkKind::Intersect, LinkSource::Body { body }).map_err(|e| bad(cmd, e.to_string()))?; - let curves: Vec = sk.link_curves(&l).iter().filter_map(|c| sk.curves.get(*c).map(|c| c.id.clone())).collect(); - sk.break_link(&l)?; - *doc.sketch_mut(id)? = sk; - *s.doc_mut() = doc; + let id = sketch_store::active(s).ok_or_else(|| EngineError::Other("no sketch is being edited".into()))?; + let curves = sketch_store::update(s, id, |s, doc, sk| { + let l = add_link(s, doc, id, sk, LinkKind::Intersect, LinkSource::Body { body }).map_err(|e| bad(cmd, e.to_string()))?; + let curves: Vec = sk.link_curves(&l).iter().filter_map(|c| sk.curves.get(*c).map(|c| c.id.clone())).collect(); + sk.break_link(&l)?; + Ok(curves) + })?; Ok(json!({"curves": curves})) } fn break_link(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.break_link"; - let id = s.active_sketch.ok_or_else(|| EngineError::Other("no sketch is being edited".into()))?; - let mut doc = (*s.doc).clone(); - let sk = doc.sketch_mut(id)?; - let mut links: Vec = Vec::new(); - if let Some(l) = str_(p, "link") { - if sk.link(l).is_none() { - return Err(bad(cmd, format!("no link `{l}`"))); + let id = sketch_store::active(s).ok_or_else(|| EngineError::Other("no sketch is being edited".into()))?; + let links = sketch_store::update(s, id, |_, _, sk| { + let mut links: Vec = Vec::new(); + if let Some(l) = str_(p, "link") { + if sk.link(l).is_none() { + return Err(bad(cmd, format!("no link `{l}`"))); + } + links.push(l.to_string()); } - links.push(l.to_string()); - } - for e in crate::params::string_list(p, "entities") { - let l = sk - .curves - .iter() - .find(|c| c.id == e) - .and_then(|c| c.link.clone()) - .or_else(|| sk.points.iter().find(|q| q.id == e).and_then(|q| q.link.clone())) - .ok_or_else(|| bad(cmd, format!("`{e}` is not linked geometry")))?; - if !links.contains(&l) { - links.push(l); + for e in crate::params::string_list(p, "entities") { + let l = sk + .curves + .iter() + .find(|c| c.id == e) + .and_then(|c| c.link.clone()) + .or_else(|| sk.points.iter().find(|q| q.id == e).and_then(|q| q.link.clone())) + .ok_or_else(|| bad(cmd, format!("`{e}` is not linked geometry")))?; + if !links.contains(&l) { + links.push(l); + } } - } - if links.is_empty() { - return Err(bad(cmd, "give `link` or `entities`")); - } - for l in &links { - sk.break_link(l)?; - } - *s.doc_mut() = doc; + if links.is_empty() { + return Err(bad(cmd, "give `link` or `entities`")); + } + for l in &links { + sk.break_link(l)?; + } + Ok(links) + })?; Ok(json!({"broken": links})) } @@ -427,7 +424,7 @@ fn auto_project(s: &mut Session, p: &Value) -> Result { /// makes a point held at the line's midpoint (and `"vertex:x,y,z"` is the vertex form). Everything /// else is left as it is. The links are added to the active sketch in the session's document. pub(super) fn snap_points(s: &mut Session, p: &Value, cmd: &str) -> Result { - let Some(id) = s.active_sketch else { return Ok(p.clone()) }; + let Some(id) = sketch_store::active(s) else { return Ok(p.clone()) }; let mut out = p.clone(); let mut doc: Option<(Document, Sketch)> = None; let fix = |v: &mut Value, s: &Session, doc: &mut Option<(Document, Sketch)>| -> Result<()> { @@ -456,7 +453,7 @@ pub(super) fn snap_points(s: &mut Session, p: &Value, cmd: &str) -> Result Result Result Result { + if let Some(v) = p.get("sketch").filter(|v| !v.is_null()) { + let (key, found) = match v { + Value::Number(n) => { + let id = n.as_u64().ok_or_else(|| bad(cmd, "`sketch` must be an id or a name"))?; + (id.to_string(), s.doc.feature(id)) + } + Value::String(x) => (x.clone(), s.doc.find_feature(x)), + _ => return Err(bad(cmd, "`sketch` must be an id or a name")), + }; + let f = found.ok_or_else(|| bad(cmd, format!("no sketch `{key}`")))?; + if !matches!(f.kind, FeatureKind::Sketch { .. }) { + return Err(bad(cmd, format!("`{key}` is not a sketch"))); + } + return Ok(f.id); + } + s.active_sketch.ok_or_else(|| EngineError::Other("no sketch is being edited".into())) +} + +/// The sketch being edited, if any; each command keeps its own refusal when there is none. +pub(super) fn active(s: &Session) -> Option { + s.active_sketch +} + +/// Sketch `id`, to read. +pub(super) fn read(doc: &Document, id: u64) -> Result<&Sketch> { + Ok(doc.sketch(id)?) +} + +/// Keep `sk` as sketch `id`. +pub(super) fn write(doc: &mut Document, id: u64, sk: Sketch) -> Result<()> { + *doc.sketch_mut(id)? = sk; + Ok(()) +} + +/// Change sketch `id` on a copy of the document, then keep both: the link and text commands' +/// edit. As those commands always have, it neither solves the sketch nor runs [`checked`]. +pub(super) fn update(s: &mut Session, id: u64, f: impl FnOnce(&Session, &Document, &mut Sketch) -> Result) -> Result { + let mut doc = (*s.doc).clone(); + let mut sk = read(&doc, id)?.clone(); + let out = f(s, &doc, &mut sk)?; + write(&mut doc, id, sk)?; + *s.doc_mut() = doc; + Ok(out) +} + +/// The checks an edited sketch passes before it is kept. +pub(super) fn checked(sk: &Sketch) -> Result<()> { + sk.validate_periodic_splines()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + + use crate::Session; + + /// No `sketch`, or a null one, is the sketch being edited; anything else that isn't an id or + /// a name is refused (#6336: sketch.inspect's callers send null for "none given"). + #[test] + fn target_reads_a_null_sketch_as_none_given() { + let mut s = Session::default(); + s.execute("sketch.create", &json!({"plane": "XY"})).unwrap(); + let active = s.active_sketch.unwrap(); + for p in [json!({}), json!({"sketch": null})] { + assert_eq!(super::target(&s, &p, "test").unwrap(), active, "{p}"); + } + assert!(super::target(&s, &json!({"sketch": true}), "test").is_err()); + } + + /// A number is an exact id, never a name (0xlillith on #6336): a sketch named "999999" isn't + /// sketch 999999, so a command given that number refuses instead of picking it, and the name + /// as text still finds it. Through the commands that read only ids before W38.0. + #[test] + fn target_reads_a_number_as_an_id_and_never_a_name() { + let mut s = Session::default(); + s.execute("sketch.create", &json!({"plane": "XY", "name": "999999"})).unwrap(); + let named = s.active_sketch.unwrap(); + assert_ne!(named, 999999); + let c = s.execute("sketch.circle.center", &json!({"center": [0, 0], "radius": 5})).unwrap()["curves"][0].clone(); + s.execute("sketch.finish", &json!({})).unwrap(); + // Glyphs and the curvature inspects need a sketch being edited; it's another one. + s.execute("sketch.create", &json!({"plane": "XZ"})).unwrap(); + for (cmd, p) in [ + ("sketch.export_dxf", json!({})), + ("sketch.glyphs", json!({})), + ("inspect.curvature_comb", json!({"curves": [c]})), + ("inspect.minimum_radius", json!({"curves": [c]})), + ] { + let with = |sketch: Value| { + let mut p = p.clone(); + p["sketch"] = sketch; + p + }; + let e = s.execute(cmd, &with(json!(999999))).unwrap_err().to_string(); + assert!(e.contains("no sketch `999999`"), "{cmd}: {e}"); + s.execute(cmd, &with(json!("999999"))).unwrap_or_else(|e| panic!("{cmd} by name: {e}")); + s.execute(cmd, &with(json!(named))).unwrap_or_else(|e| panic!("{cmd} by id: {e}")); + for bad in [json!(-1), json!(1.5)] { + let e = s.execute(cmd, &with(bad.clone())).unwrap_err().to_string(); + assert!(e.contains("must be an id or a name"), "{cmd} {bad}: {e}"); + } + } + assert_eq!(super::target(&s, &json!({"sketch": "999999"}), "test").unwrap(), named); + assert_eq!(super::target(&s, &json!({"sketch": named.to_string()}), "test").unwrap(), named); + } + + /// Each sketch command finds and keeps its sketch through this store (W38.0). Outside it, the + /// command sources (non-test code) reach a sketch directly only on a line marked + /// `// design-only:` in the files that work on the design's own sketches. + #[test] + fn each_sketch_command_goes_through_the_store() { + // Sketches read or written, and the sketch being edited taken as a value (let-else, if let, + // a match arm, `and_then`, `map`, `ok_or`); its state checks, assignments and snapshot copies + // stay allowed. + const PATTERNS: [&str; 8] = [ + ".sketch_mut(", + "doc.sketch(", + " d.sketch(", + "active_sketch.ok_or", + ") = s.active_sketch", + "=> s.active_sketch", + "s.active_sketch.and_then(", + "s.active_sketch.map(", + ]; + // A motion trace's wire, a joint's curve and Redefine Sketch Plane: the design's sketches. + const DESIGN_ONLY: [&str; 3] = ["browser.rs", "joints_inspect.rs", "motion_trace.rs"]; + let mut stack = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/cmd")]; + let (mut offenders, mut scanned) = (Vec::new(), 0); + while let Some(dir) = stack.pop() { + for entry in std::fs::read_dir(&dir).unwrap().flatten() { + let path = entry.path(); + let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default().to_string(); + if path.is_dir() { + stack.push(path); + continue; + } + if !name.ends_with(".rs") || name.ends_with("_tests.rs") || name == "sketch_store.rs" { + continue; + } + scanned += 1; + // A Windows checkout's CRLF lines, read as written, so the split below finds the tests. + let text = std::fs::read_to_string(&path).unwrap().replace("\r\n", "\n"); + let lines: Vec<&str> = text.split("\n#[cfg(test)]\nmod ").next().unwrap_or_default().lines().collect(); + for (n, line) in lines.iter().enumerate() { + let marked = n > 0 && lines[n - 1].trim_start().starts_with("// design-only:") && DESIGN_ONLY.contains(&name.as_str()); + if !line.trim_start().starts_with("//") && !marked && PATTERNS.iter().any(|p| line.contains(p)) { + offenders.push(format!("{}:{}: {}", path.display(), n + 1, line.trim())); + } + } + } + } + assert!(scanned > 50, "the command sources were scanned ({scanned} files)"); + assert!(offenders.is_empty(), "a sketch read or written outside cmd::sketch_store; go through it:\n{}", offenders.join("\n")); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8a9ed5d6a..f46c8c115 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -771,6 +771,7 @@ impl Session { /// Show the sketch a live frame changed, leaving the features after it as they were last /// evaluated (marked stale); a full `refresh` when the model cannot show it that way. fn refresh_live(&mut self, edit: LiveEdit) { + // design-only: a live drag shows the design's sketch in the model. let sketch = self.doc.sketch(edit.sketch).ok().cloned(); if sketch.is_some_and(|sketch| self.model.show_live_sketch(edit.sketch, sketch, edit.report)) { self.revision += 1; @@ -928,6 +929,7 @@ impl Session { _ => None, }; let Some(sk) = named.or(self.active_sketch).or(before.active_sketch) else { return v }; + // design-only: a command's `created` compares two snapshots of the design. let Ok(after) = self.doc.sketch(sk) else { return v }; out.insert("created".into(), cmd::sketch_created(before.doc.sketch(sk).ok(), after)); v diff --git a/docs/drawing-sheet-sketches.md b/docs/drawing-sheet-sketches.md index faee836b2..c5a85ebea 100644 --- a/docs/drawing-sheet-sketches.md +++ b/docs/drawing-sheet-sketches.md @@ -160,3 +160,34 @@ and source-edge projection remain with their existing owners. [issue]: https://github.com/tangency-labs/solidcraft/issues/7082 [storage]: https://github.com/tangency-labs/solidcraft/pull/3891 + +## Shared command-store receiver (R3) + +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`, +`read`, `write`, `update` and `checked` as in the original work. + +The receiver predates several unrelated main changes. This adaptation does not +import pattern-expression refresh, live-link caching, Cancel Sketch, newer +projection de-duplication, coincident-circle tools, motion traces, or later +MidPoint/standard-part behavior just to make a cherry-pick apply. In particular, +`run_links` retains this receiver's original projection behavior inside the +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 +`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.