Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Delete: check what a delete breaks off the window thread (#2678) (#2679)

fugazistere9b1a077d7e3
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs
index fc8e4b45aa..04b39f5ef8 100644
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@ -1075,7 +1075,7 @@ fn reorder(s: &mut Session, p: &Value) -> Result<Value> {
sort_group_features(&mut next);
require_contiguous_groups(&next, cmd)?;
// Everything that evaluated before must still evaluate.
- let mut after = solidcraft_doc::Model::new();
+ let mut after = s.model.clone();
after.evaluate(&next);
let broken = newly_broken(&s.model, &after);
if !broken.is_empty() {
@@ -1338,7 +1338,10 @@ fn dependents(s: &mut Session, p: &Value) -> Result<Value> {
let id = feature_id(s, p.get("feature"), cmd)?;
let mut next = (*s.doc).clone();
let gone = next.delete_feature(id)?;
- let mut after = solidcraft_doc::Model::new();
+ // On a copy of the session's model, which shares its evaluation cache (#2678): the features
+ // before this one are reused rather than recomputed, and the delete that usually follows
+ // finds the ones after it already computed.
+ let mut after = s.model.clone();
after.evaluate(&next);
let names = |ids: &[u64]| -> Vec<String> { ids.iter().filter(|x| **x != id).filter_map(|x| s.doc.feature(*x).map(|f| f.name.clone())).collect() };
let broken: Vec<String> = newly_broken(&s.model, &after).into_iter().map(|(n, _)| n).collect();
diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs
index d4acb82ae0..e29aede83d 100644
--- a/crates/engine/src/cmd/edit_tests.rs
+++ b/crates/engine/src/cmd/edit_tests.rs
@@ -597,6 +597,26 @@ fn edit_refuses_unknown_fields() {
assert_eq!(def["combine"], json!(true), "{def}");
}
+/// The check before a delete (`timeline.dependents`) evaluates on the session's model, so it
+/// shares the evaluation cache (#2678): the delete that follows finds the features after the
+/// deleted one already computed instead of computing them again. (What it reports is covered by
+/// the timeline tests in `tests.rs`.)
+#[test]
+fn the_dependents_check_leaves_the_delete_its_results() {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 60, "width": 20, "height": 10, "name": "Base"}));
+ run(&mut s, "solid.box", json!({"corner": [5, 5, 10], "length": 10, "width": 10, "height": 5, "operation": "join", "name": "Boss"}));
+ run(&mut s, "solid.cylinder", json!({"base": [40, 10, -1], "radius": 2, "height": 20, "operation": "cut", "name": "Hole"}));
+ let report = run(&mut s, "timeline.dependents", json!({"feature": "Boss"}));
+ assert_eq!(report, json!({"deleted_with_it": [], "would_fail": []}));
+ let hits = |s: &Session| s.model.cache.lock().map(|c| c.hits).unwrap_or(0);
+ let before = hits(&s);
+ run(&mut s, "timeline.delete", json!({"features": ["Boss"]}));
+ assert!(hits(&s) > before, "the delete takes the hole the check computed from the cache");
+ let volume = run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap();
+ assert!((volume - (12000.0 - std::f64::consts::PI * 4.0 * 10.0)).abs() < 1.0, "{volume}");
+}
+
fn suppressed(s: &Session, name: &str) -> bool {
s.doc.find_feature(name).unwrap().suppressed
}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 5129dd1fb1..9f1fc0bbaa 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -165,6 +165,13 @@ impl Ahead {
pub fn evaluate(self, commands: &[(String, Value)]) -> Result<()> {
self.0.preview_in_place(commands).map(|_| ())
}
+
+ /// Run `commands` one after another, each reply or error in turn (what they evaluate stays
+ /// in the shared evaluation cache): the checks a front end makes before a command, such as
+ /// what a delete takes with it (#2678), computed off its window thread.
+ pub fn replies(mut self, commands: &[(String, Value)]) -> Vec<Result<Value>> {
+ commands.iter().map(|(id, params)| self.0.execute(id, params)).collect()
+ }
}
/// What some commands would make, evaluated on a scratch copy of a session
diff --git a/crates/ui-egui/src/deferred.rs b/crates/ui-egui/src/deferred.rs
index 12140f8661..4a91046310 100644
--- a/crates/ui-egui/src/deferred.rs
+++ b/crates/ui-egui/src/deferred.rs
@@ -11,6 +11,12 @@
//! its features in the cache. Commands asked for meanwhile wait their turn; a marker moved again
//! replaces the move still waiting, so a drag computes where it ends rather than every slot it
//! crossed.
+//!
+//! A delete first checks what it takes with it and what it would make fail (#2678): the
+//! timeline's Delete asks `timeline.dependents`, Delete on the selection runs `selection.delete`
+//! as a dry run. Each check evaluates the history after the deleted feature, so it is computed
+//! the same way ([`DeleteCheck`]): the window goes on while it computes, then the delete runs, or
+//! the confirmation opens, with the check's results already in the cache.
use serde_json::Value;
@@ -32,6 +38,54 @@ impl Deferred {
}
}
+/// A delete's check computing off the window thread: each check command's reply, in order.
+pub struct DeleteCheck {
+ done: std::sync::mpsc::Receiver<Vec<Result<Value, String>>>,
+ /// When it started (ms).
+ pub(crate) started: f64,
+ then: AfterCheck,
+ /// The design's revision it was computed for: a design changed meanwhile checks again.
+ revision: u64,
+}
+
+/// What a delete does once its check is in.
+#[derive(Clone, Debug)]
+pub(crate) enum AfterCheck {
+ /// The timeline's Delete of these features (a `timeline.dependents` report for each).
+ Timeline(Vec<u64>),
+ /// Delete with these `selection.delete` parameters (the report of its dry run).
+ Selection(Value),
+}
+
+impl AfterCheck {
+ /// Check again, for the design as it is now.
+ fn restart(self, app: &mut SolveApp) {
+ match self {
+ AfterCheck::Timeline(ids) => {
+ let ids: Vec<u64> = ids.into_iter().filter(|id| app.session.doc.feature(*id).is_some()).collect();
+ if !ids.is_empty() {
+ crate::timeline::delete_features(app, ids);
+ }
+ }
+ AfterCheck::Selection(params) => crate::delete::request(app, params),
+ }
+ }
+
+ /// Carry on with the check's replies.
+ fn finish(self, app: &mut SolveApp, replies: Vec<Result<Value, String>>) {
+ match self {
+ AfterCheck::Timeline(ids) => {
+ let reports: Vec<Value> = replies.into_iter().map(Result::unwrap_or_default).collect();
+ crate::timeline::delete_checked_features(app, ids, &reports);
+ }
+ AfterCheck::Selection(params) => {
+ let report = replies.into_iter().next().unwrap_or_else(|| Err("the delete was not checked".into()));
+ crate::delete::checked(app, params, report);
+ }
+ }
+ }
+}
+
/// Commands a later one of the same kind replaces while they wait: where the marker ends is all
/// that counts.
fn replaced_by_a_later_one(id: &str) -> bool {
@@ -59,9 +113,64 @@ impl SolveApp {
}
}
- /// Since when a command has been computing off the window thread (ms), if one is.
+ /// Since when a command, or a delete's check, has been computing off the window thread (ms),
+ /// if one is.
pub fn computing_since(&self) -> Option<f64> {
- self.deferred.as_ref().map(|d| d.started)
+ let started = [self.deferred.as_ref().map(|d| d.started), self.delete_check.as_ref().map(|c| c.started)];
+ started.into_iter().flatten().reduce(f64::min)
+ }
+
+ /// Run a delete's check `commands` and carry on with `then` once their replies are in: off
+ /// the window thread when it takes longer than the app's wait (see the module notes),
+ /// otherwise right away. A Delete while another delete is being checked is left out.
+ pub(crate) fn check_delete(&mut self, commands: Vec<(String, Value)>, then: AfterCheck) {
+ if self.delete_check.is_some() {
+ return;
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ if let Some(wait) = self.apply_off_thread
+ && !self.file_load.busy()
+ && self.file_picker.is_none()
+ {
+ let ahead = self.session.ahead();
+ let (tx, rx) = std::sync::mpsc::channel();
+ let checks = commands.clone();
+ let spawned = std::thread::Builder::new().name("delete check".into()).spawn(move || {
+ let replies = ahead.replies(&checks).into_iter().map(|r| r.map_err(|e| e.to_string())).collect();
+ let _ = tx.send(replies);
+ });
+ if spawned.is_ok() {
+ let check = DeleteCheck { done: rx, started: crate::now_ms(), then, revision: self.session.revision };
+ // As with the history's commands, zero always leaves it for a later frame.
+ match (wait.is_zero(), check.done.recv_timeout(wait)) {
+ (false, Ok(replies)) => check.then.finish(self, replies),
+ _ => self.delete_check = Some(check),
+ }
+ return;
+ }
+ }
+ let replies = commands.iter().map(|(id, params)| self.session.execute(id, params).map_err(|e| e.to_string())).collect();
+ then.finish(self, replies);
+ }
+
+ /// Each frame: a delete whose check is in carries on (checked again when the design changed
+ /// meanwhile).
+ pub(crate) fn poll_delete_check(&mut self, ctx: &egui::Context) {
+ let Some(check) = &self.delete_check else { return };
+ let replies = match check.done.try_recv() {
+ Err(std::sync::mpsc::TryRecvError::Empty) => {
+ ctx.request_repaint_after(std::time::Duration::from_millis(100));
+ return;
+ }
+ Err(std::sync::mpsc::TryRecvError::Disconnected) => None,
+ Ok(replies) => Some(replies),
+ };
+ let Some(check) = self.delete_check.take() else { return };
+ match replies {
+ None => self.set_status("the delete could not be checked", true),
+ Some(_) if check.revision != self.session.revision => check.then.restart(self),
+ Some(replies) => check.then.finish(self, replies),
+ }
}
/// Each frame: a command whose evaluation is in runs, then the next one waiting starts.
diff --git a/crates/ui-egui/src/delete.rs b/crates/ui-egui/src/delete.rs
index 0781dde993..1f1260152d 100644
--- a/crates/ui-egui/src/delete.rs
+++ b/crates/ui-egui/src/delete.rs
@@ -50,17 +50,23 @@ pub fn delete_selection(app: &mut SolveApp) {
}
/// Delete `params` (as `selection.delete` takes them): at once, or after a confirmation when
-/// other features go with it or would fail.
+/// other features go with it or would fail. The dry run that finds out evaluates the history
+/// after what is deleted, so it may compute off the window thread (#2678).
pub fn request(app: &mut SolveApp, params: Value) {
if is_empty(&params) {
return;
}
let mut dry = params.clone();
dry["dry_run"] = json!(true);
- let report = match app.session.execute("selection.delete", &dry) {
+ app.check_delete(vec![("selection.delete".to_string(), dry)], crate::deferred::AfterCheck::Selection(params));
+}
+
+/// [`request`] once its dry run's report is in.
+pub(crate) fn checked(app: &mut SolveApp, params: Value, report: Result<Value, String>) {
+ let report = match report {
Ok(r) => r,
Err(e) => {
- app.set_status(e.to_string().replace("selection.delete: ", ""), true);
+ app.set_status(e.replace("selection.delete: ", ""), true);
return;
}
};
diff --git a/crates/ui-egui/src/history_off_thread_tests.rs b/crates/ui-egui/src/history_off_thread_tests.rs
index 99f98a7736..c06c16576c 100644
--- a/crates/ui-egui/src/history_off_thread_tests.rs
+++ b/crates/ui-egui/src/history_off_thread_tests.rs
@@ -27,7 +27,7 @@ fn block_boss_hole() -> Harness {
/// Frames until nothing computes or waits (a few seconds at most).
fn until_settled(h: &mut Harness) {
for _ in 0..500 {
- if h.app.deferred.is_none() && h.app.deferred_queue.is_empty() {
+ if h.app.deferred.is_none() && h.app.deferred_queue.is_empty() && h.app.delete_check.is_none() {
break;
}
h.frames(1);
@@ -98,3 +98,73 @@ fn a_design_changed_while_a_move_computes_is_computed_again() {
assert!(h.app.session.revision > revision, "the move ran after the change");
assert_eq!(marker(&h), Some(2));
}
+
+fn feature_ids(h: &Harness) -> Vec<u64> {
+ h.app.session.doc.features.iter().map(|f| f.id).collect()
+}
+
+/// Volume of the block with the hole through it, once the boss is deleted.
+fn block_with_hole() -> f64 {
+ 12000.0 - std::f64::consts::PI * 4.0 * 10.0
+}
+
+fn volume(h: &mut Harness) -> f64 {
+ h.app.run("inspect.measure", json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap()
+}
+
+/// The timeline's Delete checks what the delete breaks off the window thread (#2678): the design
+/// is as it was while it checks, and the feature goes once the check is in.
+#[test]
+fn the_timelines_delete_checks_off_the_window_thread() {
+ let mut h = block_boss_hole();
+ let boss = feature_ids(&h)[1];
+ crate::timeline::delete_features(&mut h.app, vec![boss]);
+ assert!(h.app.computing_since().is_some(), "checking");
+ assert!(h.app.session.doc.feature(boss).is_some(), "the design is as it was while it checks");
+ until_settled(&mut h);
+ assert!(h.app.session.doc.feature(boss).is_none(), "deleted once the check is in");
+ assert!(h.app.dialog.is_none(), "nothing breaks, so nothing to confirm");
+ assert!((volume(&mut h) - block_with_hole()).abs() < 1.0);
+}
+
+/// Delete on the selection (the Delete key) runs its dry run off the window thread too.
+#[test]
+fn delete_on_the_selection_checks_off_the_window_thread() {
+ let mut h = block_boss_hole();
+ let boss = feature_ids(&h)[1];
+ h.app.session.selection = vec![solidcraft_engine::Sel::Feature { id: boss }];
+ let params = crate::delete::selection_params(&h.app);
+ crate::delete::request(&mut h.app, params);
+ assert!(h.app.computing_since().is_some(), "checking");
+ assert!(h.app.session.doc.feature(boss).is_some());
+ until_settled(&mut h);
+ assert!(h.app.session.doc.feature(boss).is_none());
+ assert!(h.app.menu.confirm.is_none());
+ assert!((volume(&mut h) - block_with_hole()).abs() < 1.0);
+}
+
+/// A design changed while its delete is checked is checked again before anything is deleted, and
+/// a second Delete meanwhile is left out.
+#[test]
+fn a_design_changed_while_a_delete_is_checked_is_checked_again() {
+ let mut h = block_boss_hole();
+ let ids = feature_ids(&h);
+ crate::timeline::delete_features(&mut h.app, vec![ids[1]]);
+ crate::timeline::delete_features(&mut h.app, vec![ids[2]]);
+ h.app.run("solid.box", json!({"corner": [100, 0, 0], "length": 10, "width": 10, "height": 10})).unwrap();
+ until_settled(&mut h);
+ assert!(h.app.session.doc.feature(ids[1]).is_none(), "the boss is deleted");
+ assert!(h.app.session.doc.feature(ids[2]).is_some(), "the second Delete was left out");
+ assert!((volume(&mut h) - (block_with_hole() + 1000.0)).abs() < 1.0, "the box added meanwhile stays");
+}
+
+/// Without a wait (headless use, tests) the check runs in place, as before.
+#[test]
+fn without_a_wait_the_delete_checks_in_place() {
+ let mut h = block_boss_hole();
+ h.app.apply_off_thread = None;
+ let boss = feature_ids(&h)[1];
+ crate::timeline::delete_features(&mut h.app, vec![boss]);
+ assert!(h.app.delete_check.is_none());
+ assert!(h.app.session.doc.feature(boss).is_none());
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index b269fe356d..437f9fed0e 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -370,6 +370,9 @@ pub struct SolveApp {
/// thread, and those asked for meanwhile ([`deferred`]).
pub deferred: Option<deferred::Deferred>,
pub deferred_queue: Vec<(String, Value)>,
+ /// A delete's check of what it takes with it or breaks, computing off the window thread
+ /// ([`deferred::DeleteCheck`], #2678).
+ pub delete_check: Option<deferred::DeleteCheck>,
/// How long OK waits for a feature before computing it off the window thread, saying so;
/// `None`: it waits as long as it takes (headless use, tests). The desktop app sets it.
pub apply_off_thread: Option<std::time::Duration>,
@@ -492,6 +495,7 @@ impl SolveApp {
applying: None,
deferred: None,
deferred_queue: Vec::new(),
+ delete_check: None,
apply_off_thread: None,
last_command: None,
esc_handled: false,
@@ -1430,6 +1434,7 @@ impl SolveApp {
fn cad_ui(&mut self, ui: &mut egui::Ui, report_input: &mut Option<issue_report::CadInput>) {
scenario::clear_handles();
self.poll_deferred(ui.ctx());
+ self.poll_delete_check(ui.ctx());
toolbar::app_bar(self, ui);
issue_report::CadInput::block(self, ui, report_input);
file_load::show(self, ui.ctx());
diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs
index 82940ec67d..1b8745302a 100644
--- a/crates/ui-egui/src/timeline.rs
+++ b/crates/ui-egui/src/timeline.rs
@@ -2,7 +2,7 @@
pub(crate) use crate::icons::glyphs::transport_glyph;
use egui::{Rect, Sense, Stroke, UiBuilder, pos2, vec2};
-use serde_json::json;
+use serde_json::{Value, json};
use solidcraft_engine::doc::{
FeatureKind, PlaneRef, SketchId,
construct::{AxisDef, PointDef},
@@ -150,11 +150,18 @@ pub(crate) fn delete_feature(app: &mut SolveApp, id: u64) {
delete_features(app, vec![id]);
}
+/// Check what deleting `ids` takes with it or makes fail (off the window thread when that takes a
+/// while, #2678), then delete them or ask first.
pub(crate) fn delete_features(app: &mut SolveApp, ids: Vec<u64>) {
+ let checks = ids.iter().map(|id| ("timeline.dependents".to_string(), json!({ "feature": id }))).collect();
+ app.check_delete(checks, crate::deferred::AfterCheck::Timeline(ids));
+}
+
+/// [`delete_features`] once each feature's `timeline.dependents` report is in.
+pub(crate) fn delete_checked_features(app: &mut SolveApp, ids: Vec<u64>, reports: &[Value]) {
let mut with = std::collections::BTreeSet::new();
let mut fail = std::collections::BTreeSet::new();
- for id in &ids {
- let deps = app.session.execute("timeline.dependents", &json!({ "feature": id })).unwrap_or_default();
+ for deps in reports {
for (key, output) in [("deleted_with_it", &mut with), ("would_fail", &mut fail)] {
output
.extend(deps.get(key).and_then(|value| value.as_array()).into_iter().flatten().filter_map(|value| value.as_str().map(String::from)));