SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 306/509: Engine: an optional check before every command (and 3 more)
jyviko44e7ddfc9f35
diff --git a/crates/engine/src/fuzz.rs b/crates/engine/src/fuzz.rsindex 2cde15d50d..a6628016ad 100644--- a/crates/engine/src/fuzz.rs+++ b/crates/engine/src/fuzz.rs@@ -81,7 +81,9 @@ fn classify(e: &EngineError) -> Outcome {let msg = e.to_string();match e {EngineError::Internal(..) => Outcome::new("panic", msg),- EngineError::BadParams { .. } | EngineError::Disabled(..) | EngineError::UnknownCommand(_) => Outcome::new("rejected", msg),+ EngineError::BadParams { .. } | EngineError::Disabled(..) | EngineError::Refused { .. } | EngineError::UnknownCommand(_) => {+ Outcome::new("rejected", msg)+ }// A failed boolean is a failure even when it says "not supported": those are the cases// to fix. Features the kernel doesn't do yet are limitations.// Picks the generator got wrong (a centroid off its face).diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 07016b2cbd..3a45a9abca 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -66,6 +66,10 @@ pub enum EngineError {BadParams { cmd: String, msg: String },#[error("{0}")]Other(String),+ /// The host's pre-command check ([`Session::set_command_check`]) refused the command; the+ /// message is the reason it gave.+ #[error("{reason}")]+ Refused { cmd: String, reason: String },/// A command panicked; the document was kept as it was (a bug: please report it).#[error("internal error in `{0}` (the design was kept as it was): {1}")]Internal(String, String),@@ -325,6 +329,11 @@ impl ComputedCommands {}}+/// A check an app that embeds the engine runs before every command ([`Session::set_command_check`]):+/// it is shown the command's id, its parameters and the session (read only), and returns `Ok` to+/// let the command run or `Err(reason)` to refuse it.+pub type CommandCheck = Arc<dyn Fn(&str, &Value, &Session) -> std::result::Result<(), String> + Send + Sync>;+/// An editing session on one design./// Starts an upload of a file (its name, its bytes) to EasyPrint and returns at once; the host/// reports how it went and opens the answer itself. `Err`: it couldn't start.@@ -442,6 +451,9 @@ pub struct Session {/// that did is no edit of the design before it, so [`Session::execute`] never takes it for a/// change of render intent or part properties alone.replacements: u64,+ /// The host's pre-command check (none by default: every command may run). It belongs to the+ /// host, not the design: opening or starting a design keeps it, and scratch copies carry it.+ command_check: Option<CommandCheck>,/// Record this session's top-level commands in the crash journal (the app's own design;/// never previews or other scratch sessions). See [`crash`].pub crash_journal: bool,@@ -621,6 +633,7 @@ impl Session {#[cfg(test)]evaluations: 0,motion_traces: Default::default(),+ command_check: None,crash_journal: false,}}@@ -644,8 +657,10 @@ impl Session {// next frame, so commands sent right after `doc.open` or `file.new` are kept.let crash_journal = self.crash_journal;let replacements = self.replacements.wrapping_add(1);+ let command_check = self.command_check.take();*self = fresh;self.crash_journal = crash_journal;+ self.command_check = command_check;self.auto_project = auto_project;self.metric_tap_drill_major_less_pitch = metric_tap_drill_major_less_pitch;self.param_check = param_check;@@ -657,6 +672,32 @@ impl Session {self.replacements = replacements;}+ /// Install (or with `None` remove) the check [`Session::execute`] runs before every command,+ /// for an app that embeds the engine and decides which commands may run. A refusal comes back+ /// as [`EngineError::Refused`] and leaves the session as it was.+ pub fn set_command_check(&mut self, check: Option<CommandCheck>) {+ self.command_check = check;+ }++ /// The check installed with [`Session::set_command_check`], to hand on to another session.+ pub fn command_check(&self) -> Option<CommandCheck> {+ self.command_check.clone()+ }++ /// Ask the host's check, if any, whether `spec` may run with `params`. A check that panics+ /// refuses the command as an internal error instead of taking the session down.+ fn check_command(&self, spec: &CommandSpec, params: &Value) -> Result<()> {+ let Some(check) = &self.command_check else { return Ok(()) };+ // The check sees the parameters as the command will (no parameters: an empty object).+ let empty = Value::Object(Default::default());+ let params = if params.is_null() { &empty } else { params };+ match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| check(spec.id, params, self))) {+ Ok(Ok(())) => Ok(()),+ Ok(Err(reason)) => Err(EngineError::Refused { cmd: spec.id.to_string(), reason }),+ Err(_) => Err(EngineError::Internal(spec.id.to_string(), "the host's command check failed".into())),+ }+ }+/// The design has changes not in its file: in the document, or in what is hidden.pub fn is_dirty(&self) -> bool {(!Arc::ptr_eq(&self.doc, &self.saved) && *self.doc != *self.saved) || self.visibility != self.saved_visibility@@ -1131,7 +1172,9 @@ impl Session {}/// Run a command with JSON parameters (no dialogs). Undoable commands record an undo step- /// when they change the document; a failing or panicking command leaves it unchanged.+ /// when they change the document; a failing or panicking command leaves it unchanged. The+ /// host's check ([`Session::set_command_check`]) is asked first, on every call (commands that+ /// a command runs through `execute` included).////// A command that takes `live` ([`CommandSpec::live`]) run with `live: true` is one frame of/// an interactive gesture: the model shows its sketch's new solution and keeps every later@@ -1154,6 +1197,8 @@ impl Session {}}(spec.enabled)(self).map_err(|why| EngineError::Disabled(spec.id.to_string(), why))?;+ // Before anything changes: a refusal leaves the session exactly as it was.+ self.check_command(spec, params)?;let before = Snapshot {label: spec.label.to_string(),doc: self.doc.clone(),@@ -1394,6 +1439,7 @@ impl Session {#[cfg(test)]evaluations: 0,motion_traces: self.motion_traces.clone(),+ command_check: self.command_check.clone(),crash_journal: false,}}diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 950f1750e8..c2b9f736f0 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -4537,3 +4537,78 @@ fn join_leaves_a_hidden_body_alone() {run(&mut s, "browser.visibility", json!({"items": ["Plate (2)"], "visible": true}));assert_eq!(s.model.state().bodies.len(), 2);}++/// A pre-command check that refuses one command id.+fn refusing(id: &'static str) -> CommandCheck {+ std::sync::Arc::new(move |cmd: &str, _: &Value, _: &Session| if cmd == id { Err(format!("{cmd} is not allowed here")) } else { Ok(()) })+}++#[test]+fn without_a_command_check_every_command_runs() {+ let mut s = Session::default();+ assert!(s.command_check().is_none());+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));+ run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [20, 0, 0]}));+ assert_eq!(s.doc.features.len(), 2);+}++#[test]+fn a_command_check_refuses_a_command_and_leaves_the_design() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));+ s.set_command_check(Some(refusing("solid.box")));+ let doc = s.doc.clone();+ let (undo, revision) = (s.undo.len(), s.revision);+ let r = s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "corner": [20, 0, 0]}));+ match r {+ Err(EngineError::Refused { cmd, reason }) => {+ assert_eq!(cmd, "solid.box");+ assert_eq!(reason, "solid.box is not allowed here");+ }+ other => panic!("expected a refusal, got {other:?}"),+ }+ assert!(std::sync::Arc::ptr_eq(&doc, &s.doc), "the design is unchanged");+ assert_eq!((s.undo.len(), s.revision), (undo, revision));+ // Other commands still run, and the check stays with the session across new designs,+ // scripts and previews.+ run(&mut s, "file.new", json!({"name": "Next"}));+ assert!(s.execute("solid.box", &json!({"length": 1, "width": 1, "height": 1})).is_err(), "kept by file.new");+ assert!(s.run_script(&json!([{"command": "solid.box", "params": {"length": 1, "width": 1, "height": 1}}])).is_err(), "scripts");+ assert!(s.preview(&[("solid.box".into(), json!({"length": 1, "width": 1, "height": 1}))]).is_err(), "previews");+ s.set_command_check(None);+ run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1}));+}++#[test]+fn a_command_check_can_count_the_features() {+ const MAX: usize = 3;+ let mut s = Session::default();+ let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<(String, Value)>::new()));+ let log = seen.clone();+ s.set_command_check(Some(std::sync::Arc::new(move |cmd: &str, params: &Value, s: &Session| {+ if let Ok(mut log) = log.lock() {+ log.push((cmd.to_string(), params.clone()));+ }+ if cmd.starts_with("solid.") && s.doc.features.len() >= MAX { Err(format!("at most {MAX} features")) } else { Ok(()) }+ })));+ for i in 0..MAX {+ run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "corner": [i * 5, 0, 0]}));+ }+ let r = s.execute("solid.box", &json!({"length": 1, "width": 1, "height": 1, "corner": [50, 0, 0]}));+ assert!(matches!(&r, Err(EngineError::Refused { .. })), "{r:?}");+ assert_eq!(r.err().map(|e| e.to_string()).as_deref(), Some("at most 3 features"));+ assert_eq!(s.doc.features.len(), MAX);+ // The check saw each command's id and parameters.+ let seen = seen.lock().map(|l| l.clone()).unwrap_or_default();+ assert_eq!(seen.len(), MAX + 1);+ assert!(seen.iter().all(|(id, p)| id == "solid.box" && p["length"] == 1));+}++#[test]+fn a_command_check_that_panics_refuses_the_command() {+ let mut s = Session::default();+ s.set_command_check(Some(std::sync::Arc::new(|_: &str, _: &Value, _: &Session| -> std::result::Result<(), String> { panic!("host bug") })));+ let r = s.execute("solid.box", &json!({"length": 1, "width": 1, "height": 1}));+ assert!(matches!(r, Err(EngineError::Internal(..))), "{r:?}");+ assert!(s.doc.features.is_empty());+}diff --git a/crates/geom/src/tess/uv.rs b/crates/geom/src/tess/uv.rsindex 65040c9425..bd45eba6d2 100644--- a/crates/geom/src/tess/uv.rs+++ b/crates/geom/src/tess/uv.rs@@ -99,10 +99,14 @@ fn same_point(a: Option<&[f64; 4]>, b: Option<&[f64; 4]>, extent: f64) -> bool {}}-/// Knots of degree `p` over `n` control points, clamped at both ends.+/// Knots of degree `p` over `n` control points, clamped at both ends: the spline starts at its+/// first control point and ends at its last, its interval `[k[p], k[n]]` ending on knots of+/// multiplicity `p` within it. The outermost knots (`k[0]`, `k[n + p]`) take no part in the+/// spline over its interval, so they need not repeat: a periodic quadratic circle written with+/// knot multiplicities `1, 2, …, 2, 1` (as OpenCascade writes one) is clamped.fn clamped(p: usize, n: usize, k: &[f64]) -> bool {let ends = |r: std::ops::RangeInclusive<usize>| k.get(r).is_some_and(|s| s.windows(2).all(|w| w.first() == w.get(1)));- k.len() == n + p + 1 && ends(0..=p) && ends(n..=n + p)+ p >= 1 && k.len() == n + p + 1 && ends(1..=p) && ends(n..=n + p - 1)}/// `x` moved by whole periods `b − a` into `[a, b]` when it lies outside.@@ -411,6 +415,10 @@ mod tests {let dom = domain(&s);let Some(q) = project(&s, &dom, p, Some([0.98, 0.5]), 1e-9) else { panic!("projects") };assert!((unwrap(q[0], 0.98, dom.period[0]) - 1.02).abs() < 1e-9, "{q:?}");+ // Knots whose outermost values do not repeat, as OpenCascade writes a periodic circle:+ // the interval still ends on knots of multiplicity 2, so the spline is closed there.+ let outer_once = ring([0.0; 4], vec![-0.25, 0.0, 0.0, 0.25, 0.5, 0.75, 1.0, 1.0, 1.25]);+ assert_eq!(domain(&outer_once).period, [Some(1.0), None]);// Ends that only come near each other, a weight that differs, or unclamped knots: open,// and evaluated past the interval as before (the end span continued).for (what, open) in [diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rsindex c518cc6dd5..89ef216a05 100644--- a/crates/gpu/src/view.rs+++ b/crates/gpu/src/view.rs@@ -3369,14 +3369,19 @@ impl Renderer {}}tris(pass, &res.tri_hl, &h.tris);+ // Hidden edges before the visible ones, so a visible edge is drawn over them. An edge+ // within a pixel of a nearer face's outline (a face seen edge on beside it) is hidden+ // under part of its own width; drawn after, its light hidden copy covered the visible+ // edge beside it there with a light line.+ pass.set_bind_group(0, scene_bind(m, &res.bind), &[]);+ lines(pass, &res.line_hidden, &m.hidden);+ pass.set_bind_group(0, scene_bind(h, &res.bind), &[]);+ lines(pass, &res.line_hidden, &h.hidden);pass.set_bind_group(0, scene_bind(m, &res.bind), &[]);lines(pass, &res.line, &m.lines);pass.set_bind_group(0, scene_bind(sk, &res.bind), &[]);lines(pass, &res.line, &sk.lines);- pass.set_bind_group(0, scene_bind(m, &res.bind), &[]);- lines(pass, &res.line_hidden, &m.hidden);pass.set_bind_group(0, scene_bind(h, &res.bind), &[]);- lines(pass, &res.line_hidden, &h.hidden);lines(pass, &res.line, &h.lines);lines(pass, &res.guide_line, &h.guide_lines);pass.set_bind_group(0, scene_bind(pv, &res.bind), &[]);diff --git a/crates/gpu/tests/depth.rs b/crates/gpu/tests/depth.rsindex 1d83c4d3f5..8cd6d7bdf5 100644--- a/crates/gpu/tests/depth.rs+++ b/crates/gpu/tests/depth.rs@@ -575,3 +575,84 @@ fn touching_caps_are_hatched_apart_and_keep_their_hatch() {assert!(!oa.1, "{mode} depth: one hatch runs at 45 degrees");}}++/// A 40 × 20 × 30 mm box centred on the origin, a flat-shaded face per side, and its 12 edges+/// with the outward normals of the two faces beside each.+fn shaded_box() -> (Mesh, Vec<(Vec3, Vec3, [Vec3; 2])>) {+ let h = Vec3::new(20.0, 10.0, 15.0);+ let corner = |i: usize| Vec3::new(if i & 1 == 0 { -h.x } else { h.x }, if i & 2 == 0 { -h.y } else { h.y }, if i & 4 == 0 { -h.z } else { h.z });+ // Each side: its normal and its corners, counter-clockwise seen from outside.+ let sides = [+ (Vec3::new(-1.0, 0.0, 0.0), [0, 4, 6, 2]),+ (Vec3::new(1.0, 0.0, 0.0), [1, 3, 7, 5]),+ (Vec3::new(0.0, -1.0, 0.0), [0, 1, 5, 4]),+ (Vec3::new(0.0, 1.0, 0.0), [2, 6, 7, 3]),+ (Vec3::new(0.0, 0.0, -1.0), [0, 2, 3, 1]),+ (Vec3::new(0.0, 0.0, 1.0), [4, 5, 7, 6]),+ ];+ let mut mesh = Mesh::default();+ for (f, (n, c)) in sides.iter().enumerate() {+ let base = mesh.positions.len() as u32;+ mesh.positions.extend(c.iter().map(|i| corner(*i)));+ mesh.normals.extend([*n; 4]);+ mesh.triangles.extend([[base, base + 1, base + 2], [base, base + 2, base + 3]]);+ mesh.tri_face.extend([f as u32; 2]);+ }+ let mut edges = Vec::new();+ for (i, (n, c)) in sides.iter().enumerate() {+ for k in 0..4 {+ let (a, b) = (c[k], c[(k + 1) % 4]);+ // Each edge once: from the side that runs it from the lower corner.+ if a > b {+ continue;+ }+ let other = sides.iter().enumerate().find(|(j, (_, d))| *j != i && (0..4).any(|m| d[m] == b && d[(m + 1) % 4] == a));+ if let Some((_, (m, _))) = other {+ edges.push((corner(a), corner(b), [*n, *m]));+ }+ }+ }+ (mesh, edges)+}++/// The shaded-with-hidden-edges style: every edge drawn depth-tested and, in a light colour,+/// where the model hides it (`GpuScene::hidden_line`). A box turned so one side is seen almost+/// edge on (yaw 1.565): the side is under a pixel wide, so the edges along it lie within a pixel+/// of the nearer face beside it, which hides part of their width. Their hidden copy shows nowhere:+/// drawn after the visible edges, it covered the visible edge of that nearer face with a light+/// line along some 100 px. The box's back edges, which are hidden, still show.+#[test]+fn a_visible_edge_beside_a_face_seen_edge_on_has_no_hidden_copy() {+ let (mesh, edges) = shaded_box();+ let (w, h) = (400, 300);+ for (mode, c) in capturers() {+ for fov in [0.0, 0.6] {+ for yaw in [1.565_f64, 0.35] {+ let cam = Camera { yaw, distance: 120.0, fov, ..Default::default() };+ let toward = |p: Vec3| if fov > 0.0 { cam.eye() - p } else { cam.back() };+ let back = |(a, b, n): &(Vec3, Vec3, [Vec3; 2])| n.iter().all(|n| n.dot(toward((*a + *b) * 0.5)) < 0.0);+ let lines = edges+ .iter()+ .map(|(a, b, _)| SceneLine { points: vec![*a, *b], color: Rgb(20, 20, 20), alpha: 1.0, width: 1.3, on_top: false })+ .collect();+ let scene =+ Scene { meshes: vec![SceneMesh::solid(Arc::new(mesh.clone()), Rgb(160, 165, 175))], lines, radius: 40.0, ..Default::default() };+ let hidden = |keep: &dyn Fn(&(Vec3, Vec3, [Vec3; 2])) -> bool| {+ let mut sc = solidcraft_gpu::view::GpuScene::default();+ let col = sc.color([0, 255, 0, 255]);+ for e in edges.iter().filter(|e| keep(e)) {+ sc.hidden_line(e.0.to_f32(), e.1.to_f32(), col, 1.0);+ }+ c.rgba_highlighted(&scene, Some(sc), &cam, w, h).unwrap()+ };+ let green = |p: [u8; 4]| p[1] > 150 && p[0] < 120 && p[2] < 120;+ let (all, back_only, none) = (hidden(&|_| true), hidden(&back), hidden(&|_| false));+ let doubled = differing(&all, &back_only);+ assert_eq!(doubled, 0, "{mode} depth, fov {fov}, yaw {yaw}: a visible edge's hidden copy shows in {doubled} px");+ let behind = pixels(&back_only).filter(|p| green(*p)).count();+ assert!(behind > 100, "{mode} depth, fov {fov}, yaw {yaw}: the back edges show in {behind} px");+ assert_eq!(pixels(&none).filter(|p| green(*p)).count(), 0);+ }+ }+ }+}diff --git a/crates/step/src/topology.rs b/crates/step/src/topology.rsindex ce440d6585..68194361df 100644--- a/crates/step/src/topology.rs+++ b/crates/step/src/topology.rs@@ -943,6 +943,9 @@ impl<'b, 'a> Builder<'b, 'a> {fn finish(mut self, item: u64, name: String, shells: Vec<Vec<(u32, bool)>>, kind: Kind) -> R<Solid> {let _span = solidcraft_profile::span("import", "step.solid_record");let mut notes = Vec::new();+ // A whole sphere bounded by one seam has its frame on that seam, before anything is+ // measured on the frame.+ self.seat_spheres_on_seams()?;let at_poles = self.split_at_poles()?;if at_poles > 0 {notes.push(format!("{at_poles} edges split where they pass through a face's pole"));diff --git a/crates/step/src/topology/frames.rs b/crates/step/src/topology/frames.rsindex b3c4b59bb4..4874f3da33 100644--- a/crates/step/src/topology/frames.rs+++ b/crates/step/src/topology/frames.rs@@ -19,7 +19,8 @@//! group as the file has it.use solidcraft_geom::Vec3;-use solidcraft_geom::brep::{self, Curve as BCurve};+use solidcraft_geom::brep::eval::CurveEval;+use solidcraft_geom::brep::{self, Curve as BCurve, Frame, Surface as BSurface};use super::{Builder, LoopB, R};@@ -178,3 +179,50 @@ impl Builder<'_, '_> {Ok(turned)}}++impl Builder<'_, '_> {+ /// Put the frame of each whole sphere bounded by one seam alone (a meridian from pole to+ /// pole, used both ways) on that seam: its axis through the seam's ends, its x axis through+ /// the seam's middle. A sphere's frame is the writer's choice (any right-handed frame about+ /// the centre is the same surface, its natural normal outward); one whose poles are not the+ /// seam's leaves the seam a slit across the form, not the form's own seam, and no kernel+ /// takes that as the whole ball. Returns how many frames were moved.+ pub(super) fn seat_spheres_on_seams(&mut self) -> R<usize> {+ let mut seated = 0;+ for fi in 0..self.faces.len() {+ let Some(face) = self.faces.get(fi) else { continue };+ let BSurface::Sphere { frame, radius } = &face.surface else { continue };+ let (frame, radius) = (frame.clone(), *radius);+ let [LoopB::Edges(uses)] = face.loops.as_slice() else { continue };+ let [(e, a), (f, b)] = uses.as_slice() else { continue };+ if e != f || a == b {+ continue;+ }+ let edge = self.edges.get(*e as usize).ok_or("edge reference")?;+ let point = |v: u32| self.vertices.get(v as usize).map(|x| (Vec3::from(x.point), x.tolerance));+ let (Some((start, t0)), Some((end, t1))) = (point(edge.vertices[0]), point(edge.vertices[1])) else { continue };+ let centre = Vec3::from(frame.origin);+ let reach = self.tol.max(edge.tolerance).max(t0).max(t1);+ // The seam runs between antipodes: its ends on the sphere, opposite each other.+ if (start.dist(centre) - radius.abs()).abs() > reach || (start - centre).dist(centre - end) > 2.0 * reach {+ continue;+ }+ let Some(z) = (start - end).normalized() else { continue };+ let axis = Vec3::from(frame.x_axis).cross(Vec3::from(frame.y_axis));+ // Already the frame's poles.+ if axis.cross(z).len() * radius.abs() <= reach {+ continue;+ }+ let c = CurveEval::new(&edge.curve).map_err(|m| m.to_string())?;+ let middle = c.point(0.5 * (edge.interval[0] + edge.interval[1])).ok_or("edge point")?;+ let off = middle - centre;+ let Some(x) = (off - z * off.dot(z)).normalized() else { continue };+ let y = z.cross(x);+ let Some(face) = self.faces.get_mut(fi) else { continue };+ face.surface = BSurface::Sphere { frame: Frame { origin: frame.origin, x_axis: [x.x, x.y, x.z], y_axis: [y.x, y.y, y.z] }, radius };+ face.extent = None;+ seated += 1;+ }+ Ok(seated)+ }+}diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rsindex 0c0afd76ca..0c0296aa48 100644--- a/crates/ui-egui/src/documents.rs+++ b/crates/ui-egui/src/documents.rs@@ -159,6 +159,8 @@ fn swap_in(app: &mut SolveApp, mut slot: DocSlot) -> DocSlot {// Preferences the session holds go with the user, not the tab (#680).app.session.auto_project = out.session.auto_project;app.session.metric_tap_drill_major_less_pitch = out.session.metric_tap_drill_major_less_pitch;+ // So does the host's pre-command check: every tab is held to it.+ app.session.set_command_check(out.session.command_check());// Views cache by revision: the incoming design must not look unchanged.let before = app.session.revision;app.session.invalidate_view(out_rev);@@ -1495,6 +1497,30 @@ mod tests {assert!(!a.session.auto_project, "a design adopted over a blank one");}+ /// The host's pre-command check holds in every tab: new ones, the one switched to, a design+ /// adopted over a blank one and after the last tab closes.+ #[test]+ fn the_command_check_follows_the_host_across_tabs() {+ let mut a = app();+ a.session.set_command_check(Some(std::sync::Arc::new(+ |id: &str, _: &Value, _: &Session| {+ if id == "solid.box" { Err("no boxes".to_string()) } else { Ok(()) }+ },+ )));+ assert_eq!(a.run("solid.box", json!({"length": 10, "width": 10, "height": 10})), Err("no boxes".to_string()));+ a.run("solid.cylinder", json!({"radius": 5, "height": 10})).unwrap();+ new_design(&mut a);+ assert_eq!(a.docs.count(), 2);+ assert!(a.run("solid.box", json!({"length": 5, "width": 5, "height": 5})).is_err(), "a new tab");+ switch(&mut a, 0);+ assert!(a.run("solid.box", json!({"length": 5, "width": 5, "height": 5})).is_err(), "the tab switched to");+ close(&mut a, 1, true);+ close(&mut a, 0, true);+ assert!(a.run("solid.box", json!({"length": 5, "width": 5, "height": 5})).is_err(), "after the last tab closes");+ adopt(&mut a, Session::default());+ assert!(a.run("solid.box", json!({"length": 5, "width": 5, "height": 5})).is_err(), "a design adopted over a blank one");+ }+/// Hide Origin by Default hides the Origin of designs that don't keep its eye; a design that/// does keeps it, along with the rest of the browser's view, in its tab and in its file.#[test]diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rsindex cc6bfead2d..8bb48e18e4 100644--- a/crates/ui-egui/src/file_load.rs+++ b/crates/ui-egui/src/file_load.rs@@ -408,6 +408,8 @@ fn start(app: &mut SolveApp) {let before = if insert { crate::open_meshing::session_world(&app.session).bodies.iter().map(|b| b.name.clone()).collect() } else { Vec::new() };let update = request.kind == Kind::UpdateLinks;let mut scratch = if insert || update || request.kind == Kind::ExportDxf { app.session.scratch() } else { Session::default() };+ // A design opened or recovered here is run through the host's pre-command check too.+ scratch.set_command_check(app.session.command_check());if insert {scratch.selection = app.session.selection.clone();}@@ -534,6 +536,7 @@ fn start_staged(app: &mut SolveApp) {let insert = request.insert();let before = if insert { crate::open_meshing::session_world(&app.session).bodies.iter().map(|b| b.name.clone()).collect() } else { Vec::new() };let mut session = if insert { app.session.scratch() } else { Session::default() };+ session.set_command_check(app.session.command_check());if insert {session.selection = app.session.selection.clone();}