SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Apply complete feature transactions off the window thread (#3133) (#3135)
amolinari-autotex13cd45d1f1f2
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex bccac6144f..d4f9ebbd6a 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -1135,8 +1135,8 @@ impl ModelState {}});}- /// [`ModelState::warm_meshes`], and every body's display plan at the current display quality- /// (what a GPU viewport draws).++ /// Prepare reference meshes and display plans at the current quality for ahead jobs.pub fn warm_display(&self) {let q = crate::display_quality::current();let planned = |b: &ModelBody| b.plan.get(q.index()).is_none_or(|cell| cell.get().is_some());@@ -1146,6 +1146,19 @@ impl ModelState {let _ = b.display_plan();});}++ /// Prepare reference picking geometry and the GPU plan/highlight mesh at exactly the+ /// requested quality. The first viewport frame then consumes initialized caches only.+ pub fn warm_display_at(&self, quality: crate::display_quality::DisplayQuality, go_on: impl Fn() -> bool + Sync) {+ kernel::for_each_on_threads(&self.bodies, 16, |body| {+ if go_on() {+ let _ = body.mesh();+ }+ if go_on() {+ let _ = body.plan_mesh_at(quality);+ }+ });+ }pub fn sketch(&self, feature: u64) -> Option<&SolvedSketch> {self.sketches.iter().find(|s| s.feature == feature).map(|s| &**s)}@@ -8298,6 +8311,51 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mutout}+#[cfg(test)]+mod display_preparation_tests {+ use super::*;++ fn state() -> ModelState {+ let body = kernel::box_solid(Vec3::ZERO, Vec3::new(2.0, 3.0, 4.0)).unwrap();+ ModelState { bodies: vec![ModelBody::new("Box".into(), body, 1)], ..Default::default() }+ }++ #[test]+ fn prepared_display_reads_all_three_caches_without_cold_geometry_or_quality_changes() {+ use crate::display_quality::{DisplayQuality, current};+ let state = state();+ let body = &state.bodies[0];+ let quality = DisplayQuality::Fine;+ let index = quality.index();+ let current = current();+ let tolerance = body.display_tol();+ assert!(body.mesh.get().is_none() && body.plan[index].get().is_none() && body.plan_mesh[index].get().is_none());+ state.warm_display_at(quality, || true);+ // Inspect the caches before invoking any consumer that could initialize them.+ let reference = body.mesh.get().unwrap();+ let plan = body.plan[index].get().unwrap().as_ref().unwrap();+ let display = body.plan_mesh[index].get().unwrap().as_ref().unwrap();+ assert!(Arc::ptr_eq(reference, &body.mesh()));+ assert!(Arc::ptr_eq(plan, &body.display_plan_at(quality).unwrap()));+ assert!(Arc::ptr_eq(display, &body.plan_mesh_at(quality).unwrap()));+ assert_eq!(crate::display_quality::current(), current);+ assert_eq!(body.display_tol(), tolerance);+ for other in DisplayQuality::ALL.into_iter().filter(|other| *other != quality) {+ assert!(body.plan[other.index()].get().is_none() && body.plan_mesh[other.index()].get().is_none());+ }+ }++ #[test]+ fn cancelled_display_preparation_leaves_cold_caches_untouched() {+ let state = state();+ state.warm_display_at(crate::display_quality::DisplayQuality::Normal, || false);+ let body = &state.bodies[0];+ assert!(body.mesh.get().is_none());+ assert!(body.plan.iter().all(|slot| slot.get().is_none()));+ assert!(body.plan_mesh.iter().all(|slot| slot.get().is_none()));+ }+}+#[cfg(test)]mod world_placement_cache_tests {use super::*;diff --git a/crates/engine/src/computed_commands_tests.rs b/crates/engine/src/computed_commands_tests.rsnew file mode 100644index 0000000000..b5efde92af--- /dev/null+++ b/crates/engine/src/computed_commands_tests.rs@@ -0,0 +1,89 @@+//! Prepared transactions preserve live state until accepted and reject stale sources.+use crate::Session;+use serde_json::json;+use std::sync::Arc;++fn commands() -> Vec<(String, serde_json::Value)> {+ vec![("solid.box".into(), json!({"length":2,"width":3,"height":4}))]+}++#[test]+fn acceptance_preserves_file_history_and_prepared_world_without_evaluation() {+ let mut session = Session::default();+ session.execute("solid.box", &json!({"length":1,"width":1,"height":1})).unwrap();+ session.path = Some("working.solidcraft".into());+ let saved = session.saved.clone();+ let checkpoint = session.checkpoint();+ let history = session.undo.len();+ let prepared = session.scratch().compute_commands(&commands(), None).unwrap();+ prepared.warm_meshes(|| true);+ let world = prepared.computed.world_state();+ let before = session.evaluations;+ session.accept_commands(prepared).unwrap();+ assert_eq!(session.evaluations, before);+ assert_eq!(session.path.as_deref(), Some("working.solidcraft"));+ assert!(Arc::ptr_eq(&saved, &session.saved));+ assert_eq!(session.undo.len(), history + 1);+ assert!(Arc::ptr_eq(&world, &session.world_state()));+ session.restore_checkpoint(checkpoint).unwrap();+ assert_eq!(session.undo.len(), history);+ assert_eq!(session.doc.features.len(), 1);+}++#[test]+fn failure_discards_the_entire_batch() {+ let session = Session::default();+ let document = session.doc.clone();+ let mut batch = commands();+ batch.push(("solid.box".into(), json!({"length":-1})));+ assert!(session.scratch().compute_commands(&batch, None).is_err());+ assert!(Arc::ptr_eq(&document, &session.doc));+ assert!(session.undo.is_empty());+}++#[test]+fn revision_context_selection_and_replaced_document_reject_old_work() {+ for change in 0..5 {+ let mut session = Session::default();+ let prepared = session.scratch().compute_commands(&commands(), None).unwrap();+ match change {+ 0 => session.revision += 1,+ 1 => session.active_component = 17,+ 2 => session.active_occurrence_path = Some(vec![1]),+ 3 => session.selection.push(crate::Sel::Axis { name: "X".into() }),+ _ => session = Session::default(),+ }+ let document = session.doc.clone();+ assert!(!prepared.is_current(&session));+ assert!(session.accept_commands(prepared).is_err());+ assert!(Arc::ptr_eq(&document, &session.doc));+ assert!(session.undo.is_empty());+ }+}++#[test]+fn editor_marker_restoration_reuses_the_pinned_model_with_an_empty_cache() {+ let mut session = Session::default();+ session.execute("solid.box", &json!({"length":2,"width":3,"height":4})).unwrap();+ let world = session.world_state();+ let original = session.scratch();+ session.execute("timeline.roll_to", &json!({"position":0})).unwrap();+ let source = session.scratch();+ *session.model.cache.lock().unwrap() = Default::default();+ let prepared = session.scratch().compute_editor_commands(&[], &source, original).unwrap();+ assert_eq!(prepared.computed.evaluations, 0, "restoring the marker must never evaluate the old suffix");+ assert!(Arc::ptr_eq(&world, &prepared.computed.world_state()));+ session.accept_commands(prepared).unwrap();+ assert_eq!(session.doc.marker, None);+}++#[test]+fn an_editor_cannot_take_a_pinned_model_from_another_document() {+ let mut session = Session::default();+ session.execute("solid.box", &json!({"length":2,"width":3,"height":4})).unwrap();+ session.execute("timeline.roll_to", &json!({"position":0})).unwrap();+ let source = session.scratch();+ let document = session.doc.clone();+ assert!(session.scratch().compute_editor_commands(&[], &source, Session::default()).is_err());+ assert!(Arc::ptr_eq(&document, &session.doc));+}diff --git a/crates/engine/src/crash.rs b/crates/engine/src/crash.rsindex d855983b48..dfb29d3833 100644--- a/crates/engine/src/crash.rs+++ b/crates/engine/src/crash.rs@@ -507,18 +507,45 @@ pub(crate) fn command_begin(s: &Session, id: &str, params: &Value) {let ptr = std::sync::Arc::as_ptr(&s.doc) as usize;if ptr != j.last_doc {// The design changed outside commands (opened, a new tab, a dialog): what is it now?- let base = if s.is_dirty() {- json!("unknown")- } else if let Some(p) = &s.path {- json!({ "file": p })- } else if s.doc.features.is_empty() {- json!("new")- } else {- json!("unknown")- };+ j.rebase(&journal_base(s), ptr);+ }+ j.run(id, params);+}++fn journal_base(s: &Session) -> Value {+ if s.is_dirty() {+ json!("unknown")+ } else if let Some(path) = &s.path {+ json!({ "file": path })+ } else if s.doc.features.is_empty() {+ json!("new")+ } else {+ json!("unknown")+ }+}++/// Record a successful isolated command only after its entire transaction is accepted.+pub(crate) fn accepted_command(+ s: &Session,+ before: &std::sync::Arc<Document>,+ after: &std::sync::Arc<Document>,+ id: &str,+ params: &Value,+ changed: bool,+) {+ let Some(state) = STATE.get() else { return };+ if !s.crash_journal {+ return;+ }+ let Ok(mut j) = state.journal.lock() else { return };+ let ptr = std::sync::Arc::as_ptr(before) as usize;+ if ptr != j.last_doc {+ let base = if std::sync::Arc::ptr_eq(&s.doc, before) { journal_base(s) } else { json!("unknown") };j.rebase(&base, ptr);}j.run(id, params);+ j.done(&Ok(()), changed);+ j.last_doc = std::sync::Arc::as_ptr(after) as usize;}/// A top-level command ended: the journal records how, and panics caught inside it are reporteddiff --git a/crates/engine/src/crash_tests.rs b/crates/engine/src/crash_tests.rsindex e4a3742054..00f600727c 100644--- a/crates/engine/src/crash_tests.rs+++ b/crates/engine/src/crash_tests.rs@@ -46,6 +46,53 @@ fn child() {s.execute("document.inspect", &json!({})).unwrap();}match mode.as_str() {+ "prepared" => {+ let original = s.scratch();+ s.execute("timeline.roll_to", &json!({"position":0})).unwrap();+ let source = s.scratch();+ let state = STATE.get().unwrap();+ let journal_before_error = read_live_journal(state).replay;+ let invalid = vec![(+ "timeline.redefine".into(),+ json!({"feature":1,"command":"solid.box","params":{"length":"missing_extent","width":20,"height":30}}),+ )];+ assert!(s.scratch().compute_editor_commands(&invalid, &source, original.scratch()).is_err());+ assert_eq!(read_live_journal(state).replay, journal_before_error, "failed worker work never enters recovery");+ let evaluations = s.evaluations;+ s.restore_editor(&source, original).unwrap();+ assert_eq!(s.evaluations, evaluations, "Cancel restores without evaluating");+ assert_eq!(s.doc.marker, None);+ let original = s.scratch();+ s.execute("timeline.roll_to", &json!({"position":0})).unwrap();+ let source = s.scratch();+ let commands =+ vec![("timeline.redefine".into(), json!({"feature":1,"command":"solid.box","params":{"length":12,"width":20,"height":30}}))];+ let before = read_live_journal(state).replay;+ let discarded = s.scratch().compute_editor_commands(&commands, &source, original.scratch()).unwrap();+ drop(discarded);+ assert_eq!(read_live_journal(state).replay, before, "discarded work never enters recovery");+ let prepared = s.scratch().compute_editor_commands(&commands, &source, original).unwrap();+ s.accept_commands(prepared).unwrap();+ let journal = read_live_journal(state);+ assert_eq!(journal.base, json!("new"), "accepted steps form one continuous replay");+ assert_eq!(journal.replay.len(), before.len() + 2, "restore marker and redefine are recorded once");+ let mut replay = Session::default();+ for command in &journal.replay {+ replay.execute(command["command"].as_str().unwrap(), &command["params"]).unwrap();+ }+ assert_eq!(replay.doc.marker, None);+ let volume = replay.execute("inspect.measure", &json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap();+ assert!((volume - 7200.0).abs() < 0.001);+ let path = state.dir.join("prepared-source.solidcraft");+ s.execute("file.save_as", &json!({"path":path})).unwrap();+ // A host can adopt an opened tab before any command has rebased its journal.+ state.journal.lock().unwrap().last_doc = 0;+ let commands = vec![("solid.box".into(), json!({"length":1,"width":1,"height":1}))];+ let prepared = s.scratch().compute_commands(&commands, None).unwrap();+ s.accept_commands(prepared).unwrap();+ assert_eq!(read_live_journal(state).base, json!({"file":path}));+ println!("PREPARED_JOURNAL_OK");+ }"render" => {s.execute("render.settings.set", &json!({"name":"Studio","set":{"exposure_ev":2}})).unwrap();s.execute("render.settings.get", &json!({"name":"Studio"})).unwrap();@@ -112,6 +159,14 @@ fn run_child(dir: &Path, mode: &str) -> (String, bool) {(String::from_utf8_lossy(&out.stdout).into_owned(), out.status.success())}+#[test]+fn accepted_prepared_commands_replay_and_discarded_work_is_not_journaled() {+ let directory = fresh_dir("prepared");+ let (output, ok) = run_child(&directory, "prepared");+ assert!(ok && output.contains("PREPARED_JOURNAL_OK"), "{output}");+ let _ = fs::remove_dir_all(directory);+}+fn only_report(dir: &Path) -> (Summary, Value) {let all = list(dir);assert_eq!(all.len(), 1, "{all:?}");diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex de3089509f..13d2fa9181 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -273,6 +273,41 @@ impl WorldCache {}}+/// Commands evaluated in isolation, ready for an atomic handoff to their source session.+pub struct ComputedCommands {+ source: Session,+ computed: Session,+ steps: Vec<ComputedCommand>,+}++struct ComputedCommand {+ id: String,+ params: Value,+ before: Arc<Document>,+ after: Arc<Document>,+ changed: bool,+ reply: Value,+}++impl ComputedCommands {+ /// Whether the source design and authoring context still match this result.+ pub fn is_current(&self, session: &Session) -> bool {+ let source = &self.source;+ session.same_document_context(source) && session.selection == source.selection+ }++ /// Prepare display tessellation before returning the transaction to the window.+ pub fn warm_meshes(&self, keep_going: impl Fn() -> bool + Sync) {+ self.warm_display(solidcraft_doc::display_quality::DisplayQuality::Normal, keep_going);+ }++ /// Prepare both the reference picking mesh and the GPU plan/highlight mesh at the+ /// selected quality. Warming only the reference mesh leaves cold planning on the UI.+ pub fn warm_display(&self, quality: solidcraft_doc::display_quality::DisplayQuality, keep_going: impl Fn() -> bool + Sync) {+ self.computed.world_state().warm_display_at(quality, keep_going);+ }+}+/// An editing session on one design.pub struct Session {pub doc: Arc<Document>,@@ -1267,6 +1302,112 @@ impl Session {}}+ /// Evaluate a feature dialog's complete transaction, including the dependent timeline.+ /// `marker` restores an editor's original marker before recording its undo snapshot.+ /// The source remains untouched, including its history and recovery journal.+ pub fn compute_commands(self, commands: &[(String, Value)], marker: Option<Option<usize>>) -> Result<ComputedCommands> {+ self.compute_commands_inner(commands, marker, None)+ }++ /// Start an edit from its pinned original model, so restoring the original marker cannot+ /// recompute the obsolete suffix even when previews have evicted its evaluation cache.+ pub fn compute_editor_commands(self, commands: &[(String, Value)], source: &Session, original: Session) -> Result<ComputedCommands> {+ if !self.same_document_context(source) {+ return Err(EngineError::Other("the design changed while the feature editor was open".into()));+ }+ let mut expected = (*original.doc).clone();+ expected.marker = source.doc.marker;+ if expected != *source.doc {+ return Err(EngineError::Other("the original editor model does not match its source design".into()));+ }+ self.compute_commands_inner(commands, Some(original.doc.marker), Some(original))+ }++ fn compute_commands_inner(+ self,+ commands: &[(String, Value)],+ marker: Option<Option<usize>>,+ original: Option<Session>,+ ) -> Result<ComputedCommands> {+ let mut computed = self.scratch();+ let mut steps = Vec::new();+ if let Some(marker) = marker {+ let before = computed.doc.clone();+ let params = marker.map(|position| serde_json::json!({"position":position})).unwrap_or_else(|| serde_json::json!({}));+ let reply = if let Some(original) = original {+ computed.doc = original.doc;+ computed.model = original.model;+ computed.world_cache = original.world_cache;+ serde_json::json!({"marker":marker.unwrap_or(computed.doc.features.len()),"features":computed.doc.features.len()})+ } else {+ let undo = std::mem::take(&mut computed.undo);+ let redo = std::mem::take(&mut computed.redo);+ let selection = computed.selection.clone();+ let reply = computed.execute("timeline.roll_to", ¶ms)?;+ computed.undo = undo;+ computed.redo = redo;+ computed.selection = selection;+ reply+ };+ let changed = !Arc::ptr_eq(&before, &computed.doc);+ steps.push(ComputedCommand { id: "timeline.roll_to".into(), params, before, after: computed.doc.clone(), changed, reply });+ }+ for (id, params) in commands {+ let before = computed.doc.clone();+ let active_sketch = computed.active_sketch;+ let pending_moves = computed.pending_moves.clone();+ let reply = computed.execute(id, params)?;+ let changed = !Arc::ptr_eq(&before, &computed.doc)+ || active_sketch != computed.active_sketch+ || pending_moves != computed.pending_moves+ || id.starts_with("select.");+ steps.push(ComputedCommand { id: id.clone(), params: params.clone(), before, after: computed.doc.clone(), changed, reply });+ }+ Ok(ComputedCommands { source: self, computed, steps })+ }++ /// Adopt evaluated commands only if their document and authoring context are still current.+ /// No model evaluation occurs here. Rejected or cancelled work never enters the journal.+ pub fn accept_commands(&mut self, prepared: ComputedCommands) -> Result<Vec<(String, Value)>> {+ if !prepared.is_current(self) {+ return Err(EngineError::Other("the design changed while the feature was computing".into()));+ }+ for step in &prepared.steps {+ crash::accepted_command(self, &step.before, &step.after, &step.id, &step.params, step.changed);+ }+ let replies = prepared.steps.into_iter().map(|step| (step.id, step.reply)).collect();+ self.accept_computed(prepared.computed);+ Ok(replies)+ }++ fn same_document_context(&self, source: &Session) -> bool {+ Arc::ptr_eq(&self.doc, &source.doc)+ && self.revision == source.revision+ && self.active_sketch == source.active_sketch+ && self.active_component == source.active_component+ && self.active_occurrence_path == source.active_occurrence_path+ && self.pending_moves == source.pending_moves+ }++ /// Cancel an unchanged feature editor by restoring its original evaluated model, even+ /// after preview work has evicted the old suffix from the shared evaluation cache.+ pub fn restore_editor(&mut self, source: &Session, mut original: Session) -> Result<()> {+ if !self.same_document_context(source) {+ return Err(EngineError::Other("the design changed while the feature editor was open; its current timeline was preserved".into()));+ }+ let params = original.doc.marker.map(|position| serde_json::json!({"position":position})).unwrap_or_else(|| serde_json::json!({}));+ crash::accepted_command(self, &self.doc, &original.doc, "timeline.roll_to", ¶ms, !Arc::ptr_eq(&self.doc, &original.doc));+ let undo = std::mem::take(&mut self.undo);+ let redo = std::mem::take(&mut self.redo);+ let selection = std::mem::take(&mut self.selection);+ original.visibility.hidden_joints.clear();+ self.accept_computed(original);+ self.undo = undo;+ self.redo = redo;+ self.selection = selection;+ Ok(())+ }+/// Refresh UI caches when adopting a session or switching tabs, without discarding its/// already prepared world-space geometry. This does not change the document.pub fn invalidate_view(&mut self, previous_revision: u64) {@@ -1467,6 +1608,8 @@ impl Session {#[cfg(test)]mod boolean_regression_tests;#[cfg(test)]+mod computed_commands_tests;+#[cfg(test)]mod construct_tests;#[cfg(test)]mod delete_face_tests;diff --git a/crates/ui-egui/src/apply_off_thread_tests.rs b/crates/ui-egui/src/apply_off_thread_tests.rsindex b61e695237..69fdc37e42 100644--- a/crates/ui-egui/src/apply_off_thread_tests.rs+++ b/crates/ui-egui/src/apply_off_thread_tests.rs@@ -39,45 +39,114 @@ fn until_applied(h: &mut Harness) {h.frames(1);}+/// An evaluated result held behind a channel, so widget assertions do not race the worker.+fn hold_result(h: &mut Harness, different_commands: bool) -> std::sync::mpsc::Sender<Result<solidcraft_engine::ComputedCommands, String>> {+ let cmds = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();+ let (finish, done) = std::sync::mpsc::channel();+ h.app.applying = Some(crate::dialogs::Applying {+ done,+ ready: None,+ seen: true,+ started: crate::now_ms(),+ cmds: if different_commands { Vec::new() } else { cmds },+ progress: Default::default(),+ quality: Default::default(),+ });+ finish+}++fn result(h: &Harness) -> Result<solidcraft_engine::ComputedCommands, String> {+ let dialog = h.app.dialog.as_ref().unwrap();+ let commands = crate::dialogs::apply_commands(&h.app, dialog).unwrap();+ match &h.app.editing_state {+ Some(state) => h.app.session.scratch().compute_editor_commands(&commands, &state.source, state.original.scratch()),+ None => h.app.session.scratch().compute_commands(&commands, dialog.editing.map(|(_, marker)| marker)),+ }+ .map_err(|e| e.to_string())+}+#[test]fn ok_computes_off_the_window_thread_saying_so_then_applies() {let mut h = square_on_a_block();- h.app.apply_off_thread = Some(Duration::ZERO);- // The evaluation is held until the dialog has been seen saying so (it is in the cache all- // the same), so no frame can apply it before the checks below.- let (finish, gate) = std::sync::mpsc::channel();- h.app.apply_gate = Some(std::sync::Arc::new(std::sync::Mutex::new(gate)));- h.step(&json!({"key": "Enter"})).unwrap();- assert!(h.app.applying.is_some() && h.app.dialog.is_some(), "computing, the dialog open");+ let prepared = result(&h);+ let finish = hold_result(&mut h, false);h.frames(1);- assert!(h.widget("Computing… 0 s").is_some(), "the dialog says it computes");- // Enter again does not start it twice.+ assert!(h.widget("Computing\u{2026} 0 s").is_some(), "the dialog says it computes");h.step(&json!({"key": "Enter"})).unwrap();- finish.send(()).unwrap();- until_applied(&mut h);- assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone()));+ finish.send(prepared).ok().unwrap();+ let window = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default());+ solidcraft_engine::doc::progress::watch(window.clone(), || until_applied(&mut h));+ assert_eq!(window.features(), (0, 0), "adoption does not evaluate the model");+ assert!(h.app.dialog.is_none());h.step(&json!({"expect": {"bodies": 1, "volume": 13000}})).unwrap();- assert_eq!(h.app.session.doc.features.len(), 4, "one extrude added");+ assert_eq!(h.app.session.doc.features.len(), 4);}#[test]fn cancel_while_computing_applies_nothing() {let mut h = square_on_a_block();- h.app.apply_off_thread = Some(Duration::ZERO);- // Held, as the preview's evaluation is in the cache and would otherwise be in before OK's- // wait is over, applying at once.- let (finish, gate) = std::sync::mpsc::channel();- h.app.apply_gate = Some(std::sync::Arc::new(std::sync::Mutex::new(gate)));+ let prepared = result(&h);let features = h.app.session.doc.features.len();- h.step(&json!({"key": "Enter"})).unwrap();- assert!(h.app.applying.is_some());+ let finish = hold_result(&mut h, false);+ let progress = h.app.applying.as_ref().unwrap().progress.clone();h.step(&json!({"key": "Escape"})).unwrap();assert!(h.app.applying.is_none() && h.app.dialog.is_none());- finish.send(()).unwrap();+ assert!(progress.is_cancelled());+ assert!(finish.send(prepared).is_err());h.frames(5);assert_eq!(h.app.session.doc.features.len(), features);}+#[test]+fn a_ready_transaction_waits_one_frame_before_adoption() {+ let mut h = square_on_a_block();+ let features = h.app.session.doc.features.len();+ let prepared = result(&h);+ let finish = hold_result(&mut h, false);+ h.app.applying.as_mut().unwrap().seen = false;+ finish.send(prepared).ok().unwrap();+ h.frames(1);+ assert_eq!(h.app.session.doc.features.len(), features);+ assert!(h.app.applying.is_some());+ until_applied(&mut h);+ assert_eq!(h.app.session.doc.features.len(), features + 1);+}++#[test]+fn restarting_the_same_command_discards_the_previous_dialog_job() {+ let mut h = square_on_a_block();+ let document = h.app.session.doc.clone();+ let prepared = result(&h);+ let finish = hold_result(&mut h, false);+ let progress = h.app.applying.as_ref().unwrap().progress.clone();+ h.app.start("solid.extrude");+ assert!(h.app.applying.is_none());+ assert!(h.app.dialog.is_some());+ assert!(progress.is_cancelled());+ assert!(finish.send(prepared).is_err());+ h.frames(2);+ assert!(std::sync::Arc::ptr_eq(&document, &h.app.session.doc));+}++#[test]+fn switching_tabs_cancels_the_transaction_without_changing_either_document() {+ let mut h = square_on_a_block();+ let original = h.app.session.doc.clone();+ let prepared = result(&h);+ let finish = hold_result(&mut h, false);+ let progress = h.app.applying.as_ref().unwrap().progress.clone();+ let other = solidcraft_engine::Session::default();+ let other_doc = other.doc.clone();+ crate::documents::open_tab(&mut h.app, other).unwrap();+ assert!(progress.is_cancelled());+ assert!(finish.send(prepared).is_err());+ assert!(h.app.applying.is_none() && h.app.dialog.is_none() && h.app.editing_state.is_none());+ h.frames(2);+ assert!(std::sync::Arc::ptr_eq(&other_doc, &h.app.session.doc));+ crate::documents::switch(&mut h.app, 0);+ assert!(std::sync::Arc::ptr_eq(&original, &h.app.session.doc));+}+/// #2929: the feature must not appear in the frame OK starts computing in. The window thread/// can be held up between starting the evaluation and the check that takes it up, and the/// feature then appears where the dialog says it is computing - which is what made@@ -104,38 +173,258 @@ fn the_dialog_holds_its_inputs_while_ok_computes() {let mut h = square_on_a_block();h.app.fit_view();h.frames(2);- let picked = h.app.dialog.as_ref().map(|d| d.inputs[0].items.clone()).unwrap();- // OK computing, until the test lets it finish.- let (finish, done) = std::sync::mpsc::channel();- let cmds = h.app.dialog.as_ref().and_then(|d| crate::dialogs::apply_commands(&h.app, d).ok()).unwrap();- h.app.applying = Some(crate::dialogs::Applying::computing(done, cmds));- // A click on the square picked would take it out of the profiles.+ let picked = h.app.dialog.as_ref().unwrap().inputs[0].items.clone();+ let prepared = result(&h);+ let finish = hold_result(&mut h, false);h.step(&json!({"click": {"world": [10, 10, 10]}})).unwrap();h.frames(2);- assert_eq!(h.app.dialog.as_ref().map(|d| d.inputs[0].items.clone()), Some(picked), "no pick while computing");- finish.send(None).unwrap();+ assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items, picked);+ finish.send(prepared).ok().unwrap();until_applied(&mut h);assert!(h.app.dialog.is_none());h.step(&json!({"expect": {"bodies": 1, "volume": 13000}})).unwrap();}-/// Inputs that changed while OK computed (nothing should change them) are computed in turn, off-/// the window thread too, then applied: run as OK finished, they would hold the window for the-/// whole boolean.#[test]fn inputs_changed_while_ok_computes_are_computed_off_the_thread_too() {let mut h = square_on_a_block();h.app.apply_off_thread = Some(Duration::ZERO);let features = h.app.session.doc.features.len();- // OK computing other commands than the dialog's, until the test lets it finish.- let (finish, done) = std::sync::mpsc::channel();- h.app.applying = Some(crate::dialogs::Applying::computing(done, Vec::new()));- finish.send(None).unwrap();- h.frames(1);- assert!(h.app.applying.is_some(), "the dialog's own commands are computing");- assert_eq!(h.app.session.doc.features.len(), features, "nothing applied on the window thread");- until_applied(&mut h);+ let prepared = result(&h);+ let finish = hold_result(&mut h, true);+ finish.send(prepared).ok().unwrap();+ let window = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default());+ solidcraft_engine::doc::progress::watch(window.clone(), || until_applied(&mut h));+ assert_eq!(window.features(), (0, 0));assert!(h.app.dialog.is_none());assert_eq!(h.app.session.doc.features.len(), features + 1);h.step(&json!({"expect": {"bodies": 1, "volume": 13000}})).unwrap();}++#[test]+fn changed_document_rejects_a_completed_result() {+ let mut h = square_on_a_block();+ let prepared = result(&h);+ let finish = hold_result(&mut h, false);+ h.app.run("solid.box", json!({"length":2,"width":2,"height":2})).unwrap();+ let current = h.app.session.doc.clone();+ finish.send(prepared).ok().unwrap();+ until_applied(&mut h);+ assert!(std::sync::Arc::ptr_eq(¤t, &h.app.session.doc));+ assert!(h.app.dialog.as_ref().unwrap().error.is_some());+}++#[test]+fn hole_ok_adopts_real_cut_without_window_evaluation() {+ let mut h = Harness::new();+ h.app.home.open = false;+ h.app.set_origin_shown(false);+ h.app.apply_off_thread = Some(Duration::ZERO);+ h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap();+ h.call("ui.view", json!({"view":"top"}));+ h.app.fit_view();+ h.settle();+ let undo = h.app.session.undo.len();+ h.step(&json!({"start":"solid.hole"})).unwrap();+ h.step(&json!({"click":{"world":[12,9,20]}})).unwrap();+ h.step(&json!({"click":{"handle":"dialog:Diameter"}})).unwrap();+ h.step(&json!({"key":"A","cmd":true})).unwrap();+ h.step(&json!({"text":"4 mm"})).unwrap();+ let window = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default());+ solidcraft_engine::doc::progress::watch(window.clone(), || {+ h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap();+ until_applied(&mut h);+ });+ assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone()));+ assert_eq!(window.features(), (0, 0));+ assert_eq!(h.app.session.undo.len(), undo + 1);+ let volume = h.app.run("inspect.measure", json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap();+ assert!(volume < 23990.0 && volume > 23000.0, "the hole removed actual material: {volume}");+ h.app.run("edit.undo", json!({})).unwrap();+ h.step(&json!({"expect":{"volume":24000,"bodies":1}})).unwrap();+}++fn cut_chain() -> (Harness, u64) {+ let mut h = Harness::new();+ h.app.home.open = false;+ h.app.apply_off_thread = Some(std::time::Duration::ZERO);+ h.app.run("solid.box", json!({"length":80,"width":50,"height":20,"body_name":"Stock"})).unwrap();+ let mut target = 0;+ for index in 0..6 {+ let sketch = format!("Circle{}", index + 1);+ h.app.run("sketch.create", json!({"plane":"XY","offset":20,"name":sketch})).unwrap();+ h.app.run("sketch.circle.center", json!({"center":[10 + 10 * index,25],"diameter":4})).unwrap();+ h.app.run("sketch.finish", json!({})).unwrap();+ let result = h+ .app+ .run(+ "solid.extrude",+ json!({"sketch":sketch,"profiles":"all","distance":6,"direction":"negative","operation":"cut","name":format!("Cut{}", index+1)}),+ )+ .unwrap();+ if index == 0 {+ target = result["feature"].as_u64().unwrap();+ }+ }+ (h, target)+}++#[test]+fn changed_first_cut_adopts_its_entire_suffix_without_window_evaluation() {+ let (mut h, target) = cut_chain();+ let before = h.app.run("inspect.measure", json!({})).unwrap();+ let undo = h.app.session.undo.len();+ h.call("ui.editFeature", json!({"feature":target}));+ h.frames(3);+ assert!(h.app.session.feature_edit_sketch.is_some(), "the edited Extrude keeps its input sketch visible");+ h.step(&json!({"click":{"handle":"dialog:Distance"}})).unwrap();+ h.step(&json!({"key":"A","cmd":true})).unwrap();+ h.step(&json!({"text":"9 mm"})).unwrap();+ let window = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default());+ solidcraft_engine::doc::progress::watch(window.clone(), || {+ h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap();+ for _ in 0..5000 {+ h.frames(1);+ if h.app.dialog.is_none() {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(1));+ }+ });+ assert_eq!(window.features(), (0, 0), "the complete changed suffix is adopted without UI evaluation");+ assert!(h.app.dialog.is_none(), "changed edit did not complete");+ assert_eq!(h.app.session.feature_edit_sketch, None, "Apply clears the temporary sketch override");+ let after = h.app.run("inspect.measure", json!({})).unwrap();+ let before_volume = before["total"]["volume_mm3"].as_f64().unwrap();+ let after_volume = after["total"]["volume_mm3"].as_f64().unwrap();+ assert!(before_volume - after_volume > 30.0, "the edit must change actual geometry: {before_volume} -> {after_volume}");+ assert_eq!(h.app.session.undo.len(), undo + 1);+ assert_eq!(h.app.session.doc.marker, None);+ h.app.run("edit.undo", json!({})).unwrap();+ let restored = h.app.run("inspect.measure", json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap();+ assert!((restored - before_volume).abs() < 0.001);+ h.app.run("edit.redo", json!({})).unwrap();+ let redone = h.app.run("inspect.measure", json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap();+ assert!((redone - after_volume).abs() < 0.001);+}++#[test]+fn cancelling_an_edit_restores_pinned_geometry_without_evaluating_an_evicted_suffix() {+ let (mut h, target) = cut_chain();+ h.app.run("solid.box", json!({"corner":[100,0,0],"length":2,"width":2,"height":2})).unwrap();+ h.app.run("edit.undo", json!({})).unwrap();+ let before = h.app.session.world_state();+ let history = (h.app.session.undo.len(), h.app.session.redo.len());+ let visibility = h.app.session.visibility.clone();+ h.call("ui.editFeature", json!({"feature":target}));+ crate::dialogs::sync_feature_edit_sketch(&mut h.app);+ let sketch = h.app.session.feature_edit_sketch.expect("edited Extrude exposes its sketch");+ assert!(solidcraft_engine::view::sketch_shown(&h.app.session, sketch));+ let prepared = result(&h);+ let finish = hold_result(&mut h, false);+ *h.app.session.model.cache.lock().unwrap() = Default::default();+ // Picks are view state: cancellation keeps a newer selection.+ h.app.session.selection = vec![solidcraft_engine::Sel::Axis { name: "X".into() }];+ let window = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default());+ solidcraft_engine::doc::progress::watch(window.clone(), || {+ h.step(&json!({"key":"Escape"})).unwrap();+ });+ assert_eq!(window.features(), (0, 0), "Cancel never rebuilds the old suffix on the window thread");+ assert!(h.app.dialog.is_none() && h.app.applying.is_none() && h.app.editing_state.is_none());+ assert!(finish.send(prepared).is_err());+ assert_eq!(h.app.session.feature_edit_sketch, None, "Cancel clears the temporary sketch override");+ assert_eq!(h.app.session.visibility, visibility, "temporary sketch display does not change stored visibility");+ assert_eq!(h.app.session.doc.marker, None);+ assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history);+ assert!(std::sync::Arc::ptr_eq(&before, &h.app.session.world_state()));+ assert_eq!(h.app.session.selection, vec![solidcraft_engine::Sel::Axis { name: "X".into() }]);+}++#[test]+fn replacing_a_document_discards_pending_apply_and_editor_backup() {+ let (mut h, target) = cut_chain();+ h.call("ui.editFeature", json!({"feature":target}));+ let prepared = result(&h);+ let finish = hold_result(&mut h, false);+ h.app.run("file.new", json!({})).unwrap();+ assert!(h.app.dialog.is_none() && h.app.applying.is_none() && h.app.editing_state.is_none());+ assert!(finish.send(prepared).is_err());+ h.frames(3);+ assert!(h.app.session.doc.features.is_empty());+}++#[test]+fn cancelling_a_stale_editor_preserves_the_newer_document() {+ let (mut h, target) = cut_chain();+ h.call("ui.editFeature", json!({"feature":target}));+ h.app.session.execute("solid.box", &json!({"length":2,"width":2,"height":2})).unwrap();+ let document = h.app.session.doc.clone();+ h.step(&json!({"key":"Escape"})).unwrap();+ assert!(std::sync::Arc::ptr_eq(&document, &h.app.session.doc));+ assert!(h.app.dialog.is_none());+ assert!(h.app.status.as_ref().is_some_and(|(_, _, error)| *error));+}++#[test]+fn a_worker_error_then_cancel_preserves_original_world_history_redo_and_selection() {+ let (mut h, target) = cut_chain();+ h.app.run("solid.box", json!({"corner":[100,0,0],"length":2,"width":2,"height":2})).unwrap();+ h.app.run("edit.undo", json!({})).unwrap();+ let world = h.app.session.world_state();+ let document = h.app.session.doc.clone();+ let history = (h.app.session.undo.len(), h.app.session.redo.len());+ h.app.session.selection = vec![solidcraft_engine::Sel::Feature { id: target }];+ let selection = h.app.session.selection.clone();+ h.call("ui.editFeature", json!({"feature":target}));+ let prefix = h.app.session.doc.clone();+ let dialog = h.app.dialog.as_mut().unwrap();+ if let crate::dialogs::Kind::Extrude { distance, .. } = &mut dialog.kind {+ *distance = "missing_extent".into();+ }+ let dialog = dialog.clone();+ let window = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default());+ solidcraft_engine::doc::progress::watch(window.clone(), || {+ // Exercise the production worker directly: a preview may disable the OK widget+ // for this deliberately invalid expression before a synthetic click reaches it.+ h.app.applying = crate::dialogs::begin_applying(&h.app, &dialog);+ assert!(h.app.applying.is_some(), "the real apply worker was started");+ until_applied(&mut h);+ assert!(h.app.dialog.as_ref().and_then(|d| d.error.as_ref()).is_some_and(|error| error.contains("missing_extent")), "{:?}", h.app.dialog);+ assert!(std::sync::Arc::ptr_eq(&prefix, &h.app.session.doc), "worker failure leaves the live prefix untouched");+ h.step(&json!({"key":"Escape"})).unwrap();+ });+ assert_eq!(window.features(), (0, 0));+ assert!(std::sync::Arc::ptr_eq(&document, &h.app.session.doc));+ assert!(std::sync::Arc::ptr_eq(&world, &h.app.session.world_state()));+ assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history);+ assert_eq!(h.app.session.selection, selection);+}++#[test]+fn another_interactive_command_closes_the_editor_without_rebuilding_its_old_suffix() {+ let (mut h, target) = cut_chain();+ let document = h.app.session.doc.clone();+ h.call("ui.editFeature", json!({"feature":target}));+ let window = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default());+ solidcraft_engine::doc::progress::watch(window.clone(), || h.app.start("solid.hole"));+ assert_eq!(window.features(), (0, 0));+ assert!(std::sync::Arc::ptr_eq(&document, &h.app.session.doc));+ assert!(h.app.editing_state.is_none());+ assert!(h.app.dialog.as_ref().is_some_and(|d| d.editing.is_none() && matches!(d.kind, crate::dialogs::Kind::Hole { .. })));+}++#[test]+fn a_changed_display_quality_warms_the_result_without_replaying_commands() {+ let mut h = square_on_a_block();+ h.app.apply_off_thread = Some(Duration::ZERO);+ let prepared = result(&h);+ let finish = hold_result(&mut h, false);+ h.app.preferences.display_quality = "fine".into();+ finish.send(prepared).ok().unwrap();+ h.frames(1);+ let progress = h.app.applying.as_ref().expect("the new display plans run off the window thread").progress.clone();+ until_applied(&mut h);+ assert_eq!(progress.features(), (0, 0), "changing display quality does not replay the geometry commands");+ assert!(h.app.dialog.is_none());+ h.step(&json!({"expect":{"bodies":1,"volume":13000}})).unwrap();+}diff --git a/crates/ui-egui/src/cli_link.rs b/crates/ui-egui/src/cli_link.rsindex 3400bc9258..e55c108731 100644--- a/crates/ui-egui/src/cli_link.rs+++ b/crates/ui-egui/src/cli_link.rs@@ -159,6 +159,7 @@ mod tests {// `link_in` only makes links on Unix, and the test makes its own with `std::os::unix`.#[cfg(unix)]#[test]+ #[cfg(unix)]fn links_only_where_it_may() {let d = std::env::temp_dir().join(format!("solidcraft-cli-link-{}", std::process::id()));let _ = std::fs::remove_dir_all(&d);diff --git a/crates/ui-egui/src/deferred.rs b/crates/ui-egui/src/deferred.rsindex 26b45d38bb..9de30f139c 100644--- a/crates/ui-egui/src/deferred.rs+++ b/crates/ui-egui/src/deferred.rs@@ -155,7 +155,11 @@ impl SolveApp {/// 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> {- let started = [self.deferred.as_ref().map(|d| d.started), self.delete_check.as_ref().map(|c| c.started)];+ let started = [+ self.deferred.as_ref().map(|d| d.started),+ self.delete_check.as_ref().map(|c| c.started),+ self.pending_feature_edit.as_ref().map(|edit| edit.started),+ ];started.into_iter().flatten().reduce(f64::min)}diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex fa1f8a1d8d..f05aa13926 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -480,111 +480,170 @@ struct ShellChain {faces: Vec<Sel>,}-/// OK computing off the window thread: the dialog's commands evaluated on a copy of the-/// session. Once that is in, OK runs them for real, taking what the copy evaluated-/// ([`solidcraft_engine::Session::prime`]) rather than computing it again; meanwhile the window-/// stays live and the dialog says it is computing.+/// Pin the pre-edit model so Cancel never depends on the shared cache retaining it.+pub(crate) struct EditingState {+ pub(crate) source: Session,+ pub(crate) original: Session,+}++struct DialogComputation {+ session: Session,+ cmds: Vec<(String, Value)>,+ marker: Option<Option<usize>>,+ editing: Option<EditingState>,+}++impl DialogComputation {+ fn new(app: &SolveApp, d: &Dialog) -> Result<Self, String> {+ if app.file_load.busy() || app.file_picker_busy() {+ return Err("a file operation is in progress".into());+ }+ Ok(Self {+ session: app.session.scratch(),+ cmds: apply_commands(app, d)?,+ marker: d.editing.map(|(_, marker)| marker),+ editing: d+ .editing+ .and(app.editing_state.as_ref())+ .map(|state| EditingState { source: state.source.scratch(), original: state.original.scratch() }),+ })+ }++ fn compute(self) -> Result<solidcraft_engine::ComputedCommands, String> {+ match self.editing {+ Some(state) => self.session.compute_editor_commands(&self.cmds, &state.source, state.original),+ None => self.session.compute_commands(&self.cmds, self.marker),+ }+ .map_err(|e| e.to_string())+ }+}++fn adopt_dialog(app: &mut SolveApp, prepared: solidcraft_engine::ComputedCommands) -> Result<(), String> {+ if app.file_load.busy() || app.file_picker_busy() {+ return Err("a file operation is in progress".into());+ }+ let replies = app.session.accept_commands(prepared).map_err(|e| e.to_string())?;+ app.big_operation = true;+ for (id, reply) in replies {+ let stop = (id == "joint.drive").then(|| crate::dialogs_assembly::drive_stop(&reply)).flatten();+ app.command_completed(&id, Ok(reply))?;+ if let Some(why) = stop {+ app.set_status(why, false);+ }+ }+ Ok(())+}++/// A complete feature transaction, evaluated without changing the displayed session.pub struct Applying {- pub(crate) done: std::sync::mpsc::Receiver<Option<solidcraft_engine::Evaluated>>,- /// What it evaluated, once in (`Some(None)`: it failed, or its worker is gone).- evaluated: Option<Option<solidcraft_engine::Evaluated>>,+ pub(crate) done: std::sync::mpsc::Receiver<Result<solidcraft_engine::ComputedCommands, String>>,+ pub(crate) ready: Option<Result<solidcraft_engine::ComputedCommands, String>>,+ pub(crate) seen: bool,/// When OK was pressed (ms).pub(crate) started: f64,- /// The commands being computed.pub(crate) cmds: Vec<(String, Value)>,- /// The job has been in a frame. A job that has just started is not taken up in the frame it- /// starts, so the dialog says it is computing before the feature appears.- pub(crate) seen: bool,+ pub(crate) progress: std::sync::Arc<solidcraft_engine::doc::progress::Progress>,+ pub(crate) quality: solidcraft_engine::doc::display_quality::DisplayQuality,}impl Applying {- /// OK computing `cmds`, in once `done` says what was evaluated (tests stand in for the worker).- #[cfg(test)]- pub(crate) fn computing(done: std::sync::mpsc::Receiver<Option<solidcraft_engine::Evaluated>>, cmds: Vec<(String, Value)>) -> Self {- Applying { done, evaluated: None, started: crate::now_ms(), cmds, seen: true }- }-- /// The evaluation is in and the job has been in a frame. A job that has just started waits- /// one frame: the window thread may be held up between starting it and the check, and the- /// feature must not appear where the dialog says it is computing.- fn ready(&mut self) -> bool {- self.seen && self.finished()- }-- /// The evaluation is in (or its worker ended).- fn finished(&mut self) -> bool {- if self.evaluated.is_none() {- match self.done.try_recv() {- Ok(evaluated) => self.evaluated = Some(evaluated),- Err(std::sync::mpsc::TryRecvError::Disconnected) => self.evaluated = Some(None),- Err(std::sync::mpsc::TryRecvError::Empty) => {}- }+ fn finished(&mut self) -> Option<Result<solidcraft_engine::ComputedCommands, String>> {+ if !self.seen {+ self.seen = true;+ return None;}- self.evaluated.is_some()+ self.ready.take().or_else(|| match self.done.try_recv() {+ Ok(result) => Some(result),+ Err(std::sync::mpsc::TryRecvError::Empty) => None,+ Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(Err("feature computation ended without a result".into())),+ })}}-/// How OK goes.-enum Begun {- /// It computes off the window thread.- Later(Applying),- /// It runs now, with what was evaluated for it (if anything).- Now(Option<solidcraft_engine::Evaluated>),-}--/// Run the dialog's commands, taking the features `evaluated` computed for them ahead.-fn run_evaluated(app: &mut SolveApp, d: &Dialog, evaluated: Option<&solidcraft_engine::Evaluated>) -> Result<(), String> {- if let Some(evaluated) = evaluated {- app.session.prime(evaluated);+impl Drop for Applying {+ fn drop(&mut self) {+ self.progress.cancel();}- let r = run_dialog(app, d);- app.session.unprime();- r}-/// How long the desktop app's OK waits for its evaluation before it lets the window go on and-/// shows that it is computing ([`SolveApp::apply_off_thread`]): a feature quicker than this-/// applies at once, as it always did.+/// How long OK waits before displaying its computing state.pub const APPLY_AT_ONCE: std::time::Duration = std::time::Duration::from_millis(150);-/// Start OK's evaluation off the window thread, for a feature dialog. `Now` when OK should-/// just run: not a feature, not asked for ([`SolveApp::apply_off_thread`]), no threads (the-/// web), or done within the wait.+fn display_quality(app: &SolveApp) -> solidcraft_engine::doc::display_quality::DisplayQuality {+ solidcraft_engine::doc::display_quality::DisplayQuality::parse(&app.preferences.display_quality).unwrap_or_default()+}++/// Desktop feature dialogs evaluate the entire command and its dependent suffix once.+/// Results wait until a later frame before adoption, keeping the computing state visible.#[cfg(not(target_arch = "wasm32"))]-fn begin_applying(app: &SolveApp, d: &Dialog) -> Begun {- let Some(wait) = app.apply_off_thread else { return Begun::Now(None) };+pub(crate) fn begin_applying(app: &SolveApp, d: &Dialog) -> Option<Applying> {+ let wait = app.apply_off_thread?;if !d.previews() {- return Begun::Now(None);+ return None;}- let Ok(cmds) = apply_commands(app, d) else { return Begun::Now(None) };- let ahead = app.session.ahead();- let (tx, rx) = std::sync::mpsc::channel();- let computed = cmds.clone();+ let computation = DialogComputation::new(app, d).ok()?;+ let cmds = computation.cmds.clone();#[cfg(test)]let gate = app.apply_gate.clone();- let spawned = std::thread::Builder::new().name("apply".into()).spawn(move || {- let evaluated = ahead.evaluate(&computed).ok();+ Some(start_applying(cmds, display_quality(app), crate::now_ms(), wait, move || {+ let result = computation.compute();#[cfg(test)]if let Some(gate) = gate {let _ = gate.lock().unwrap().recv();}- let _ = tx.send(evaluated);+ result+ }))+}++#[cfg(not(target_arch = "wasm32"))]+fn start_applying(+ cmds: Vec<(String, Value)>,+ quality: solidcraft_engine::doc::display_quality::DisplayQuality,+ started: f64,+ wait: std::time::Duration,+ compute: impl FnOnce() -> Result<solidcraft_engine::ComputedCommands, String> + Send + 'static,+) -> Applying {+ let progress = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default());+ let watching = progress.clone();+ let (tx, rx) = std::sync::mpsc::channel();+ let worker = std::thread::Builder::new().name("apply".into()).spawn(move || {+ let result = solidcraft_engine::doc::progress::watch(watching.clone(), || {+ let prepared = compute()?;+ if watching.is_cancelled() {+ return Err("feature computation cancelled".into());+ }+ prepared.warm_display(quality, || !watching.is_cancelled());+ if watching.is_cancelled() {+ return Err("feature computation cancelled".into());+ }+ Ok(prepared)+ });+ let _ = tx.send(result);});- if spawned.is_err() {- return Begun::Now(None);- }- match rx.recv_timeout(wait) {- Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {- Begun::Later(Applying { done: rx, evaluated: None, started: crate::now_ms(), cmds, seen: false })- }- Ok(evaluated) => Begun::Now(evaluated),- Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Begun::Now(None),- }+ let ready = match worker {+ Err(error) => Some(Err(format!("could not start feature computation: {error}"))),+ Ok(_) => match rx.recv_timeout(wait) {+ Ok(result) => Some(result),+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => None,+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Some(Err("feature computation ended without a result".into())),+ },+ };+ Applying { done: rx, ready, seen: false, started, cmds, progress, quality }+}++#[cfg(not(target_arch = "wasm32"))]+fn warm_applying(app: &SolveApp, prepared: solidcraft_engine::ComputedCommands, cmds: Vec<(String, Value)>, started: f64) -> Option<Applying> {+ Some(start_applying(cmds, display_quality(app), started, std::time::Duration::ZERO, move || Ok(prepared)))}#[cfg(target_arch = "wasm32")]-fn begin_applying(_app: &SolveApp, _d: &Dialog) -> Begun {- Begun::Now(None)+fn warm_applying(_app: &SolveApp, _prepared: solidcraft_engine::ComputedCommands, _cmds: Vec<(String, Value)>, _started: f64) -> Option<Applying> {+ None+}++#[cfg(target_arch = "wasm32")]+pub(crate) fn begin_applying(_app: &SolveApp, _d: &Dialog) -> Option<Applying> {+ None}/// The commands a dialog's inputs make (or why they make none), its picks, and the design's@@ -2653,6 +2712,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {let mut ok = false;let mut applied = false;let mut apply_again = app.applying.is_some() && d.repeat_after_apply;+ let mut adopted = false;let mut cancel = false;let mut enter = false;let mut value_fields = Vec::new();@@ -2870,7 +2930,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {Err(error) => d.refuse(app, error),}}- if ok && app.applying.is_none() {+ cancel |= !keep;+ if ok && !cancel && app.applying.is_none() {d.repeat_after_apply = apply_again;// Edit Text applies its own way: its live changes and OK are one undo step.let run = match &mut d.kind {@@ -2878,44 +2939,68 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {Kind::ChatContext => Some(crate::agent_chat::pick_done(app, &d)),_ => match begin_applying(app, &d) {// Computing: the dialog stays, saying so, until it is in.- Begun::Later(job) => {+ Some(job) => {app.applying = Some(job);None}- Begun::Now(evaluated) => Some(run_evaluated(app, &d, evaluated.as_ref())),+ None => Some(run_dialog(app, &d)),},};match run {Some(Ok(())) => {applied = true;cancel = !apply_again;+ adopted = d.previews();}Some(Err(e)) => d.refuse(app, e),None => {}}}- // OK's evaluation is in: run it, taking what was evaluated. Inputs changed meanwhile- // (nothing should change them) are computed in turn, off the window thread too: run here,- // they would hold the window for the whole boolean.- // A job that has just started is not in yet: it waits a frame, so the dialog says it is- // computing before the feature appears.- let ready = app.applying.as_mut().is_some_and(Applying::ready);- if let Some(job) = &mut app.applying {- job.seen = true;- }- if ready && !cancel {- let (computed, evaluated) = app.applying.take().map(|job| (Some(job.cmds), job.evaluated.flatten())).unwrap_or_default();+ // Adopt the complete transaction. Never rerun a Boolean on the window thread.+ let finished = if cancel { None } else { app.applying.as_mut().and_then(Applying::finished) };+ // Preferences received after this frame's renderer setup take effect next frame.+ // Keep the result ready until the viewport will consume the prepared quality.+ let finished = if finished.is_some() && solidcraft_engine::doc::display_quality::current() != display_quality(app) {+ if let Some(job) = app.applying.as_mut() {+ job.ready = finished;+ }+ ctx.request_repaint();+ None+ } else {+ finished+ };+ if let Some(result) = finished {+ let commands = app.applying.as_ref().map(|job| job.cmds.clone());+ let quality = app.applying.as_ref().map(|job| job.quality);+ let started = app.applying.as_ref().map_or_else(crate::now_ms, |job| job.started);+ app.applying = None;let current = apply_commands(app, &d).ok();- let again = if current.is_some() && current != computed { begin_applying(app, &d) } else { Begun::Now(evaluated) };- match again {- Begun::Later(job) => app.applying = Some(job),- Begun::Now(evaluated) => match run_evaluated(app, &d, evaluated.as_ref()) {+ let source_current = result.as_ref().is_ok_and(|prepared| prepared.is_current(&app.session));+ if current.is_some() && current != commands && source_current {+ app.applying = begin_applying(app, &d);+ } else if current != commands && source_current {+ d.refuse(app, "the feature inputs changed while computing".into());+ } else if source_current && quality.is_some_and(|quality| quality != display_quality(app)) {+ // A different display quality needs new plans, never another Boolean evaluation.+ match result {+ Ok(prepared) => {+ app.applying = warm_applying(app, prepared, current.unwrap_or_default(), started);+ if app.applying.is_none() {+ d.refuse(app, "the display quality changed while computing".into());+ }+ }+ Err(error) => d.refuse(app, error),+ }+ } else {+ let run = result.and_then(|prepared| adopt_dialog(app, prepared));+ match run {Ok(()) => {cancel = !apply_again;applied = true;+ adopted = true;}- Err(e) => d.refuse(app, e),- },+ Err(error) => d.refuse(app, error),+ }}}if applied && apply_again {@@ -2952,8 +3037,14 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {}app.dialog = Some(d);} else if let Some((_, marker)) = d.editing {- // Editing done: put the timeline marker back where it was.- let _ = roll_marker(app, marker);+ if applied {+ app.editing_state = None;+ if !adopted && app.session.doc.marker != marker {+ let _ = roll_marker(app, marker);+ }+ } else {+ restore_editing(app, marker);+ }}// The shortcut that asked for this sketch starts its tool in it.if let Some(id) = then_start {@@ -2964,6 +3055,9 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {/// Close the dialog without applying it (Esc, Cancel). An edit puts the timeline marker back.pub fn cancel(app: &mut SolveApp) {app.session.feature_edit_sketch = None;+ if let Some(pending) = &mut app.pending_feature_edit {+ pending.cancel();+ }app.applying = None;if let Some(mut d) = app.dialog.take() {crate::dialogs_motion::closed(app, &mut d, false);@@ -2975,6 +3069,17 @@ pub fn cancel(app: &mut SolveApp) {if let Some(d) = app.dialog.take()&& let Some((_, marker)) = d.editing{+ restore_editing(app, marker);+ }+ app.editing_state = None;+}++pub(crate) fn restore_editing(app: &mut SolveApp, marker: Option<usize>) {+ if let Some(state) = app.editing_state.take() {+ if let Err(error) = app.session.restore_editor(&state.source, state.original) {+ app.set_status(error.to_string(), true);+ }+ } else {let _ = roll_marker(app, marker);}}@@ -3341,6 +3446,10 @@ pub(crate) fn run_dialog(app: &mut SolveApp, d: &Dialog) -> Result<(), String> {if let Kind::SaveMesh(k) = &d.kind {return crate::dialogs_save_mesh::run(app, k, &d.inputs);}+ if d.previews() {+ let prepared = DialogComputation::new(app, d)?.compute()?;+ return adopt_dialog(app, prepared);+ }let commands = apply_commands(app, d)?;if let Some((_, marker)) = d.editing {// Record the actual pre-edit timeline state in the command's undo snapshot.diff --git a/crates/ui-egui/src/dialogs_sketch_tests.rs b/crates/ui-egui/src/dialogs_sketch_tests.rsindex c593482716..844fe82210 100644--- a/crates/ui-egui/src/dialogs_sketch_tests.rs+++ b/crates/ui-egui/src/dialogs_sketch_tests.rs@@ -192,14 +192,16 @@ fn apply_keeps_the_panel_open_after_asynchronous_evaluation() {let mut h = fixture();let mut d = picked(&h, "sketch.pattern.rectangular");let cmds = apply_commands(&h.app, &d).unwrap();+ let prepared = h.app.session.scratch().compute_commands(&cmds, None).unwrap();d.repeat_after_apply = true;h.app.dialog = Some(d);let (finish, done) = std::sync::mpsc::channel();- h.app.applying = Some(Applying::computing(done, cmds));+ h.app.applying =+ Some(Applying { done, ready: None, started: crate::now_ms(), cmds, seen: true, progress: Default::default(), quality: Default::default() });let undo = h.app.session.undo.len();h.frames(2);assert_eq!(h.app.session.undo.len(), undo);- finish.send(None).unwrap();+ finish.send(Ok(prepared)).ok().unwrap();h.frames(3);assert!(h.app.applying.is_none());let d = h.app.dialog.as_ref().unwrap();diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rsindex 6cdcb929c1..d106d4fff4 100644--- a/crates/ui-egui/src/documents.rs+++ b/crates/ui-egui/src/documents.rs@@ -25,6 +25,7 @@ pub struct DocSlot {pub(crate) big_operation: bool,cam: Camera,pre_sketch_marker: Option<Option<usize>>,+ pub(crate) pending_feature_edit: Option<crate::feature_edit::PendingFeatureEdit>,view: DocView,occurrence_move: Option<crate::browser::OccMove>,agent_chat: crate::agent_chat::AgentChat,@@ -45,6 +46,7 @@ impl DocSlot {big_operation: false,cam: Camera::default(),pre_sketch_marker: None,+ pending_feature_edit: None,view: DocView::default(),occurrence_move: None,agent_chat: Default::default(),@@ -126,6 +128,7 @@ fn swap_in(app: &mut SolveApp, mut slot: DocSlot) -> DocSlot {big_operation: std::mem::replace(&mut app.big_operation, slot.big_operation),cam: std::mem::replace(&mut app.cam, slot.cam),pre_sketch_marker: std::mem::replace(&mut app.pre_sketch_marker, slot.pre_sketch_marker),+ pending_feature_edit: std::mem::replace(&mut app.pending_feature_edit, slot.pending_feature_edit),view: take_view(app),occurrence_move: std::mem::replace(&mut app.tree.occurrence_move, slot.occurrence_move),agent_chat: slot.agent_chat,@@ -137,7 +140,11 @@ 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;// Views cache by revision: the incoming design must not look unchanged.+ let before = app.session.revision;app.session.invalidate_view(out_rev);+ if let Some(pending) = &mut app.pending_feature_edit {+ pending.view_changed(before, app.session.revision);+ }app.ui.ribbon_context = None;app.ui.tab = "MODEL".into();crate::workspace::sync_context(app);diff --git a/crates/ui-egui/src/feature_edit.rs b/crates/ui-egui/src/feature_edit.rsnew file mode 100644index 0000000000..93eeb3ac6e--- /dev/null+++ b/crates/ui-egui/src/feature_edit.rs@@ -0,0 +1,114 @@+//! Prepare the original and rollback models when transferring a sketch's history marker.++use solidcraft_engine::Session;++use crate::SolveApp;++pub(crate) struct PendingFeatureEdit {+ source: Session,+ done: std::sync::mpsc::Receiver<Result<(Session, Session), String>>,+ feature: Option<u64>,+ next_command: Option<String>,+ pub(crate) marker: Option<usize>,+ pub(crate) started: f64,+}++impl PendingFeatureEdit {+ pub(crate) fn cancel(&mut self) {+ self.feature = None;+ self.next_command = None;+ }++ pub(crate) fn then_start(&mut self, command: &str) {+ self.cancel();+ self.next_command = Some(command.to_owned());+ }++ pub(crate) fn view_changed(&mut self, before: u64, after: u64) {+ if self.source.revision == before {+ self.source.revision = after;+ }+ }++ fn result(&self) -> Option<Result<(Session, Session), String>> {+ match self.done.try_recv() {+ Ok(result) => Some(result),+ Err(std::sync::mpsc::TryRecvError::Empty) => None,+ Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(Err("feature editor preparation ended without a result".into())),+ }+ }+}++impl SolveApp {+ pub(crate) fn prepare_feature_edit(&mut self, feature: u64, index: usize, marker: Option<usize>) {+ let source = self.session.scratch();+ let mut original = source.scratch();+ let quality = solidcraft_engine::doc::display_quality::DisplayQuality::parse(&self.preferences.display_quality).unwrap_or_default();+ let compute = move || {+ let params = marker.map(|position| serde_json::json!({"position": position})).unwrap_or_else(|| serde_json::json!({}));+ original.execute("timeline.roll_to", ¶ms).map_err(|error| error.to_string())?;+ let mut rolled = original.scratch();+ rolled.execute("timeline.roll_to", &serde_json::json!({"position": index})).map_err(|error| error.to_string())?;+ original.world_state().warm_display_at(quality, || true);+ rolled.world_state().warm_display_at(quality, || true);+ Ok((original, rolled))+ };+ let (tx, done) = std::sync::mpsc::channel();+ #[cfg(not(target_arch = "wasm32"))]+ if let Err(error) = std::thread::Builder::new().name("feature edit".into()).spawn(move || {+ let _ = tx.send(compute());+ }) {+ self.set_status(format!("could not prepare feature editor: {error}"), true);+ return;+ }+ #[cfg(target_arch = "wasm32")]+ let _ = tx.send(compute());+ self.pending_feature_edit =+ Some(PendingFeatureEdit { source, done, feature: Some(feature), next_command: None, marker, started: crate::now_ms() });+ }++ pub(crate) fn poll_feature_edit(&mut self, ctx: &egui::Context) {+ // A tab switch cancels opening the editor, but its original model still belongs+ // to that design. Finish its guarded restoration in its own inactive slot.+ for slot in self.docs.background_mut() {+ let Some(pending) = slot.pending_feature_edit.take() else { continue };+ match pending.result() {+ None => {+ slot.pending_feature_edit = Some(pending);+ ctx.request_repaint_after(std::time::Duration::from_millis(16));+ }+ Some(Ok((original, _))) => {+ let _ = slot.session.restore_editor(&pending.source, original);+ }+ Some(Err(_)) => {}+ }+ }+ let Some(mut pending) = self.pending_feature_edit.take() else { return };+ if ctx.input(|input| input.key_pressed(egui::Key::Escape)) {+ self.esc_handled = true;+ pending.cancel();+ }+ let Some(result) = pending.result() else {+ self.pending_feature_edit = Some(pending);+ ctx.request_repaint_after(std::time::Duration::from_millis(16));+ return;+ };+ match result {+ Ok((original, rolled)) => {+ // A stale result is discarded, never restarted against a newer design.+ // Adoption preserves the live history stacks and current selection.+ let restore = if pending.feature.is_some() { rolled } else { original.scratch() };+ if let Err(error) = self.session.restore_editor(&pending.source, restore) {+ self.set_status(error.to_string(), true);+ return;+ }+ if let Some(feature) = pending.feature {+ self.open_feature_edit(feature, pending.marker, original);+ } else if let Some(command) = pending.next_command {+ self.start(&command);+ }+ }+ Err(error) => self.set_status(error, true),+ }+ }+}diff --git a/crates/ui-egui/src/history_off_thread_tests.rs b/crates/ui-egui/src/history_off_thread_tests.rsindex 534dbd8928..a2cd340330 100644--- a/crates/ui-egui/src/history_off_thread_tests.rs+++ b/crates/ui-egui/src/history_off_thread_tests.rs@@ -28,7 +28,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() && h.app.delete_check.is_none() {+ if h.app.deferred.is_none() && h.app.deferred_queue.is_empty() && h.app.delete_check.is_none() && h.app.pending_feature_edit.is_none() {break;}h.frames(1);@@ -220,6 +220,178 @@ fn switching_from_a_sketch_to_a_feature_keeps_the_original_marker_with_backgrounassert_eq!(h.app.session.model.state().bodies.len(), bodies, "all later bodies return");}+#[test]+fn switching_from_a_sketch_to_a_feature_restores_partial_markers_and_sketch_changes() {+ for original_marker in [None, Some(4)] {+ let (mut h, sketches) = sketches_with_later_bodies();+ h.app.run("timeline.roll_to", json!({"position": original_marker})).unwrap();+ let bodies = h.app.session.model.state().bodies.len();+ let feature = h.app.session.doc.features[3].id;+ h.app.edit_sketch(sketches[0]);+ h.app.run("sketch.line", json!({"points": [[0, 2], [10, 2]]})).unwrap();+ h.app.edit_feature(feature);+ let history = (h.app.session.undo.len(), h.app.session.redo.len());+ let changed = h.app.session.doc.sketch(sketches[0]).unwrap().clone();+ until_settled(&mut h);+ assert!(h.app.dialog.is_some());+ h.app.session.selection = vec![solidcraft_engine::Sel::Axis { name: "X".into() }];+ *h.app.session.model.cache.lock().unwrap() = Default::default();+ let window = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default());+ solidcraft_engine::doc::progress::watch(window.clone(), || crate::dialogs::cancel(&mut h.app));+ assert_eq!(window.features(), (0, 0), "Cancel uses the pinned matching model");+ assert_eq!(marker(&h), original_marker);+ assert_eq!(h.app.session.model.state().bodies.len(), bodies);+ assert_eq!(h.app.session.doc.sketch(sketches[0]).unwrap(), &changed);+ assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history);+ assert_eq!(h.app.session.selection, vec![solidcraft_engine::Sel::Axis { name: "X".into() }]);+ }+}++#[test]+fn switching_from_a_sketch_to_a_feature_rejects_replaced_or_changed_documents() {+ for action in ["new", "change"] {+ let (mut h, sketches) = sketches_with_later_bodies();+ let feature = h.app.session.doc.features[3].id;+ h.app.edit_sketch(sketches[0]);+ h.app.edit_feature(feature);+ assert!(h.app.computing_since().is_some());+ match action {+ "new" => {+ h.app.run("file.new", json!({})).unwrap();+ }+ "change" => {+ h.app.run("solid.box", json!({"corner": [80, 0, 0], "length": 2, "width": 2, "height": 2})).unwrap();+ }+ _ => assert_eq!(action, "change", "unexpected test action"),+ }+ let current = h.app.session.doc.clone();+ let sketch = h.app.session.active_sketch;+ until_settled(&mut h);+ assert!(h.app.dialog.is_none(), "{action} must not open the obsolete editor");+ assert!(std::sync::Arc::ptr_eq(¤t, &h.app.session.doc), "{action} must preserve the current document");+ assert_eq!(h.app.session.active_sketch, sketch);+ }+}++#[test]+fn switching_from_a_sketch_to_a_feature_applies_with_one_undo_and_redo() {+ let (mut h, sketches) = sketches_with_later_bodies();+ let feature = h.app.session.doc.features[3].id;+ let before = h.app.run("inspect.measure", json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap();+ h.app.edit_sketch(sketches[0]);+ h.app.edit_feature(feature);+ let undo = h.app.session.undo.len();+ until_settled(&mut h);+ h.frames(2);+ h.step(&json!({"click":{"handle":"dialog:length"}})).unwrap();+ h.step(&json!({"key":"A","cmd":true})).unwrap();+ h.step(&json!({"text":"12 mm"})).unwrap();+ h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap();+ for _ in 0..500 {+ if h.app.dialog.is_none() {+ break;+ }+ h.frames(1);+ std::thread::sleep(Duration::from_millis(10));+ }+ assert!(h.app.dialog.is_none(), "the edit must finish");+ assert_eq!(marker(&h), None);+ assert_eq!(h.app.session.undo.len(), undo + 1);+ let after = h.app.run("inspect.measure", json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap();+ assert!((after - before - 200.0).abs() < 0.001);+ h.app.run("edit.undo", json!({})).unwrap();+ assert_eq!(marker(&h), None);+ let restored = h.app.run("inspect.measure", json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap();+ assert!((restored - before).abs() < 0.001);+ h.app.run("edit.redo", json!({})).unwrap();+ let redone = h.app.run("inspect.measure", json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap();+ assert!((redone - after).abs() < 0.001);+}++#[test]+fn switching_from_a_sketch_to_a_feature_preserves_the_marker_through_cancel_and_superseding_editors() {+ for next in ["cancel", "escape", "sketch", "feature", "tab", "tab_back_pending"] {+ let (mut h, sketches) = sketches_with_later_bodies();+ let feature = h.app.session.doc.features[3].id;+ h.app.edit_sketch(sketches[0]);+ h.app.edit_feature(feature);+ match next {+ "cancel" => crate::dialogs::cancel(&mut h.app),+ "escape" => {+ h.step(&json!({"key":"Escape"})).unwrap();+ }+ "sketch" => {+ h.app.edit_sketch(sketches[1]);+ h.app.finish_sketch();+ }+ "feature" => {+ h.app.edit_feature(feature);+ until_settled(&mut h);+ crate::dialogs::cancel(&mut h.app);+ }+ _ => {+ let other = solidcraft_engine::Session::new(Default::default());+ crate::documents::open_tab(&mut h.app, other).unwrap();+ if next == "tab" {+ h.frames(10);+ }+ assert!(h.app.session.doc.features.is_empty());+ crate::documents::switch(&mut h.app, 0);+ }+ }+ until_settled(&mut h);+ assert!(h.app.dialog.is_none(), "{next} must leave no feature editor");+ assert_eq!(marker(&h), None, "{next} must restore the original marker");+ assert_eq!(h.app.session.model.state().bodies.len(), 3);+ }+}++#[test]+fn switching_from_a_sketch_to_a_feature_defers_a_new_command_until_restoration() {+ let (mut h, sketches) = sketches_with_later_bodies();+ let feature = h.app.session.doc.features[3].id;+ let count = h.app.session.doc.features.len();+ h.app.edit_sketch(sketches[0]);+ h.app.edit_feature(feature);+ h.app.start("solid.box");+ assert!(h.app.dialog.is_none(), "the next dialog waits for the matching model");+ until_settled(&mut h);+ assert_eq!(marker(&h), None);+ assert_eq!(h.app.dialog.as_ref().unwrap().editing, None);+ let undo = h.app.session.undo.len();+ h.frames(2);+ h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap();+ for _ in 0..500 {+ if h.app.dialog.is_none() {+ break;+ }+ h.frames(1);+ std::thread::sleep(Duration::from_millis(10));+ }+ assert!(h.app.dialog.is_none());+ assert_eq!(marker(&h), None);+ assert_eq!(h.app.session.doc.features.len(), count + 1);+ assert_eq!(h.app.session.undo.len(), undo + 1);+}++#[test]+fn switching_from_a_sketch_to_a_feature_defers_press_pull_with_its_pick_contract() {+ let (mut h, sketches) = sketches_with_later_bodies();+ let feature = h.app.session.doc.features[3].id;+ h.app.edit_sketch(sketches[0]);+ h.app.edit_feature(feature);+ h.app.session.selection.clear();+ h.app.start("solid.press_pull");+ assert!(h.app.dialog.is_none());+ until_settled(&mut h);+ assert_eq!(marker(&h), None);+ let dialog = h.app.dialog.as_ref().unwrap();+ assert!(dialog.press_pull);+ let picks = dialog.inputs[0].accept;+ assert_ne!(picks & crate::selection::FACES, 0);+ assert_ne!(picks & crate::selection::EDGES, 0);+}+/// A control request for the app, and where its reply lands.fn ask(tx: &std::sync::mpsc::Sender<crate::ControlRequest>, method: &str, params: serde_json::Value) -> std::sync::mpsc::Receiver<serde_json::Value> {let (req, reply) = crate::ControlRequest::new(method, params);diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex ea743ee073..140defbcad 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -57,6 +57,7 @@ pub mod documents;pub mod drag_extrude;pub mod drag_snap;pub mod edit_clipboard;+mod feature_edit;#[cfg(test)]mod font_literals_tests;pub mod fonts;@@ -459,6 +460,8 @@ pub struct SolveApp {pub preview: preview::PreviewState,/// OK pressed on a feature that takes a while: its evaluation runs off the window thread.pub applying: Option<dialogs::Applying>,+ pub(crate) editing_state: Option<dialogs::EditingState>,+ pub(crate) pending_feature_edit: Option<feature_edit::PendingFeatureEdit>,/// A command recomputing the history (the marker moved, undo) computing off the window/// thread, and those asked for meanwhile ([`deferred`]).pub deferred: Option<deferred::Deferred>,@@ -634,6 +637,8 @@ impl SolveApp {slicer_menu: dialogs_save_mesh::SlicerMenu::default(),preview: preview::PreviewState::default(),applying: None,+ editing_state: None,+ pending_feature_edit: None,deferred: None,deferred_queue: Vec::new(),start_after_roll: None,@@ -902,6 +907,11 @@ impl SolveApp {let t0 = now_ms();let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string());self.big_operation |= now_ms() - t0 >= recovery_ui::BIG_OPERATION_MS;+ self.command_completed(id, r)+ }++ /// Host effects shared by directly executed and already evaluated commands.+ pub(crate) fn command_completed(&mut self, id: &str, r: Result<Value, String>) -> Result<Value, String> {if let Ok(v) = &r {if id == "view.layout" {let layout =@@ -1000,6 +1010,9 @@ impl SolveApp {// The old document is already replaced: discard its editor without// applying cancellation hooks (such as restoring its timeline marker).self.dialog = None;+ self.applying = None;+ self.editing_state = None;+ self.pending_feature_edit = None;self.tool = None;self.preview.reset();self.cam = Camera::default();@@ -1225,6 +1238,10 @@ impl SolveApp {}// Press Pull: edges get a fillet, curved faces an offset, planar faces and profiles an extrude.if id == "solid.press_pull" {+ if let Some(pending) = &mut self.pending_feature_edit {+ pending.then_start(id);+ return;+ }let sel = &self.session.selection;let edges = sel.iter().any(|s| matches!(s, solidcraft_engine::Sel::Edge { .. }));let curved = sel.iter().any(@@ -1247,6 +1264,15 @@ impl SolveApp {}return;}+ let interactive = self.interactive(id);+ if interactive && let Some(pending) = &mut self.pending_feature_edit {+ pending.then_start(id);+ return;+ }+ // Cancel before finishing a sketch or waiting for its history marker.+ if interactive && (self.editing_state.is_some() || self.applying.is_some()) {+ dialogs::cancel(self);+ }let finished_sketch = self.session.active_sketch.filter(|_| ends_sketch(id) && self.interactive(id));if finished_sketch.is_some() {self.finish_sketch();@@ -1352,6 +1378,7 @@ impl SolveApp {/// timeline back to just before themselves and reopen their dialog, filled in.pub fn edit_feature(&mut self, id: u64) {use solidcraft_engine::doc::FeatureKind;+ dialogs::cancel(self);let Some(f) = self.session.doc.feature(id) else { return };if matches!(f.kind, FeatureKind::Sketch { .. }) {self.edit_sketch(id);@@ -1360,14 +1387,28 @@ impl SolveApp {let Some(idx) = self.session.doc.feature_index(id) else { return };let marker = self.finish_sketch_for_edit();self.tool = None;+ if self.session.doc.marker != marker {+ self.prepare_feature_edit(id, idx, marker);+ return;+ }+ let original = self.session.scratch();if dialogs::roll_marker(self, Some(idx)).is_err() {return;}+ self.open_feature_edit(id, marker, original);+ }++ fn open_feature_edit(&mut self, id: u64, marker: Option<usize>, original: Session) {+ self.editing_state = Some(dialogs::EditingState { source: self.session.scratch(), original });match dialogs::for_feature(self, id, marker) {- Some(d) => self.dialog = Some(d),+ Some(d) => {+ if !d.previews() {+ self.editing_state = None;+ }+ self.dialog = Some(d);+ }None => {- let _ = dialogs::roll_marker(self, marker);- // No dialog for this feature: open the search box with the command to edit it.+ dialogs::restore_editing(self, marker);self.sbox.text = format!("timeline.edit {{\"feature\": {id}, \"set\": {{}}}}");self.ui.palette_open = true;}@@ -1407,7 +1448,11 @@ impl SolveApp {/// Pass the original marker to the next editor. Restoring it between editors could finish/// in the background after the next rollback, moving the marker out from under that edit.fn finish_sketch_for_edit(&mut self) -> Option<usize> {- let marker = self.pre_sketch_marker.take().unwrap_or(self.session.doc.marker);+ let marker = self+ .pending_feature_edit+ .take()+ .map(|pending| pending.marker)+ .unwrap_or_else(|| self.pre_sketch_marker.take().unwrap_or(self.session.doc.marker));if self.session.active_sketch.is_some() {self.finish_sketch();}@@ -1933,6 +1978,7 @@ impl SolveApp {}self.ui.layout.publish(ui.ctx());scenario::clear_handles();+ self.poll_feature_edit(ui.ctx());self.poll_deferred(ui.ctx());self.poll_delete_check(ui.ctx());if !self.embedded {diff --git a/crates/ui-egui/src/save_job.rs b/crates/ui-egui/src/save_job.rsindex fe54eb2837..5b2095a7c1 100644--- a/crates/ui-egui/src/save_job.rs+++ b/crates/ui-egui/src/save_job.rs@@ -68,6 +68,45 @@ pub fn tick(app: &mut SolveApp, wait: bool) {mod tests {use serde_json::json;+ #[test]+ fn a_pending_save_blocks_feature_computation_and_completed_transaction_adoption() {+ let mut h = crate::scenario::Harness::new();+ h.app.home.open = false;+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();+ h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[10,10]})).unwrap();+ h.app.finish_sketch();+ h.app.start("solid.extrude");+ h.frames(2);+ let dialog = h.app.dialog.as_ref().unwrap().clone();+ let cmds = crate::dialogs::apply_commands(&h.app, &dialog).unwrap();+ let prepared = h.app.session.scratch().compute_commands(&cmds, None).unwrap();+ let document = h.app.session.doc.clone();+ let history = h.app.session.undo.len();+ let (_save_finish, save_done) = std::sync::mpsc::channel();+ h.app.saving = Some(super::Saving { command: "file.save", done: save_done });+ h.app.apply_off_thread = Some(std::time::Duration::ZERO);+ assert!(crate::dialogs::begin_applying(&h.app, &dialog).is_none());+ assert!(crate::dialogs::run_dialog(&mut h.app, &dialog).unwrap_err().contains("file operation"));+ let (finish, done) = std::sync::mpsc::channel();+ h.app.applying = Some(crate::dialogs::Applying {+ done,+ ready: None,+ seen: true,+ started: crate::now_ms(),+ cmds,+ progress: Default::default(),+ quality: Default::default(),+ });+ finish.send(Ok(prepared)).ok().unwrap();+ // Run just the dialog, without the normal frame's save polling.+ let mut out = h.ctx.run_ui(Default::default(), |ui| crate::dialogs::show(&mut h.app, ui.ctx()));+ // Not drawn: discard the texture updates explicitly.+ out.textures_delta.clear();+ assert!(std::sync::Arc::ptr_eq(&document, &h.app.session.doc));+ assert_eq!(h.app.session.undo.len(), history);+ assert!(h.app.dialog.as_ref().unwrap().error.as_ref().unwrap().contains("file operation"));+ }+/// #3044: Save writes on a worker while the window keeps drawing; the design waits (commands/// are refused) until the save is taken up, which leaves it saved under its file, in the/// recent files, with the command echoed, as a save run here does.diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rsindex e544059356..de3f32224c 100644--- a/crates/ui-egui/src/toolbar.rs+++ b/crates/ui-egui/src/toolbar.rs@@ -2095,7 +2095,7 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) {crate::select_other::close(app);} else if app.tool.is_some() {crate::tools::finish(app);- } else if app.dialog.is_some() {+ } else if app.dialog.is_some() || app.pending_feature_edit.is_some() {crate::dialogs::cancel(app);} else if !app.session.selection.is_empty() || app.session.active_sketch.is_none() {app.tree.picked_joints.clear();