From 866029aaa2a2f17063b7de270877cf2c901c88b2 Mon Sep 17 00:00:00 2001 From: CamWight <91156642+CamWight@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:56:05 +0000 Subject: [PATCH] Engine: one sketch store for the sketch commands (W38.0, #5425) (#6336) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Engine: one sketch store for the sketch commands (W38.0, #5425, no behaviour change) The sketch commands found and kept the sketch they work on in about forty places, each its own way. They now go through one module, cmd::sketch_store, so a drawing session (W38a/b) can put sheet and view sketches behind the same calls without the commands changing again. - target: the command's `sketch` param or the sketch being edited (target_sketch, moved). - active: the sketch being edited, if any. The thirteen commands that need one keep their own refusal text; unifying the three texts is a separate, visible change. - read and write: the only calls from the sketch commands to Document::sketch and sketch_mut. - update: change a sketch on a copy of the document and keep both, the edit the text and link commands made by hand (sketch.text, sketch.edit_text, the projection, intersection and include links, sketch.fit_curves_to_section, sketch.break_link). As before, those paths neither solve the sketch nor run its checks. - checked: the checks an edited sketch passes (the periodic splines), shared by edit_solved and sketch.offset.break. edit and edit_solved stay in sketch.rs and load and keep their sketch through read and write. Imported text, snap points and the face projections keep their own shape (a text that can't be linked is skipped, snap points copy the document only when one is needed) through read and write. The reads and writes that are about the design's own sketches stay as they are, each on a line marked `// design-only:` (Redefine Sketch Plane, a joint's curve, a motion trace's wire, and the session's live drag, parameter edits and `created` diff). A source scan, each_sketch_command_goes_through_the_store, fails when a command reads or writes a sketch, or asks for the active one, anywhere but the store or a marked design-only line in the files that work on the design's sketches. Every existing sketch test is unchanged. Co-Authored-By: Claude Opus 5.5 * Engine: the sketch store's scan also catches the active sketch taken as a value (#5425, review of #6336) The scan only caught `active_sketch.ok_or`, so main's `let Some(id) = s.active_sketch else …` could have come back unseen (0xlillith's review). It now also flags the value-read forms: `) = s.active_sketch` (let-else and if let), `=> s.active_sketch` (a match arm), `s.active_sketch.and_then(` and `s.active_sketch.map(`. State checks (`is_some`, `is_none`, `== Some(`), assignments and snapshot copies stay allowed. The wider scan found five commands that hand-rolled the store's `target` rule (a `sketch` param or the sketch being edited). They now call `sketch_store::target`: sketch.inspect, sketch.glyphs, sketch.export_dxf, inspect.curvature_comb and inspect.minimum_radius (their `curves` form). Their refusals become target's: - no `sketch` and none being edited: "no sketch is being edited" (was "no such sketch (and none is active)", or "no such sketch" for sketch.glyphs); - an unknown name or id: "no sketch `X`" (an unknown id used to reach "that sketch is not evaluated"); - a feature that is not a sketch: "`X` is not a sketch"; - a `sketch` that is neither an id nor a name (true, a list, an object): refused, where it used to fall back to the sketch being edited. A null `sketch` still means none given (the scenario harness sends one): target now reads it that way for every sketch command (target_reads_a_null_sketch_as_none_given). No test, doc or schema text named the old wording; the params docs ("sketch?: id|name (default active)") still hold. The two remaining value reads, the default sketch for a feature (features.rs) and the sketch a measurement prefers (measure_sel.rs), go through `sketch_store::active`, with no change. Co-Authored-By: Claude Opus 5.5 * Engine: a number in `sketch` is an exact sketch id, never a name (#5425, review of #6336) `sketch_store::target` turned a JSON number into text and looked it up with `Document::find_feature`, which falls back to a name when no feature has that id. So `{"sketch": 999999}` could pick a sketch named "999999" whose id is something else, and export or inspect it. sketch.export_dxf, sketch.glyphs and the two curvature inspects read an exact id before they moved onto the store; the other sketch commands (the old `target_sketch`) and sketch.inspect read a number as text. One rule now, for every command that takes `sketch`: a number is an exact id (`as_u64`, then the feature with that id); text is an id written out or a name, as before. A number that isn't a whole number of 0 or more (negative, fractional) is refused with "`sketch` must be an id or a name"; an id no feature has gives "no sketch `N`", as before. Nothing in the tests, docs, scenarios or examples names a sketch with digits, so nothing relied on the old fallback. Test (sketch_store): a sketch named "999999" with another id. sketch.export_dxf, sketch.glyphs (with another sketch being edited, for its enabled check), inspect.curvature_comb and inspect.minimum_radius (with a real curve id) refuse `{"sketch": 999999}`, find the sketch as `"999999"` and by its own id, and refuse -1 and 1.5. Co-Authored-By: Claude Opus 5.5 * Engine: MidPoint finds its sketch through the store too (#5425, after #5011) #5011 added a caller of the old `target_sketch` (MidPoint's `line_stays`, which swaps a point picked after its line) after this branch's base. It now reads the sketch through `sketch_store::target` and `sketch_store::read`, as the other sketch commands do, so a number there is an exact id too. Co-Authored-By: Claude Opus 5.5 * Engine: standard parts fix their sketch's entities through the store (#5425, after #6376) #6376 (a standard part's sketches are fully defined) reads the sketch being drawn straight from the document's features, after this branch's base. `fix_all` now takes it from `sketch_store::active` and `sketch_store::read`, as the store's scan requires, with the same result. Co-Authored-By: Claude Opus 5.5 * Engine: Toggle Diameter and Delete on a profile find their sketch through the store (#5425) Two sketch commands landed on main after the store: sketch.toggle_diameter (#7729) still called the removed sketch::target_sketch, and Delete on a picked profile (#7107) read the sketch straight from the document. Both now go through sketch_store (target and read), and the store's source scan passes again. Co-Authored-By: Claude Opus 5.5 * Sketch dimensioned: use the sketch store's target after the rebase Co-Authored-By: Claude Opus 5.5 * Sketch dimensioned: read the sketch through the store Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/engine/src/cmd/browser.rs | 1 + crates/engine/src/cmd/delete.rs | 4 +- crates/engine/src/cmd/features.rs | 2 +- crates/engine/src/cmd/inspect.rs | 7 +- crates/engine/src/cmd/joints_inspect.rs | 1 + crates/engine/src/cmd/measure_sel.rs | 2 +- crates/engine/src/cmd/mod.rs | 1 + crates/engine/src/cmd/motion_trace.rs | 4 + crates/engine/src/cmd/parameters.rs | 13 +- crates/engine/src/cmd/parts.rs | 5 +- crates/engine/src/cmd/sketch.rs | 61 +++---- crates/engine/src/cmd/sketch_3d.rs | 9 +- crates/engine/src/cmd/sketch_clipboard.rs | 9 +- crates/engine/src/cmd/sketch_constraints.rs | 16 +- crates/engine/src/cmd/sketch_create.rs | 45 +++-- crates/engine/src/cmd/sketch_dimensioned.rs | 4 +- crates/engine/src/cmd/sketch_ends.rs | 5 +- crates/engine/src/cmd/sketch_import.rs | 15 +- crates/engine/src/cmd/sketch_inspect.rs | 14 +- crates/engine/src/cmd/sketch_modify.rs | 5 +- crates/engine/src/cmd/sketch_project.rs | 156 +++++++++--------- crates/engine/src/cmd/sketch_store.rs | 173 ++++++++++++++++++++ crates/engine/src/lib.rs | 3 + 23 files changed, 351 insertions(+), 204 deletions(-) create mode 100644 crates/engine/src/cmd/sketch_store.rs diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rs index c814fbe24..4812e009e 100644 --- a/crates/engine/src/cmd/browser.rs +++ b/crates/engine/src/cmd/browser.rs @@ -1029,6 +1029,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/delete.rs b/crates/engine/src/cmd/delete.rs index 291d69620..0a3496d4a 100644 --- a/crates/engine/src/cmd/delete.rs +++ b/crates/engine/src/cmd/delete.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use solidcraft_doc::FeatureKind; use solidcraft_geom::Vec3; -use super::CommandSpec; +use super::{CommandSpec, sketch_store}; use crate::params::{bad, bool_}; use crate::{EngineError, Result, Sel, Session}; @@ -119,7 +119,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { // whole text, so no counters are left behind. Sel::Profile { sketch, index } if s.active_sketch == Some(*sketch) => { let st = s.model.state(); - let (Some(ss), Ok(sk)) = (st.sketch(*sketch), s.doc.sketch(*sketch)) else { + let (Some(ss), Ok(sk)) = (st.sketch(*sketch), sketch_store::read(&s.doc, *sketch)) else { skip("nothing around that profile can be deleted".into()); continue; }; diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index c82fe7852..3eefa45a1 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -346,7 +346,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 00c457951..11f2fe133 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -252,12 +252,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 75398a529..86d96d3f4 100644 --- a/crates/engine/src/cmd/joints_inspect.rs +++ b/crates/engine/src/cmd/joints_inspect.rs @@ -184,6 +184,7 @@ fn face_ref(doc: &Document, name: &str) -> Value { // A side swept from a sketch curve (a later profile's too, `side:s.`). if let Base::Made { role: Role::Side { curve, .. }, .. } = &face.base { 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 97665bb43..7279dd2e7 100644 --- a/crates/engine/src/cmd/measure_sel.rs +++ b/crates/engine/src/cmd/measure_sel.rs @@ -150,7 +150,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 b00885253..da7769150 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -94,6 +94,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/motion_trace.rs b/crates/engine/src/cmd/motion_trace.rs index 954f3ba76..531bf5657 100644 --- a/crates/engine/src/cmd/motion_trace.rs +++ b/crates/engine/src/cmd/motion_trace.rs @@ -254,6 +254,7 @@ fn seeded(s: &Session, t: &MotionTrace) -> Session { pub(super) fn remember(s: &mut Session, t: &MotionTrace) { let key = inputs(s, t).map_err(|e| e.to_string()); if let Ok(key) = &key + // design-only: a motion trace's wire is in one of the design's sketches. && let Some(points) = s.doc.sketch(t.sketch).ok().and_then(|sk| sk.wires.iter().find(|w| w.id == t.wire)).map(|w| w.fit.clone()) { remember_points(s, t.sketch, key.clone(), points); @@ -330,6 +331,7 @@ pub(crate) fn refresh(s: &mut Session) { let unchanged = s.motion_traces.entries.get(&t.sketch).is_some_and(|old| old.inputs == key); if unchanged && cached.as_ref().is_none_or(|points| { + // design-only: a motion trace's wire is in one of the design's sketches. s.doc.sketch(t.sketch).ok().and_then(|sk| sk.wires.iter().find(|w| w.id == t.wire)).is_some_and(|w| same_points(&w.fit, points)) }) { @@ -352,9 +354,11 @@ pub(crate) fn refresh(s: &mut Session) { remember_points(s, t.sketch, key.clone(), points.clone()); } let error = match result { + // design-only: a motion trace's wire is in one of the design's sketches. Ok(points) => match s.doc.sketch(t.sketch).ok().and_then(|sk| sk.wires.iter().find(|w| w.id == t.wire)) { Some(wire) if same_points(&wire.fit, &points) => None, Some(_) => { + // design-only: a motion trace's wire is in one of the design's sketches. if let Ok(sk) = s.doc_mut().sketch_mut(t.sketch) && let Some(wire) = sk.wires.iter_mut().find(|w| w.id == t.wire) { diff --git a/crates/engine/src/cmd/parameters.rs b/crates/engine/src/cmd/parameters.rs index d99d57d2f..44478ddec 100644 --- a/crates/engine/src/cmd/parameters.rs +++ b/crates/engine/src/cmd/parameters.rs @@ -7,7 +7,7 @@ use solidcraft_doc::FeatureKind; use solidcraft_doc::expr::{self, Kind}; use solidcraft_sketch::{Analysis, ConstraintKind, CurveKind, Hold, Sketch, solve_with}; -use super::CommandSpec; +use super::{CommandSpec, sketch_store}; use crate::params::{bad, bool_, str_}; use crate::{EngineError, Result, Session}; @@ -223,7 +223,7 @@ fn keep_dimension_start(s: &mut Session, name: &str) { } let vals = s.doc.evaluation_values(); for (id, start) in targets { - let Ok(stored) = s.doc.sketch(id) else { continue }; + let Ok(stored) = sketch_store::read(&s.doc, id) else { continue }; let mut trial = stored.clone(); if s.doc.apply_dimension_values(&vals, &mut trial).is_err() { continue; @@ -233,12 +233,13 @@ fn keep_dimension_start(s: &mut Session, name: &str) { if !solve_with(&mut trial, &hold, Some(&reference), Analysis::StatusOnly, None).keeps_orientation() { continue; } - if let Ok(stored) = s.doc_mut().sketch_mut(id) - && stored.points.len() == trial.points.len() - { - for (p, q) in stored.points.iter_mut().zip(&trial.points) { + if stored.points.len() == trial.points.len() { + // Only the points move: the stored dimensions keep their own values. + let mut kept = stored.clone(); + for (p, q) in kept.points.iter_mut().zip(&trial.points) { p.pos = q.pos; } + let _ = sketch_store::write(s.doc_mut(), id, kept); } } } diff --git a/crates/engine/src/cmd/parts.rs b/crates/engine/src/cmd/parts.rs index b340251d0..e6230bd8a 100644 --- a/crates/engine/src/cmd/parts.rs +++ b/crates/engine/src/cmd/parts.rs @@ -272,10 +272,7 @@ fn revolve(s: &mut Session, pts: &[(f64, f64)], op: &str) -> Result<()> { /// Fix every point and curve of the sketch being drawn: a standard part's outline is its size, so /// its sketches are fully defined and a check of the design finds nothing left free in them. fn fix_all(s: &mut Session) -> Result<()> { - let sketch = s.active_sketch.and_then(|id| s.doc.features.iter().find(|f| f.id == id)).and_then(|f| match &f.kind { - solidcraft_doc::FeatureKind::Sketch { sketch, .. } => Some(sketch), - _ => None, - }); + let sketch = super::sketch_store::active(s).and_then(|id| super::sketch_store::read(&s.doc, id).ok()); let entities: Vec = sketch.map(|sk| sk.points.iter().map(|p| p.id.clone()).chain(sk.curves.iter().map(|c| c.id.clone())).collect()).unwrap_or_default(); if !entities.is_empty() { diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 3cccaf359..6643d3514 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; pub use dimensioned::dimension_roles; use dimensioned::draw as draw_dimensioned; use drag::drag_entity; @@ -219,23 +220,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( @@ -245,7 +229,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))) } @@ -289,7 +273,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(); if sk.patterns.iter().any(|p| p.count_expression.is_some() || !p.expressions.is_empty()) { doc.apply_pattern_values(&doc.param_values().0, &mut sk)?; } @@ -336,8 +320,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)) } @@ -882,7 +866,7 @@ fn entry_point(s: &Session) -> SketchEntry { /// and Undo is the way back. fn cancel_sketch(s: &mut Session, _p: &Value) -> Result { let cmd = "sketch.cancel"; - 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 entry = s.sketch_entry.clone().filter(|entry| entry.sketch == id); let current = entry.filter(|entry| { let top = entry.undo_len.checked_sub(1).and_then(|i| s.undo.get(i)).map(|snap| &snap.doc); @@ -1578,7 +1562,12 @@ fn draw_point(s: &mut Session, p: &Value) -> Result { // end refuses it, rather than answered as if a point had been made. let made = str_(p, "point") .filter(|_| p.get("point") != Some(&given)) - .filter(|id| target_sketch(s, p, cmd).ok().and_then(|sid| s.doc.sketch(sid).ok()).is_some_and(|sk| sk.resolve_point(id).is_some())) + .filter(|id| { + sketch_store::target(s, p, cmd) + .ok() + .and_then(|sid| sketch_store::read(&s.doc, sid).ok()) + .is_some_and(|sk| sk.resolve_point(id).is_some()) + }) .map(str::to_string); let Some(pid) = made else { return Err(bad( @@ -1800,7 +1789,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() @@ -1935,7 +1924,7 @@ fn c_coincident(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.constraint.coincident"; let p = &super::sketch_project::project_operands(s, p, cmd, &["a", "b"])?; // 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)?)?; if let Some((a, b)) = two_round(sk, p) { return coincident_circles(s, p, cmd, a, b); } @@ -2160,7 +2149,7 @@ fn c_midpoint(s: &mut Session, p: &Value) -> Result { /// moves when the point can't. fn line_stays(s: &Session, p: &Value, cmd: &str) -> Value { let swapped = (|| { - 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 (a, b) = (p.get("a")?.as_str()?, p.get("b")?.as_str()?); let line = sk.curve_index(b).filter(|c| matches!(sk.curves.get(*c).map(|c| &c.kind), Some(CurveKind::Line { .. }))); (sk.curve_index(a).is_none() && sk.resolve_point(a).is_some() && line.is_some()).then(|| { @@ -2735,7 +2724,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)?)) } @@ -3049,7 +3038,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, _| { @@ -3075,7 +3064,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)); @@ -3112,7 +3101,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()) { @@ -3187,8 +3176,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; @@ -3214,14 +3203,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 7bdfe9df2..938ecfedc 100644 --- a/crates/engine/src/cmd/sketch_3d.rs +++ b/crates/engine/src/cmd/sketch_3d.rs @@ -7,7 +7,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}; @@ -53,8 +54,8 @@ fn needs_3d(sk: &solidcraft_sketch::Sketch, cmd: &str) -> Result<()> { /// The 3D Arc button starts an interactive tool, so it is only offered while a 3D sketch is /// being edited; otherwise the tool could only fail on its third click. fn in_sketch_3d(s: &Session) -> std::result::Result<(), String> { - let id = s.active_sketch.ok_or("no sketch is being edited (Create Sketch or Edit Sketch first)")?; - match s.doc.sketch(id) { + let id = sketch_store::active(s).ok_or("no sketch is being edited (Create Sketch or Edit Sketch first)")?; + match sketch_store::read(&s.doc, id) { Ok(sk) if sk.view.three_d => Ok(()), Ok(_) => Err("turn on 3D Sketch (sketch.options sketch_3d: true) to draw 3D arcs".into()), Err(_) => Err("no sketch is being edited (Create Sketch or Edit Sketch first)".into()), @@ -64,7 +65,7 @@ fn in_sketch_3d(s: &Session) -> std::result::Result<(), String> { /// 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 5d06fcc4d..b9eddfa49 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, cmd)?; 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 459cde79e..2fad3462a 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::schema::sketch_constraints::{ToggleDiameterParams, ToggleDiameterResult}; @@ -403,8 +404,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; } @@ -422,7 +423,7 @@ fn toggle_diameter(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.toggle_diameter"; let cid = str_(p, "constraint").ok_or_else(|| bad(cmd, "`constraint` must be a dimension id"))?.to_string(); let want = crate::params::bool_(p, "diameter"); - let sketch = super::sketch::target_sketch(s, p, cmd)?; + let sketch = sketch_store::target(s, p, cmd)?; let (diameter, info) = edit(s, p, cmd, true, |sk, doc| { let c = sk.constraints.iter().find(|c| c.id == cid).cloned().ok_or_else(|| bad(cmd, format!("no constraint `{cid}`")))?; let round = |curve: usize| matches!(sk.curves.get(curve).map(|c| &c.kind), Some(CurveKind::Circle { .. } | CurveKind::Arc { .. })); @@ -520,12 +521,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; @@ -559,7 +555,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 1af364279..75597ae86 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::schema::sketch_create::{SplineReverseParams, SplineReverseResult}; @@ -286,20 +287,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; @@ -374,23 +374,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_dimensioned.rs b/crates/engine/src/cmd/sketch_dimensioned.rs index 466d6d247..db158803f 100644 --- a/crates/engine/src/cmd/sketch_dimensioned.rs +++ b/crates/engine/src/cmd/sketch_dimensioned.rs @@ -306,8 +306,8 @@ fn place_from_origin(scratch: &mut Session, out: &Value, params: &Value, mut dof /// Where a point of the target sketch is now, in the frame's coordinates: a plane sketch's /// points have z = 0 (a 3D frame would read its points' own z). fn coordinate(s: &Session, params: &Value, point: &str) -> Option { - let id = super::target_sketch(s, params, "sketch.draw.dimensioned").ok()?; - let sketch = s.doc.sketch(id).ok()?; + let id = super::sketch_store::target(s, params, "sketch.draw.dimensioned").ok()?; + let sketch = super::sketch_store::read(&s.doc, id).ok()?; let at = sketch.point(sketch.resolve_point(point)?)?; Some(Vec3::new(at.x, at.y, 0.0)) } diff --git a/crates/engine/src/cmd/sketch_ends.rs b/crates/engine/src/cmd/sketch_ends.rs index cfd531a16..2f41d6fba 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 af92369cb..dc6a8c77a 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}; @@ -233,12 +234,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: own } = 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, @@ -249,7 +251,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; } @@ -268,12 +270,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 9f5285404..abe4d354d 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(cmd, 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(cmd, 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 e3234a7f9..06f935b26 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, intersections_within}; 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_expr, req_vec2, str_, string_list, vec2, vec2_list}; use crate::{Result, Session}; @@ -2070,7 +2071,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); @@ -2090,7 +2091,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 a74c8069c..53cb334ed 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, Vec2, Vec3}; use solidcraft_sketch::{ConstraintKind, LinkKind, LinkSource, Sketch, nearest_crossing}; +use super::sketch_store; use super::{CommandSpec, in_sketch}; use crate::params::{bad, bool_, str_, vec3}; use crate::{EngineError, Result, Session}; @@ -198,7 +199,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(); @@ -292,28 +293,28 @@ 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(); - // Projecting what the sketch already shows (the border of the face it is on, an edge - // projected before) would lay a second copy over the first: those references are skipped. - let mut present = Vec::new(); - for src in sources { - let what = src.describe(); - match add_link_unless_present(s, &doc, id, &mut sk, kind, src, kind == LinkKind::Project) { - Ok(Some(l)) => out.push(link_json(&sk, &l)), - Ok(None) => present.push(what), - Err(e) => return Err(bad(cmd, format!("{what}: {e}"))), + let (out, present) = sketch_store::update(s, id, |s, doc, sk| { + refresh(s, doc, id, sk); + let mut out = Vec::new(); + // Projecting what the sketch already shows (the border of the face it is on, an edge + // projected before) would lay a second copy over the first: those references are skipped. + let mut present = Vec::new(); + for src in sources { + let what = src.describe(); + match add_link_unless_present(s, doc, id, sk, kind, src, kind == LinkKind::Project) { + Ok(Some(l)) => out.push(link_json(sk, &l)), + Ok(None) => present.push(what), + Err(e) => return Err(bad(cmd, format!("{what}: {e}"))), + } } - } - if out.is_empty() { - return Err(bad(cmd, format!("already projected into this sketch: {}", present.join(", ")))); - } - *doc.sketch_mut(id)? = sk; - *s.doc_mut() = doc; + // Nothing new: the sketch is kept as it was. + if out.is_empty() { + return Err(bad(cmd, format!("already projected into this sketch: {}", present.join(", ")))); + } + Ok((out, present)) + })?; let mut r = json!({"links": out}); if !present.is_empty() { r["already_projected"] = json!(present); @@ -343,9 +344,9 @@ pub(super) fn project_operands(s: &mut Session, p: &Value, cmd: &str, keys: &[&s if !keys.iter().any(|k| p.get(*k).is_some_and(model)) { return Ok(p.clone()); } - let id = super::sketch::target_sketch(s, p, cmd)?; + let id = sketch_store::target(s, p, cmd)?; let mut doc = (*s.doc).clone(); - let mut sk = doc.sketch(id)?.clone(); + let mut sk = sketch_store::read(&doc, id)?.clone(); refresh(s, &doc, id, &mut sk); let mut out = p.clone(); for key in keys { @@ -360,25 +361,23 @@ pub(super) fn project_operands(s: &mut Session, p: &Value, cmd: &str, keys: &[&s .ok_or_else(|| bad(cmd, format!("{what} projects to nothing on this sketch")))?; out[*key] = json!(entity); } - *doc.sketch_mut(id)? = sk; + sketch_store::write(&mut doc, id, sk)?; *s.doc_mut() = doc; Ok(out) } /// 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 { @@ -421,7 +420,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}`")))?; @@ -454,48 +453,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(cmd, 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(cmd, 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})) } @@ -537,7 +535,7 @@ fn curve_intersection_arg(v: &Value, cmd: &str) -> Result 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<()> { @@ -567,7 +565,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 ba02014e7..8726eb8bc 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1070,6 +1070,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; @@ -1118,6 +1119,7 @@ impl Session { } } for (id, sketch) in updated { + // design-only: a parameter edit rewrites the design's pattern-quantity sketches. *self.doc_mut().sketch_mut(id)? = sketch; } self.refresh(); @@ -1322,6 +1324,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