Skip to content

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

perf: Save and Save As write on a worker thread (#3044) (#3146)

bherbruck9e7a7b260b96
diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs
index d346b1f2d4..c4489c6fb1 100644
--- a/apps/solidcraft/src/main.rs
+++ b/apps/solidcraft/src/main.rs
@@ -91,6 +91,8 @@ impl eframe::App for App {
fn on_exit(&mut self) {
// The agent chat's agent and everything it started end with the app.
solidcraft_ui_egui::agent_chat::shutdown(&mut self.solve);
+ // A save still being written ends before the app does.
+ solidcraft_ui_egui::save_job::tick(&mut self.solve, true);
solidcraft_ui_egui::recovery_ui::close(&mut self.solve);
solidcraft_engine::crash::end_session();
// An update asked to restart into the new version or to run its installer.
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index efc83fda11..9d336559e0 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -382,6 +382,22 @@ fn write_bytes(
}
impl Session {
+ /// Take up a save that ran on `done`, a [`Session::scratch`] copy of this session that
+ /// `file.save` or `file.save_as` ran on (on another thread, so the window keeps drawing)
+ /// while this one did not change: the name and link paths the save gave the design, its
+ /// file, and its saved state, as running the command here would have left them.
+ pub fn adopt_save(&mut self, done: &Session) {
+ if done.doc.name != self.doc.name {
+ let (from, to) = (self.doc.name.clone(), done.doc.name.clone());
+ rename_design(self, &from, &to);
+ }
+ if done.doc.links != self.doc.links {
+ self.doc_mut().links.clone_from(&done.doc.links);
+ }
+ self.path.clone_from(&done.path);
+ self.mark_saved();
+ }
+
/// Container bytes for desktop and browser saves. Only already evaluated bodies
/// and warm meshes are eligible; saving never forces evaluation or tessellation.
pub fn design_container(&self, compression: solidcraft_io::DesignCompression, preview: bool, cache: bool) -> solidcraft_io::Result<Vec<u8>> {
@@ -645,6 +661,34 @@ mod urdf_tests;
mod tests {
use super::*;
+ /// #3044: a save run on a scratch copy of the session (on a worker, so the window keeps
+ /// drawing) and taken up with `adopt_save` leaves the session as saving it directly does:
+ /// the design named after its first file, its file, and nothing unsaved; undo keeps the name.
+ #[test]
+ fn a_save_run_on_a_copy_and_adopted_matches_saving_directly() {
+ let dir = std::env::temp_dir().join(format!("solidcraft-adopt-save-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let mut direct = Session::default();
+ direct.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap();
+ let mut adopted = Session::new((*direct.doc).clone());
+ adopted.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap();
+ let a = dir.join("Bracket.solidcraft");
+ let b = dir.join("Bracket copy.solidcraft");
+ direct.execute("file.save_as", &json!({"path": a.to_string_lossy()})).unwrap();
+ let mut copy = adopted.scratch();
+ copy.path.clone_from(&adopted.path);
+ copy.execute("file.save_as", &json!({"path": b.to_string_lossy()})).unwrap();
+ assert!(adopted.is_dirty(), "nothing taken up yet");
+ adopted.adopt_save(&copy);
+ assert!(!adopted.is_dirty());
+ assert_eq!(adopted.path.as_deref(), b.to_str());
+ assert_eq!(adopted.doc.name, "Bracket copy");
+ assert_eq!(direct.doc.name, "Bracket");
+ assert_eq!(adopted.undo.iter().map(|u| u.doc.name.clone()).collect::<Vec<_>>(), vec!["Bracket copy".to_string(); adopted.undo.len()]);
+ assert_eq!(solidcraft_io::read_design(&std::fs::read(&b).unwrap()).unwrap(), *adopted.doc);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[test]
#[ignore = "manual warmed engine save and provisional-open benchmark"]
fn benchmark_warm_design_save_with_preview() {
diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs
index 5b869b2795..6f240ecd3b 100644
--- a/crates/ui-egui/src/documents.rs
+++ b/crates/ui-egui/src/documents.rs
@@ -761,6 +761,7 @@ mod tests {
assert_eq!(a.docs.closing, Some(0), "the first unsaved design is asked about first");
assert_eq!(a.docs.active, 0, "and shown");
answer_prompt(&mut a, Answer::Save);
+ crate::save_job::tick(&mut a, true);
assert!(!dirty(&a, 0), "saved");
assert_eq!(
std::fs::read(&file).ok().and_then(|b| solidcraft_engine::io::read_design(&b).ok()).map(|d| d.features.len()),
@@ -802,6 +803,7 @@ mod tests {
answer_prompt(&mut a, Answer::Save);
assert!(!a.quit_requested && a.file_picker_busy());
crate::file_picker::tick(&mut a, &egui::Context::default());
+ crate::save_job::tick(&mut a, true);
assert!(a.quit_requested && file.exists());
let _ = std::fs::remove_file(&file);
}
diff --git a/crates/ui-egui/src/file_picker.rs b/crates/ui-egui/src/file_picker.rs
index 3ec09ab655..afd683ddd0 100644
--- a/crates/ui-egui/src/file_picker.rs
+++ b/crates/ui-egui/src/file_picker.rs
@@ -29,8 +29,9 @@ impl Wake for Repaint {
impl SolveApp {
/// Keep the target design and editors unchanged until the picker answers.
+ /// (A save being written keeps it unchanged too, see [`crate::save_job`].)
pub fn file_picker_busy(&self) -> bool {
- self.file_picker.is_some()
+ self.file_picker.is_some() || self.saving.is_some()
}
pub(crate) fn pick_open(&mut self, complete: impl FnOnce(&mut SolveApp, Option<String>) + 'static) {
@@ -175,6 +176,8 @@ mod tests {
waker.wake();
}
tick(app, &egui::Context::default());
+ // A save the answer started is written on a worker: wait for it.
+ crate::save_job::tick(app, true);
assert!(!app.file_picker_busy());
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 9b17c23cad..3d344ca6bf 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -141,6 +141,7 @@ pub mod render_workspace;
mod revolve_edit_tests;
#[cfg(test)]
mod revolve_manipulator_tests;
+pub mod save_job;
pub mod scenario;
pub mod select_other;
pub mod selection;
@@ -311,6 +312,8 @@ pub struct SolveApp {
pub pre_sketch_marker: Option<Option<usize>>,
pub services: Services,
file_picker: Option<file_picker::Pending>,
+ /// A Save or Save As being written on a worker (see [`save_job`]).
+ saving: Option<save_job::Saving>,
pub viewport: viewport::ViewportState,
pub render_workspace: render_workspace::State,
pub tool: Option<tools::Tool>,
@@ -452,6 +455,7 @@ impl SolveApp {
pre_sketch_marker: None,
services,
file_picker: None,
+ saving: None,
viewport: viewport::ViewportState::default(),
render_workspace,
tool: None,
@@ -652,7 +656,7 @@ impl SolveApp {
/// Run a command programmatically (JSON parameters, no dialogs).
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
- if self.file_load.busy() || self.file_picker.is_some() {
+ if self.file_load.busy() || self.file_picker.is_some() || self.saving.is_some() {
return Err("a file operation is in progress".into());
}
let t0 = now_ms();
@@ -683,7 +687,14 @@ impl SolveApp {
// Curves drawn in construction (or centerline) mode take that line type.
sketch_palette::apply_mode(self, id, v);
}
- match &r {
+ self.finish_command(id, &r);
+ r
+ }
+
+ /// What follows a command's run, whether it ran here or on a worker (a save): its echo,
+ /// the status line when it failed, what opening and saving update, and the toolbar tab.
+ pub(crate) fn finish_command(&mut self, id: &str, r: &Result<Value, String>) {
+ match r {
Ok(v) => {
// Programmatic callers (the control channel, scripts) run outside a render
// language scope, so resolve the echo from the saved preference instead of the
@@ -735,7 +746,6 @@ impl SolveApp {
self.ui.tab = "SOLID".into();
self.tool = None;
}
- r
}
/// Start a command the way a toolbar click does: interactive tools and dialogs for commands
@@ -1295,6 +1305,10 @@ impl SolveApp {
render_workspace::sync_backend(self);
render_workspace::tick(self, ctx);
file_load::tick(self, ctx);
+ save_job::tick(self, false);
+ if self.saving.is_some() {
+ ctx.request_repaint_after(std::time::Duration::from_millis(16));
+ }
self.esc_handled = false;
prefs::apply(self, ctx);
if !self.styled || theme::is_dark() != self.ui.dark || theme::vision() != self.preferences.color_vision {
diff --git a/crates/ui-egui/src/save_job.rs b/crates/ui-egui/src/save_job.rs
new file mode 100644
index 0000000000..fe54eb2837
--- /dev/null
+++ b/crates/ui-egui/src/save_job.rs
@@ -0,0 +1,95 @@
+//! Save and Save As off the window's thread (#3044): writing a large design (and the model a
+//! save keeps with it) takes long enough that the window must keep drawing meanwhile. The
+//! command runs on a copy of the session on a worker; the design waits for it like it waits for
+//! a file picker, and the outcome is taken up as running the command here would have left it.
+
+use serde_json::Value;
+use solidcraft_engine::Session;
+
+use crate::SolveApp;
+
+/// A save being written on a worker thread.
+pub struct Saving {
+ command: &'static str,
+ done: std::sync::mpsc::Receiver<(Session, Result<Value, String>)>,
+}
+
+/// Run `file.save` or `file.save_as` with `params`. On the desktop it runs on a worker and is
+/// taken up by [`tick`] (true: it is under way); in the browser, or when no thread can start, it
+/// runs here and is finished on return (false).
+pub fn start(app: &mut SolveApp, command: &'static str, params: Value) -> bool {
+ #[cfg(not(target_arch = "wasm32"))]
+ if app.saving.is_none() && app.file_picker.is_none() && !app.file_load.busy() {
+ let mut copy = app.session.scratch();
+ // The copy has no file: the command saves to this session's (and names the design after it).
+ copy.path.clone_from(&app.session.path);
+ let (tx, rx) = std::sync::mpsc::channel();
+ let given = params.clone();
+ let job = std::thread::Builder::new().name("save".into()).spawn(move || {
+ let r = copy.execute(command, &given).map_err(|e| e.to_string());
+ let _ = tx.send((copy, r));
+ });
+ if job.is_ok() {
+ app.saving = Some(Saving { command, done: rx });
+ return true;
+ }
+ // No thread to write on: save here, as before.
+ }
+ let _ = app.run(command, params);
+ false
+}
+
+/// Take up a finished save (`wait`: wait for a running one).
+pub fn tick(app: &mut SolveApp, wait: bool) {
+ let Some(saving) = app.saving.as_ref() else { return };
+ let outcome = if wait {
+ saving.done.recv().ok()
+ } else {
+ match saving.done.try_recv() {
+ Ok(outcome) => Some(outcome),
+ Err(std::sync::mpsc::TryRecvError::Empty) => return,
+ Err(std::sync::mpsc::TryRecvError::Disconnected) => None,
+ }
+ };
+ let Some(Saving { command, .. }) = app.saving.take() else { return };
+ let r = match outcome {
+ Some((copy, Ok(v))) => {
+ app.session.adopt_save(&copy);
+ Ok(v)
+ }
+ Some((_, Err(e))) => Err(e),
+ None => Err(format!("{command}: the save stopped")),
+ };
+ app.finish_command(command, &r);
+ crate::documents::saved_for_close(app);
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ /// #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.
+ #[test]
+ fn save_writes_on_a_worker_and_is_taken_up_like_a_save_here() {
+ let mut h = crate::scenario::Harness::new();
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap();
+ let path = h.dir.join("Plate.solidcraft");
+ assert!(super::start(&mut h.app, "file.save_as", json!({"path": path.to_string_lossy()})), "under way on a worker");
+ assert!(h.app.file_picker_busy() && h.app.run("solid.sphere", json!({"diameter": 4})).is_err(), "the design waits for it");
+ h.frame();
+ h.settle();
+ assert!(h.app.saving.is_none() && !h.app.session.is_dirty());
+ assert_eq!(h.app.session.path.as_deref(), path.to_str());
+ assert_eq!(h.app.session.doc.name, "Plate");
+ assert!(h.app.home.recent.iter().any(|r| r.as_str() == path.to_str().unwrap()), "{:?}", h.app.home.recent);
+ assert!(h.app.session.log.iter().any(|l| l.contains("Save As")), "{:?}", h.app.session.log);
+ // A failing save reports why, and leaves the changes unsaved.
+ h.app.run("solid.sphere", json!({"diameter": 4})).unwrap();
+ let bad = h.dir.join("missing").join("x.solidcraft");
+ super::start(&mut h.app, "file.save_as", json!({"path": bad.to_string_lossy()}));
+ super::tick(&mut h.app, true);
+ assert!(h.app.session.is_dirty() && h.app.status.as_ref().is_some_and(|(_, _, error)| *error));
+ }
+}
diff --git a/crates/ui-egui/src/scenario.rs b/crates/ui-egui/src/scenario.rs
index 3a83a0b96c..04a56dac00 100644
--- a/crates/ui-egui/src/scenario.rs
+++ b/crates/ui-egui/src/scenario.rs
@@ -254,9 +254,9 @@ impl Harness {
}
self.frame();
}
- // A file opening or recovering in the background: wait for it (as a person would).
+ // A file opening, recovering or saving in the background: wait for it (as a person would).
let began = std::time::Instant::now();
- while !self.app.file_load.idle() && began.elapsed() < std::time::Duration::from_secs(120) {
+ while (!self.app.file_load.idle() || self.app.saving.is_some()) && began.elapsed() < std::time::Duration::from_secs(120) {
self.frame();
std::thread::sleep(std::time::Duration::from_millis(1));
}
diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs
index e6aeb9bab5..e9650a9443 100644
--- a/crates/ui-egui/src/toolbar.rs
+++ b/crates/ui-egui/src/toolbar.rs
@@ -596,7 +596,7 @@ pub fn save(app: &mut SolveApp) {
return;
}
if app.session.path.is_some() {
- let _ = app.run("file.save", json!({}));
+ crate::save_job::start(app, "file.save", json!({}));
} else {
save_as(app);
}
@@ -609,8 +609,11 @@ fn save_as(app: &mut SolveApp) {
fn save_as_with_extension(app: &mut SolveApp, extension: &str) {
let name = format!("{}.{extension}", app.session.doc.name);
app.pick_save(&name, &[solidcraft_engine::io::DESIGN_EXT, "json"], |app, path| {
- if let Some(path) = path {
- let _ = app.run("file.save_as", json!({"path": path}));
+ // A save under way answers a closing tab when it ends.
+ if let Some(path) = path
+ && crate::save_job::start(app, "file.save_as", json!({"path": path}))
+ {
+ return;
}
crate::documents::saved_for_close(app);
});
@@ -1467,6 +1470,8 @@ mod header_report_tests {
h.frames(3);
h.step(&json!({"click":{"handle":"appbar:folder"}})).unwrap();
h.step(&json!({"widget":"Save As JSON…"})).unwrap();
+ // Written on a worker: the window keeps drawing until it is done.
+ h.settle();
let saved = h.app.session.path.clone().unwrap();
let bytes = std::fs::read(&saved).unwrap();
assert!(!solidcraft_engine::io::is_design_container(&bytes));