SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Update Links: show which linked design it reads, off the window thread (#5329) (#5512)
HiroKenEzaa8e8cf69cfc
diff --git a/assets/locales/en.json b/assets/locales/en.jsonindex af72f5eefa..73f6a97d66 100644--- a/assets/locales/en.json+++ b/assets/locales/en.json@@ -1136,6 +1136,7 @@"file_load.built": "Built so far: {built} of {total} features.","file_load.converting": "Converting solid {done} of {total}","file_load.inserting": "Inserting geometry",+ "file_load.link_item": "{name} ({done} of {total})","file_load.opening": "Opening design","file_load.preparing_thumbnail": "Preparing the thumbnail...","file_load.preparing_view": "Preparing the view...",@@ -1145,6 +1146,7 @@"file_load.rebuilding": "Rebuilding feature {done} of {total}","file_load.recovering": "Recovering design","file_load.stopping": "Waiting for the previous operation to stop...",+ "file_load.updating_links": "Updating links","file_load.waiting": "Waiting for file operation","fits the face, e.g. M8": "fits the face, e.g. M8","from the profile": "from the profile",diff --git a/assets/locales/ja.json b/assets/locales/ja.jsonindex 8fd28b2e7b..835940e1ba 100644--- a/assets/locales/ja.json+++ b/assets/locales/ja.json@@ -1136,6 +1136,7 @@"file_load.built": "構築済み: 全{total}フィーチャー中{built}件。","file_load.converting": "ソリッドを変換中: {done}/{total}","file_load.inserting": "ジオメトリを挿入中",+ "file_load.link_item": "{name} ({done}/{total})","file_load.opening": "デザインを開いています","file_load.preparing_thumbnail": "サムネイルを準備中...","file_load.preparing_view": "ビューを準備中...",@@ -1145,6 +1146,7 @@"file_load.rebuilding": "フィーチャーを再構築中: {done}/{total}","file_load.recovering": "デザインを復元中","file_load.stopping": "前の操作の停止を待っています...",+ "file_load.updating_links": "リンクを更新中","file_load.waiting": "ファイル操作を待っています","fits the face, e.g. M8": "面に適合するサイズ (例: M8)","from the profile": "形材から",diff --git a/assets/locales/zh.json b/assets/locales/zh.jsonindex 9a177cce0f..14592e6c34 100644--- a/assets/locales/zh.json+++ b/assets/locales/zh.json@@ -1136,6 +1136,7 @@"file_load.built": "已构建:{built}/{total} 个特征。","file_load.converting": "正在转换实体 {done}/{total}","file_load.inserting": "正在插入几何体",+ "file_load.link_item": "{name} ({done}/{total})","file_load.opening": "正在打开设计","file_load.preparing_thumbnail": "正在准备缩略图...","file_load.preparing_view": "正在准备视图...",@@ -1145,6 +1146,7 @@"file_load.rebuilding": "正在重建特征 {done}/{total}","file_load.recovering": "正在恢复设计","file_load.stopping": "正在等待上一次操作停止...",+ "file_load.updating_links": "正在更新链接","file_load.waiting": "正在等待文件操作","fits the face, e.g. M8": "适配该面,例如 M8","from the profile": "取自型材",diff --git a/crates/doc/src/progress.rs b/crates/doc/src/progress.rsindex 22a76cd83b..e78dc4a979 100644--- a/crates/doc/src/progress.rs+++ b/crates/doc/src/progress.rs@@ -21,6 +21,9 @@ pub struct Progress {work_stage: std::sync::Mutex<&'static str>,work_done: AtomicUsize,work_total: AtomicUsize,+ /// The item a command works through one at a time (the linked design Update Links reads+ /// again): its name, its place and how many there are ([`item`]).+ item: std::sync::Mutex<Option<(String, usize, usize)>>,/// A window wants the model as far as it is built, to show while the rest is ([`Progress::want_partial`]).partial_wanted: AtomicBool,/// The latest such model and when it was offered.@@ -48,6 +51,7 @@ impl Default for Progress {work_stage: std::sync::Mutex::new(""),work_done: AtomicUsize::new(0),work_total: AtomicUsize::new(0),+ item: std::sync::Mutex::new(None),partial_wanted: AtomicBool::new(false),partial: std::sync::Mutex::new((None, None)),}@@ -86,6 +90,23 @@ impl Progress {let stage = self.work_stage.lock().map(|s| *s).unwrap_or("");(total > 0 && !stage.is_empty()).then(|| (stage, self.work_done.load(Ordering::Relaxed).min(total), total))}+ /// The item being worked on, as [`item`] reported it: (name, index from 0, count).+ pub fn item(&self) -> Option<(String, usize, usize)> {+ self.item.lock().ok().and_then(|i| i.clone())+ }+}++/// Tell a watcher which item a command is on (`name`, `index` from 0 of `count`), such as the+/// linked design Update Links reads again; `None` once it is past them. Nothing happens unless+/// the work is watched ([`watch`]).+pub fn item(current: Option<(&str, usize, usize)>) {+ CURRENT.with(|c| {+ if let Some(cur) = c.borrow().as_ref()+ && let Ok(mut i) = cur.progress.item.lock()+ {+ *i = current.map(|(name, index, count)| (name.to_string(), index.min(count), count));+ }+ });}/// The kernel's long work (STEP import) reports to the same progress and stops on Cancel.@@ -242,6 +263,22 @@ mod tests {assert!(!begin(1).step(0), "the watch ends with its scope");}+ /// The item a command is on reaches its watcher, and only a watcher.+ #[test]+ fn items_go_to_the_watcher() {+ item(Some(("unwatched", 0, 1)));+ let p = Arc::new(Progress::default());+ assert_eq!(p.item(), None);+ watch(p.clone(), || {+ item(Some(("plate", 1, 3)));+ assert_eq!(p.item(), Some(("plate".to_string(), 1, 3)));+ item(None);+ });+ assert_eq!(p.item(), None, "cleared once past the items");+ item(Some(("after", 0, 1)));+ assert_eq!(p.item(), None, "the watch ends with its scope");+ }+/// A watcher that asks for partial models gets the model built so far, placed, now and then;/// one that doesn't ask, or an unwatched evaluation, never pays for it.#[test]diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rsindex 205ab7b4e7..1f2713b9b4 100644--- a/crates/engine/src/cmd/component_link.rs+++ b/crates/engine/src/cmd/component_link.rs@@ -233,13 +233,16 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {}let links: Vec<(u64, DesignLink)> = s.doc.links.iter().filter(|(c, _)| only.is_none_or(|o| o == **c)).map(|(c, l)| (*c, l.clone())).collect();let (mut updated, mut unchanged, mut warnings) = (Vec::new(), Vec::new(), Vec::new());- for (comp, link) in links {+ let count = links.len();+ for (index, (comp, link)) in links.into_iter().enumerate() {let cname = s.doc.components.iter().find(|c| c.id == comp).map(|c| c.name.clone());let Some(cname) = cname else {// The component was deleted: the link goes with it.s.doc_mut().links.remove(&comp);continue;};+ // A window running this off its thread names the design being read again (#5329).+ solidcraft_doc::progress::item(Some((&cname, index, count)));let Some(FeatureKind::Import { step: old, .. }) = s.doc.feature(link.feature).filter(|f| f.component == comp).map(|f| &f.kind) else {return Err(bad(cmd,@@ -279,6 +282,7 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {}if changed { updated.push(cname) } else { unchanged.push(cname) }}+ solidcraft_doc::progress::item(None);s.refresh();if let Some(e) = s.doc.links.values().find_map(|l| s.model.result(l.feature).and_then(|r| r.error.clone())) {return Err(EngineError::Other(e));diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rsindex e608cd2cfd..cf5113a23f 100644--- a/crates/ui-egui/src/file_load.rs+++ b/crates/ui-egui/src/file_load.rs@@ -6,6 +6,10 @@//! progress with Cancel. The overlay takes the pointer, shortcuts and commands wait, and//! control-channel commands that change the design are held until the file is in. A control//! (MCP) `doc.open` or import is answered when its file finishes loading.+//!+//! Update Links from the toolbar runs the same way (#5329): it reads every linked design again+//! and rebuilds it, which takes a while in an assembly of many parts, so the overlay names the+//! linked design being read and its rebuild's progress.use crate::ui_kit::{Container, Surface};use std::collections::VecDeque;@@ -33,6 +37,8 @@ pub enum Kind {Recover { id: String, dir: Option<String> },/// Export a snapshot of the current design without adopting the worker's session.ExportDxf,+ /// Read the active design's linked designs again (`component.update_links`).+ UpdateLinks,}pub struct Request {@@ -68,6 +74,7 @@ impl Request {Kind::Insert => ("file.insert_step", self.params()),Kind::Recover { id, dir } => ("doc.recover", json!({"id": id, "dir": dir})),Kind::ExportDxf => ("file.export_view_dxf", Value::Object(self.options.clone())),+ Kind::UpdateLinks => ("component.update_links", json!({})),}}fn answer(&self, r: Result<Value, String>) {@@ -241,6 +248,10 @@ pub fn begin_request(app: &mut SolveApp, request: Request) -> Result<(), String>}r}+ Kind::UpdateLinks => {+ let (command, params) = request.command();+ app.run(command, params)+ }};request.answer(r);Ok(())@@ -344,10 +355,15 @@ fn start(app: &mut SolveApp) {}let insert = request.insert();let before = if insert { app.session.world_state().bodies.iter().map(|b| b.name.clone()).collect() } else { Vec::new() };- let mut scratch = if insert || request.kind == Kind::ExportDxf { app.session.scratch() } else { Session::default() };+ let update = request.kind == Kind::UpdateLinks;+ let mut scratch = if insert || update || request.kind == Kind::ExportDxf { app.session.scratch() } else { Session::default() };if insert {scratch.selection = app.session.selection.clone();}+ if update {+ // Link paths are kept relative to the design's own file.+ scratch.path.clone_from(&app.session.path);+ }let base = app.session.doc.clone();let base_revision = app.session.revision;let phase = Arc::new(AtomicU8::new(0));@@ -814,6 +830,16 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) {request.answer(Ok(made.result));}_ if running.cancelled() => request.answer(Err("file operation cancelled".into())),+ Ok(made) if request.kind == Kind::UpdateLinks && running.matches(&app.session) => {+ let (id, _) = request.command();+ app.session.accept_computed(made.session);+ app.big_operation = true;+ let r = Ok(made.result);+ app.finish_command(id, &r);+ let language = crate::i18n::Locale::for_language(&app.preferences.language);+ app.set_status(language.format("ui.command_done", &[("command", language.label(crate::command_label(id)))]), false);+ request.answer(r);+ }Ok(made) if running.matches(&app.session) => {// Not meshed yet: framing it while it goes in must not mesh it here.app.open_meshing_next = true;@@ -862,7 +888,10 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) {}Err(e) => {request.answer(Err(e.clone()));- if let Kind::Recover { id, dir } = &request.kind {+ if request.kind == Kind::UpdateLinks {+ // Said as when the command ran here (the status line, the run's messages).+ app.finish_command(request.command().0, &Err(e));+ } else if let Kind::Recover { id, dir } = &request.kind {reoffer(app, id, dir.as_deref());app.set_status(format!("could not recover {}: {e}. Discard it or choose Later", request.path), true);} else {@@ -902,6 +931,13 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {}let name = match &r.request.kind {Kind::Recover { .. } => r.request.path.clone(),+ // The linked design being read again, once the worker is on one.+ Kind::UpdateLinks => match r.progress.item() {+ Some((name, i, n)) => {+ crate::i18n::format("file_load.link_item", &[("name", &name), ("done", &(i + 1).min(n).to_string()), ("total", &n.to_string())])+ }+ None => app.session.doc.name.clone(),+ },_ => std::path::Path::new(&r.request.path).file_name().map(|p| p.to_string_lossy().to_string()).unwrap_or_default(),};let phase = r.phase.load(Ordering::Relaxed);@@ -944,6 +980,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {Kind::Open => "file_load.opening",Kind::Recover { .. } => "file_load.recovering",Kind::ExportDxf => "dxf.exporting",+ Kind::UpdateLinks => "file_load.updating_links",})};let icon = match r.request.kind {@@ -951,6 +988,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {Kind::Open => "open",Kind::Recover { .. } => "restore",Kind::ExportDxf => "export",+ Kind::UpdateLinks => "update",};let (closed, action) = ui_kit::Window::new(card_id, icon, title).cards(((cover.width() - 16.0) / crate::theme::Tokens::get().form_card_width).clamp(0.5, 1.3))@@ -1002,6 +1040,11 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {} else {1.0};+ // Linked designs read again: how far through them, the one being read in part.+ let fraction = match r.progress.item().filter(|_| r.request.kind == Kind::UpdateLinks && !cancelled) {+ Some((_, i, n)) => (i as f32 + fraction.clamp(0.0, 1.0)) / n.max(1) as f32,+ None => fraction,+ };ui_kit::progress(ui, "file_load", fraction);});// Cancel (and Esc) was a handle of its own before the card became a kit Prompt.diff --git a/crates/ui-egui/src/file_load_ui_tests.rs b/crates/ui-egui/src/file_load_ui_tests.rsindex d802df3250..f7d4a2aca5 100644--- a/crates/ui-egui/src/file_load_ui_tests.rs+++ b/crates/ui-egui/src/file_load_ui_tests.rs@@ -181,6 +181,76 @@ fn cancel_stops_the_open_and_keeps_the_current_design() {let _ = std::fs::remove_dir_all(&dir);}+/// Update Links reads the linked designs again off the window thread (#5329): the overlay says+/// so and names the design being read, the assembly stays as it was meanwhile (Cancel keeps it),+/// and the new bodies come in once it is done, as one undo step.+#[test]+fn update_links_names_the_design_it_reads_while_the_window_draws() {+ let dir = scratch("links");+ let part = dir.join("plate.solidcraft");+ let case = dir.join("case.solidcraft");+ // A plate with two holes (three features: the read can be held at the third).+ let save_part = |height: f64| {+ let mut s = Session::default();+ s.execute("solid.box", &json!({"length": 40, "width": 20, "height": height})).unwrap();+ for x in [10, 30] {+ s.execute("solid.cylinder", &json!({"radius": 2, "height": 200, "base": [x, 10, -1], "operation": "cut"})).unwrap();+ }+ s.execute("file.save", &json!({"path": part})).unwrap();+ s.execute("inspect.measure", &json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap()+ };+ let volume = |app: &mut SolveApp| app.session.execute("inspect.measure", &json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap();+ // The holes come through the link's exchange as surfaces of their own: a close match.+ let near = |app: &mut SolveApp, v: f64| {+ let got = volume(app);+ assert!((got - v).abs() < 1e-3 * v, "{got} mm³, not {v}");+ };+ let thin = save_part(5.0);+ let mut h = crate::scenario::Harness::new();+ h.app.home.open = false;+ h.app.run("component.insert_design", json!({"path": part})).unwrap();+ h.app.run("file.save", json!({"path": case})).unwrap();+ near(&mut h.app, thin);+ let thick = save_part(12.0);+ let until = |h: &mut crate::scenario::Harness, done: &dyn Fn(&SolveApp) -> bool| {+ let began = std::time::Instant::now();+ while !done(&h.app) {+ assert!(began.elapsed() < std::time::Duration::from_secs(120), "Update Links went on");+ h.frames(1);+ std::thread::sleep(std::time::Duration::from_millis(1));+ }+ h.frames(3);+ };++ // Held before the part's third feature: the window draws, saying what it reads.+ let assembly = h.app.session.doc.clone();+ h.app.file_load.hold_at = Some(2);+ h.app.start("component.update_links");+ assert!(h.app.file_load.busy(), "Update Links runs off the window thread");+ until(&mut h, &|app| app.file_load.features().is_some_and(|(done, total)| done >= 2 && total == 3));+ assert!(h.app.file_load.busy(), "Update Links is still reading the part");+ assert!(h.widget("Updating links").is_some(), "the overlay says Update Links is running");+ assert!(h.widget("plate (1 of 1)…").is_some(), "and names the linked design being read");+ assert!(h.widget("Rebuilding feature 3 of 3").is_some(), "with the part's rebuild progress");+ assert!(std::sync::Arc::ptr_eq(&h.app.session.doc, &assembly), "the assembly waits");+ // Cancel keeps the assembly as it was.+ h.app.file_load.cancel();+ until(&mut h, &|app| app.file_load.idle());+ assert!(std::sync::Arc::ptr_eq(&h.app.session.doc, &assembly), "a cancelled update changes nothing");+ near(&mut h.app, thin);++ // Run through, it brings the edited part in, and says it is done.+ h.app.start("component.update_links");+ until(&mut h, &|app| app.file_load.idle());+ assert!(h.widget("Updating links").is_none(), "the overlay goes once it is done");+ near(&mut h.app, thick);+ assert_eq!(h.app.status.as_ref().map(|s| s.0.as_str()), Some("Update Links done"));+ h.app.run("edit.undo", json!({})).unwrap();+ // One undo step takes it back.+ near(&mut h.app, thin);+ let _ = std::fs::remove_dir_all(&dir);+}+/// A control-channel (MCP) open is answered when the file is in, with the synchronous/// command's reply, and the window draws frames while it waits. Commands sent meanwhile wait.#[test]diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 3f78d14b35..81547cdf76 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1089,6 +1089,12 @@ impl SolveApp {self.pick_open_command(id, json!({}), &[ext]);return;}+ if id == "component.update_links" && !self.session.doc.links.is_empty() {+ // Reading the linked designs again takes a while in a large assembly: off the window+ // thread, the overlay naming the one being read (#5329).+ let _ = file_load::begin_request(self, file_load::Request::new("", file_load::Kind::UpdateLinks));+ return;+ }if id == "component.insert_design" {// Another design becomes a linked component; a STEP or mesh file picked here is// inserted the way Insert STEP or Insert Mesh would (#1240).