From 0415dc3d251cf0af7387c940c7d0826277e6cfb8 Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 10:10:44 +0100 Subject: [PATCH 01/20] Links: update linked designs that changed while the assembly's tab was away A design coming back to its tab compares the modification time and size of its linked design files with what they were when it went to the background, and runs Update Links on the worker thread for those that changed: saved in another tab, another window or by a checkout. Preference update_changed_links (Design, Linked designs) turns it off. Co-Authored-By: Claude Opus 5.5 --- .../locales/pending/update-changed-links.json | 26 ++++ crates/ui-egui/src/documents.rs | 12 +- crates/ui-egui/src/file_load.rs | 5 +- crates/ui-egui/src/linked_source.rs | 118 ++++++++++++++++++ crates/ui-egui/src/prefs.rs | 3 + crates/ui-egui/src/prefs/design.rs | 3 + 6 files changed, 163 insertions(+), 4 deletions(-) create mode 100644 assets/locales/pending/update-changed-links.json diff --git a/assets/locales/pending/update-changed-links.json b/assets/locales/pending/update-changed-links.json new file mode 100644 index 00000000000..fedf308e7b4 --- /dev/null +++ b/assets/locales/pending/update-changed-links.json @@ -0,0 +1,26 @@ +{ + "en": { + "prefs.linked_designs": "Linked designs", + "settings.update_changed_links": "Update linked designs that changed while another tab was open" + }, + "ar": { + "prefs.linked_designs": "التصاميم المرتبطة", + "settings.update_changed_links": "تحديث التصاميم المرتبطة التي تغيّرت أثناء فتح علامة تبويب أخرى" + }, + "de": { + "prefs.linked_designs": "Verknüpfte Designs", + "settings.update_changed_links": "Verknüpfte Designs aktualisieren, die sich geändert haben, während ein anderer Tab offen war" + }, + "he": { + "prefs.linked_designs": "תכנים מקושרים", + "settings.update_changed_links": "עדכון תכנים מקושרים שהשתנו בזמן שלשונית אחרת הייתה פתוחה" + }, + "ja": { + "prefs.linked_designs": "リンクされたデザイン", + "settings.update_changed_links": "別のタブを開いている間に変更されたリンク先デザインを更新" + }, + "zh": { + "prefs.linked_designs": "链接设计", + "settings.update_changed_links": "更新在打开其他标签页期间已更改的链接设计" + } +} diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index c6ba36de0e7..29c631b19aa 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -30,6 +30,8 @@ pub struct DocSlot { view: DocView, occurrence_move: Option, agent_chat: crate::agent_chat::AgentChat, + /// Its linked design files as they were on disk when the design went to the background. + link_stamps: Vec<(u64, crate::linked_source::Stamp)>, } /// The per-design part of the UI state the session doesn't keep (what is hidden, shown or locked @@ -58,6 +60,7 @@ impl DocSlot { view: DocView::default(), occurrence_move: None, agent_chat: Default::default(), + link_stamps: Vec::new(), } } } @@ -151,6 +154,7 @@ fn swap_in(app: &mut SolveApp, mut slot: DocSlot) -> DocSlot { view: take_view(app), occurrence_move: std::mem::replace(&mut app.tree.occurrence_move, slot.occurrence_move), agent_chat: slot.agent_chat, + link_stamps: Vec::new(), }; // Only the displayed design owns the process-wide crash replay journal. app.session.crash_journal = out.session.crash_journal; @@ -205,13 +209,17 @@ pub fn switch(app: &mut SolveApp, i: usize) { if i == app.docs.active || i >= app.docs.slots.len() { return; } - let Some(incoming) = app.docs.slots.get_mut(i).and_then(Option::take) else { return }; - let out = swap_in(app, incoming); + let Some(mut incoming) = app.docs.slots.get_mut(i).and_then(Option::take) else { return }; + let stamps = std::mem::take(&mut incoming.link_stamps); + let leaving = crate::linked_source::link_stamps(app); + let mut out = swap_in(app, incoming); + out.link_stamps = leaving; let a = app.docs.active; if let Some(s) = app.docs.slots.get_mut(a) { *s = Some(out); } app.docs.active = i; + crate::linked_source::update_changed(app, &stamps); } /// Select an already-open saved design without reloading or framing it. Identity is derived diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index 496f7e5c847..352595efc1d 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -37,7 +37,8 @@ pub enum Kind { Recover { id: String, dir: Option }, /// 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`). + /// Read the active design's linked designs again (`component.update_links`, with the + /// request's options: `component` reads only that link). UpdateLinks, } @@ -83,7 +84,7 @@ impl Request { Kind::Insert => (insert_command(&self.path), 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!({})), + Kind::UpdateLinks => ("component.update_links", Value::Object(self.options.clone())), } } fn answer(&self, r: Result) { diff --git a/crates/ui-egui/src/linked_source.rs b/crates/ui-egui/src/linked_source.rs index 6ea4c0b1c97..cb91e495d82 100644 --- a/crates/ui-egui/src/linked_source.rs +++ b/crates/ui-egui/src/linked_source.rs @@ -105,6 +105,60 @@ fn report(app: &mut SolveApp, result: &serde_json::Value, done: &str) { } } +/// A linked design file as it is on disk: its modification time and size (`None`: not there, +/// not allowed, or the platform keeps no times). +pub(crate) type Stamp = Option<(std::time::SystemTime, u64)>; + +fn stamp(file: &str) -> Stamp { + #[cfg(not(target_arch = "wasm32"))] + { + let meta = std::fs::metadata(file).ok()?; + Some((meta.modified().ok()?, meta.len())) + } + #[cfg(target_arch = "wasm32")] + { + let _ = file; + None + } +} + +/// The active design's linked components with their files as they are on disk now. A file on a +/// network location not allowed is never looked at (`component.links` reports it unfound). +pub(crate) fn link_stamps(app: &mut SolveApp) -> Vec<(u64, Stamp)> { + if !app.preferences.update_changed_links || app.session.doc.links.is_empty() { + return Vec::new(); + } + let Ok(links) = app.session.execute("component.links", &json!({})) else { return Vec::new() }; + let found = |l: &&serde_json::Value| l["found"].as_bool() == Some(true); + links["links"] + .as_array() + .into_iter() + .flatten() + .filter(found) + .filter_map(|l| Some((l["component"].as_u64()?, stamp(l["file"].as_str()?)))) + .collect() +} + +/// Take up, off the window thread as Update Links does, the linked designs whose files changed +/// since `before` ([`link_stamps`] as the design went to the background). +pub(crate) fn update_changed(app: &mut SolveApp, before: &[(u64, Stamp)]) { + if before.is_empty() { + return; + } + let changed: Vec = + link_stamps(app).into_iter().filter(|(c, now)| now.is_some() && before.iter().any(|(b, was)| b == c && was != now)).map(|(c, _)| c).collect(); + let mut request = crate::file_load::Request::new("", crate::file_load::Kind::UpdateLinks); + match changed[..] { + [] => return, + // Several: one run over every link reads each design once. + [component] => { + request.options.insert("component".into(), json!(component)); + } + _ => {} + } + let _ = crate::file_load::begin_request(app, request); +} + /// Components Extract to File found to build the same bodies as the one it linked. #[derive(Clone, Debug)] pub struct Copies { @@ -317,6 +371,70 @@ mod tests { let _ = std::fs::remove_dir_all(folder); } + #[test] + fn changed_linked_designs_update_the_assembly_when_its_tab_returns() { + let folder = std::env::temp_dir().join(format!("solidcraft-changed-link-ui-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let file = folder.join("plate.solidcraft"); + let mut part = Session::default(); + part.execute("solid.box", &json!({"length": 10, "width": 20, "height": 30})).unwrap(); + part.execute("file.save", &json!({"path": file})).unwrap(); + let mut app = SolveApp::new(Session::default(), Default::default()); + app.run("component.insert_design", json!({"path": file})).unwrap(); + let volume = |app: &SolveApp| { + app.session.world_state().bodies.iter().map(|b| solidcraft_engine::kernel::measure(&b.body).unwrap().volume).sum::() + }; + let ctx = egui::Context::default(); + let settle = |app: &mut SolveApp| { + let began = std::time::Instant::now(); + while !app.file_load.idle() { + assert!(began.elapsed() < std::time::Duration::from_secs(120), "Update Links went on"); + crate::file_load::tick(app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + }; + let saved_box = |app: &mut SolveApp| { + crate::documents::switch(app, 1); + app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "operation": "new"})).unwrap(); + app.run("file.save", json!({})).unwrap(); + crate::documents::switch(app, 0); + }; + assert!((volume(&app) - 6000.0).abs() < 1e-6); + let mut opened = Session::default(); + opened.execute("doc.open", &json!({"path": file})).unwrap(); + crate::documents::open_tab(&mut app, opened).unwrap(); + assert_eq!(app.docs.active, 1); + // Back without saving: nothing to take up + crate::documents::switch(&mut app, 0); + assert!(app.file_load.idle()); + assert!((volume(&app) - 6000.0).abs() < 1e-6); + // Changed and saved there: coming back updates the link, off the window thread + saved_box(&mut app); + assert!(app.file_load.busy(), "the update runs as Update Links does"); + settle(&mut app); + assert!((volume(&app) - 7000.0).abs() < 1e-6, "{}", volume(&app)); + assert_eq!(app.status.as_ref().map(|s| s.0.as_str()), Some("Update Links done")); + // Changed outside the app (another window, a checkout) while the tab was away: the same. + // The part's own tab now refuses to save over that change, so it stays out of the rest + let saved_elsewhere = |app: &mut SolveApp| { + crate::documents::switch(app, 1); + let mut elsewhere = Session::default(); + elsewhere.execute("doc.open", &json!({"path": file})).unwrap(); + elsewhere.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "operation": "new"})).unwrap(); + elsewhere.execute("file.save", &json!({})).unwrap(); + crate::documents::switch(app, 0); + }; + saved_elsewhere(&mut app); + settle(&mut app); + assert!((volume(&app) - 8000.0).abs() < 1e-6, "{}", volume(&app)); + // Turned off, the link waits for Update Links as before + app.preferences.update_changed_links = false; + saved_elsewhere(&mut app); + assert!(app.file_load.idle()); + assert!((volume(&app) - 8000.0).abs() < 1e-6, "{}", volume(&app)); + let _ = std::fs::remove_dir_all(folder); + } + #[test] fn relink_displays_the_warning_when_changed_geometry_has_joints() { let (mut app, component, occurrence, folder, moved) = fixture("warning"); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index cb8cd1050c0..b6e30d8c22a 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -614,6 +614,9 @@ preference_settings! { /// Up/Down and the wheel over a focused value field step its plain number (`value_step`, /// #2320). Off by default: the keys move the text cursor and the wheel scrolls, as before. step_values: bool = false, PAGE_DESIGN => check_id("ui.step_values"); + /// A design coming back to its tab reads again the linked designs whose files changed while + /// it was in the background. Off: they wait for Update Links, as before. + update_changed_links: bool = true, PAGE_DESIGN => check_id("settings.update_changed_links"); /// Reopen the saved designs that were open when the app was last closed (#5542). reopen_designs: bool = true, PAGE_GENERAL; /// Those designs' files, in tab order, as the last quit left them. diff --git a/crates/ui-egui/src/prefs/design.rs b/crates/ui-egui/src/prefs/design.rs index 162cf1632e9..1cedc737fda 100644 --- a/crates/ui-egui/src/prefs/design.rs +++ b/crates/ui-egui/src/prefs/design.rs @@ -78,6 +78,9 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::settings_section(ui, "placement", app.tr("prefs.placement"), |ui| { setting::placement_handles(app, ui); }); + ui_kit::settings_section(ui, "linked_designs", app.tr("prefs.linked_designs"), |ui| { + setting::update_changed_links(app, ui); + }); // Where the files a design names may be: never a network location the user hasn't allowed. ui_kit::settings_section(ui, "network_locations", app.tr("prefs.network_locations_section"), |ui| { setting::network_locations(app, ui); From 87213ad29664b4202c0741364406226aa6e0807b Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 10:57:26 +0100 Subject: [PATCH 02/20] Docs: the assembly guide says linked designs update when their tab returns Co-Authored-By: Claude Opus 5.5 --- docs/book/src/guide/assemblies.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index 1b2e219bcf3..deabfce3451 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -354,6 +354,11 @@ Mesh** would. The part's solid bodies come in as they sit in that design, and they are kept in the assembly, so it opens even without the part file. The link is stored relative to the assembly's folder once the assembly is saved. After the part file changes, **Update Links** (`component.update_links`) reads it again. +An assembly whose tab comes back to the front does that by itself for the parts whose files +changed while another tab was open, whether the part was saved in another tab, another window or +by a checkout. **Update linked designs that changed while another tab was open** +(Preferences, Design, `update_changed_links`) turns this off. A tab opened since starts watching +once it has been in the background. To edit the source, right-click a linked component or occurrence in the Browser and choose **Open Linked Design**. It opens the part in another tab and reports if its file is missing. **Break Link** (`component.break_link`) keeps the bodies and forgets the file, and From 4de37aa79ae6878cc6b0c0603380f364b3dc10cd Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 12:50:51 +0100 Subject: [PATCH 03/20] Links: Vietnamese strings, now that vi is a complete catalog Co-Authored-By: Claude Opus 5.5 --- assets/locales/pending/update-changed-links.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/assets/locales/pending/update-changed-links.json b/assets/locales/pending/update-changed-links.json index fedf308e7b4..9e61a319f45 100644 --- a/assets/locales/pending/update-changed-links.json +++ b/assets/locales/pending/update-changed-links.json @@ -19,6 +19,10 @@ "prefs.linked_designs": "リンクされたデザイン", "settings.update_changed_links": "別のタブを開いている間に変更されたリンク先デザインを更新" }, + "vi": { + "prefs.linked_designs": "Thiết kế liên kết", + "settings.update_changed_links": "Cập nhật các thiết kế liên kết đã thay đổi trong khi một thẻ khác đang mở" + }, "zh": { "prefs.linked_designs": "链接设计", "settings.update_changed_links": "更新在打开其他标签页期间已更改的链接设计" From f28b238030fd31a3562d65c8713d544783fedc57 Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 14:03:45 +0100 Subject: [PATCH 04/20] Links: remember what each design last read, so an update that fails is tried again A design's linked files are now recorded as the design last read them: when Update Links reads a link without an error, or when the link is first seen. Coming back to the tab reads again what differs, one link per run, so a file that cannot be read holds up no other and is tried again the next time, and a part changed while the assembly was shown is taken up on its next return. Closing several tabs together reads nothing on the way, and the web build, which keeps no file times, looks at nothing. Co-Authored-By: Claude Opus 5.5 --- .../locales/pending/update-changed-links.json | 14 +- crates/ui-egui/src/documents.rs | 32 ++-- crates/ui-egui/src/file_load.rs | 1 + crates/ui-egui/src/linked_source.rs | 160 ++++++++++++++++-- crates/ui-egui/src/prefs.rs | 4 +- docs/book/src/guide/assemblies.md | 8 +- 6 files changed, 178 insertions(+), 41 deletions(-) diff --git a/assets/locales/pending/update-changed-links.json b/assets/locales/pending/update-changed-links.json index 9e61a319f45..464c6937d6d 100644 --- a/assets/locales/pending/update-changed-links.json +++ b/assets/locales/pending/update-changed-links.json @@ -1,30 +1,30 @@ { "en": { "prefs.linked_designs": "Linked designs", - "settings.update_changed_links": "Update linked designs that changed while another tab was open" + "settings.update_changed_links": "Update changed linked designs when a tab comes back" }, "ar": { "prefs.linked_designs": "التصاميم المرتبطة", - "settings.update_changed_links": "تحديث التصاميم المرتبطة التي تغيّرت أثناء فتح علامة تبويب أخرى" + "settings.update_changed_links": "تحديث التصاميم المرتبطة التي تغيّرت عند العودة إلى علامة التبويب" }, "de": { "prefs.linked_designs": "Verknüpfte Designs", - "settings.update_changed_links": "Verknüpfte Designs aktualisieren, die sich geändert haben, während ein anderer Tab offen war" + "settings.update_changed_links": "Geänderte verknüpfte Designs aktualisieren, wenn ein Tab wieder angezeigt wird" }, "he": { "prefs.linked_designs": "תכנים מקושרים", - "settings.update_changed_links": "עדכון תכנים מקושרים שהשתנו בזמן שלשונית אחרת הייתה פתוחה" + "settings.update_changed_links": "עדכון תכנים מקושרים שהשתנו כשלשונית מוצגת שוב" }, "ja": { "prefs.linked_designs": "リンクされたデザイン", - "settings.update_changed_links": "別のタブを開いている間に変更されたリンク先デザインを更新" + "settings.update_changed_links": "タブに戻ったときに変更されたリンク先デザインを更新" }, "vi": { "prefs.linked_designs": "Thiết kế liên kết", - "settings.update_changed_links": "Cập nhật các thiết kế liên kết đã thay đổi trong khi một thẻ khác đang mở" + "settings.update_changed_links": "Cập nhật các thiết kế liên kết đã thay đổi khi quay lại một thẻ" }, "zh": { "prefs.linked_designs": "链接设计", - "settings.update_changed_links": "更新在打开其他标签页期间已更改的链接设计" + "settings.update_changed_links": "返回标签页时更新已更改的链接设计" } } diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 29c631b19aa..aaeb55e585c 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -30,7 +30,7 @@ pub struct DocSlot { view: DocView, occurrence_move: Option, agent_chat: crate::agent_chat::AgentChat, - /// Its linked design files as they were on disk when the design went to the background. + /// Its linked design files as the design last read them (`Documents::link_stamps`). link_stamps: Vec<(u64, crate::linked_source::Stamp)>, } @@ -82,6 +82,10 @@ pub struct Documents { /// is closed first, so the ones before it keep their places). One with unsaved changes asks /// first; Cancel stops the rest (#3055). pub batch: Option>, + /// The shown design's linked design files as it last read them: their modification time and + /// size when Update Links last read each without an error, or when the link was first seen. + /// Coming back to its tab reads again those that differ (`linked_source::update_changed`). + pub(crate) link_stamps: Vec<(u64, crate::linked_source::Stamp)>, } impl Documents { @@ -154,7 +158,7 @@ fn swap_in(app: &mut SolveApp, mut slot: DocSlot) -> DocSlot { view: take_view(app), occurrence_move: std::mem::replace(&mut app.tree.occurrence_move, slot.occurrence_move), agent_chat: slot.agent_chat, - link_stamps: Vec::new(), + link_stamps: std::mem::replace(&mut app.docs.link_stamps, slot.link_stamps), }; // Only the displayed design owns the process-wide crash replay journal. app.session.crash_journal = out.session.crash_journal; @@ -209,17 +213,18 @@ pub fn switch(app: &mut SolveApp, i: usize) { if i == app.docs.active || i >= app.docs.slots.len() { return; } - let Some(mut incoming) = app.docs.slots.get_mut(i).and_then(Option::take) else { return }; - let stamps = std::mem::take(&mut incoming.link_stamps); - let leaving = crate::linked_source::link_stamps(app); - let mut out = swap_in(app, incoming); - out.link_stamps = leaving; + let Some(incoming) = app.docs.slots.get_mut(i).and_then(Option::take) else { return }; + crate::linked_source::note_unread(app); + let out = swap_in(app, incoming); let a = app.docs.active; if let Some(s) = app.docs.slots.get_mut(a) { *s = Some(out); } app.docs.active = i; - crate::linked_source::update_changed(app, &stamps); + // Closing several tabs or quitting goes through them: what they missed waits for their return. + if app.docs.batch.is_none() && app.docs.quitting.is_none() { + crate::linked_source::update_changed(app); + } } /// Select an already-open saved design without reloading or framing it. Identity is derived @@ -446,18 +451,23 @@ fn batch_step(app: &mut SolveApp) { if app.docs.closing.is_some() || app.docs.quitting.is_some() { return; } - let Some(mut left) = app.docs.batch.take() else { return }; - while let Some(i) = left.pop() { + if app.docs.batch.is_none() { + return; + } + // The tabs left stay in `batch` while each closes, so the tabs shown on the way know it. + while let Some(i) = app.docs.batch.as_mut().and_then(Vec::pop) { if i >= app.docs.count() { continue; } if dirty(app, i) { app.docs.closing = Some(i); - app.docs.batch = Some(left); return; } close(app, i, true); } + app.docs.batch = None; + // The tab left in front reads now what it skipped on the way. + crate::linked_source::update_changed(app); } /// Quit (the title bar's ×, File ▸ Quit, the window being closed): asks "save changes?" for each diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index 352595efc1d..8fd84c2163d 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -890,6 +890,7 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { let (id, _) = request.command(); app.session.accept_computed(made.session); app.big_operation = true; + crate::linked_source::read_again(app, request.options.get("component").and_then(Value::as_u64)); let r = Ok(made.result); app.finish_command(id, &r); let language = crate::i18n::Locale::for_language(&app.preferences.language); diff --git a/crates/ui-egui/src/linked_source.rs b/crates/ui-egui/src/linked_source.rs index cb91e495d82..ab0ab67ec5d 100644 --- a/crates/ui-egui/src/linked_source.rs +++ b/crates/ui-egui/src/linked_source.rs @@ -122,10 +122,11 @@ fn stamp(file: &str) -> Stamp { } } -/// The active design's linked components with their files as they are on disk now. A file on a -/// network location not allowed is never looked at (`component.links` reports it unfound). -pub(crate) fn link_stamps(app: &mut SolveApp) -> Vec<(u64, Stamp)> { - if !app.preferences.update_changed_links || app.session.doc.links.is_empty() { +/// The shown design's linked components with their files as they are on disk now. A file on a +/// network location not allowed is never looked at (`component.links` reports it unfound), and +/// the web build keeps no times, so it looks at nothing. +fn disk_stamps(app: &mut SolveApp) -> Vec<(u64, Stamp)> { + if cfg!(target_arch = "wasm32") || !app.preferences.update_changed_links || app.session.doc.links.is_empty() { return Vec::new(); } let Ok(links) = app.session.execute("component.links", &json!({})) else { return Vec::new() }; @@ -139,24 +140,57 @@ pub(crate) fn link_stamps(app: &mut SolveApp) -> Vec<(u64, Stamp)> { .collect() } -/// Take up, off the window thread as Update Links does, the linked designs whose files changed -/// since `before` ([`link_stamps`] as the design went to the background). -pub(crate) fn update_changed(app: &mut SolveApp, before: &[(u64, Stamp)]) { - if before.is_empty() { +/// Set `component`'s entry in `stamps` (each link's file as the design last read it). +fn record(stamps: &mut Vec<(u64, Stamp)>, component: u64, stamp: Stamp) { + match stamps.iter_mut().find(|(c, _)| *c == component) { + Some(entry) => entry.1 = stamp, + None => stamps.push((component, stamp)), + } +} + +/// The links of the shown design it holds no record of yet (it was just opened, a link was just +/// made) are taken as their files are now. +pub(crate) fn note_unread(app: &mut SolveApp) { + if app.session.doc.links.keys().all(|c| app.docs.link_stamps.iter().any(|(k, _)| k == c)) { return; } + for (c, s) in disk_stamps(app) { + if !app.docs.link_stamps.iter().any(|(k, _)| *k == c) { + app.docs.link_stamps.push((c, s)); + } + } +} + +/// The shown design came back to its tab: read again, off the window thread as Update Links +/// does, the linked designs whose files changed since it last read them. Each is a run of its +/// own, so one that cannot be read holds up no other; one that fails is tried again next time. +pub(crate) fn update_changed(app: &mut SolveApp) { + let now = disk_stamps(app); let changed: Vec = - link_stamps(app).into_iter().filter(|(c, now)| now.is_some() && before.iter().any(|(b, was)| b == c && was != now)).map(|(c, _)| c).collect(); - let mut request = crate::file_load::Request::new("", crate::file_load::Kind::UpdateLinks); - match changed[..] { - [] => return, - // Several: one run over every link reads each design once. - [component] => { - request.options.insert("component".into(), json!(component)); + now.iter().filter(|(c, s)| s.is_some() && app.docs.link_stamps.iter().any(|(k, was)| k == c && was != s)).map(|(c, _)| *c).collect(); + for (c, s) in now { + if !app.docs.link_stamps.iter().any(|(k, _)| *k == c) { + app.docs.link_stamps.push((c, s)); } - _ => {} } - let _ = crate::file_load::begin_request(app, request); + if changed.len() > crate::documents::MAX_OPEN { + // More than can wait at once: one run over every link. + let _ = crate::file_load::begin_request(app, crate::file_load::Request::new("", crate::file_load::Kind::UpdateLinks)); + return; + } + for component in changed { + let mut request = crate::file_load::Request::new("", crate::file_load::Kind::UpdateLinks); + request.options.insert("component".into(), json!(component)); + let _ = crate::file_load::begin_request(app, request); + } +} + +/// Update Links read the shown design's link to `component` (`None`: all of them) without an +/// error: those links are now as their files are. +pub(crate) fn read_again(app: &mut SolveApp, component: Option) { + for (c, s) in disk_stamps(app).into_iter().filter(|(c, _)| component.is_none_or(|o| o == *c)) { + record(&mut app.docs.link_stamps, c, s); + } } /// Components Extract to File found to build the same bodies as the one it linked. @@ -435,6 +469,98 @@ mod tests { let _ = std::fs::remove_dir_all(folder); } + /// An assembly saved in `folder` linking a 10x20x30 plate and a 10 mm cube, with a blank + /// second tab to step away to; the helpers save a part, settle the background work and + /// measure the assembly. + fn two_links(name: &str) -> (SolveApp, std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) { + let folder = std::env::temp_dir().join(format!("solidcraft-two-links-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + let (plate, cube) = (folder.join("plate.solidcraft"), folder.join("cube.solidcraft")); + save_part(&plate, [10.0, 20.0, 30.0], false); + save_part(&cube, [10.0, 10.0, 10.0], false); + let mut app = SolveApp::new(Session::default(), Default::default()); + app.run("component.insert_design", json!({"path": plate})).unwrap(); + app.run("component.insert_design", json!({"path": cube, "translate": [100, 0, 0]})).unwrap(); + app.run("file.save", json!({"path": folder.join("case.solidcraft")})).unwrap(); + crate::documents::open_tab(&mut app, Session::default()).unwrap(); + crate::documents::switch(&mut app, 0); + (app, folder, plate, cube) + } + + /// A box design at `path`; `extra` adds a 5x5x10 box on top (250 mm³). + fn save_part(path: &std::path::Path, size: [f64; 3], extra: bool) { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": size[0], "width": size[1], "height": size[2]})).unwrap(); + if extra { + s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 10, "corner": [0, 0, size[2]], "operation": "join"})).unwrap(); + } + s.execute("file.save", &json!({"path": path, "overwrite": true})).unwrap(); + } + + fn settle(app: &mut SolveApp) { + let ctx = egui::Context::default(); + let began = std::time::Instant::now(); + while !app.file_load.idle() { + assert!(began.elapsed() < std::time::Duration::from_secs(120), "Update Links went on"); + crate::file_load::tick(app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + + fn volume(app: &SolveApp) -> f64 { + app.session.world_state().bodies.iter().map(|b| solidcraft_engine::kernel::measure(&b.body).unwrap().volume).sum() + } + + /// Away to the blank tab and back to the assembly. + fn come_back(app: &mut SolveApp) { + crate::documents::switch(app, 1); + crate::documents::switch(app, 0); + settle(app); + } + + #[test] + fn a_link_that_cannot_be_read_holds_up_no_other_and_is_read_again_next_time() { + let (mut app, folder, plate, cube) = two_links("unreadable"); + assert!((volume(&app) - 7000.0).abs() < 1e-6); + std::fs::write(&plate, b"not a design").unwrap(); + save_part(&cube, [10.0, 10.0, 10.0], true); + come_back(&mut app); + assert!((volume(&app) - 7250.0).abs() < 1e-6, "the cube is read, the plate keeps its bodies: {}", volume(&app)); + // Readable again (and changed): the next return takes it up + save_part(&plate, [10.0, 20.0, 30.0], true); + come_back(&mut app); + assert!((volume(&app) - 7500.0).abs() < 1e-6, "{}", volume(&app)); + // Nothing changed since: nothing is read + crate::documents::switch(&mut app, 1); + crate::documents::switch(&mut app, 0); + assert!(app.file_load.idle()); + let _ = std::fs::remove_dir_all(folder); + } + + #[test] + fn a_change_made_while_the_assembly_is_shown_is_read_when_it_next_comes_back() { + let (mut app, folder, plate, _) = two_links("shown"); + // Changed elsewhere while the assembly is the tab in front + save_part(&plate, [10.0, 20.0, 30.0], true); + come_back(&mut app); + assert!((volume(&app) - 7250.0).abs() < 1e-6, "{}", volume(&app)); + let _ = std::fs::remove_dir_all(folder); + } + + #[test] + fn closing_tabs_together_reads_nothing_on_the_way() { + let (mut app, folder, plate, _) = two_links("batch"); + crate::documents::switch(&mut app, 1); + save_part(&plate, [10.0, 20.0, 30.0], true); + // Close All from the blank tab: the assembly is shown on the way, and closed + crate::documents::close_many(&mut app, vec![0, 1]); + assert!(app.file_load.idle(), "no Update Links for a tab that is closing"); + assert_eq!(app.docs.count(), 1); + assert!(app.status.as_ref().is_none_or(|(_, _, error)| !error), "{:?}", app.status); + let _ = std::fs::remove_dir_all(folder); + } + #[test] fn relink_displays_the_warning_when_changed_geometry_has_joints() { let (mut app, component, occurrence, folder, moved) = fixture("warning"); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index b6e30d8c22a..1ca505fedf3 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -614,8 +614,8 @@ preference_settings! { /// Up/Down and the wheel over a focused value field step its plain number (`value_step`, /// #2320). Off by default: the keys move the text cursor and the wheel scrolls, as before. step_values: bool = false, PAGE_DESIGN => check_id("ui.step_values"); - /// A design coming back to its tab reads again the linked designs whose files changed while - /// it was in the background. Off: they wait for Update Links, as before. + /// A design coming back to its tab reads again the linked designs whose files changed since + /// it last read them. Off: they wait for Update Links, as before. update_changed_links: bool = true, PAGE_DESIGN => check_id("settings.update_changed_links"); /// Reopen the saved designs that were open when the app was last closed (#5542). reopen_designs: bool = true, PAGE_GENERAL; diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index deabfce3451..a5dda3b73ae 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -355,10 +355,10 @@ in as they sit in that design, and they are kept in the assembly, so it opens ev part file. The link is stored relative to the assembly's folder once the assembly is saved. After the part file changes, **Update Links** (`component.update_links`) reads it again. An assembly whose tab comes back to the front does that by itself for the parts whose files -changed while another tab was open, whether the part was saved in another tab, another window or -by a checkout. **Update linked designs that changed while another tab was open** -(Preferences, Design, `update_changed_links`) turns this off. A tab opened since starts watching -once it has been in the background. +changed since it last read them, whether the part was saved in another tab, another window or by +a checkout. A part that cannot be read is tried again the next time, and holds up no other. +**Update changed linked designs when a tab comes back** (Preferences, Design, +`update_changed_links`) turns this off. To edit the source, right-click a linked component or occurrence in the Browser and choose **Open Linked Design**. It opens the part in another tab and reports if its file is missing. **Break Link** (`component.break_link`) keeps the bodies and forgets the file, and From 60547becef5132f6c3768077a4cf9698d8471298 Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 14:14:35 +0100 Subject: [PATCH 05/20] Links: no read during a save-changes prompt, records for adopted designs and missing files A tab shown to answer "save changes?" reads no link before its save, and Cancel there or on a batch lets the tab left in front read what it skipped. A design opened in place of the blank one records its links at once, a link whose file is missing is recorded as missing so it is read when the file comes back, and a read queued for a design that is no longer shown by the time it starts is dropped. More changed links than can wait at once are read on the next return. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/documents.rs | 19 +++-- crates/ui-egui/src/file_load.rs | 15 +++- crates/ui-egui/src/linked_source.rs | 120 +++++++++++++++++++++++++--- 3 files changed, 136 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index aaeb55e585c..590e6775cff 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -83,7 +83,8 @@ pub struct Documents { /// first; Cancel stops the rest (#3055). pub batch: Option>, /// The shown design's linked design files as it last read them: their modification time and - /// size when Update Links last read each without an error, or when the link was first seen. + /// size when Update Links last read each without an error, or when the design first showed + /// the link (opened, adopted in place, the link just made). /// Coming back to its tab reads again those that differ (`linked_source::update_changed`). pub(crate) link_stamps: Vec<(u64, crate::linked_source::Stamp)>, } @@ -221,8 +222,9 @@ pub fn switch(app: &mut SolveApp, i: usize) { *s = Some(out); } app.docs.active = i; - // Closing several tabs or quitting goes through them: what they missed waits for their return. - if app.docs.batch.is_none() && app.docs.quitting.is_none() { + // Closing several tabs, quitting, or a "save changes?" for this tab goes through them, and a + // save then must not wait for a read: what they missed waits for their return. + if app.docs.batch.is_none() && app.docs.quitting.is_none() && app.docs.closing.is_none() { crate::linked_source::update_changed(app); } } @@ -249,7 +251,7 @@ pub(crate) fn reuse_path(app: &mut SolveApp, path: &str) -> Result Ok(true) } -fn same_path(a: &str, b: &str) -> bool { +pub(crate) fn same_path(a: &str, b: &str) -> bool { if a == b { return true; } @@ -303,6 +305,9 @@ pub fn adopt(app: &mut SolveApp, session: Session) { app.menu.props = None; crate::sketch_attachment_ui::clear(app); app.session.replace_design(session); + // The blank design's record of its links goes with it; the new one's start now. + app.docs.link_stamps.clear(); + crate::linked_source::note_unread(app); crate::render_workspace::reset_document(app); app.session.invalidate_view(rev); app.cam = Camera::default(); @@ -1019,6 +1024,8 @@ pub fn answer_prompt(app: &mut SolveApp, answer: Answer) { app.docs.closing = None; app.docs.quitting = None; app.docs.batch = None; + // The tab left in front was shown on the way without reading what it missed. + crate::linked_source::update_changed(app); } } quit_step(app); @@ -1035,12 +1042,14 @@ pub(crate) fn saved_for_close(app: &mut SolveApp) { if app.docs.quitting.is_some() { if !saved { app.docs.quitting = None; + crate::linked_source::update_changed(app); } } else if saved { close(app, app.docs.active, true); } else { - // Save As cancelled: the tabs not closed yet stay. + // Save As cancelled: the tabs not closed yet stay, the one in front reads what it missed. app.docs.batch = None; + crate::linked_source::update_changed(app); } quit_step(app); batch_step(app); diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index 8fd84c2163d..0f94b8aa085 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -55,6 +55,9 @@ pub struct Request { pub options: serde_json::Map, /// Network servers the user allowed for this one request ("Allow once", `network_prompt`). pub allow_hosts: Vec, + /// The saved design this request is for, when it must not run on another: one shown in its + /// place by the time the request starts drops it. + pub design: Option, } impl Request { @@ -66,6 +69,7 @@ impl Request { scope: solidcraft_engine::io::vfs::current_scope(), options: Default::default(), allow_hosts: Vec::new(), + design: None, } } fn insert(&self) -> bool { @@ -195,6 +199,10 @@ pub struct FileLoad { } impl FileLoad { + /// How many more requests can wait. + pub(crate) fn room(&self) -> usize { + crate::documents::MAX_OPEN.saturating_sub(self.queued.len()) + } /// A file operation is under way: the design waits for it. pub fn busy(&self) -> bool { self.running.as_ref().is_some_and(|r| !r.cancelled()) || !self.queued.is_empty() @@ -360,7 +368,8 @@ pub fn control(app: &mut SolveApp, req: crate::control::ControlRequest) -> Optio options.remove("path"); options.retain(|_, v| !v.is_null()); } - let _ = begin_request(app, Request { path: path.into(), kind, reply: Some(req.reply.clone()), scope, options, allow_hosts: Vec::new() }); + let request = Request { path: path.into(), kind, reply: Some(req.reply.clone()), scope, options, allow_hosts: Vec::new(), design: None }; + let _ = begin_request(app, request); None } @@ -396,6 +405,10 @@ fn start(app: &mut SolveApp) { if reuse_open(app, &request) { return; } + if request.design.as_deref().is_some_and(|d| !app.session.path.as_deref().is_some_and(|p| crate::documents::same_path(p, d))) { + request.answer(Err("the design it was for is no longer shown".into())); + return; + } if matches!(request.kind, Kind::Open | Kind::Recover { .. }) && app.docs.count() >= crate::documents::MAX_OPEN && !crate::documents::active_is_blank(app) diff --git a/crates/ui-egui/src/linked_source.rs b/crates/ui-egui/src/linked_source.rs index ab0ab67ec5d..27f3f692a4b 100644 --- a/crates/ui-egui/src/linked_source.rs +++ b/crates/ui-egui/src/linked_source.rs @@ -122,21 +122,22 @@ fn stamp(file: &str) -> Stamp { } } -/// The shown design's linked components with their files as they are on disk now. A file on a -/// network location not allowed is never looked at (`component.links` reports it unfound), and -/// the web build keeps no times, so it looks at nothing. +/// The shown design's linked components with their files as they are on disk now: `None` for a +/// file that is missing, or on a network location not allowed, which is never looked at +/// (`component.links` reports it unfound). The web build keeps no times, so it looks at nothing. fn disk_stamps(app: &mut SolveApp) -> Vec<(u64, Stamp)> { if cfg!(target_arch = "wasm32") || !app.preferences.update_changed_links || app.session.doc.links.is_empty() { return Vec::new(); } let Ok(links) = app.session.execute("component.links", &json!({})) else { return Vec::new() }; - let found = |l: &&serde_json::Value| l["found"].as_bool() == Some(true); links["links"] .as_array() .into_iter() .flatten() - .filter(found) - .filter_map(|l| Some((l["component"].as_u64()?, stamp(l["file"].as_str()?)))) + .filter_map(|l| { + let found = l["found"].as_bool() == Some(true); + Some((l["component"].as_u64()?, if found { stamp(l["file"].as_str()?) } else { None })) + }) .collect() } @@ -173,14 +174,12 @@ pub(crate) fn update_changed(app: &mut SolveApp) { app.docs.link_stamps.push((c, s)); } } - if changed.len() > crate::documents::MAX_OPEN { - // More than can wait at once: one run over every link. - let _ = crate::file_load::begin_request(app, crate::file_load::Request::new("", crate::file_load::Kind::UpdateLinks)); - return; - } - for component in changed { + // More than can wait at once: the rest are still changed when the tab next comes back. + let room = app.file_load.room(); + for component in changed.into_iter().take(room) { let mut request = crate::file_load::Request::new("", crate::file_load::Kind::UpdateLinks); request.options.insert("component".into(), json!(component)); + request.design.clone_from(&app.session.path); let _ = crate::file_load::begin_request(app, request); } } @@ -561,6 +560,103 @@ mod tests { let _ = std::fs::remove_dir_all(folder); } + #[test] + fn saving_a_tab_from_its_save_changes_prompt_is_not_held_up_by_its_links() { + let (mut app, folder, plate, _) = two_links("prompt"); + app.run("solid.box", json!({"length": 1, "width": 1, "height": 1, "corner": [0, 300, 0], "operation": "new"})).unwrap(); + crate::documents::switch(&mut app, 1); + save_part(&plate, [10.0, 20.0, 30.0], true); + // Closing the unsaved assembly from the other tab asks; Save shows it, saves and closes it + crate::documents::close(&mut app, 0, false); + assert_eq!(app.docs.closing, Some(0)); + crate::documents::answer_prompt(&mut app, crate::documents::Answer::Save); + assert!(app.file_load.idle(), "no link read before the save"); + crate::save_job::tick(&mut app, true); + crate::documents::saved_for_close(&mut app); + assert_eq!(app.docs.count(), 1, "saved and closed: {:?}", app.status); + let _ = std::fs::remove_dir_all(folder); + } + + #[test] + fn a_design_opened_in_place_of_the_blank_one_reads_what_changes_while_it_is_shown() { + let (app, folder, plate, _) = two_links("adopted"); + drop(app); + let mut app = SolveApp::new(Session::default(), Default::default()); + let mut opened = Session::default(); + opened.execute("doc.open", &json!({"path": folder.join("case.solidcraft")})).unwrap(); + crate::documents::adopt(&mut app, opened); + assert_eq!(app.docs.count(), 1); + save_part(&plate, [10.0, 20.0, 30.0], true); + crate::documents::open_tab(&mut app, Session::default()).unwrap(); + crate::documents::switch(&mut app, 0); + settle(&mut app); + assert!((volume(&app) - 7250.0).abs() < 1e-6, "{}", volume(&app)); + let _ = std::fs::remove_dir_all(folder); + } + + #[test] + fn cancelling_a_close_all_reads_what_the_tab_left_in_front_missed() { + let (assembly, folder, plate, _) = two_links("cancelled"); + drop(assembly); + // An unsaved design, a blank tab (shown) and the assembly after it + let mut unsaved = Session::default(); + unsaved.execute("solid.box", &json!({"length": 1, "width": 1, "height": 1})).unwrap(); + let mut app = SolveApp::new(unsaved, Default::default()); + crate::documents::open_tab(&mut app, Session::default()).unwrap(); + let mut opened = Session::default(); + opened.execute("doc.open", &json!({"path": folder.join("case.solidcraft")})).unwrap(); + crate::documents::open_tab(&mut app, opened).unwrap(); + settle(&mut app); + crate::documents::switch(&mut app, 1); + save_part(&plate, [10.0, 20.0, 30.0], true); + // Closing the first two shows the assembly on the way, then asks about the unsaved one + crate::documents::close_many(&mut app, vec![0, 1]); + assert_eq!(app.docs.closing, Some(0)); + assert!(app.file_load.idle()); + crate::documents::answer_prompt(&mut app, crate::documents::Answer::Cancel); + settle(&mut app); + assert!(app.session.path.as_deref().is_some_and(|p| p.ends_with("case.solidcraft"))); + assert!((volume(&app) - 7250.0).abs() < 1e-6, "{}", volume(&app)); + let _ = std::fs::remove_dir_all(folder); + } + + #[test] + fn a_link_whose_file_comes_back_is_read() { + let (app, folder, plate, _) = two_links("returns"); + drop(app); + std::fs::remove_file(&plate).unwrap(); + let mut app = SolveApp::new(Session::default(), Default::default()); + let mut opened = Session::default(); + opened.execute("doc.open", &json!({"path": folder.join("case.solidcraft")})).unwrap(); + crate::documents::adopt(&mut app, opened); + crate::documents::open_tab(&mut app, Session::default()).unwrap(); + crate::documents::switch(&mut app, 0); + assert!(app.file_load.idle(), "a missing file is not read"); + save_part(&plate, [10.0, 20.0, 30.0], true); + come_back(&mut app); + assert!((volume(&app) - 7250.0).abs() < 1e-6, "{}", volume(&app)); + let _ = std::fs::remove_dir_all(folder); + } + + #[test] + fn reads_waiting_for_a_design_no_longer_shown_are_dropped_and_done_on_its_return() { + let (mut app, folder, plate, cube) = two_links("dropped"); + save_part(&plate, [10.0, 20.0, 30.0], true); + save_part(&cube, [10.0, 10.0, 10.0], true); + crate::documents::switch(&mut app, 1); + crate::documents::switch(&mut app, 0); + assert!(app.file_load.busy()); + // Another design is shown before the two reads are done (the control channel can) + crate::documents::switch(&mut app, 1); + settle(&mut app); + assert!(app.session.doc.links.is_empty() && app.session.path.is_none(), "the blank design is left alone"); + assert!(!app.status.as_ref().is_some_and(|(s, _, _)| s.contains("not linked")), "{:?}", app.status); + crate::documents::switch(&mut app, 0); + settle(&mut app); + assert!((volume(&app) - 7500.0).abs() < 1e-6, "both are read on the return: {}", volume(&app)); + let _ = std::fs::remove_dir_all(folder); + } + #[test] fn relink_displays_the_warning_when_changed_geometry_has_joints() { let (mut app, component, occurrence, folder, moved) = fixture("warning"); From c99f9a477b8d41f297211953b433915311eb1b3a Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 13:17:26 +0100 Subject: [PATCH 06/20] Assemblies: edit a linked component in place, with the assembly around it Activating a linked component opens the design it comes from in a tab of its own, with the rest of the assembly drawn faded around it where the component sits, so the part's own history, browser and commands are at hand. Finish Editing in the browser saves the part, goes back to the assembly and closes the part's tab when the edit opened it; coming back to the assembly updates the changed link (or Finish Editing runs Update Links when that is turned off). Update Links in the part also reads the assembly's links again, off the window thread, and redraws the assembly around the part; a result for an assembly changed meanwhile is dropped with a message. The part is an ordinary tab, so saving, autosave, recovery, closing and quitting treat it as any other design. The model scene's ghost triangles are now drawn (only the preview's were). Preference edit_linked_in_place turns it off. Builds on the update of changed links when an assembly's tab returns. Co-Authored-By: Claude Opus 5.5 --- assets/locales/pending/edit-in-place.json | 65 +++++ crates/gpu/src/view.rs | 1 + crates/ui-egui/src/browser.rs | 7 +- crates/ui-egui/src/context_menu.rs | 2 +- crates/ui-egui/src/documents.rs | 23 ++ crates/ui-egui/src/edit_in_place.rs | 320 ++++++++++++++++++++++ crates/ui-egui/src/edit_in_place_tests.rs | 255 +++++++++++++++++ crates/ui-egui/src/lib.rs | 14 +- crates/ui-egui/src/prefs.rs | 3 + crates/ui-egui/src/prefs/design.rs | 1 + crates/ui-egui/src/viewport.rs | 7 +- 11 files changed, 691 insertions(+), 7 deletions(-) create mode 100644 assets/locales/pending/edit-in-place.json create mode 100644 crates/ui-egui/src/edit_in_place.rs create mode 100644 crates/ui-egui/src/edit_in_place_tests.rs diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json new file mode 100644 index 00000000000..64a381cd742 --- /dev/null +++ b/assets/locales/pending/edit-in-place.json @@ -0,0 +1,65 @@ +{ + "en": { + "settings.edit_linked_in_place": "Activating a linked component edits its design in place", + "ui.edit_in_place_assembly_closed": "{name} is no longer open", + "ui.edit_in_place_banner": "Editing in {name}", + "ui.edit_in_place_refresh_dropped": "The assembly changed while Update Links ran; run it again", + "ui.edit_in_place_refreshing": "Updating links in {name}…", + "ui.edit_in_place_save_first": "Save the assembly first: its linked designs are found from its file", + "ui.finish_editing": "Finish Editing" + }, + "ar": { + "settings.edit_linked_in_place": "تنشيط مكوّن مرتبط يحرّر تصميمه في مكانه", + "ui.edit_in_place_assembly_closed": "{name} لم يعد مفتوحًا", + "ui.edit_in_place_banner": "تحرير داخل {name}", + "ui.edit_in_place_refresh_dropped": "تغيّر التجميع أثناء تحديث الروابط؛ شغّله مرة أخرى", + "ui.edit_in_place_refreshing": "جارٍ تحديث الروابط في {name}…", + "ui.edit_in_place_save_first": "احفظ التجميع أولاً: يُعثر على تصاميمه المرتبطة انطلاقًا من ملفه", + "ui.finish_editing": "إنهاء التحرير" + }, + "de": { + "settings.edit_linked_in_place": "Aktivieren einer verknüpften Komponente bearbeitet ihr Design an Ort und Stelle", + "ui.edit_in_place_assembly_closed": "{name} ist nicht mehr geöffnet", + "ui.edit_in_place_banner": "Bearbeitung in {name}", + "ui.edit_in_place_refresh_dropped": "Die Baugruppe wurde während der Aktualisierung der Verknüpfungen geändert; bitte erneut ausführen", + "ui.edit_in_place_refreshing": "Verknüpfungen in {name} werden aktualisiert…", + "ui.edit_in_place_save_first": "Zuerst die Baugruppe speichern: ihre verknüpften Designs werden von ihrer Datei aus gefunden", + "ui.finish_editing": "Bearbeitung beenden" + }, + "he": { + "settings.edit_linked_in_place": "הפעלת רכיב מקושר עורכת את התכן שלו במקומו", + "ui.edit_in_place_assembly_closed": "{name} כבר אינו פתוח", + "ui.edit_in_place_banner": "עריכה בתוך {name}", + "ui.edit_in_place_refresh_dropped": "ההרכבה השתנתה בזמן עדכון הקישורים; יש להריץ שוב", + "ui.edit_in_place_refreshing": "מעדכן קישורים ב-{name}…", + "ui.edit_in_place_save_first": "יש לשמור קודם את ההרכבה: התכנים המקושרים שלה נמצאים לפי הקובץ שלה", + "ui.finish_editing": "סיום עריכה" + }, + "ja": { + "settings.edit_linked_in_place": "リンクされたコンポーネントをアクティブにすると、そのデザインをその場で編集する", + "ui.edit_in_place_assembly_closed": "{name} はもう開いていません", + "ui.edit_in_place_banner": "{name} 内で編集中", + "ui.edit_in_place_refresh_dropped": "リンクの更新中にアセンブリが変更されました。もう一度実行してください", + "ui.edit_in_place_refreshing": "{name} のリンクを更新中…", + "ui.edit_in_place_save_first": "先にアセンブリを保存してください。リンクされたデザインはそのファイルから見つけます", + "ui.finish_editing": "編集を終了" + }, + "vi": { + "settings.edit_linked_in_place": "Kích hoạt một thành phần liên kết sẽ chỉnh sửa thiết kế của nó tại chỗ", + "ui.edit_in_place_assembly_closed": "{name} không còn mở", + "ui.edit_in_place_banner": "Đang chỉnh sửa trong {name}", + "ui.edit_in_place_refresh_dropped": "Cụm lắp ráp đã thay đổi trong khi cập nhật liên kết; hãy chạy lại", + "ui.edit_in_place_refreshing": "Đang cập nhật liên kết trong {name}…", + "ui.edit_in_place_save_first": "Hãy lưu cụm lắp ráp trước: các thiết kế liên kết của nó được tìm từ tệp của nó", + "ui.finish_editing": "Kết thúc chỉnh sửa" + }, + "zh": { + "settings.edit_linked_in_place": "激活链接组件时在原位编辑其设计", + "ui.edit_in_place_assembly_closed": "{name} 已不再打开", + "ui.edit_in_place_banner": "正在 {name} 中编辑", + "ui.edit_in_place_refresh_dropped": "更新链接期间装配体已更改;请再次运行", + "ui.edit_in_place_refreshing": "正在更新 {name} 中的链接…", + "ui.edit_in_place_save_first": "请先保存装配体:其链接设计根据其文件查找", + "ui.finish_editing": "完成编辑" + } +} diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs index 2ae93b40f74..ead4dbf9271 100644 --- a/crates/gpu/src/view.rs +++ b/crates/gpu/src/view.rs @@ -3608,6 +3608,7 @@ impl Renderer { pass.set_bind_group(0, scene_bind(pv, &res.bind), &[]); tris(pass, &res.ghost, &pv.ghost); pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); + tris(pass, &res.ghost, &m.ghost); tris(pass, &res.trans, &m.shadow); if phase == Phase::BeforeSeeThrough { return; diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index f2fb8de10c3..cd5e01f2352 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -1131,6 +1131,7 @@ fn browser_contents(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions, c } t.secondary_hline(ui.painter(), ui.max_rect().x_range(), ui.cursor().top() + 1.0, t.toolbar.lerp_to_gamma(t.border, 0.5)); ui.add_space(t.space_3); + crate::edit_in_place::browser_strip(app, ui); if collapsible && !stacked { browser_rows_hugging(app, ui, acts); } else { @@ -1390,7 +1391,7 @@ fn component_rows_inner( toggle(app, key, true); } if r.radio { - let _ = app.run("component.activate", json!({ "component": id })); + crate::edit_in_place::activate(app, json!({ "component": id })); } if r.eye { if visible { @@ -1421,7 +1422,7 @@ fn component_rows_inner( if app.session.doc.parts.contains_key(&id) { crate::dialogs_part_size::open(app, id); } else { - let _ = app.run("component.activate", json!({ "component": id })); + crate::edit_in_place::activate(app, json!({ "component": id })); } } if r.hovered { @@ -1553,7 +1554,7 @@ fn occurrence_rows_inner( let _ = app.run("browser.visibility", json!({"visible": app.session.occurrence_hidden(path), "paths": [path]})); } if r.radio || (r.double && !app.session.doc.parts.contains_key(&placement.component)) { - let _ = app.run("component.activate", json!({"component": placement.component, "occurrence": placement.occurrence, "path": path})); + crate::edit_in_place::activate(app, json!({"component": placement.component, "occurrence": placement.occurrence, "path": path})); } if r.double && app.session.doc.parts.contains_key(&placement.component) { crate::dialogs_part_size::open(app, placement.component); diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 692c2655d5b..5e1fdb7551f 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -1379,7 +1379,7 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { } "ui.activate" => { if id_of(&p, "component").is_some() { - let _ = app.run("component.activate", p); + crate::edit_in_place::activate(app, p); } } "ui.openLinkedDesign" => { diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 590e6775cff..09155b7caa1 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -32,6 +32,7 @@ pub struct DocSlot { agent_chat: crate::agent_chat::AgentChat, /// Its linked design files as the design last read them (`Documents::link_stamps`). link_stamps: Vec<(u64, crate::linked_source::Stamp)>, + edit_in_place: Option, } /// The per-design part of the UI state the session doesn't keep (what is hidden, shown or locked @@ -61,6 +62,7 @@ impl DocSlot { occurrence_move: None, agent_chat: Default::default(), link_stamps: Vec::new(), + edit_in_place: None, } } } @@ -160,6 +162,7 @@ fn swap_in(app: &mut SolveApp, mut slot: DocSlot) -> DocSlot { occurrence_move: std::mem::replace(&mut app.tree.occurrence_move, slot.occurrence_move), agent_chat: slot.agent_chat, link_stamps: std::mem::replace(&mut app.docs.link_stamps, slot.link_stamps), + edit_in_place: std::mem::replace(&mut app.edit_in_place.active, slot.edit_in_place), }; // Only the displayed design owns the process-wide crash replay journal. app.session.crash_journal = out.session.crash_journal; @@ -227,6 +230,25 @@ pub fn switch(app: &mut SolveApp, i: usize) { if app.docs.batch.is_none() && app.docs.quitting.is_none() && app.docs.closing.is_none() { crate::linked_source::update_changed(app); } + crate::edit_in_place::attach(app); +} + +/// The open design saved at `path`, shown or in the background. +pub(crate) fn session_at<'a>(app: &'a SolveApp, path: &str) -> Option<&'a Session> { + let saved_at = |s: &Session| s.path.as_deref().is_some_and(|p| same_path(p, path)); + if saved_at(&app.session) { + return Some(&app.session); + } + app.docs.slots.iter().flatten().map(|s| &s.session).find(|s| saved_at(s)) +} + +/// [`session_at`], to change it. +pub(crate) fn session_at_mut<'a>(app: &'a mut SolveApp, path: &str) -> Option<&'a mut Session> { + let saved_at = |s: &Session| s.path.as_deref().is_some_and(|p| same_path(p, path)); + if saved_at(&app.session) { + return Some(&mut app.session); + } + app.docs.slots.iter_mut().flatten().map(|s| &mut s.session).find(|s| saved_at(s)) } /// Select an already-open saved design without reloading or framing it. Identity is derived @@ -401,6 +423,7 @@ pub fn close(app: &mut SolveApp, i: usize, force: bool) { app.fit_view(); put_view(app, DocView::default()); app.docs = Documents::default(); + app.edit_in_place = Default::default(); app.home.open = true; return; } diff --git a/crates/ui-egui/src/edit_in_place.rs b/crates/ui-egui/src/edit_in_place.rs new file mode 100644 index 00000000000..5b1f9b2d839 --- /dev/null +++ b/crates/ui-egui/src/edit_in_place.rs @@ -0,0 +1,320 @@ +//! Edit in place: activating a linked component opens the design it comes from, with the rest of +//! the assembly drawn faded around it where the component sits, so its own timeline, browser and +//! commands are at hand. Finish Editing saves the part, goes back to the assembly and reads the +//! link again. +//! +//! The part is an ordinary tab: saving, autosave, recovery, closing and quitting treat it as any +//! other design. The assembly around it is a picture of the assembly's tab, taken when the edit +//! starts and again after Update Links. + +use std::sync::Arc; +use std::sync::mpsc::Receiver; + +use serde_json::{Value, json}; +use solidcraft_engine::Session; +use solidcraft_engine::doc::{Mat, apply_point, apply_vector, mat_inverse, mat_mul}; +use solidcraft_engine::geom::{Aabb3, Mesh}; + +use crate::SolveApp; +use crate::gpu::GpuScene; +use crate::theme::Tokens; + +/// The assembly around a part being edited in place. +#[derive(Clone)] +pub struct PartContext { + /// The assembly's file and name. + pub assembly: String, + pub assembly_name: String, + /// The part's file. + pub part: String, + /// The linked component edited, and the placement the assembly is drawn around. + pub component: u64, + pub placement: Vec, + /// The assembly's other bodies in the part's frame: their meshes and placements. + pub bodies: Arc, Mat)>>, + /// Their extent in the part's frame, so fitting the view frames the assembly too. + pub bounds: Aabb3, + /// The part's tab was opened for this edit, so Finish Editing closes it again. + pub opened: bool, + /// The number of tabs when the edit started (more once the part has opened in a new one). + tabs: usize, +} + +/// Update Links run on the assembly while its part is edited in place. +struct Refresh { + /// The assembly's file, and its document and revision when the run started: a result for an + /// assembly changed since is dropped. + assembly: String, + base: Arc, + revision: u64, + done: Receiver>, +} + +/// The edit in place of the tab shown, and one waiting for its part to open. +#[derive(Default)] +pub struct EditInPlace { + pub active: Option, + pending: Option, + /// Finish Editing is waiting for the part's save. + finish_after_save: bool, + refresh: Option, +} + +impl EditInPlace { + /// Update Links is running on an assembly whose part is edited in place. + pub fn refreshing(&self) -> bool { + self.refresh.is_some() + } +} + +/// Activate a component: a linked one is edited in place (Preferences: `edit_linked_in_place`), +/// any other is made the active component (`component.activate` with `params`). +pub(crate) fn activate(app: &mut SolveApp, params: Value) { + let component = params["component"].as_u64().unwrap_or(0); + if app.preferences.edit_linked_in_place && app.session.doc.links.contains_key(&component) { + let path = params["path"].as_array().map(|p| p.iter().filter_map(Value::as_u64).collect::>()); + enter(app, component, path); + } else { + let _ = app.run("component.activate", params); + } +} + +/// Something runs that a change of the design shown would spoil. +fn busy(app: &SolveApp) -> bool { + app.file_picker_busy() || app.file_load.busy() || app.saving.is_some() || app.edit_in_place.refreshing() +} + +/// The bodies of `session` around its linked component `component`, in that component's frame +/// at `placement`, with their extent. `None` when the placement is gone. +fn snapshot(session: &Session, component: u64, placement: &[u64]) -> Option<(Vec<(Arc, Mat)>, Aabb3)> { + let frame = session.occurrence_placement(placement).ok().and_then(|p| mat_inverse(&p.world))?; + let world = session.world_state(); + let bodies: Vec<_> = world + .bodies + .iter() + .filter(|b| b.component != component && session.body_visible(&b.name)) + .map(|b| { + let (mesh, placed) = b.mesh_in_place(); + (mesh, mat_mul(&frame, &placed)) + }) + .collect(); + let mut bounds = Aabb3::default(); + for (mesh, m) in &bodies { + for p in &mesh.positions { + bounds.add(apply_point(m, *p)); + } + } + Some((bodies, bounds)) +} + +/// Open the design the linked component `component` comes from, with the assembly around it as +/// its placement `path` (default: its first) puts it. +pub(crate) fn enter(app: &mut SolveApp, component: u64, path: Option>) { + if busy(app) { + return; + } + let Some(assembly) = app.session.path.clone() else { + app.set_status(crate::i18n::tr("ui.edit_in_place_save_first").to_string(), true); + return; + }; + let links = match app.session.execute("component.links", &json!({})) { + Ok(links) => links, + Err(e) => { + app.set_status(e.to_string(), true); + return; + } + }; + let Some(link) = links["links"].as_array().into_iter().flatten().find(|l| l["component"].as_u64() == Some(component)).cloned() else { + app.set_status(app.tr_label("ui.relink_not_linked").to_string(), true); + return; + }; + let Some(part) = link["file"].as_str().map(str::to_string) else { return }; + let placement = path.unwrap_or_else(|| app.session.doc.first_path(component)); + let Some((bodies, bounds)) = snapshot(&app.session, component, &placement) else { return }; + app.edit_in_place.pending = Some(PartContext { + assembly, + assembly_name: app.session.doc.name.clone(), + part, + component, + placement, + bodies: Arc::new(bodies), + bounds, + opened: false, + tabs: app.docs.count(), + }); + crate::network_prompt::open_linked(app, &link); +} + +/// The design shown has become the part an edit waits for: the edit starts there. +pub(crate) fn attach(app: &mut SolveApp) { + let shown = app.session.path.as_deref(); + let Some(mut context) = app.edit_in_place.pending.take_if(|c| shown.is_some_and(|p| crate::documents::same_path(p, &c.part))) else { + return; + }; + context.opened = app.docs.count() > context.tabs; + app.edit_in_place.active = Some(context); + app.fit_view(); +} + +/// Update Links pressed while a part is edited in place: the assembly's tab reads its links again +/// (off the window thread), and the picture around the part follows. +pub(crate) fn refresh(app: &mut SolveApp) { + if app.edit_in_place.refreshing() { + return; + } + let Some(assembly) = app.edit_in_place.active.as_ref().map(|c| c.assembly.clone()) else { return }; + let Some(session) = crate::documents::session_at(app, &assembly) else { + let name = app.edit_in_place.active.as_ref().map(|c| c.assembly_name.clone()).unwrap_or_default(); + app.set_status(crate::i18n::format("ui.edit_in_place_assembly_closed", &[("name", &name)]), true); + return; + }; + let mut scratch = session.scratch(); + // Link paths are kept relative to the design's own file. + scratch.path.clone_from(&session.path); + let (base, revision) = (session.doc.clone(), session.revision); + let (tx, done) = std::sync::mpsc::channel(); + let run = move || { + let r = scratch.execute("component.update_links", &json!({})).map(|_| scratch).map_err(|e| e.to_string()); + let _ = tx.send(r); + }; + #[cfg(not(target_arch = "wasm32"))] + if std::thread::Builder::new().name("edit-in-place-links".into()).spawn(run).is_err() { + app.set_status("could not start Update Links", true); + return; + } + #[cfg(target_arch = "wasm32")] + run(); + app.edit_in_place.refresh = Some(Refresh { assembly, base, revision, done }); + let name = app.edit_in_place.active.as_ref().map(|c| c.assembly_name.clone()).unwrap_or_default(); + app.set_status(crate::i18n::format("ui.edit_in_place_refreshing", &[("name", &name)]), false); +} + +/// Take up a finished refresh: the assembly's tab adopts it when it is still the assembly the +/// run started from, and the picture around the part is taken again. +fn take_refresh(app: &mut SolveApp) { + let Some(r) = &app.edit_in_place.refresh else { return }; + let result = match r.done.try_recv() { + Ok(result) => result, + Err(std::sync::mpsc::TryRecvError::Empty) => return, + Err(std::sync::mpsc::TryRecvError::Disconnected) => Err("Update Links stopped".into()), + }; + let Some(r) = app.edit_in_place.refresh.take() else { return }; + let computed = match result { + Ok(computed) => computed, + Err(e) => { + app.set_status(e, true); + return; + } + }; + let Some(session) = crate::documents::session_at_mut(app, &r.assembly) else { return }; + if !Arc::ptr_eq(&session.doc, &r.base) || session.revision != r.revision { + app.set_status(crate::i18n::tr("ui.edit_in_place_refresh_dropped").to_string(), true); + return; + } + session.accept_computed(computed); + let Some(context) = app.edit_in_place.active.as_ref().filter(|c| crate::documents::same_path(&c.assembly, &r.assembly)) else { return }; + let (component, placement) = (context.component, context.placement.clone()); + let Some(snap) = crate::documents::session_at(app, &r.assembly).and_then(|s| snapshot(s, component, &placement)) else { return }; + if let Some(context) = app.edit_in_place.active.as_mut() { + context.bodies = Arc::new(snap.0); + context.bounds = snap.1; + } + let language = crate::i18n::Locale::for_language(&app.preferences.language); + app.set_status(language.format("ui.command_done", &[("command", language.label(crate::command_label("component.update_links")))]), false); +} + +/// Finish Editing: save the part (and wait for it), go back to the assembly, close the part's +/// tab when the edit opened it and read the assembly's links again. +pub(crate) fn finish(app: &mut SolveApp) { + if app.edit_in_place.active.is_none() || busy(app) { + return; + } + if app.session.is_dirty() { + app.edit_in_place.finish_after_save = true; + crate::toolbar::save(app); + return; + } + let Some(context) = app.edit_in_place.active.take() else { return }; + let part_tab = app.docs.active; + match crate::documents::reuse_path(app, &context.assembly) { + Ok(true) => {} + _ => { + app.set_status(crate::i18n::format("ui.edit_in_place_assembly_closed", &[("name", &context.assembly_name)]), true); + app.edit_in_place.active = Some(context); + return; + } + } + if context.opened { + crate::documents::close(app, part_tab, false); + } + // Coming back to its tab already updates what changed (`update_changed_links`). + if !app.preferences.update_changed_links { + crate::network_prompt::update_links(app); + } +} + +/// Each frame: a refresh that finished is taken up, and Finish Editing goes on once the part's +/// save is done (a save that failed or was cancelled leaves the edit as it was). +pub(crate) fn tick(app: &mut SolveApp) { + take_refresh(app); + if app.edit_in_place.finish_after_save && app.saving.is_none() && app.file_picker.is_none() { + app.edit_in_place.finish_after_save = false; + if !app.session.is_dirty() { + finish(app); + } + } +} + +/// What the scene key needs of the edit: the assembly picture shown (0: none). +pub(crate) fn scene_key(app: &SolveApp) -> usize { + app.edit_in_place.active.as_ref().map_or(0, |c| Arc::as_ptr(&c.bodies) as usize) +} + +/// The extent of the assembly around the part, when one is shown. +pub(crate) fn bounds(app: &SolveApp) -> Option { + app.edit_in_place.active.as_ref().map(|c| c.bounds).filter(|b| !b.is_empty()) +} + +/// Draw the assembly around the part, faded and out of reach of picks. +pub(crate) fn draw_context(app: &SolveApp, sc: &mut GpuScene) { + let Some(context) = &app.edit_in_place.active else { return }; + let col = sc.color(crate::viewport::c4(Tokens::get().body.gamma_multiply(0.35))); + for (mesh, m) in context.bodies.iter() { + for t in &mesh.triangles { + for k in t { + let i = *k as usize; + if let (Some(p), Some(n)) = (mesh.positions.get(i), mesh.normals.get(i)) { + sc.ghost_tri(apply_point(m, *p).to_f32(), apply_vector(m, *n).to_f32(), col); + } + } + } + } +} + +/// Above the browser's rows while a part is edited in place: which assembly it is in, and +/// Finish Editing. +pub(crate) fn browser_strip(app: &mut SolveApp, ui: &mut egui::Ui) { + let Some(context) = &app.edit_in_place.active else { return }; + let t = Tokens::get(); + let refreshing = app.edit_in_place.refreshing(); + let key = if refreshing { "ui.edit_in_place_refreshing" } else { "ui.edit_in_place_banner" }; + let text = crate::i18n::format(key, &[("name", &context.assembly_name)]); + let mut finish_clicked = false; + ui.horizontal(|ui| { + ui.add_space(t.space_6); + crate::ui_kit::text(ui, &text, crate::ui_kit::Text::Hint("edit_in_place")); + let label = crate::i18n::tr("ui.finish_editing"); + let button = ui.add_enabled_ui(!refreshing, |ui| crate::ui_kit::button(ui, label, crate::ui_kit::Button::Small)).inner; + crate::scenario::publish_handle("edit_in_place:finish", button.rect.center()); + finish_clicked = button.clicked(); + }); + ui.add_space(t.space_3); + if finish_clicked { + finish(app); + } +} + +#[cfg(test)] +#[path = "edit_in_place_tests.rs"] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests; diff --git a/crates/ui-egui/src/edit_in_place_tests.rs b/crates/ui-egui/src/edit_in_place_tests.rs new file mode 100644 index 00000000000..9ad1bf01e19 --- /dev/null +++ b/crates/ui-egui/src/edit_in_place_tests.rs @@ -0,0 +1,255 @@ +use super::*; +use serde_json::json; +use solidcraft_engine::Session; + +fn volume_of(session: &Session, prefix: &str) -> f64 { + session + .world_state() + .bodies + .iter() + .filter(|b| b.name.starts_with(prefix)) + .map(|b| solidcraft_engine::kernel::measure(&b.body).unwrap().volume) + .sum() +} + +fn volume(app: &SolveApp) -> f64 { + volume_of(&app.session, "") +} + +/// Ticks the window's background work until it is done: opens, saves, Update Links and the +/// assembly refresh of an edit in place. +fn settle(app: &mut SolveApp) { + let ctx = egui::Context::default(); + let began = std::time::Instant::now(); + while !app.file_load.idle() || app.saving.is_some() || app.edit_in_place.finish_after_save || app.edit_in_place.refreshing() { + assert!(began.elapsed() < std::time::Duration::from_secs(120), "the background work went on"); + crate::file_load::tick(app, &ctx); + crate::save_job::tick(app, false); + tick(app); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +/// Saves a box design at `path`; `extra` adds a second box on top of it. +fn save_box(path: &std::path::Path, size: [f64; 3], extra: bool) { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": size[0], "width": size[1], "height": size[2]})).unwrap(); + if extra { + s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 10, "corner": [0, 0, size[2]], "operation": "join"})).unwrap(); + } + s.execute("file.save", &json!({"path": path, "overwrite": true})).unwrap(); +} + +struct Fixture { + app: SolveApp, + folder: std::path::PathBuf, + plate: u64, + plate_file: std::path::PathBuf, + post_file: std::path::PathBuf, +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.folder); + } +} + +/// An assembly that links a 10x20x30 plate placed 50 mm along X and a 10 mm post cube placed +/// 100 mm the other way, saved next to them. +fn assembly(name: &str) -> Fixture { + let folder = std::env::temp_dir().join(format!("solidcraft-edit-in-place-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + let (plate_file, post_file) = (folder.join("plate.solidcraft"), folder.join("post.solidcraft")); + save_box(&plate_file, [10.0, 20.0, 30.0], false); + save_box(&post_file, [10.0, 10.0, 10.0], false); + let mut app = SolveApp::new(Session::default(), Default::default()); + let plate = app.run("component.insert_design", json!({"path": plate_file, "translate": [50, 0, 0]})).unwrap()["component"].as_u64().unwrap(); + app.run("component.insert_design", json!({"path": post_file, "translate": [-100, 0, 0]})).unwrap(); + app.run("file.save", json!({"path": folder.join("case.solidcraft")})).unwrap(); + assert!((volume(&app) - 7000.0).abs() < 1e-6); + Fixture { app, folder, plate, plate_file, post_file } +} + +fn showing(app: &SolveApp, file: &std::path::Path) -> bool { + app.session.path.as_deref().is_some_and(|p| crate::documents::same_path(p, &file.to_string_lossy())) +} + +fn context(app: &SolveApp) -> PartContext { + app.edit_in_place.active.clone().expect("a part is edited in place") +} + +#[test] +fn a_linked_component_is_edited_in_place_and_finish_editing_updates_the_assembly() { + let mut f = assembly("finish"); + activate(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + // The part in a tab of its own, the post around it in the part's frame + assert_eq!(f.app.docs.count(), 2); + assert!(showing(&f.app, &f.plate_file)); + let c = context(&f.app); + assert!(c.opened); + assert_eq!(c.bodies.len(), 1, "only the post: the part's own bodies are not context"); + assert!((c.bounds.min.x - -150.0).abs() < 1e-6 && (c.bounds.max.x - -140.0).abs() < 1e-6, "{:?}", c.bounds); + assert!((volume(&f.app) - 6000.0).abs() < 1e-6, "the part's own design, not the assembly"); + // Changed and finished: saved, back in the assembly, the part's tab closed, the link read again + f.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "operation": "new"})).unwrap(); + finish(&mut f.app); + settle(&mut f.app); + assert!(f.app.edit_in_place.active.is_none()); + assert_eq!(f.app.docs.count(), 1); + assert!(f.app.session.path.as_deref().is_some_and(|p| p.ends_with("case.solidcraft"))); + assert!((volume(&f.app) - 8000.0).abs() < 1e-6, "{}", volume(&f.app)); +} + +#[test] +fn with_changed_links_left_alone_finish_editing_updates_the_assembly_itself() { + let mut f = assembly("finish-manual"); + f.app.preferences.update_changed_links = false; + activate(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + f.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "operation": "new"})).unwrap(); + finish(&mut f.app); + settle(&mut f.app); + assert_eq!(f.app.docs.count(), 1); + assert!((volume(&f.app) - 8000.0).abs() < 1e-6, "Finish Editing promises the change: {}", volume(&f.app)); +} + +#[test] +fn update_links_in_the_part_refreshes_the_assembly_around_it() { + let mut f = assembly("refresh"); + activate(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + let before = context(&f.app); + // The post grows on disk (another window, a checkout) while the plate is edited + save_box(&f.post_file, [10.0, 10.0, 10.0], true); + f.app.start("component.update_links"); + assert!(f.app.edit_in_place.refreshing(), "the assembly is read again off the window thread"); + assert!(f.app.status.as_ref().is_some_and(|(s, _, error)| s.starts_with("Updating links in") && !error), "{:?}", f.app.status); + settle(&mut f.app); + // Still in the part, the assembly's tab updated and the picture around the part with it + assert!(showing(&f.app, &f.plate_file)); + let after = context(&f.app); + assert!(!Arc::ptr_eq(&before.bodies, &after.bodies)); + assert!((after.bounds.max.z - 20.0).abs() < 1e-6, "the post's new box shows: {:?}", after.bounds); + let assembly = crate::documents::session_at(&f.app, &after.assembly).unwrap(); + assert!((volume_of(assembly, "") - 7250.0).abs() < 1e-6, "{}", volume_of(assembly, "")); + assert!(assembly.is_dirty(), "the assembly keeps its own copy of the linked bodies"); + assert_eq!(f.app.status.as_ref().map(|s| s.0.as_str()), Some("Update Links done")); + // Finishing afterwards changes nothing more in the assembly + finish(&mut f.app); + settle(&mut f.app); + assert!((volume(&f.app) - 7250.0).abs() < 1e-6, "{}", volume(&f.app)); +} + +#[test] +fn a_refresh_for_an_assembly_changed_meanwhile_is_dropped() { + let mut f = assembly("dropped"); + // Coming back to the assembly would read the changed post itself: only the edit made there counts here + f.app.preferences.update_changed_links = false; + activate(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + save_box(&f.post_file, [10.0, 10.0, 10.0], true); + refresh(&mut f.app); + // Before the result is taken up, the assembly changes in its own tab + crate::documents::switch(&mut f.app, 0); + f.app.run("solid.box", json!({"length": 1, "width": 1, "height": 1, "corner": [0, 300, 0], "operation": "new"})).unwrap(); + crate::documents::switch(&mut f.app, 1); + settle(&mut f.app); + let assembly = crate::documents::session_at(&f.app, &context(&f.app).assembly).unwrap(); + assert!((volume_of(assembly, "") - 7001.0).abs() < 1e-6, "the change made meanwhile stays, the stale result goes: {}", volume_of(assembly, "")); + assert!(f.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", f.app.status); + // Run again, it goes through + refresh(&mut f.app); + settle(&mut f.app); + let assembly = crate::documents::session_at(&f.app, &context(&f.app).assembly).unwrap(); + assert!((volume_of(assembly, "") - 7251.0).abs() < 1e-6, "{}", volume_of(assembly, "")); +} + +#[test] +fn with_the_assembly_closed_the_edit_stays_and_says_so() { + let mut f = assembly("closed"); + activate(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + crate::documents::close(&mut f.app, 0, false); + assert_eq!(f.app.docs.count(), 1); + assert!(showing(&f.app, &f.plate_file)); + refresh(&mut f.app); + assert!(!f.app.edit_in_place.refreshing()); + assert!(f.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", f.app.status); + finish(&mut f.app); + settle(&mut f.app); + assert!(f.app.edit_in_place.active.is_some(), "nothing to go back to: the edit stays"); + assert!(showing(&f.app, &f.plate_file)); + // Closing the part's tab ends the edit with it + crate::documents::close(&mut f.app, 0, true); + assert!(f.app.edit_in_place.active.is_none()); +} + +#[test] +fn a_part_already_open_is_reused_and_stays_open() { + let mut f = assembly("reused"); + let mut opened = Session::default(); + opened.execute("doc.open", &json!({"path": f.plate_file})).unwrap(); + crate::documents::open_tab(&mut f.app, opened).unwrap(); + crate::documents::switch(&mut f.app, 0); + activate(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + assert_eq!(f.app.docs.count(), 2); + assert!(showing(&f.app, &f.plate_file)); + assert!(!context(&f.app).opened); + finish(&mut f.app); + settle(&mut f.app); + assert_eq!(f.app.docs.count(), 2, "the tab was there before the edit, so it stays"); + assert!(f.app.session.path.as_deref().is_some_and(|p| p.ends_with("case.solidcraft"))); +} + +#[test] +fn a_turned_placement_draws_the_assembly_turned_the_other_way() { + let mut f = assembly("turned"); + // A quarter turn about Z through the plate's origin + let turn = json!({"occurrence": "plate:1", "space": "world", "axis": [0, 0, 1], "angle": "90 deg", "origin": [50, 0, 0], "move_grounded": true}); + f.app.run("occurrence.move", turn).unwrap(); + f.app.run("file.save", json!({})).unwrap(); + activate(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + // The post at x -100..-90, y 0..10 lies along +Y of the turned plate: x 0..10, y 140..150 + let b = context(&f.app).bounds; + assert!((b.min.y - 140.0).abs() < 1e-6 && (b.max.y - 150.0).abs() < 1e-6, "{b:?}"); + assert!((b.min.x - 0.0).abs() < 1e-6 && (b.max.x - 10.0).abs() < 1e-6, "{b:?}"); +} + +#[test] +fn a_second_placement_is_the_frame_and_no_copy_of_the_part_is_context() { + let mut f = assembly("second"); + let second = f.app.run("component.insert_design", json!({"path": f.plate_file, "translate": [0, 100, 0], "reuse": true})).unwrap(); + assert_eq!(second["component"].as_u64(), Some(f.plate), "{second}"); + f.app.run("file.save", json!({})).unwrap(); + let (_, path, world) = f.app.session.doc.placements().into_iter().find(|(c, _, world)| *c == f.plate && world[3][1] > 50.0).unwrap(); + activate(&mut f.app, json!({"component": f.plate, "path": path})); + settle(&mut f.app); + let c = context(&f.app); + assert_eq!(c.bodies.len(), 1, "both placements of the plate are the part itself"); + // The post's corner at (-100, 0) seen from the second placement, not the first + let (x, y) = (-100.0 - world[3][0], -world[3][1]); + assert!((c.bounds.min.x - x).abs() < 1e-6 && (c.bounds.min.y - y).abs() < 1e-6, "{:?} from {:?}", c.bounds, world[3]); + assert!(world[3][1] > 50.0 && (y - -100.0).abs() < 1e-6, "the frame is the second placement's: {:?}", world[3]); +} + +#[test] +fn turned_off_or_unsaved_activating_a_linked_component_does_what_it_did() { + let mut f = assembly("off"); + f.app.preferences.edit_linked_in_place = false; + activate(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + assert_eq!(f.app.session.active_component, f.plate); + assert_eq!(f.app.docs.count(), 1); + assert!(f.app.edit_in_place.active.is_none()); + // An assembly never saved has no folder to find its links from + let mut fresh = SolveApp::new(Session::default(), Default::default()); + let linked = fresh.run("component.insert_design", json!({"path": f.plate_file})).unwrap()["component"].as_u64().unwrap(); + activate(&mut fresh, json!({"component": linked})); + settle(&mut fresh); + assert!(fresh.edit_in_place.active.is_none() && fresh.edit_in_place.pending.is_none()); + assert!(fresh.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", fresh.status); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e76b0d61fb3..625d83dca5f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -61,6 +61,7 @@ pub mod drag_extrude; pub mod drag_snap; pub mod easyprint_ui; pub mod edit_clipboard; +pub mod edit_in_place; mod feature_edit; #[cfg(test)] mod font_literals_tests; @@ -495,6 +496,8 @@ pub struct SolveApp { /// OK pressed on a feature that takes a while: its evaluation runs off the window thread. pub applying: Option, pub(crate) editing_state: Option, + /// A linked component's design edited in place, with its assembly around it. + pub edit_in_place: edit_in_place::EditInPlace, pub(crate) pending_feature_edit: Option, /// A command recomputing the history (the marker moved, undo) computing off the window /// thread, and those asked for meanwhile ([`deferred`]). @@ -691,6 +694,7 @@ impl SolveApp { preview: preview::PreviewState::default(), applying: None, editing_state: None, + edit_in_place: Default::default(), pending_feature_edit: None, deferred: None, deferred_queue: Vec::new(), @@ -1308,6 +1312,13 @@ impl SolveApp { }); return; } + if id == "component.update_links" && self.edit_in_place.active.is_some() { + // In a part edited in place it also refreshes the assembly around it. + edit_in_place::refresh(self); + if self.session.doc.links.is_empty() { + 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). A link on a network server @@ -2010,7 +2021,8 @@ impl SolveApp { render_workspace::tick(self, ctx); file_load::tick(self, ctx); save_job::tick(self, false); - if self.saving.is_some() { + edit_in_place::tick(self); + if self.saving.is_some() || self.edit_in_place.refreshing() { ctx.request_repaint_after(std::time::Duration::from_millis(16)); } open_meshing::tick(self, ctx); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 1ca505fedf3..ba06d17962b 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -617,6 +617,9 @@ preference_settings! { /// A design coming back to its tab reads again the linked designs whose files changed since /// it last read them. Off: they wait for Update Links, as before. update_changed_links: bool = true, PAGE_DESIGN => check_id("settings.update_changed_links"); + /// Activating a linked component opens its design with the assembly around it + /// (`edit_in_place`). Off: it becomes the active component, as before. + edit_linked_in_place: bool = true, PAGE_DESIGN => check_id("settings.edit_linked_in_place"); /// Reopen the saved designs that were open when the app was last closed (#5542). reopen_designs: bool = true, PAGE_GENERAL; /// Those designs' files, in tab order, as the last quit left them. diff --git a/crates/ui-egui/src/prefs/design.rs b/crates/ui-egui/src/prefs/design.rs index 1cedc737fda..489785e4f88 100644 --- a/crates/ui-egui/src/prefs/design.rs +++ b/crates/ui-egui/src/prefs/design.rs @@ -80,6 +80,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { }); ui_kit::settings_section(ui, "linked_designs", app.tr("prefs.linked_designs"), |ui| { setting::update_changed_links(app, ui); + setting::edit_linked_in_place(app, ui); }); // Where the files a design names may be: never a network location the user hasn't allowed. ui_kit::settings_section(ui, "network_locations", app.tr("prefs.network_locations_section"), |ui| { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 9e2285ae47c..da80681af54 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -386,7 +386,8 @@ pub fn view_bounds(app: &SolveApp) -> solidcraft_engine::geom::Aabb3 { if crate::open_meshing::framing(app) { return solidcraft_engine::view::unmeshed_bounds(&app.session); } - solidcraft_engine::view::bounds(&app.session) + let own = solidcraft_engine::view::bounds(&app.session); + crate::edit_in_place::bounds(app).map_or(own, |context| if own.is_empty() { context } else { own.union(&context) }) } /// The middle of the shown bodies the view shows part of: what a cursor orbit begun over empty @@ -460,6 +461,7 @@ fn scene_key(app: &SolveApp) -> u64 { // Two themes may share a light/dark base while drawing different geometry colours. crate::theme_files::color_key(&Tokens::get()).hash(&mut h); app.session.active_sketch.hash(&mut h); + crate::edit_in_place::scene_key(app).hash(&mut h); // A reset palette arena (another design) invalidates every cached block's indices. app.viewport.palette.lock().map_or(0, |a| a.generation()).hash(&mut h); // Continuity seams are model-scene lines but are not part of the document or world state. @@ -1434,6 +1436,7 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene { } } } + crate::edit_in_place::draw_context(app, &mut sc); sc } @@ -1684,7 +1687,7 @@ pub(crate) fn dashes(pts: &[Vec3], pattern: &[f64]) -> Vec<(Vec3, Vec3)> { } /// Colour as straight (unpremultiplied) sRGBA bytes for the GPU. -fn c4(c: Color32) -> [u8; 4] { +pub(crate) fn c4(c: Color32) -> [u8; 4] { c.to_srgba_unmultiplied() } From 03287f6290caacfedaeb470a34e7abd8d7ca6499 Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 13:29:39 +0100 Subject: [PATCH 07/20] Edit in place: a double-click opens it, Activate only activates A double-click on a linked component edits it in place, in the browser as on a face in the view (around the placement clicked), and the component's menu gets Edit in Place. Activate and the browser's radio button make it the active component as they always did, so a linked component can still be activated without opening its design. Co-Authored-By: Claude Opus 5.5 --- assets/locales/pending/edit-in-place.json | 21 ++++--- crates/ui-egui/src/browser.rs | 11 ++-- crates/ui-egui/src/context_menu.rs | 10 +++- crates/ui-egui/src/edit_in_place.rs | 29 ++++++++- crates/ui-egui/src/edit_in_place_tests.rs | 73 +++++++++++++++++++---- crates/ui-egui/src/prefs.rs | 4 +- crates/ui-egui/src/viewport.rs | 11 ++++ 7 files changed, 132 insertions(+), 27 deletions(-) diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json index 64a381cd742..85b33b6c9d3 100644 --- a/assets/locales/pending/edit-in-place.json +++ b/assets/locales/pending/edit-in-place.json @@ -1,6 +1,7 @@ { "en": { - "settings.edit_linked_in_place": "Activating a linked component edits its design in place", + "settings.edit_linked_in_place": "Double-clicking a linked component edits its design in place", + "ui.edit_in_place": "Edit in Place", "ui.edit_in_place_assembly_closed": "{name} is no longer open", "ui.edit_in_place_banner": "Editing in {name}", "ui.edit_in_place_refresh_dropped": "The assembly changed while Update Links ran; run it again", @@ -9,7 +10,8 @@ "ui.finish_editing": "Finish Editing" }, "ar": { - "settings.edit_linked_in_place": "تنشيط مكوّن مرتبط يحرّر تصميمه في مكانه", + "settings.edit_linked_in_place": "النقر المزدوج على مكوّن مرتبط يحرّر تصميمه في مكانه", + "ui.edit_in_place": "تحرير في المكان", "ui.edit_in_place_assembly_closed": "{name} لم يعد مفتوحًا", "ui.edit_in_place_banner": "تحرير داخل {name}", "ui.edit_in_place_refresh_dropped": "تغيّر التجميع أثناء تحديث الروابط؛ شغّله مرة أخرى", @@ -18,7 +20,8 @@ "ui.finish_editing": "إنهاء التحرير" }, "de": { - "settings.edit_linked_in_place": "Aktivieren einer verknüpften Komponente bearbeitet ihr Design an Ort und Stelle", + "settings.edit_linked_in_place": "Doppelklick auf eine verknüpfte Komponente bearbeitet ihr Design an Ort und Stelle", + "ui.edit_in_place": "An Ort und Stelle bearbeiten", "ui.edit_in_place_assembly_closed": "{name} ist nicht mehr geöffnet", "ui.edit_in_place_banner": "Bearbeitung in {name}", "ui.edit_in_place_refresh_dropped": "Die Baugruppe wurde während der Aktualisierung der Verknüpfungen geändert; bitte erneut ausführen", @@ -27,7 +30,8 @@ "ui.finish_editing": "Bearbeitung beenden" }, "he": { - "settings.edit_linked_in_place": "הפעלת רכיב מקושר עורכת את התכן שלו במקומו", + "settings.edit_linked_in_place": "לחיצה כפולה על רכיב מקושר עורכת את התכן שלו במקומו", + "ui.edit_in_place": "עריכה במקום", "ui.edit_in_place_assembly_closed": "{name} כבר אינו פתוח", "ui.edit_in_place_banner": "עריכה בתוך {name}", "ui.edit_in_place_refresh_dropped": "ההרכבה השתנתה בזמן עדכון הקישורים; יש להריץ שוב", @@ -36,7 +40,8 @@ "ui.finish_editing": "סיום עריכה" }, "ja": { - "settings.edit_linked_in_place": "リンクされたコンポーネントをアクティブにすると、そのデザインをその場で編集する", + "settings.edit_linked_in_place": "リンクされたコンポーネントをダブルクリックすると、そのデザインをその場で編集する", + "ui.edit_in_place": "その場で編集", "ui.edit_in_place_assembly_closed": "{name} はもう開いていません", "ui.edit_in_place_banner": "{name} 内で編集中", "ui.edit_in_place_refresh_dropped": "リンクの更新中にアセンブリが変更されました。もう一度実行してください", @@ -45,7 +50,8 @@ "ui.finish_editing": "編集を終了" }, "vi": { - "settings.edit_linked_in_place": "Kích hoạt một thành phần liên kết sẽ chỉnh sửa thiết kế của nó tại chỗ", + "settings.edit_linked_in_place": "Nhấp đúp vào một thành phần liên kết sẽ chỉnh sửa thiết kế của nó tại chỗ", + "ui.edit_in_place": "Chỉnh sửa tại chỗ", "ui.edit_in_place_assembly_closed": "{name} không còn mở", "ui.edit_in_place_banner": "Đang chỉnh sửa trong {name}", "ui.edit_in_place_refresh_dropped": "Cụm lắp ráp đã thay đổi trong khi cập nhật liên kết; hãy chạy lại", @@ -54,7 +60,8 @@ "ui.finish_editing": "Kết thúc chỉnh sửa" }, "zh": { - "settings.edit_linked_in_place": "激活链接组件时在原位编辑其设计", + "settings.edit_linked_in_place": "双击链接组件时在原位编辑其设计", + "ui.edit_in_place": "原位编辑", "ui.edit_in_place_assembly_closed": "{name} 已不再打开", "ui.edit_in_place_banner": "正在 {name} 中编辑", "ui.edit_in_place_refresh_dropped": "更新链接期间装配体已更改;请再次运行", diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index cd5e01f2352..b564c235ff3 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -1391,7 +1391,7 @@ fn component_rows_inner( toggle(app, key, true); } if r.radio { - crate::edit_in_place::activate(app, json!({ "component": id })); + let _ = app.run("component.activate", json!({ "component": id })); } if r.eye { if visible { @@ -1422,7 +1422,7 @@ fn component_rows_inner( if app.session.doc.parts.contains_key(&id) { crate::dialogs_part_size::open(app, id); } else { - crate::edit_in_place::activate(app, json!({ "component": id })); + crate::edit_in_place::double_click_component(app, json!({ "component": id })); } } if r.hovered { @@ -1553,8 +1553,11 @@ fn occurrence_rows_inner( if r.eye { let _ = app.run("browser.visibility", json!({"visible": app.session.occurrence_hidden(path), "paths": [path]})); } - if r.radio || (r.double && !app.session.doc.parts.contains_key(&placement.component)) { - crate::edit_in_place::activate(app, json!({"component": placement.component, "occurrence": placement.occurrence, "path": path})); + let params = json!({"component": placement.component, "occurrence": placement.occurrence, "path": path}); + if r.radio { + let _ = app.run("component.activate", params); + } else if r.double && !app.session.doc.parts.contains_key(&placement.component) { + crate::edit_in_place::double_click_component(app, params); } if r.double && app.session.doc.parts.contains_key(&placement.component) { crate::dialogs_part_size::open(app, placement.component); diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 5e1fdb7551f..315d7b64646 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -777,6 +777,7 @@ fn occurrence_items(app: &SolveApp, path: &[u64]) -> Vec { item.params = Some(json!({"component": placement.component, "occurrence": placement.occurrence, "path": path})); item.enabled = app.session.active_occurrence_path.as_deref() != Some(path); } + "ui.editInPlace" => item.params = Some(json!({"component": placement.component, "path": path})), "occurrence.ground" => { item.label = if placement.grounded { "Unground" } else { "Ground" }.into(); item.params = Some(json!({"occurrence": placement.occurrence, "grounded": !placement.grounded})); @@ -851,6 +852,7 @@ fn component_items(app: &SolveApp, id: u64) -> Vec { let oid = occ.map(|o| o.id).unwrap_or(0); v.push(act("ui.activate", "Activate", "component").with(json!({ "component": id })).on(!active)); if doc.links.contains_key(&id) { + v.push(act("ui.editInPlace", "Edit in Place", "edit").with(json!({ "component": id }))); v.push(act("ui.openLinkedDesign", "Open Linked Design", "open").with(json!({ "component": id }))); } v.push(cmd(app, "occurrence.ground", if grounded { "Unground" } else { "Ground" }).with(json!({ "occurrence": oid, "grounded": !grounded }))); @@ -1379,7 +1381,13 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { } "ui.activate" => { if id_of(&p, "component").is_some() { - crate::edit_in_place::activate(app, p); + let _ = app.run("component.activate", p); + } + } + "ui.editInPlace" => { + if let Some(component) = id_of(&p, "component") { + let path = p["path"].as_array().map(|path| path.iter().filter_map(Value::as_u64).collect()); + crate::edit_in_place::enter(app, component, path); } } "ui.openLinkedDesign" => { diff --git a/crates/ui-egui/src/edit_in_place.rs b/crates/ui-egui/src/edit_in_place.rs index 5b1f9b2d839..2865868e776 100644 --- a/crates/ui-egui/src/edit_in_place.rs +++ b/crates/ui-egui/src/edit_in_place.rs @@ -67,9 +67,10 @@ impl EditInPlace { } } -/// Activate a component: a linked one is edited in place (Preferences: `edit_linked_in_place`), -/// any other is made the active component (`component.activate` with `params`). -pub(crate) fn activate(app: &mut SolveApp, params: Value) { +/// A component double-clicked in the browser: a linked one is edited in place (Preferences: +/// `edit_linked_in_place`), any other is made the active component (`component.activate` with +/// `params`). Activate itself always does the latter. +pub(crate) fn double_click_component(app: &mut SolveApp, params: Value) { let component = params["component"].as_u64().unwrap_or(0); if app.preferences.edit_linked_in_place && app.session.doc.links.contains_key(&component) { let path = params["path"].as_array().map(|p| p.iter().filter_map(Value::as_u64).collect::>()); @@ -79,6 +80,28 @@ pub(crate) fn activate(app: &mut SolveApp, params: Value) { } } +/// A face of the body `body` double-clicked in the view: when it is a linked component's, that +/// component is edited in place around the placement the body belongs to. Whether it was. +pub(crate) fn double_click_face(app: &mut SolveApp, body: &str) -> bool { + if !app.preferences.edit_linked_in_place { + return false; + } + let Some(component) = app.session.world_state().body(body).map(|b| b.component) else { return false }; + if !app.session.doc.links.contains_key(&component) { + return false; + } + let placement = app + .session + .doc + .placements() + .into_iter() + .filter(|(c, _, _)| *c == component) + .map(|(_, path, _)| path) + .find(|path| app.session.occurrence_bodies(path, true).is_ok_and(|bodies| bodies.iter().any(|b| b == body))); + enter(app, component, placement); + true +} + /// Something runs that a change of the design shown would spoil. fn busy(app: &SolveApp) -> bool { app.file_picker_busy() || app.file_load.busy() || app.saving.is_some() || app.edit_in_place.refreshing() diff --git a/crates/ui-egui/src/edit_in_place_tests.rs b/crates/ui-egui/src/edit_in_place_tests.rs index 9ad1bf01e19..85e394f56aa 100644 --- a/crates/ui-egui/src/edit_in_place_tests.rs +++ b/crates/ui-egui/src/edit_in_place_tests.rs @@ -82,7 +82,7 @@ fn context(app: &SolveApp) -> PartContext { #[test] fn a_linked_component_is_edited_in_place_and_finish_editing_updates_the_assembly() { let mut f = assembly("finish"); - activate(&mut f.app, json!({"component": f.plate})); + double_click_component(&mut f.app, json!({"component": f.plate})); settle(&mut f.app); // The part in a tab of its own, the post around it in the part's frame assert_eq!(f.app.docs.count(), 2); @@ -106,7 +106,7 @@ fn a_linked_component_is_edited_in_place_and_finish_editing_updates_the_assembly fn with_changed_links_left_alone_finish_editing_updates_the_assembly_itself() { let mut f = assembly("finish-manual"); f.app.preferences.update_changed_links = false; - activate(&mut f.app, json!({"component": f.plate})); + double_click_component(&mut f.app, json!({"component": f.plate})); settle(&mut f.app); f.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "operation": "new"})).unwrap(); finish(&mut f.app); @@ -118,7 +118,7 @@ fn with_changed_links_left_alone_finish_editing_updates_the_assembly_itself() { #[test] fn update_links_in_the_part_refreshes_the_assembly_around_it() { let mut f = assembly("refresh"); - activate(&mut f.app, json!({"component": f.plate})); + double_click_component(&mut f.app, json!({"component": f.plate})); settle(&mut f.app); let before = context(&f.app); // The post grows on disk (another window, a checkout) while the plate is edited @@ -147,7 +147,7 @@ fn a_refresh_for_an_assembly_changed_meanwhile_is_dropped() { let mut f = assembly("dropped"); // Coming back to the assembly would read the changed post itself: only the edit made there counts here f.app.preferences.update_changed_links = false; - activate(&mut f.app, json!({"component": f.plate})); + double_click_component(&mut f.app, json!({"component": f.plate})); settle(&mut f.app); save_box(&f.post_file, [10.0, 10.0, 10.0], true); refresh(&mut f.app); @@ -169,7 +169,7 @@ fn a_refresh_for_an_assembly_changed_meanwhile_is_dropped() { #[test] fn with_the_assembly_closed_the_edit_stays_and_says_so() { let mut f = assembly("closed"); - activate(&mut f.app, json!({"component": f.plate})); + double_click_component(&mut f.app, json!({"component": f.plate})); settle(&mut f.app); crate::documents::close(&mut f.app, 0, false); assert_eq!(f.app.docs.count(), 1); @@ -193,7 +193,7 @@ fn a_part_already_open_is_reused_and_stays_open() { opened.execute("doc.open", &json!({"path": f.plate_file})).unwrap(); crate::documents::open_tab(&mut f.app, opened).unwrap(); crate::documents::switch(&mut f.app, 0); - activate(&mut f.app, json!({"component": f.plate})); + double_click_component(&mut f.app, json!({"component": f.plate})); settle(&mut f.app); assert_eq!(f.app.docs.count(), 2); assert!(showing(&f.app, &f.plate_file)); @@ -211,7 +211,7 @@ fn a_turned_placement_draws_the_assembly_turned_the_other_way() { let turn = json!({"occurrence": "plate:1", "space": "world", "axis": [0, 0, 1], "angle": "90 deg", "origin": [50, 0, 0], "move_grounded": true}); f.app.run("occurrence.move", turn).unwrap(); f.app.run("file.save", json!({})).unwrap(); - activate(&mut f.app, json!({"component": f.plate})); + double_click_component(&mut f.app, json!({"component": f.plate})); settle(&mut f.app); // The post at x -100..-90, y 0..10 lies along +Y of the turned plate: x 0..10, y 140..150 let b = context(&f.app).bounds; @@ -226,7 +226,7 @@ fn a_second_placement_is_the_frame_and_no_copy_of_the_part_is_context() { assert_eq!(second["component"].as_u64(), Some(f.plate), "{second}"); f.app.run("file.save", json!({})).unwrap(); let (_, path, world) = f.app.session.doc.placements().into_iter().find(|(c, _, world)| *c == f.plate && world[3][1] > 50.0).unwrap(); - activate(&mut f.app, json!({"component": f.plate, "path": path})); + double_click_component(&mut f.app, json!({"component": f.plate, "path": path})); settle(&mut f.app); let c = context(&f.app); assert_eq!(c.bodies.len(), 1, "both placements of the plate are the part itself"); @@ -236,11 +236,64 @@ fn a_second_placement_is_the_frame_and_no_copy_of_the_part_is_context() { assert!(world[3][1] > 50.0 && (y - -100.0).abs() < 1e-6, "the frame is the second placement's: {:?}", world[3]); } +#[test] +fn double_clicking_a_linked_part_in_the_view_edits_the_placement_clicked() { + let mut f = assembly("double"); + f.app.run("component.insert_design", json!({"path": f.plate_file, "translate": [0, 100, 0], "reuse": true})).unwrap(); + f.app.run("file.save", json!({})).unwrap(); + let (_, path, world) = f.app.session.doc.placements().into_iter().find(|(c, _, world)| *c == f.plate && world[3][1] > 50.0).unwrap(); + let body = f.app.session.occurrence_bodies(&path, true).unwrap().into_iter().next().unwrap(); + assert!(double_click_face(&mut f.app, &body)); + settle(&mut f.app); + assert!(showing(&f.app, &f.plate_file)); + let c = context(&f.app); + assert_eq!(c.placement, path, "the placement whose face was clicked, not the first one"); + assert!((c.bounds.min.y - -world[3][1]).abs() < 1e-6, "{:?}", c.bounds); +} + +#[test] +fn double_clicking_a_body_of_this_design_or_with_the_preference_off_does_nothing_here() { + let mut f = assembly("double-off"); + let made = f.app.run("solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [0, -200, 0], "operation": "new"})).unwrap(); + let own = made["created_bodies"][0].as_str().unwrap().to_string(); + assert!(!double_click_face(&mut f.app, &own), "a body modelled here is not a linked design"); + let linked = f.app.session.occurrence_bodies(&f.app.session.doc.first_path(f.plate), true).unwrap().into_iter().next().unwrap(); + f.app.preferences.edit_linked_in_place = false; + assert!(!double_click_face(&mut f.app, &linked)); + settle(&mut f.app); + assert_eq!(f.app.docs.count(), 1); + assert!(f.app.edit_in_place.active.is_none() && f.app.edit_in_place.pending.is_none()); +} + +#[test] +fn activate_only_activates_and_edit_in_place_opens_the_placement_right_clicked() { + use crate::context_menu::{self, Target}; + let mut f = assembly("menu"); + let inserted = f.app.run("component.insert_design", json!({"path": f.plate_file, "translate": [0, 100, 0], "reuse": true})).unwrap(); + let second = inserted["occurrence"].as_u64().unwrap(); + f.app.run("file.save", json!({})).unwrap(); + let item = |app: &SolveApp, target: Target, id: &str| context_menu::items(app, &target).into_iter().find(|i| i.id == id).unwrap(); + // Activate: the linked component becomes the active one, nothing opens + let activate = item(&f.app, Target::Component { id: f.plate }, "ui.activate"); + context_menu::run_item(&mut f.app, &activate, egui::Pos2::ZERO); + settle(&mut f.app); + assert_eq!(f.app.session.active_component, f.plate); + assert_eq!(f.app.docs.count(), 1); + assert!(f.app.edit_in_place.active.is_none() && f.app.edit_in_place.pending.is_none()); + // Edit in Place on the second placement: the part opens around that one + let path = f.app.session.doc.placements().into_iter().map(|(_, path, _)| path).find(|p| p.last() == Some(&second)).unwrap(); + let edit = item(&f.app, Target::Occurrence { path: path.clone() }, "ui.editInPlace"); + context_menu::run_item(&mut f.app, &edit, egui::Pos2::ZERO); + settle(&mut f.app); + assert!(showing(&f.app, &f.plate_file)); + assert_eq!(context(&f.app).placement, path); +} + #[test] fn turned_off_or_unsaved_activating_a_linked_component_does_what_it_did() { let mut f = assembly("off"); f.app.preferences.edit_linked_in_place = false; - activate(&mut f.app, json!({"component": f.plate})); + double_click_component(&mut f.app, json!({"component": f.plate})); settle(&mut f.app); assert_eq!(f.app.session.active_component, f.plate); assert_eq!(f.app.docs.count(), 1); @@ -248,7 +301,7 @@ fn turned_off_or_unsaved_activating_a_linked_component_does_what_it_did() { // An assembly never saved has no folder to find its links from let mut fresh = SolveApp::new(Session::default(), Default::default()); let linked = fresh.run("component.insert_design", json!({"path": f.plate_file})).unwrap()["component"].as_u64().unwrap(); - activate(&mut fresh, json!({"component": linked})); + double_click_component(&mut fresh, json!({"component": linked})); settle(&mut fresh); assert!(fresh.edit_in_place.active.is_none() && fresh.edit_in_place.pending.is_none()); assert!(fresh.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", fresh.status); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index ba06d17962b..3abcb9e9863 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -617,8 +617,8 @@ preference_settings! { /// A design coming back to its tab reads again the linked designs whose files changed since /// it last read them. Off: they wait for Update Links, as before. update_changed_links: bool = true, PAGE_DESIGN => check_id("settings.update_changed_links"); - /// Activating a linked component opens its design with the assembly around it - /// (`edit_in_place`). Off: it becomes the active component, as before. + /// Double-clicking a linked component, in the browser or the view, opens its design with the + /// assembly around it (`edit_in_place`). Off: a double-click activates it, as before. edit_linked_in_place: bool = true, PAGE_DESIGN => check_id("settings.edit_linked_in_place"); /// Reopen the saved designs that were open when the app was last closed (#5542). reopen_designs: bool = true, PAGE_GENERAL; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index da80681af54..a04ec14b732 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -4160,6 +4160,17 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { .collect(); let _ = app.run("select.set", json!({ "items": items, "add": add })); } + // Double-click a linked component's face: edit its design in place. + if resp.double_clicked() + && !held + && !dim_edit + && app.tool.is_none() + && app.dialog.is_none() + && app.session.active_sketch.is_none() + && let Some(Hit::Face { body, .. }) = app.viewport.hover.clone() + { + crate::edit_in_place::double_click_face(app, &body); + } // A right-click, unless the same press opened the mouse gestures' ring. if resp.secondary_clicked() && delta == egui::Vec2::ZERO && !crate::mouse_gesture::took_press(app) { if app.tool.is_some() { From 2513e5b91ea5e00dd5691e60d7f4e246c67778df Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 13:38:37 +0100 Subject: [PATCH 08/20] Double-click on a component's face: edit a linked one in place, activate any other A double-click on a face in the view activates the component the body belongs to, at that placement, as a double-click on its row does; a linked one is edited in place. Bodies of the design itself or of the active component are left alone, and so is a double-click with a modifier. One preference, double_click_components, covers both gestures. Co-Authored-By: Claude Opus 5.5 --- assets/locales/pending/edit-in-place.json | 14 +++++----- crates/ui-egui/src/edit_in_place.rs | 31 ++++++++++++++--------- crates/ui-egui/src/edit_in_place_tests.rs | 19 ++++++++++++-- crates/ui-egui/src/prefs.rs | 8 +++--- crates/ui-egui/src/prefs/design.rs | 2 +- crates/ui-egui/src/viewport.rs | 3 ++- 6 files changed, 51 insertions(+), 26 deletions(-) diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json index 85b33b6c9d3..55b27cdcbe8 100644 --- a/assets/locales/pending/edit-in-place.json +++ b/assets/locales/pending/edit-in-place.json @@ -1,6 +1,6 @@ { "en": { - "settings.edit_linked_in_place": "Double-clicking a linked component edits its design in place", + "settings.double_click_components": "Double-click a component to activate it, or to edit a linked one in place", "ui.edit_in_place": "Edit in Place", "ui.edit_in_place_assembly_closed": "{name} is no longer open", "ui.edit_in_place_banner": "Editing in {name}", @@ -10,7 +10,7 @@ "ui.finish_editing": "Finish Editing" }, "ar": { - "settings.edit_linked_in_place": "النقر المزدوج على مكوّن مرتبط يحرّر تصميمه في مكانه", + "settings.double_click_components": "انقر نقرًا مزدوجًا على مكوّن لتنشيطه، أو لتحرير مكوّن مرتبط في مكانه", "ui.edit_in_place": "تحرير في المكان", "ui.edit_in_place_assembly_closed": "{name} لم يعد مفتوحًا", "ui.edit_in_place_banner": "تحرير داخل {name}", @@ -20,7 +20,7 @@ "ui.finish_editing": "إنهاء التحرير" }, "de": { - "settings.edit_linked_in_place": "Doppelklick auf eine verknüpfte Komponente bearbeitet ihr Design an Ort und Stelle", + "settings.double_click_components": "Doppelklick auf eine Komponente aktiviert sie oder bearbeitet eine verknüpfte an Ort und Stelle", "ui.edit_in_place": "An Ort und Stelle bearbeiten", "ui.edit_in_place_assembly_closed": "{name} ist nicht mehr geöffnet", "ui.edit_in_place_banner": "Bearbeitung in {name}", @@ -30,7 +30,7 @@ "ui.finish_editing": "Bearbeitung beenden" }, "he": { - "settings.edit_linked_in_place": "לחיצה כפולה על רכיב מקושר עורכת את התכן שלו במקומו", + "settings.double_click_components": "לחיצה כפולה על רכיב מפעילה אותו, או עורכת רכיב מקושר במקומו", "ui.edit_in_place": "עריכה במקום", "ui.edit_in_place_assembly_closed": "{name} כבר אינו פתוח", "ui.edit_in_place_banner": "עריכה בתוך {name}", @@ -40,7 +40,7 @@ "ui.finish_editing": "סיום עריכה" }, "ja": { - "settings.edit_linked_in_place": "リンクされたコンポーネントをダブルクリックすると、そのデザインをその場で編集する", + "settings.double_click_components": "コンポーネントをダブルクリックしてアクティブにする、またはリンクされたものをその場で編集する", "ui.edit_in_place": "その場で編集", "ui.edit_in_place_assembly_closed": "{name} はもう開いていません", "ui.edit_in_place_banner": "{name} 内で編集中", @@ -50,7 +50,7 @@ "ui.finish_editing": "編集を終了" }, "vi": { - "settings.edit_linked_in_place": "Nhấp đúp vào một thành phần liên kết sẽ chỉnh sửa thiết kế của nó tại chỗ", + "settings.double_click_components": "Nhấp đúp vào một thành phần để kích hoạt nó, hoặc chỉnh sửa tại chỗ một thành phần liên kết", "ui.edit_in_place": "Chỉnh sửa tại chỗ", "ui.edit_in_place_assembly_closed": "{name} không còn mở", "ui.edit_in_place_banner": "Đang chỉnh sửa trong {name}", @@ -60,7 +60,7 @@ "ui.finish_editing": "Kết thúc chỉnh sửa" }, "zh": { - "settings.edit_linked_in_place": "双击链接组件时在原位编辑其设计", + "settings.double_click_components": "双击组件以激活它,或在原位编辑链接组件", "ui.edit_in_place": "原位编辑", "ui.edit_in_place_assembly_closed": "{name} 已不再打开", "ui.edit_in_place_banner": "正在 {name} 中编辑", diff --git a/crates/ui-egui/src/edit_in_place.rs b/crates/ui-egui/src/edit_in_place.rs index 2865868e776..8d372925a05 100644 --- a/crates/ui-egui/src/edit_in_place.rs +++ b/crates/ui-egui/src/edit_in_place.rs @@ -68,11 +68,11 @@ impl EditInPlace { } /// A component double-clicked in the browser: a linked one is edited in place (Preferences: -/// `edit_linked_in_place`), any other is made the active component (`component.activate` with -/// `params`). Activate itself always does the latter. +/// `double_click_components`), any other is made the active component (`component.activate` +/// with `params`). Activate itself always does the latter. pub(crate) fn double_click_component(app: &mut SolveApp, params: Value) { let component = params["component"].as_u64().unwrap_or(0); - if app.preferences.edit_linked_in_place && app.session.doc.links.contains_key(&component) { + if app.preferences.double_click_components && app.session.doc.links.contains_key(&component) { let path = params["path"].as_array().map(|p| p.iter().filter_map(Value::as_u64).collect::>()); enter(app, component, path); } else { @@ -80,16 +80,14 @@ pub(crate) fn double_click_component(app: &mut SolveApp, params: Value) { } } -/// A face of the body `body` double-clicked in the view: when it is a linked component's, that -/// component is edited in place around the placement the body belongs to. Whether it was. +/// A face of the body `body` double-clicked in the view: the component the body belongs to, at +/// that body's placement, is edited in place when it is linked and activated otherwise. A body of +/// the design itself or of the active component is left alone, as are features. Whether it acted. pub(crate) fn double_click_face(app: &mut SolveApp, body: &str) -> bool { - if !app.preferences.edit_linked_in_place { - return false; - } - let Some(component) = app.session.world_state().body(body).map(|b| b.component) else { return false }; - if !app.session.doc.links.contains_key(&component) { + if !app.preferences.double_click_components { return false; } + let Some(component) = app.session.world_state().body(body).map(|b| b.component).filter(|c| *c != 0) else { return false }; let placement = app .session .doc @@ -98,8 +96,17 @@ pub(crate) fn double_click_face(app: &mut SolveApp, body: &str) -> bool { .filter(|(c, _, _)| *c == component) .map(|(_, path, _)| path) .find(|path| app.session.occurrence_bodies(path, true).is_ok_and(|bodies| bodies.iter().any(|b| b == body))); - enter(app, component, placement); - true + if app.session.doc.links.contains_key(&component) { + enter(app, component, placement); + return true; + } + let active = app.session.active_component == component + && (placement.is_none() || app.session.active_occurrence_path.is_none() || app.session.active_occurrence_path == placement); + if active { + return false; + } + let occurrence = placement.as_ref().and_then(|p| p.last().copied()); + app.run("component.activate", json!({"component": component, "occurrence": occurrence, "path": placement})).is_ok() } /// Something runs that a change of the design shown would spoil. diff --git a/crates/ui-egui/src/edit_in_place_tests.rs b/crates/ui-egui/src/edit_in_place_tests.rs index 85e394f56aa..1e5a399d074 100644 --- a/crates/ui-egui/src/edit_in_place_tests.rs +++ b/crates/ui-egui/src/edit_in_place_tests.rs @@ -251,6 +251,21 @@ fn double_clicking_a_linked_part_in_the_view_edits_the_placement_clicked() { assert!((c.bounds.min.y - -world[3][1]).abs() < 1e-6, "{:?}", c.bounds); } +#[test] +fn double_clicking_a_component_modelled_here_activates_it_once() { + let mut f = assembly("double-activate"); + let bracket = f.app.run("component.create", json!({"name": "Bracket"})).unwrap()["component"].as_u64().unwrap(); + let made = f.app.run("solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [0, -200, 0]})).unwrap(); + let body = made["created_bodies"][0].as_str().unwrap().to_string(); + f.app.run("component.activate", json!({"component": "root"})).unwrap(); + assert!(double_click_face(&mut f.app, &body)); + assert_eq!(f.app.session.active_component, bracket); + assert_eq!(f.app.docs.count(), 1, "a component modelled here opens nothing"); + assert!(f.app.edit_in_place.active.is_none() && f.app.edit_in_place.pending.is_none()); + // Active already: the double-click is left to whatever the face itself offers + assert!(!double_click_face(&mut f.app, &body)); +} + #[test] fn double_clicking_a_body_of_this_design_or_with_the_preference_off_does_nothing_here() { let mut f = assembly("double-off"); @@ -258,7 +273,7 @@ fn double_clicking_a_body_of_this_design_or_with_the_preference_off_does_nothing let own = made["created_bodies"][0].as_str().unwrap().to_string(); assert!(!double_click_face(&mut f.app, &own), "a body modelled here is not a linked design"); let linked = f.app.session.occurrence_bodies(&f.app.session.doc.first_path(f.plate), true).unwrap().into_iter().next().unwrap(); - f.app.preferences.edit_linked_in_place = false; + f.app.preferences.double_click_components = false; assert!(!double_click_face(&mut f.app, &linked)); settle(&mut f.app); assert_eq!(f.app.docs.count(), 1); @@ -292,7 +307,7 @@ fn activate_only_activates_and_edit_in_place_opens_the_placement_right_clicked() #[test] fn turned_off_or_unsaved_activating_a_linked_component_does_what_it_did() { let mut f = assembly("off"); - f.app.preferences.edit_linked_in_place = false; + f.app.preferences.double_click_components = false; double_click_component(&mut f.app, json!({"component": f.plate})); settle(&mut f.app); assert_eq!(f.app.session.active_component, f.plate); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 3abcb9e9863..2a6e2e2ebf5 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -617,9 +617,11 @@ preference_settings! { /// A design coming back to its tab reads again the linked designs whose files changed since /// it last read them. Off: they wait for Update Links, as before. update_changed_links: bool = true, PAGE_DESIGN => check_id("settings.update_changed_links"); - /// Double-clicking a linked component, in the browser or the view, opens its design with the - /// assembly around it (`edit_in_place`). Off: a double-click activates it, as before. - edit_linked_in_place: bool = true, PAGE_DESIGN => check_id("settings.edit_linked_in_place"); + /// A double-click on a component, in the browser or on its face in the view, opens a linked + /// one's design with the assembly around it (`edit_in_place`) and activates any other. Off: + /// a double-click in the browser activates every component and one in the view does nothing, + /// as before. + double_click_components: bool = true, PAGE_DESIGN => check_id("settings.double_click_components"); /// Reopen the saved designs that were open when the app was last closed (#5542). reopen_designs: bool = true, PAGE_GENERAL; /// Those designs' files, in tab order, as the last quit left them. diff --git a/crates/ui-egui/src/prefs/design.rs b/crates/ui-egui/src/prefs/design.rs index 489785e4f88..7ea8f28c65c 100644 --- a/crates/ui-egui/src/prefs/design.rs +++ b/crates/ui-egui/src/prefs/design.rs @@ -80,7 +80,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { }); ui_kit::settings_section(ui, "linked_designs", app.tr("prefs.linked_designs"), |ui| { setting::update_changed_links(app, ui); - setting::edit_linked_in_place(app, ui); + setting::double_click_components(app, ui); }); // Where the files a design names may be: never a network location the user hasn't allowed. ui_kit::settings_section(ui, "network_locations", app.tr("prefs.network_locations_section"), |ui| { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index a04ec14b732..71adf7efe77 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -4160,10 +4160,11 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { .collect(); let _ = app.run("select.set", json!({ "items": items, "add": add })); } - // Double-click a linked component's face: edit its design in place. + // Double-click a component's face: edit a linked one in place, activate any other. if resp.double_clicked() && !held && !dim_edit + && mods.is_none() && app.tool.is_none() && app.dialog.is_none() && app.session.active_sketch.is_none() From f0c0180877f80cb5633dfb614186a68bb842b303 Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 14:53:54 +0100 Subject: [PATCH 09/20] Edit in place: fixes from review An edit whose part never opens is forgotten instead of starting on a later open of the same file, and the web build starts the edit after its synchronous open. Finish Editing goes on only for a save into the linked file and in the part's own tab, waits for a "changed on disk" answer, and says so when the part was saved elsewhere. Showing the assembly no longer drops a refresh, which now records the links it read so coming back reads nothing twice. The faded assembly is worked out once per picture, a bad mesh index skips its whole triangle, and the last two status texts come from the catalogs. Co-Authored-By: Claude Opus 5.5 --- assets/locales/pending/edit-in-place.json | 14 +++ crates/ui-egui/src/documents.rs | 16 +++ crates/ui-egui/src/edit_in_place.rs | 124 ++++++++++++---------- crates/ui-egui/src/edit_in_place_tests.rs | 68 ++++++++++-- crates/ui-egui/src/file_load.rs | 2 + crates/ui-egui/src/linked_source.rs | 12 ++- 6 files changed, 167 insertions(+), 69 deletions(-) diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json index 55b27cdcbe8..c7f4f991897 100644 --- a/assets/locales/pending/edit-in-place.json +++ b/assets/locales/pending/edit-in-place.json @@ -5,8 +5,10 @@ "ui.edit_in_place_assembly_closed": "{name} is no longer open", "ui.edit_in_place_banner": "Editing in {name}", "ui.edit_in_place_refresh_dropped": "The assembly changed while Update Links ran; run it again", + "ui.edit_in_place_refresh_stopped": "Update Links stopped before it was done", "ui.edit_in_place_refreshing": "Updating links in {name}…", "ui.edit_in_place_save_first": "Save the assembly first: its linked designs are found from its file", + "ui.edit_in_place_saved_elsewhere": "The part was saved to another file; the assembly still links {name}", "ui.finish_editing": "Finish Editing" }, "ar": { @@ -15,8 +17,10 @@ "ui.edit_in_place_assembly_closed": "{name} لم يعد مفتوحًا", "ui.edit_in_place_banner": "تحرير داخل {name}", "ui.edit_in_place_refresh_dropped": "تغيّر التجميع أثناء تحديث الروابط؛ شغّله مرة أخرى", + "ui.edit_in_place_refresh_stopped": "توقّف تحديث الروابط قبل أن ينتهي", "ui.edit_in_place_refreshing": "جارٍ تحديث الروابط في {name}…", "ui.edit_in_place_save_first": "احفظ التجميع أولاً: يُعثر على تصاميمه المرتبطة انطلاقًا من ملفه", + "ui.edit_in_place_saved_elsewhere": "حُفظ الجزء في ملف آخر؛ ما زال التجميع مرتبطًا بـ {name}", "ui.finish_editing": "إنهاء التحرير" }, "de": { @@ -25,8 +29,10 @@ "ui.edit_in_place_assembly_closed": "{name} ist nicht mehr geöffnet", "ui.edit_in_place_banner": "Bearbeitung in {name}", "ui.edit_in_place_refresh_dropped": "Die Baugruppe wurde während der Aktualisierung der Verknüpfungen geändert; bitte erneut ausführen", + "ui.edit_in_place_refresh_stopped": "Die Aktualisierung der Verknüpfungen wurde vorzeitig beendet", "ui.edit_in_place_refreshing": "Verknüpfungen in {name} werden aktualisiert…", "ui.edit_in_place_save_first": "Zuerst die Baugruppe speichern: ihre verknüpften Designs werden von ihrer Datei aus gefunden", + "ui.edit_in_place_saved_elsewhere": "Das Teil wurde in eine andere Datei gespeichert; die Baugruppe verknüpft weiterhin {name}", "ui.finish_editing": "Bearbeitung beenden" }, "he": { @@ -35,8 +41,10 @@ "ui.edit_in_place_assembly_closed": "{name} כבר אינו פתוח", "ui.edit_in_place_banner": "עריכה בתוך {name}", "ui.edit_in_place_refresh_dropped": "ההרכבה השתנתה בזמן עדכון הקישורים; יש להריץ שוב", + "ui.edit_in_place_refresh_stopped": "עדכון הקישורים נעצר לפני שהסתיים", "ui.edit_in_place_refreshing": "מעדכן קישורים ב-{name}…", "ui.edit_in_place_save_first": "יש לשמור קודם את ההרכבה: התכנים המקושרים שלה נמצאים לפי הקובץ שלה", + "ui.edit_in_place_saved_elsewhere": "החלק נשמר לקובץ אחר; ההרכבה עדיין מקושרת אל {name}", "ui.finish_editing": "סיום עריכה" }, "ja": { @@ -45,8 +53,10 @@ "ui.edit_in_place_assembly_closed": "{name} はもう開いていません", "ui.edit_in_place_banner": "{name} 内で編集中", "ui.edit_in_place_refresh_dropped": "リンクの更新中にアセンブリが変更されました。もう一度実行してください", + "ui.edit_in_place_refresh_stopped": "リンクの更新が完了前に停止しました", "ui.edit_in_place_refreshing": "{name} のリンクを更新中…", "ui.edit_in_place_save_first": "先にアセンブリを保存してください。リンクされたデザインはそのファイルから見つけます", + "ui.edit_in_place_saved_elsewhere": "部品は別のファイルに保存されました。アセンブリは引き続き {name} にリンクしています", "ui.finish_editing": "編集を終了" }, "vi": { @@ -55,8 +65,10 @@ "ui.edit_in_place_assembly_closed": "{name} không còn mở", "ui.edit_in_place_banner": "Đang chỉnh sửa trong {name}", "ui.edit_in_place_refresh_dropped": "Cụm lắp ráp đã thay đổi trong khi cập nhật liên kết; hãy chạy lại", + "ui.edit_in_place_refresh_stopped": "Cập nhật liên kết đã dừng trước khi hoàn tất", "ui.edit_in_place_refreshing": "Đang cập nhật liên kết trong {name}…", "ui.edit_in_place_save_first": "Hãy lưu cụm lắp ráp trước: các thiết kế liên kết của nó được tìm từ tệp của nó", + "ui.edit_in_place_saved_elsewhere": "Chi tiết đã được lưu vào tệp khác; cụm lắp ráp vẫn liên kết với {name}", "ui.finish_editing": "Kết thúc chỉnh sửa" }, "zh": { @@ -65,8 +77,10 @@ "ui.edit_in_place_assembly_closed": "{name} 已不再打开", "ui.edit_in_place_banner": "正在 {name} 中编辑", "ui.edit_in_place_refresh_dropped": "更新链接期间装配体已更改;请再次运行", + "ui.edit_in_place_refresh_stopped": "更新链接在完成前已停止", "ui.edit_in_place_refreshing": "正在更新 {name} 中的链接…", "ui.edit_in_place_save_first": "请先保存装配体:其链接设计根据其文件查找", + "ui.edit_in_place_saved_elsewhere": "零件已保存到其他文件;装配体仍链接 {name}", "ui.finish_editing": "完成编辑" } } diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 09155b7caa1..022d25aae73 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -242,6 +242,22 @@ pub(crate) fn session_at<'a>(app: &'a SolveApp, path: &str) -> Option<&'a Sessio app.docs.slots.iter().flatten().map(|s| &s.session).find(|s| saved_at(s)) } +/// The open design saved at `path` read every link again without an error: its record of them +/// (`Documents::link_stamps`, or its tab's) is now its files as they are. +pub(crate) fn read_again_at(app: &mut SolveApp, path: &str) { + if app.session.path.as_deref().is_some_and(|p| same_path(p, path)) { + crate::linked_source::read_again(app, None); + return; + } + let on = app.preferences.update_changed_links; + let saved_at = |s: &DocSlot| s.session.path.as_deref().is_some_and(|p| same_path(p, path)); + if let Some(slot) = app.docs.slots.iter_mut().flatten().find(|s| saved_at(s)) { + for (c, s) in crate::linked_source::stamps_of(&mut slot.session, on) { + crate::linked_source::record(&mut slot.link_stamps, c, s); + } + } +} + /// [`session_at`], to change it. pub(crate) fn session_at_mut<'a>(app: &'a mut SolveApp, path: &str) -> Option<&'a mut Session> { let saved_at = |s: &Session| s.path.as_deref().is_some_and(|p| same_path(p, path)); diff --git a/crates/ui-egui/src/edit_in_place.rs b/crates/ui-egui/src/edit_in_place.rs index 8d372925a05..422f5fd4535 100644 --- a/crates/ui-egui/src/edit_in_place.rs +++ b/crates/ui-egui/src/edit_in_place.rs @@ -1,7 +1,7 @@ -//! Edit in place: activating a linked component opens the design it comes from, with the rest of -//! the assembly drawn faded around it where the component sits, so its own timeline, browser and -//! commands are at hand. Finish Editing saves the part, goes back to the assembly and reads the -//! link again. +//! Edit in place: double-clicking a linked component opens the design it comes from, with the +//! rest of the assembly drawn faded around it where the component sits, so its own timeline, +//! browser and commands are at hand. Finish Editing saves the part and goes back to the assembly, +//! which reads the link again. //! //! The part is an ordinary tab: saving, autosave, recovery, closing and quitting treat it as any //! other design. The assembly around it is a picture of the assembly's tab, taken when the edit @@ -12,8 +12,8 @@ use std::sync::mpsc::Receiver; use serde_json::{Value, json}; use solidcraft_engine::Session; -use solidcraft_engine::doc::{Mat, apply_point, apply_vector, mat_inverse, mat_mul}; -use solidcraft_engine::geom::{Aabb3, Mesh}; +use solidcraft_engine::doc::{apply_point, apply_vector, mat_inverse, mat_mul}; +use solidcraft_engine::geom::Aabb3; use crate::SolveApp; use crate::gpu::GpuScene; @@ -30,8 +30,10 @@ pub struct PartContext { /// The linked component edited, and the placement the assembly is drawn around. pub component: u64, pub placement: Vec, - /// The assembly's other bodies in the part's frame: their meshes and placements. - pub bodies: Arc, Mat)>>, + /// How many of the assembly's bodies are drawn around the part. + pub bodies: usize, + /// Their triangles in the part's frame, three points and normals each, worked out once. + pub triangles: Arc>, /// Their extent in the part's frame, so fitting the view frames the assembly too. pub bounds: Aabb3, /// The part's tab was opened for this edit, so Finish Editing closes it again. @@ -42,11 +44,10 @@ pub struct PartContext { /// Update Links run on the assembly while its part is edited in place. struct Refresh { - /// The assembly's file, and its document and revision when the run started: a result for an - /// assembly changed since is dropped. + /// The assembly's file, and its document when the run started: a result for an assembly + /// changed since is dropped (showing it changes nothing). assembly: String, base: Arc, - revision: u64, done: Receiver>, } @@ -55,8 +56,8 @@ struct Refresh { pub struct EditInPlace { pub active: Option, pending: Option, - /// Finish Editing is waiting for the part's save. - finish_after_save: bool, + /// Finish Editing is waiting for the save of the part at this file. + finish_after_save: Option, refresh: Option, } @@ -115,26 +116,26 @@ fn busy(app: &SolveApp) -> bool { } /// The bodies of `session` around its linked component `component`, in that component's frame -/// at `placement`, with their extent. `None` when the placement is gone. -fn snapshot(session: &Session, component: u64, placement: &[u64]) -> Option<(Vec<(Arc, Mat)>, Aabb3)> { +/// at `placement`: how many, their triangles and their extent. `None` when the placement is gone. +fn snapshot(session: &Session, component: u64, placement: &[u64]) -> Option<(usize, Vec<([f32; 3], [f32; 3])>, Aabb3)> { let frame = session.occurrence_placement(placement).ok().and_then(|p| mat_inverse(&p.world))?; let world = session.world_state(); - let bodies: Vec<_> = world - .bodies - .iter() - .filter(|b| b.component != component && session.body_visible(&b.name)) - .map(|b| { - let (mesh, placed) = b.mesh_in_place(); - (mesh, mat_mul(&frame, &placed)) - }) - .collect(); - let mut bounds = Aabb3::default(); - for (mesh, m) in &bodies { - for p in &mesh.positions { - bounds.add(apply_point(m, *p)); + let (mut bodies, mut triangles, mut bounds) = (0, Vec::new(), Aabb3::default()); + for b in world.bodies.iter().filter(|b| b.component != component && session.body_visible(&b.name)) { + let (mesh, placed) = b.mesh_in_place(); + let m = mat_mul(&frame, &placed); + bodies += 1; + for t in &mesh.triangles { + // A triangle with an index out of range is left out whole, so the rest stay in step. + let corners: Option> = t.iter().map(|k| Some((*mesh.positions.get(*k as usize)?, *mesh.normals.get(*k as usize)?))).collect(); + for (p, n) in corners.into_iter().flatten() { + let p = apply_point(&m, p); + bounds.add(p); + triangles.push((p.to_f32(), apply_vector(&m, n).to_f32())); + } } } - Some((bodies, bounds)) + Some((bodies, triangles, bounds)) } /// Open the design the linked component `component` comes from, with the assembly around it as @@ -160,14 +161,15 @@ pub(crate) fn enter(app: &mut SolveApp, component: u64, path: Option>) }; let Some(part) = link["file"].as_str().map(str::to_string) else { return }; let placement = path.unwrap_or_else(|| app.session.doc.first_path(component)); - let Some((bodies, bounds)) = snapshot(&app.session, component, &placement) else { return }; + let Some((bodies, triangles, bounds)) = snapshot(&app.session, component, &placement) else { return }; app.edit_in_place.pending = Some(PartContext { assembly, assembly_name: app.session.doc.name.clone(), part, component, placement, - bodies: Arc::new(bodies), + bodies, + triangles: Arc::new(triangles), bounds, opened: false, tabs: app.docs.count(), @@ -175,7 +177,8 @@ pub(crate) fn enter(app: &mut SolveApp, component: u64, path: Option>) crate::network_prompt::open_linked(app, &link); } -/// The design shown has become the part an edit waits for: the edit starts there. +/// The design shown has become the part an edit waits for: the edit starts there. An edit whose +/// part did not open (the open failed or was cancelled) is dropped by [`tick`]. pub(crate) fn attach(app: &mut SolveApp) { let shown = app.session.path.as_deref(); let Some(mut context) = app.edit_in_place.pending.take_if(|c| shown.is_some_and(|p| crate::documents::same_path(p, &c.part))) else { @@ -201,7 +204,7 @@ pub(crate) fn refresh(app: &mut SolveApp) { let mut scratch = session.scratch(); // Link paths are kept relative to the design's own file. scratch.path.clone_from(&session.path); - let (base, revision) = (session.doc.clone(), session.revision); + let base = session.doc.clone(); let (tx, done) = std::sync::mpsc::channel(); let run = move || { let r = scratch.execute("component.update_links", &json!({})).map(|_| scratch).map_err(|e| e.to_string()); @@ -209,12 +212,12 @@ pub(crate) fn refresh(app: &mut SolveApp) { }; #[cfg(not(target_arch = "wasm32"))] if std::thread::Builder::new().name("edit-in-place-links".into()).spawn(run).is_err() { - app.set_status("could not start Update Links", true); + app.set_status(crate::i18n::tr("ui.edit_in_place_refresh_stopped").to_string(), true); return; } #[cfg(target_arch = "wasm32")] run(); - app.edit_in_place.refresh = Some(Refresh { assembly, base, revision, done }); + app.edit_in_place.refresh = Some(Refresh { assembly, base, done }); let name = app.edit_in_place.active.as_ref().map(|c| c.assembly_name.clone()).unwrap_or_default(); app.set_status(crate::i18n::format("ui.edit_in_place_refreshing", &[("name", &name)]), false); } @@ -226,7 +229,7 @@ fn take_refresh(app: &mut SolveApp) { let result = match r.done.try_recv() { Ok(result) => result, Err(std::sync::mpsc::TryRecvError::Empty) => return, - Err(std::sync::mpsc::TryRecvError::Disconnected) => Err("Update Links stopped".into()), + Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(crate::i18n::tr("ui.edit_in_place_refresh_stopped").to_string()), }; let Some(r) = app.edit_in_place.refresh.take() else { return }; let computed = match result { @@ -237,17 +240,19 @@ fn take_refresh(app: &mut SolveApp) { } }; let Some(session) = crate::documents::session_at_mut(app, &r.assembly) else { return }; - if !Arc::ptr_eq(&session.doc, &r.base) || session.revision != r.revision { + if !Arc::ptr_eq(&session.doc, &r.base) { app.set_status(crate::i18n::tr("ui.edit_in_place_refresh_dropped").to_string(), true); return; } session.accept_computed(computed); + // Every link was read: coming back to the assembly need not read them again. + crate::documents::read_again_at(app, &r.assembly); let Some(context) = app.edit_in_place.active.as_ref().filter(|c| crate::documents::same_path(&c.assembly, &r.assembly)) else { return }; let (component, placement) = (context.component, context.placement.clone()); - let Some(snap) = crate::documents::session_at(app, &r.assembly).and_then(|s| snapshot(s, component, &placement)) else { return }; + let snap = crate::documents::session_at(app, &r.assembly).and_then(|s| snapshot(s, component, &placement)); + let Some((bodies, triangles, bounds)) = snap else { return }; if let Some(context) = app.edit_in_place.active.as_mut() { - context.bodies = Arc::new(snap.0); - context.bounds = snap.1; + (context.bodies, context.triangles, context.bounds) = (bodies, Arc::new(triangles), bounds); } let language = crate::i18n::Locale::for_language(&app.preferences.language); app.set_status(language.format("ui.command_done", &[("command", language.label(crate::command_label("component.update_links")))]), false); @@ -256,11 +261,18 @@ fn take_refresh(app: &mut SolveApp) { /// Finish Editing: save the part (and wait for it), go back to the assembly, close the part's /// tab when the edit opened it and read the assembly's links again. pub(crate) fn finish(app: &mut SolveApp) { - if app.edit_in_place.active.is_none() || busy(app) { + let Some(part) = app.edit_in_place.active.as_ref().map(|c| c.part.clone()) else { return }; + if busy(app) { + return; + } + // Saved to another file (Save As, a copy of a read-only design): the assembly still links this one. + if !app.session.path.as_deref().is_some_and(|p| crate::documents::same_path(p, &part)) { + let name = std::path::Path::new(&part).file_stem().map_or_else(|| part.clone(), |n| n.to_string_lossy().into_owned()); + app.set_status(crate::i18n::format("ui.edit_in_place_saved_elsewhere", &[("name", &name)]), true); return; } if app.session.is_dirty() { - app.edit_in_place.finish_after_save = true; + app.edit_in_place.finish_after_save = Some(part); crate::toolbar::save(app); return; } @@ -283,13 +295,18 @@ pub(crate) fn finish(app: &mut SolveApp) { } } -/// Each frame: a refresh that finished is taken up, and Finish Editing goes on once the part's -/// save is done (a save that failed or was cancelled leaves the edit as it was). +/// Each frame: a refresh that finished is taken up; an edit waiting for a part that nothing will +/// open any more is dropped; and Finish Editing goes on once the part's save is done, in the +/// part's own tab (a save that failed, was cancelled or went elsewhere leaves the edit as it was). pub(crate) fn tick(app: &mut SolveApp) { take_refresh(app); - if app.edit_in_place.finish_after_save && app.saving.is_none() && app.file_picker.is_none() { - app.edit_in_place.finish_after_save = false; - if !app.session.is_dirty() { + if app.edit_in_place.pending.is_some() && !app.file_load.busy() && app.network_prompt.is_none() && app.lock_prompts.is_empty() { + app.edit_in_place.pending = None; + } + let waiting = app.saving.is_some() || app.file_picker.is_some() || app.disk_prompt; + if !waiting && let Some(part) = app.edit_in_place.finish_after_save.take() { + let shown = app.session.path.as_deref().is_some_and(|p| crate::documents::same_path(p, &part)); + if shown && !app.session.is_dirty() { finish(app); } } @@ -297,7 +314,7 @@ pub(crate) fn tick(app: &mut SolveApp) { /// What the scene key needs of the edit: the assembly picture shown (0: none). pub(crate) fn scene_key(app: &SolveApp) -> usize { - app.edit_in_place.active.as_ref().map_or(0, |c| Arc::as_ptr(&c.bodies) as usize) + app.edit_in_place.active.as_ref().map_or(0, |c| Arc::as_ptr(&c.triangles) as usize) } /// The extent of the assembly around the part, when one is shown. @@ -309,15 +326,8 @@ pub(crate) fn bounds(app: &SolveApp) -> Option { pub(crate) fn draw_context(app: &SolveApp, sc: &mut GpuScene) { let Some(context) = &app.edit_in_place.active else { return }; let col = sc.color(crate::viewport::c4(Tokens::get().body.gamma_multiply(0.35))); - for (mesh, m) in context.bodies.iter() { - for t in &mesh.triangles { - for k in t { - let i = *k as usize; - if let (Some(p), Some(n)) = (mesh.positions.get(i), mesh.normals.get(i)) { - sc.ghost_tri(apply_point(m, *p).to_f32(), apply_vector(m, *n).to_f32(), col); - } - } - } + for (p, n) in context.triangles.iter() { + sc.ghost_tri(*p, *n, col); } } diff --git a/crates/ui-egui/src/edit_in_place_tests.rs b/crates/ui-egui/src/edit_in_place_tests.rs index 1e5a399d074..60f7f2ff4de 100644 --- a/crates/ui-egui/src/edit_in_place_tests.rs +++ b/crates/ui-egui/src/edit_in_place_tests.rs @@ -16,16 +16,20 @@ fn volume(app: &SolveApp) -> f64 { volume_of(&app.session, "") } -/// Ticks the window's background work until it is done: opens, saves, Update Links and the -/// assembly refresh of an edit in place. +/// Ticks the window's background work, at least one frame's worth, until it is done: opens, +/// saves, Update Links and the assembly refresh of an edit in place. fn settle(app: &mut SolveApp) { let ctx = egui::Context::default(); let began = std::time::Instant::now(); - while !app.file_load.idle() || app.saving.is_some() || app.edit_in_place.finish_after_save || app.edit_in_place.refreshing() { - assert!(began.elapsed() < std::time::Duration::from_secs(120), "the background work went on"); + loop { crate::file_load::tick(app, &ctx); crate::save_job::tick(app, false); tick(app); + let busy = !app.file_load.idle() || app.saving.is_some() || app.edit_in_place.finish_after_save.is_some() || app.edit_in_place.refreshing(); + if !busy { + return; + } + assert!(began.elapsed() < std::time::Duration::from_secs(120), "the background work went on"); std::thread::sleep(std::time::Duration::from_millis(1)); } } @@ -89,7 +93,7 @@ fn a_linked_component_is_edited_in_place_and_finish_editing_updates_the_assembly assert!(showing(&f.app, &f.plate_file)); let c = context(&f.app); assert!(c.opened); - assert_eq!(c.bodies.len(), 1, "only the post: the part's own bodies are not context"); + assert_eq!(c.bodies, 1, "only the post: the part's own bodies are not context"); assert!((c.bounds.min.x - -150.0).abs() < 1e-6 && (c.bounds.max.x - -140.0).abs() < 1e-6, "{:?}", c.bounds); assert!((volume(&f.app) - 6000.0).abs() < 1e-6, "the part's own design, not the assembly"); // Changed and finished: saved, back in the assembly, the part's tab closed, the link read again @@ -130,18 +134,64 @@ fn update_links_in_the_part_refreshes_the_assembly_around_it() { // Still in the part, the assembly's tab updated and the picture around the part with it assert!(showing(&f.app, &f.plate_file)); let after = context(&f.app); - assert!(!Arc::ptr_eq(&before.bodies, &after.bodies)); + assert!(!Arc::ptr_eq(&before.triangles, &after.triangles)); assert!((after.bounds.max.z - 20.0).abs() < 1e-6, "the post's new box shows: {:?}", after.bounds); let assembly = crate::documents::session_at(&f.app, &after.assembly).unwrap(); assert!((volume_of(assembly, "") - 7250.0).abs() < 1e-6, "{}", volume_of(assembly, "")); assert!(assembly.is_dirty(), "the assembly keeps its own copy of the linked bodies"); assert_eq!(f.app.status.as_ref().map(|s| s.0.as_str()), Some("Update Links done")); - // Finishing afterwards changes nothing more in the assembly + // Finishing afterwards reads nothing again: the refresh read every link finish(&mut f.app); + assert!(f.app.file_load.idle(), "the assembly read its links in the refresh already"); settle(&mut f.app); assert!((volume(&f.app) - 7250.0).abs() < 1e-6, "{}", volume(&f.app)); } +#[test] +fn looking_at_the_assembly_while_it_refreshes_keeps_the_refresh() { + let mut f = assembly("looked"); + f.app.preferences.update_changed_links = false; + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + save_box(&f.post_file, [10.0, 10.0, 10.0], true); + refresh(&mut f.app); + crate::documents::switch(&mut f.app, 0); + crate::documents::switch(&mut f.app, 1); + settle(&mut f.app); + let assembly = crate::documents::session_at(&f.app, &context(&f.app).assembly).unwrap(); + assert!((volume_of(assembly, "") - 7250.0).abs() < 1e-6, "showing the assembly changes nothing in it: {}", volume_of(assembly, "")); +} + +#[test] +fn an_edit_whose_part_does_not_open_is_forgotten() { + let mut f = assembly("unopened"); + std::fs::remove_file(&f.plate_file).unwrap(); + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + assert!(f.app.edit_in_place.active.is_none() && f.app.edit_in_place.pending.is_none()); + assert_eq!(f.app.docs.count(), 1); + // The part opened by hand later is a plain tab, not an old edit + save_box(&f.plate_file, [10.0, 20.0, 30.0], false); + let mut opened = Session::default(); + opened.execute("doc.open", &json!({"path": f.plate_file})).unwrap(); + crate::documents::open_tab(&mut f.app, opened).unwrap(); + assert!(showing(&f.app, &f.plate_file)); + assert!(f.app.edit_in_place.active.is_none()); +} + +#[test] +fn finishing_a_part_saved_to_another_file_keeps_the_edit_and_says_so() { + let mut f = assembly("elsewhere"); + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + f.app.run("file.save", json!({"path": f.folder.join("copy.solidcraft")})).unwrap(); + finish(&mut f.app); + settle(&mut f.app); + assert!(f.app.edit_in_place.active.is_some(), "the assembly still links the part, not the copy"); + assert!(f.app.session.path.as_deref().is_some_and(|p| p.ends_with("copy.solidcraft"))); + assert!(f.app.status.as_ref().is_some_and(|(s, _, error)| *error && s.contains("plate")), "{:?}", f.app.status); +} + #[test] fn a_refresh_for_an_assembly_changed_meanwhile_is_dropped() { let mut f = assembly("dropped"); @@ -229,7 +279,7 @@ fn a_second_placement_is_the_frame_and_no_copy_of_the_part_is_context() { double_click_component(&mut f.app, json!({"component": f.plate, "path": path})); settle(&mut f.app); let c = context(&f.app); - assert_eq!(c.bodies.len(), 1, "both placements of the plate are the part itself"); + assert_eq!(c.bodies, 1, "both placements of the plate are the part itself"); // The post's corner at (-100, 0) seen from the second placement, not the first let (x, y) = (-100.0 - world[3][0], -world[3][1]); assert!((c.bounds.min.x - x).abs() < 1e-6 && (c.bounds.min.y - y).abs() < 1e-6, "{:?} from {:?}", c.bounds, world[3]); @@ -305,7 +355,7 @@ fn activate_only_activates_and_edit_in_place_opens_the_placement_right_clicked() } #[test] -fn turned_off_or_unsaved_activating_a_linked_component_does_what_it_did() { +fn turned_off_or_unsaved_double_clicking_a_linked_component_does_what_it_did() { let mut f = assembly("off"); f.app.preferences.double_click_components = false; double_click_component(&mut f.app, json!({"component": f.plate})); diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index 0f94b8aa085..49b03233ef3 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -257,6 +257,8 @@ pub fn begin_request(app: &mut SolveApp, request: Request) -> Result<(), String> } Kind::Open => { app.open_path(&request.path); + // Opened in place of the blank tab it made, with no switch to it. + crate::edit_in_place::attach(app); Ok(Value::Null) } Kind::Recover { .. } => { diff --git a/crates/ui-egui/src/linked_source.rs b/crates/ui-egui/src/linked_source.rs index 27f3f692a4b..e89160ae1f8 100644 --- a/crates/ui-egui/src/linked_source.rs +++ b/crates/ui-egui/src/linked_source.rs @@ -126,10 +126,16 @@ fn stamp(file: &str) -> Stamp { /// file that is missing, or on a network location not allowed, which is never looked at /// (`component.links` reports it unfound). The web build keeps no times, so it looks at nothing. fn disk_stamps(app: &mut SolveApp) -> Vec<(u64, Stamp)> { - if cfg!(target_arch = "wasm32") || !app.preferences.update_changed_links || app.session.doc.links.is_empty() { + let on = app.preferences.update_changed_links; + stamps_of(&mut app.session, on) +} + +/// [`disk_stamps`] for any open design (`on`: the preference `update_changed_links`). +pub(crate) fn stamps_of(session: &mut solidcraft_engine::Session, on: bool) -> Vec<(u64, Stamp)> { + if cfg!(target_arch = "wasm32") || !on || session.doc.links.is_empty() { return Vec::new(); } - let Ok(links) = app.session.execute("component.links", &json!({})) else { return Vec::new() }; + let Ok(links) = session.execute("component.links", &json!({})) else { return Vec::new() }; links["links"] .as_array() .into_iter() @@ -142,7 +148,7 @@ fn disk_stamps(app: &mut SolveApp) -> Vec<(u64, Stamp)> { } /// Set `component`'s entry in `stamps` (each link's file as the design last read it). -fn record(stamps: &mut Vec<(u64, Stamp)>, component: u64, stamp: Stamp) { +pub(crate) fn record(stamps: &mut Vec<(u64, Stamp)>, component: u64, stamp: Stamp) { match stamps.iter_mut().find(|(c, _)| *c == component) { Some(entry) => entry.1 = stamp, None => stamps.push((component, stamp)), From 7f66211a11fbc2b42b03d8969a82ebdc9b378f48 Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 15:10:37 +0100 Subject: [PATCH 10/20] Edit in place: Finish Editing on the MODEL tab and the mouse's back button Finish Editing is a command now, component.finish_edit, with its schemas: the app window answers it, anywhere else nothing changes, as with view.fit. While a linked design is edited in place the MODEL tab ends with a FINISH EDITING panel, pinned at the right as FINISH SKETCH is, with a new left-arrow icon; the browser keeps only the line naming the assembly. The mouse's back button, or a keyboard's Back key, finishes too unless a dialog, tool or sketch is open. The assembly guide describes editing in place. Co-Authored-By: Claude Opus 5.5 --- assets/icons/ui/design/requested_icons.txt | 1 + .../icons/ui/design/svg/model/finish_edit.svg | 4 ++ assets/locales/pending/edit-in-place.json | 21 ++++++---- attribution/pending/finish-edit-icon.md | 1 + crates/engine/src/cmd/component.rs | 17 ++++++++ crates/engine/src/schema/component.rs | 23 +++++++++++ crates/engine/src/schema/component_tests.rs | 23 +++++++++++ crates/engine/src/schema/mod.rs | 1 + crates/ui-egui/src/edit_in_place.rs | 25 ++++++------ crates/ui-egui/src/edit_in_place_tests.rs | 39 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 7 ++++ crates/ui-egui/src/toolbar.rs | 10 +++-- crates/ui-egui/src/workspace.rs | 3 ++ docs/book/src/guide/assemblies.md | 12 ++++++ 14 files changed, 164 insertions(+), 23 deletions(-) create mode 100644 assets/icons/ui/design/svg/model/finish_edit.svg create mode 100644 attribution/pending/finish-edit-icon.md create mode 100644 crates/engine/src/schema/component.rs create mode 100644 crates/engine/src/schema/component_tests.rs diff --git a/assets/icons/ui/design/requested_icons.txt b/assets/icons/ui/design/requested_icons.txt index 3676e1c56f6..64cb8cb0c81 100644 --- a/assets/icons/ui/design/requested_icons.txt +++ b/assets/icons/ui/design/requested_icons.txt @@ -101,6 +101,7 @@ eye false fastener false fillet false finish false +finish_edit false fit false fit_section false flange false diff --git a/assets/icons/ui/design/svg/model/finish_edit.svg b/assets/icons/ui/design/svg/model/finish_edit.svg new file mode 100644 index 00000000000..60de7219776 --- /dev/null +++ b/assets/icons/ui/design/svg/model/finish_edit.svg @@ -0,0 +1,4 @@ + + Finish Edit + + diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json index c7f4f991897..017debe83ed 100644 --- a/assets/locales/pending/edit-in-place.json +++ b/assets/locales/pending/edit-in-place.json @@ -1,6 +1,7 @@ { "en": { "settings.double_click_components": "Double-click a component to activate it, or to edit a linked one in place", + "ui.heading_finish_editing": "FINISH EDITING", "ui.edit_in_place": "Edit in Place", "ui.edit_in_place_assembly_closed": "{name} is no longer open", "ui.edit_in_place_banner": "Editing in {name}", @@ -9,10 +10,11 @@ "ui.edit_in_place_refreshing": "Updating links in {name}…", "ui.edit_in_place_save_first": "Save the assembly first: its linked designs are found from its file", "ui.edit_in_place_saved_elsewhere": "The part was saved to another file; the assembly still links {name}", - "ui.finish_editing": "Finish Editing" + "cmd.component_finish_edit": "Finish Editing" }, "ar": { "settings.double_click_components": "انقر نقرًا مزدوجًا على مكوّن لتنشيطه، أو لتحرير مكوّن مرتبط في مكانه", + "ui.heading_finish_editing": "إنهاء التحرير", "ui.edit_in_place": "تحرير في المكان", "ui.edit_in_place_assembly_closed": "{name} لم يعد مفتوحًا", "ui.edit_in_place_banner": "تحرير داخل {name}", @@ -21,10 +23,11 @@ "ui.edit_in_place_refreshing": "جارٍ تحديث الروابط في {name}…", "ui.edit_in_place_save_first": "احفظ التجميع أولاً: يُعثر على تصاميمه المرتبطة انطلاقًا من ملفه", "ui.edit_in_place_saved_elsewhere": "حُفظ الجزء في ملف آخر؛ ما زال التجميع مرتبطًا بـ {name}", - "ui.finish_editing": "إنهاء التحرير" + "cmd.component_finish_edit": "إنهاء التحرير" }, "de": { "settings.double_click_components": "Doppelklick auf eine Komponente aktiviert sie oder bearbeitet eine verknüpfte an Ort und Stelle", + "ui.heading_finish_editing": "BEARBEITUNG BEENDEN", "ui.edit_in_place": "An Ort und Stelle bearbeiten", "ui.edit_in_place_assembly_closed": "{name} ist nicht mehr geöffnet", "ui.edit_in_place_banner": "Bearbeitung in {name}", @@ -33,10 +36,11 @@ "ui.edit_in_place_refreshing": "Verknüpfungen in {name} werden aktualisiert…", "ui.edit_in_place_save_first": "Zuerst die Baugruppe speichern: ihre verknüpften Designs werden von ihrer Datei aus gefunden", "ui.edit_in_place_saved_elsewhere": "Das Teil wurde in eine andere Datei gespeichert; die Baugruppe verknüpft weiterhin {name}", - "ui.finish_editing": "Bearbeitung beenden" + "cmd.component_finish_edit": "Bearbeitung beenden" }, "he": { "settings.double_click_components": "לחיצה כפולה על רכיב מפעילה אותו, או עורכת רכיב מקושר במקומו", + "ui.heading_finish_editing": "סיום עריכה", "ui.edit_in_place": "עריכה במקום", "ui.edit_in_place_assembly_closed": "{name} כבר אינו פתוח", "ui.edit_in_place_banner": "עריכה בתוך {name}", @@ -45,10 +49,11 @@ "ui.edit_in_place_refreshing": "מעדכן קישורים ב-{name}…", "ui.edit_in_place_save_first": "יש לשמור קודם את ההרכבה: התכנים המקושרים שלה נמצאים לפי הקובץ שלה", "ui.edit_in_place_saved_elsewhere": "החלק נשמר לקובץ אחר; ההרכבה עדיין מקושרת אל {name}", - "ui.finish_editing": "סיום עריכה" + "cmd.component_finish_edit": "סיום עריכה" }, "ja": { "settings.double_click_components": "コンポーネントをダブルクリックしてアクティブにする、またはリンクされたものをその場で編集する", + "ui.heading_finish_editing": "編集を終了", "ui.edit_in_place": "その場で編集", "ui.edit_in_place_assembly_closed": "{name} はもう開いていません", "ui.edit_in_place_banner": "{name} 内で編集中", @@ -57,10 +62,11 @@ "ui.edit_in_place_refreshing": "{name} のリンクを更新中…", "ui.edit_in_place_save_first": "先にアセンブリを保存してください。リンクされたデザインはそのファイルから見つけます", "ui.edit_in_place_saved_elsewhere": "部品は別のファイルに保存されました。アセンブリは引き続き {name} にリンクしています", - "ui.finish_editing": "編集を終了" + "cmd.component_finish_edit": "編集を終了" }, "vi": { "settings.double_click_components": "Nhấp đúp vào một thành phần để kích hoạt nó, hoặc chỉnh sửa tại chỗ một thành phần liên kết", + "ui.heading_finish_editing": "KẾT THÚC CHỈNH SỬA", "ui.edit_in_place": "Chỉnh sửa tại chỗ", "ui.edit_in_place_assembly_closed": "{name} không còn mở", "ui.edit_in_place_banner": "Đang chỉnh sửa trong {name}", @@ -69,10 +75,11 @@ "ui.edit_in_place_refreshing": "Đang cập nhật liên kết trong {name}…", "ui.edit_in_place_save_first": "Hãy lưu cụm lắp ráp trước: các thiết kế liên kết của nó được tìm từ tệp của nó", "ui.edit_in_place_saved_elsewhere": "Chi tiết đã được lưu vào tệp khác; cụm lắp ráp vẫn liên kết với {name}", - "ui.finish_editing": "Kết thúc chỉnh sửa" + "cmd.component_finish_edit": "Kết thúc chỉnh sửa" }, "zh": { "settings.double_click_components": "双击组件以激活它,或在原位编辑链接组件", + "ui.heading_finish_editing": "完成编辑", "ui.edit_in_place": "原位编辑", "ui.edit_in_place_assembly_closed": "{name} 已不再打开", "ui.edit_in_place_banner": "正在 {name} 中编辑", @@ -81,6 +88,6 @@ "ui.edit_in_place_refreshing": "正在更新 {name} 中的链接…", "ui.edit_in_place_save_first": "请先保存装配体:其链接设计根据其文件查找", "ui.edit_in_place_saved_elsewhere": "零件已保存到其他文件;装配体仍链接 {name}", - "ui.finish_editing": "完成编辑" + "cmd.component_finish_edit": "完成编辑" } } diff --git a/attribution/pending/finish-edit-icon.md b/attribution/pending/finish-edit-icon.md new file mode 100644 index 00000000000..636d522e030 --- /dev/null +++ b/attribution/pending/finish-edit-icon.md @@ -0,0 +1 @@ +| assets/icons/ui/design/svg/model/finish_edit.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index de893162988..b7f299f7be8 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -11,8 +11,12 @@ use solidcraft_geom::Vec3; use super::CommandSpec; use crate::params::{bad, bool_, str_, string_list, vec3}; +use crate::schema::component::{FinishEditParams, FinishEditResult}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; +const FINISH_EDIT_CONTRACT: TypedContract = TypedContract::new(); + #[path = "component_drag.rs"] mod drag; #[path = "component_matrix.rs"] @@ -43,6 +47,13 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("component") .params("bodies: [names] → one new component per body, named after it"), CommandSpec::new("component.activate", "Activate Component", activate).icon("activate").noundo().params("component: id or name (0 or \"root\" for the design); occurrence?, path?: exact placement used to author shared geometry"), + CommandSpec::new("component.finish_edit", "Finish Editing", crate::checked!("component.finish_edit", finish_edit)) + .icon("finish_edit") + .noundo() + .doc_only() + .contract(&FINISH_EDIT_CONTRACT) + .output(output_schema_for::) + .params("no parameters → in the app window: save the linked design edited in place and go back to its assembly; elsewhere nothing changes"), CommandSpec::new("component.list", "List Components", list).icon("list").noundo().params( "compact?: bool (counts of bodies, features, sketches and construction planes instead of their names; occurrences leave out \ identity transforms; children as occurrence ids); bodies?: bool (with compact: body names, not their count)", @@ -193,6 +204,12 @@ fn from_bodies(s: &mut Session, p: &Value) -> Result { transfer::from_bodies(s, p) } +/// The app window finishes an edit in place (it knows the part's tab and its assembly); here +/// there is none, so nothing changes. +fn finish_edit(_s: &mut Session, _p: &Value) -> Result { + serde_json::to_value(FinishEditResult::default()).map_err(|e| crate::EngineError::Other(e.to_string())) +} + fn activate(s: &mut Session, p: &Value) -> Result { let id = component(s, p, "component", "component.activate")?; let path = if p.get("path").is_some() || p.get("occurrence").is_some() { diff --git a/crates/engine/src/schema/component.rs b/crates/engine/src/schema/component.rs new file mode 100644 index 00000000000..464f996e8b8 --- /dev/null +++ b/crates/engine/src/schema/component.rs @@ -0,0 +1,23 @@ +//! Contracts and result types for the commands in `cmd/component.rs`. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +/// Finish editing a linked component's design in place. In the app window: save the part, go back +/// to the assembly around it, which reads the link again, and close the part's tab when the edit +/// opened it. Outside the window nothing is edited in place, so nothing changes. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct FinishEditParams {} + +/// What `component.finish_edit` returns. +#[derive(Debug, Default, Serialize, JsonSchema)] +pub struct FinishEditResult { + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "component_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/component_tests.rs b/crates/engine/src/schema/component_tests.rs new file mode 100644 index 00000000000..5b47f0010b0 --- /dev/null +++ b/crates/engine/src/schema/component_tests.rs @@ -0,0 +1,23 @@ +use std::sync::Arc; + +use serde_json::json; + +use super::FinishEditParams; +use crate::Session; +use crate::schema::input_schema_for; +use crate::schema::tests::assert_keys; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &[]); +} + +#[test] +fn finishing_an_edit_outside_the_window_changes_nothing() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}")); + let (doc, undo) = (s.doc.clone(), s.undo.len()); + let r = s.execute("component.finish_edit", &json!({})).unwrap_or_else(|e| panic!("{e}")); + assert!(r.as_object().is_some_and(serde_json::Map::is_empty), "{r}"); + assert!(Arc::ptr_eq(&doc, &s.doc) && s.undo.len() == undo); +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 0e95a16485e..bada62ce251 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -54,6 +54,7 @@ mod coverage_tests; mod tests; // The contracts, by command file. +pub mod component; pub mod edit; pub mod features; pub mod inspect; diff --git a/crates/ui-egui/src/edit_in_place.rs b/crates/ui-egui/src/edit_in_place.rs index 422f5fd4535..4d45aa73e80 100644 --- a/crates/ui-egui/src/edit_in_place.rs +++ b/crates/ui-egui/src/edit_in_place.rs @@ -312,6 +312,14 @@ pub(crate) fn tick(app: &mut SolveApp) { } } +/// The mouse's back button (or a keyboard's Back key) pressed: Finish Editing, unless a dialog, a +/// tool or a sketch is open in the part. +pub(crate) fn back(app: &mut SolveApp) { + if app.edit_in_place.active.is_some() && app.dialog.is_none() && app.tool.is_none() && app.session.active_sketch.is_none() { + finish(app); + } +} + /// What the scene key needs of the edit: the assembly picture shown (0: none). pub(crate) fn scene_key(app: &SolveApp) -> usize { app.edit_in_place.active.as_ref().map_or(0, |c| Arc::as_ptr(&c.triangles) as usize) @@ -331,27 +339,18 @@ pub(crate) fn draw_context(app: &SolveApp, sc: &mut GpuScene) { } } -/// Above the browser's rows while a part is edited in place: which assembly it is in, and -/// Finish Editing. -pub(crate) fn browser_strip(app: &mut SolveApp, ui: &mut egui::Ui) { +/// Above the browser's rows while a part is edited in place: which assembly it is in (Finish +/// Editing is on the MODEL tab). +pub(crate) fn browser_strip(app: &SolveApp, ui: &mut egui::Ui) { let Some(context) = &app.edit_in_place.active else { return }; let t = Tokens::get(); - let refreshing = app.edit_in_place.refreshing(); - let key = if refreshing { "ui.edit_in_place_refreshing" } else { "ui.edit_in_place_banner" }; + let key = if app.edit_in_place.refreshing() { "ui.edit_in_place_refreshing" } else { "ui.edit_in_place_banner" }; let text = crate::i18n::format(key, &[("name", &context.assembly_name)]); - let mut finish_clicked = false; ui.horizontal(|ui| { ui.add_space(t.space_6); crate::ui_kit::text(ui, &text, crate::ui_kit::Text::Hint("edit_in_place")); - let label = crate::i18n::tr("ui.finish_editing"); - let button = ui.add_enabled_ui(!refreshing, |ui| crate::ui_kit::button(ui, label, crate::ui_kit::Button::Small)).inner; - crate::scenario::publish_handle("edit_in_place:finish", button.rect.center()); - finish_clicked = button.clicked(); }); ui.add_space(t.space_3); - if finish_clicked { - finish(app); - } } #[cfg(test)] diff --git a/crates/ui-egui/src/edit_in_place_tests.rs b/crates/ui-egui/src/edit_in_place_tests.rs index 60f7f2ff4de..71dc0355c9b 100644 --- a/crates/ui-egui/src/edit_in_place_tests.rs +++ b/crates/ui-egui/src/edit_in_place_tests.rs @@ -354,6 +354,45 @@ fn activate_only_activates_and_edit_in_place_opens_the_placement_right_clicked() assert_eq!(context(&f.app).placement, path); } +#[test] +fn finish_editing_is_a_model_tab_button_only_while_a_part_is_edited_in_place() { + let mut f = assembly("ribbon"); + let mut h = crate::scenario::Harness::new(); + h.app = std::mem::replace(&mut f.app, SolveApp::new(Session::default(), Default::default())); + h.app.home.open = false; + h.frames(3); + assert!(crate::scenario::rect_of("panel:MODEL:FINISH EDITING").is_none(), "no edit in place, no button"); + double_click_component(&mut h.app, json!({"component": f.plate})); + settle(&mut h.app); + h.frames(3); + assert!(crate::scenario::rect_of("panel:MODEL:FINISH EDITING").is_some(), "the part's MODEL tab ends with Finish Editing"); + h.app.start("component.finish_edit"); + settle(&mut h.app); + h.frames(3); + assert!(h.app.edit_in_place.active.is_none()); + assert_eq!(h.app.docs.count(), 1); + assert!(crate::scenario::rect_of("panel:MODEL:FINISH EDITING").is_none()); +} + +#[test] +fn the_back_button_finishes_the_edit_unless_a_dialog_is_open() { + let mut f = assembly("back"); + back(&mut f.app); + assert_eq!(f.app.docs.count(), 1, "nothing is edited in place: nothing happens"); + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + f.app.start("solid.box"); + assert!(f.app.dialog.is_some()); + back(&mut f.app); + settle(&mut f.app); + assert!(f.app.edit_in_place.active.is_some() && f.app.dialog.is_some(), "the open dialog keeps the edit"); + crate::dialogs::cancel(&mut f.app); + back(&mut f.app); + settle(&mut f.app); + assert!(f.app.edit_in_place.active.is_none()); + assert_eq!(f.app.docs.count(), 1); +} + #[test] fn turned_off_or_unsaved_double_clicking_a_linked_component_does_what_it_did() { let mut f = assembly("off"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 625d83dca5f..9d925b24463 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1387,6 +1387,10 @@ impl SolveApp { self.finish_sketch(); return; } + if id == "component.finish_edit" { + edit_in_place::finish(self); + return; + } if id == "sketch.cancel" { self.cancel_sketch(); return; @@ -2022,6 +2026,9 @@ impl SolveApp { file_load::tick(self, ctx); save_job::tick(self, false); edit_in_place::tick(self); + if ctx.input(|i| i.pointer.button_clicked(egui::PointerButton::Extra1) || i.key_pressed(egui::Key::BrowserBack)) { + edit_in_place::back(self); + } if self.saving.is_some() || self.edit_in_place.refreshing() { ctx.request_repaint_after(std::time::Duration::from_millis(16)); } diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 45587f5c13e..daaf224d4c2 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -1275,8 +1275,10 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let mut overflow = Vec::new(); // Every panel with all its buttons (the user's pins have no cap); a toolbar too narrow // for them narrows the buttons, then trims panels into their drop-down and the » menu. + let editing_in_place = app.edit_in_place.active.is_some(); let lists: Vec<_> = crate::toolbar_custom::panel_lists(&tab) .into_iter() + .filter(|(panel, _, _)| editing_in_place || !(tab == "MODEL" && *panel == "FINISH EDITING")) .map(|(panel, cmds, promote)| { let mut shown = crate::toolbar_custom::buttons(app, &tab, panel, &cmds, promote); // Gallery cells are painted together after the large buttons, in reading order. @@ -1319,7 +1321,8 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let right = r.right(); // The Sketch exit group follows the last sketch panel, and is always kept room for so it // stays reachable at every width; when panels go into the » menu it moves to the far right. - let finish_plan = sizes.last().and_then(|size| if tab == "SKETCH" { Some(Plan::full(size)) } else { None }); + let finish_plan = + sizes.last().and_then(|size| if tab == "SKETCH" || (tab == "MODEL" && editing_in_place) { Some(Plan::full(size)) } else { None }); let finish_width = finish_plan.as_ref().map_or(0.0, |p| p.width().max(80.0)); let normal_count = sizes.len().saturating_sub(usize::from(finish_plan.is_some())); let mut plans = fit(sizes.get(..normal_count).unwrap_or_default(), right - 4.0 - px - finish_width); @@ -1342,7 +1345,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { // commands never vanish from the toolbar (#7166). Both are COLLAPSED_WIDTH wide. let collapsed = plan.fit == Fit::Collapsed || (shown.is_empty() && !cmds.is_empty()); let trimmed = plan.shown < plan.widths.len(); - let finish = tab == "SKETCH" && *panel == "FINISH SKETCH"; + let finish = (tab == "SKETCH" && *panel == "FINISH SKETCH") || (tab == "MODEL" && *panel == "FINISH EDITING"); let pinned = finish; let width = if pinned { finish_width } else { plan.width() }; if pinned && finish_right { @@ -3604,7 +3607,8 @@ mod fill_width_tests { let right = bar.right() - 4.0 - finish.map_or(0.0, |f| f.width() + 4.0); let count = |name: &str| crate::scenario::count_of(name).unwrap_or(-1.0); let (collapsed, trimmed, more) = (count("toolbar_collapsed"), count("toolbar_trimmed"), count("toolbar_more")); - let lists = crate::toolbar_custom::panel_lists(tab); + // FINISH EDITING is shown only while a linked design is edited in place. + let lists: Vec<_> = crate::toolbar_custom::panel_lists(tab).into_iter().filter(|(panel, _, _)| *panel != "FINISH EDITING").collect(); let mut end = bar.left(); let mut on_bar = 0; for (panel, cmds, promote) in &lists { diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index d253662e218..1f43a2d670d 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -100,6 +100,8 @@ pub const SECTIONS: &[Section] = &[ }, Section { tab: "MODEL", panel: "CONFIGURE", promoted: 2, ids: CONFIGURE }, Section { tab: "MODEL", panel: "CONSTRUCT", promoted: 1, ids: &["construct.plane.offset"] }, + // Only while a linked design is edited in place, pinned at the right as FINISH SKETCH is. + Section { tab: "MODEL", panel: "FINISH EDITING", promoted: 1, ids: &["component.finish_edit"] }, // Sketches drive surfaces too: New Sketch leads the tab, as on MODEL and SHEET METAL. Section { tab: "SURFACE", panel: "SKETCH", promoted: 1, ids: &["sketch.create"] }, Section { tab: "SURFACE", panel: "CREATE", promoted: 4, ids: &["surface.extrude", "surface.revolve", "surface.sweep", "surface.loft"] }, @@ -417,6 +419,7 @@ pub const RIBBON_LABELS: &[(&str, &str)] = &[ ("sketch.create", "New Sketch"), ("sketch.dimension", "Dimension"), ("sketch.finish", "Finish Sketch"), + ("component.finish_edit", "Finish"), ("sketch.pattern.circular", "Circular"), ("sketch.pattern.rectangular", "Rectangular"), ("sketch.rectangle.two_point", "Rectangle"), diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index a5dda3b73ae..58c9ffb8d43 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -366,6 +366,18 @@ To edit the source, right-click a linked component or occurrence in the Browser the part's bodies only: its timeline, parameters and sheet-metal data (flat pattern, bend table) stay in the part's own design. +To edit a linked part where it sits, double-click it, in the Browser or on one of its faces in +the view, or choose **Edit in Place** from its menu. Its design opens in a tab of its own with the +rest of the assembly drawn faded around it, at the placement you picked, and the part's own +history, Browser and commands work as usual. **Update Links** there also reads the assembly's +links again and redraws it. **Finish Editing** (`component.finish_edit`), at the right end of the +**MODEL** tab, or the mouse's back button, saves the part and goes back to the assembly, which +takes up the change; the part's tab closes again when the edit opened it. **Activate** still makes +a linked component the active one without opening it, and a double-click on a component that +is not linked activates it. **Double-click a component to activate it, or to edit a linked one in +place** (Preferences, Design, `double_click_components`) turns this off: a double-click in the +Browser then activates every component, and one in the view does nothing. + If a source file moves or is renamed, right-click its linked component or occurrence in the Browser and choose **Relink Source (All Instances)…**. Choose the saved `.solidcraft` design to use. Relinking updates that component's stored path and solid bodies for **all its From 7810fc945c50e774fbd1267bba1ad8a76f9cc100 Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 15:37:57 +0100 Subject: [PATCH 11/20] Edit in place: fixes from the second review Saving the assembly waits while it reads its links for the part Finish Editing waits for dialogs, tools, sketches and prompts open in the part, also when run as a command The assembly reads the edited part explicitly when it does not check its links on its own The FINISH EDITING panel cannot be customized A tab opened by an edit stays that edit's to close when the part is entered again The mouse's back button finishes editing; the keyboard's only while no text field has focus Refreshing the assembly keeps its selection and active component Co-Authored-By: Claude Opus 5.5 --- assets/locales/pending/edit-in-place.json | 28 +++++++++ crates/ui-egui/src/edit_in_place.rs | 77 ++++++++++++++++++----- crates/ui-egui/src/edit_in_place_tests.rs | 62 ++++++++++++++++++ crates/ui-egui/src/lib.rs | 9 ++- crates/ui-egui/src/save_job.rs | 6 ++ crates/ui-egui/src/toolbar_custom.rs | 13 +++- 6 files changed, 172 insertions(+), 23 deletions(-) diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json index 017debe83ed..e2b811e1d9a 100644 --- a/assets/locales/pending/edit-in-place.json +++ b/assets/locales/pending/edit-in-place.json @@ -5,10 +5,14 @@ "ui.edit_in_place": "Edit in Place", "ui.edit_in_place_assembly_closed": "{name} is no longer open", "ui.edit_in_place_banner": "Editing in {name}", + "ui.edit_in_place_busy": "Finish or cancel what is open in the part first", + "ui.edit_in_place_none": "No linked design is edited in place", + "ui.edit_in_place_not_saved": "The part has changes that are not saved; save it to finish editing", "ui.edit_in_place_refresh_dropped": "The assembly changed while Update Links ran; run it again", "ui.edit_in_place_refresh_stopped": "Update Links stopped before it was done", "ui.edit_in_place_refreshing": "Updating links in {name}…", "ui.edit_in_place_save_first": "Save the assembly first: its linked designs are found from its file", + "ui.edit_in_place_save_waits": "Update Links is running in {name}; save it once it is done", "ui.edit_in_place_saved_elsewhere": "The part was saved to another file; the assembly still links {name}", "cmd.component_finish_edit": "Finish Editing" }, @@ -18,10 +22,14 @@ "ui.edit_in_place": "تحرير في المكان", "ui.edit_in_place_assembly_closed": "{name} لم يعد مفتوحًا", "ui.edit_in_place_banner": "تحرير داخل {name}", + "ui.edit_in_place_busy": "أنهِ ما هو مفتوح في الجزء أو ألغِه أولاً", + "ui.edit_in_place_none": "لا يُحرَّر أي تصميم مرتبط في مكانه", + "ui.edit_in_place_not_saved": "في الجزء تغييرات غير محفوظة؛ احفظه لإنهاء التحرير", "ui.edit_in_place_refresh_dropped": "تغيّر التجميع أثناء تحديث الروابط؛ شغّله مرة أخرى", "ui.edit_in_place_refresh_stopped": "توقّف تحديث الروابط قبل أن ينتهي", "ui.edit_in_place_refreshing": "جارٍ تحديث الروابط في {name}…", "ui.edit_in_place_save_first": "احفظ التجميع أولاً: يُعثر على تصاميمه المرتبطة انطلاقًا من ملفه", + "ui.edit_in_place_save_waits": "يجري تحديث الروابط في {name}؛ احفظه بعد انتهائه", "ui.edit_in_place_saved_elsewhere": "حُفظ الجزء في ملف آخر؛ ما زال التجميع مرتبطًا بـ {name}", "cmd.component_finish_edit": "إنهاء التحرير" }, @@ -31,10 +39,14 @@ "ui.edit_in_place": "An Ort und Stelle bearbeiten", "ui.edit_in_place_assembly_closed": "{name} ist nicht mehr geöffnet", "ui.edit_in_place_banner": "Bearbeitung in {name}", + "ui.edit_in_place_busy": "Zuerst abschließen oder abbrechen, was im Teil offen ist", + "ui.edit_in_place_none": "Es wird kein verknüpftes Design an Ort und Stelle bearbeitet", + "ui.edit_in_place_not_saved": "Das Teil hat ungespeicherte Änderungen; zum Beenden der Bearbeitung speichern", "ui.edit_in_place_refresh_dropped": "Die Baugruppe wurde während der Aktualisierung der Verknüpfungen geändert; bitte erneut ausführen", "ui.edit_in_place_refresh_stopped": "Die Aktualisierung der Verknüpfungen wurde vorzeitig beendet", "ui.edit_in_place_refreshing": "Verknüpfungen in {name} werden aktualisiert…", "ui.edit_in_place_save_first": "Zuerst die Baugruppe speichern: ihre verknüpften Designs werden von ihrer Datei aus gefunden", + "ui.edit_in_place_save_waits": "In {name} werden die Verknüpfungen aktualisiert; danach speichern", "ui.edit_in_place_saved_elsewhere": "Das Teil wurde in eine andere Datei gespeichert; die Baugruppe verknüpft weiterhin {name}", "cmd.component_finish_edit": "Bearbeitung beenden" }, @@ -44,10 +56,14 @@ "ui.edit_in_place": "עריכה במקום", "ui.edit_in_place_assembly_closed": "{name} כבר אינו פתוח", "ui.edit_in_place_banner": "עריכה בתוך {name}", + "ui.edit_in_place_busy": "יש לסיים או לבטל קודם את מה שפתוח בחלק", + "ui.edit_in_place_none": "אין תכן מקושר בעריכה במקום", + "ui.edit_in_place_not_saved": "בחלק יש שינויים שלא נשמרו; יש לשמור כדי לסיים את העריכה", "ui.edit_in_place_refresh_dropped": "ההרכבה השתנתה בזמן עדכון הקישורים; יש להריץ שוב", "ui.edit_in_place_refresh_stopped": "עדכון הקישורים נעצר לפני שהסתיים", "ui.edit_in_place_refreshing": "מעדכן קישורים ב-{name}…", "ui.edit_in_place_save_first": "יש לשמור קודם את ההרכבה: התכנים המקושרים שלה נמצאים לפי הקובץ שלה", + "ui.edit_in_place_save_waits": "עדכון הקישורים פועל ב-{name}; יש לשמור לאחר שיסתיים", "ui.edit_in_place_saved_elsewhere": "החלק נשמר לקובץ אחר; ההרכבה עדיין מקושרת אל {name}", "cmd.component_finish_edit": "סיום עריכה" }, @@ -57,10 +73,14 @@ "ui.edit_in_place": "その場で編集", "ui.edit_in_place_assembly_closed": "{name} はもう開いていません", "ui.edit_in_place_banner": "{name} 内で編集中", + "ui.edit_in_place_busy": "先に部品で開いているものを終了またはキャンセルしてください", + "ui.edit_in_place_none": "その場で編集中のリンクされたデザインはありません", + "ui.edit_in_place_not_saved": "部品に保存されていない変更があります。編集を終了するには保存してください", "ui.edit_in_place_refresh_dropped": "リンクの更新中にアセンブリが変更されました。もう一度実行してください", "ui.edit_in_place_refresh_stopped": "リンクの更新が完了前に停止しました", "ui.edit_in_place_refreshing": "{name} のリンクを更新中…", "ui.edit_in_place_save_first": "先にアセンブリを保存してください。リンクされたデザインはそのファイルから見つけます", + "ui.edit_in_place_save_waits": "{name} のリンクを更新中です。完了してから保存してください", "ui.edit_in_place_saved_elsewhere": "部品は別のファイルに保存されました。アセンブリは引き続き {name} にリンクしています", "cmd.component_finish_edit": "編集を終了" }, @@ -70,10 +90,14 @@ "ui.edit_in_place": "Chỉnh sửa tại chỗ", "ui.edit_in_place_assembly_closed": "{name} không còn mở", "ui.edit_in_place_banner": "Đang chỉnh sửa trong {name}", + "ui.edit_in_place_busy": "Hãy hoàn tất hoặc hủy những gì đang mở trong chi tiết trước", + "ui.edit_in_place_none": "Không có thiết kế liên kết nào đang được chỉnh sửa tại chỗ", + "ui.edit_in_place_not_saved": "Chi tiết có thay đổi chưa lưu; hãy lưu để kết thúc chỉnh sửa", "ui.edit_in_place_refresh_dropped": "Cụm lắp ráp đã thay đổi trong khi cập nhật liên kết; hãy chạy lại", "ui.edit_in_place_refresh_stopped": "Cập nhật liên kết đã dừng trước khi hoàn tất", "ui.edit_in_place_refreshing": "Đang cập nhật liên kết trong {name}…", "ui.edit_in_place_save_first": "Hãy lưu cụm lắp ráp trước: các thiết kế liên kết của nó được tìm từ tệp của nó", + "ui.edit_in_place_save_waits": "Đang cập nhật liên kết trong {name}; hãy lưu sau khi hoàn tất", "ui.edit_in_place_saved_elsewhere": "Chi tiết đã được lưu vào tệp khác; cụm lắp ráp vẫn liên kết với {name}", "cmd.component_finish_edit": "Kết thúc chỉnh sửa" }, @@ -83,10 +107,14 @@ "ui.edit_in_place": "原位编辑", "ui.edit_in_place_assembly_closed": "{name} 已不再打开", "ui.edit_in_place_banner": "正在 {name} 中编辑", + "ui.edit_in_place_busy": "请先完成或取消零件中打开的操作", + "ui.edit_in_place_none": "没有正在原位编辑的链接设计", + "ui.edit_in_place_not_saved": "零件有未保存的更改;请保存以完成编辑", "ui.edit_in_place_refresh_dropped": "更新链接期间装配体已更改;请再次运行", "ui.edit_in_place_refresh_stopped": "更新链接在完成前已停止", "ui.edit_in_place_refreshing": "正在更新 {name} 中的链接…", "ui.edit_in_place_save_first": "请先保存装配体:其链接设计根据其文件查找", + "ui.edit_in_place_save_waits": "正在更新 {name} 中的链接;请在完成后保存", "ui.edit_in_place_saved_elsewhere": "零件已保存到其他文件;装配体仍链接 {name}", "cmd.component_finish_edit": "完成编辑" } diff --git a/crates/ui-egui/src/edit_in_place.rs b/crates/ui-egui/src/edit_in_place.rs index 4d45aa73e80..2b2c796f1d2 100644 --- a/crates/ui-egui/src/edit_in_place.rs +++ b/crates/ui-egui/src/edit_in_place.rs @@ -38,8 +38,6 @@ pub struct PartContext { pub bounds: Aabb3, /// The part's tab was opened for this edit, so Finish Editing closes it again. pub opened: bool, - /// The number of tabs when the edit started (more once the part has opened in a new one). - tabs: usize, } /// Update Links run on the assembly while its part is edited in place. @@ -162,6 +160,7 @@ pub(crate) fn enter(app: &mut SolveApp, component: u64, path: Option>) let Some(part) = link["file"].as_str().map(str::to_string) else { return }; let placement = path.unwrap_or_else(|| app.session.doc.first_path(component)); let Some((bodies, triangles, bounds)) = snapshot(&app.session, component, &placement) else { return }; + let opened = crate::documents::session_at(app, &part).is_none(); app.edit_in_place.pending = Some(PartContext { assembly, assembly_name: app.session.doc.name.clone(), @@ -171,8 +170,7 @@ pub(crate) fn enter(app: &mut SolveApp, component: u64, path: Option>) bodies, triangles: Arc::new(triangles), bounds, - opened: false, - tabs: app.docs.count(), + opened, }); crate::network_prompt::open_linked(app, &link); } @@ -184,15 +182,26 @@ pub(crate) fn attach(app: &mut SolveApp) { let Some(mut context) = app.edit_in_place.pending.take_if(|c| shown.is_some_and(|p| crate::documents::same_path(p, &c.part))) else { return; }; - context.opened = app.docs.count() > context.tabs; + // Entered again in a tab an earlier edit opened: that tab is still this edit's to close. + if let Some(old) = app.edit_in_place.active.as_ref().filter(|c| crate::documents::same_path(&c.part, &context.part)) { + context.opened |= old.opened; + } app.edit_in_place.active = Some(context); app.fit_view(); } +/// The name of the design shown, while it reads its links for a part edited in place (it is +/// not saved until the read is done). +pub(crate) fn refreshing_assembly(app: &SolveApp) -> Option { + let r = app.edit_in_place.refresh.as_ref()?; + app.session.path.as_deref().filter(|p| crate::documents::same_path(p, &r.assembly))?; + Some(app.session.doc.name.clone()) +} + /// Update Links pressed while a part is edited in place: the assembly's tab reads its links again /// (off the window thread), and the picture around the part follows. pub(crate) fn refresh(app: &mut SolveApp) { - if app.edit_in_place.refreshing() { + if busy(app) { return; } let Some(assembly) = app.edit_in_place.active.as_ref().map(|c| c.assembly.clone()) else { return }; @@ -232,7 +241,7 @@ fn take_refresh(app: &mut SolveApp) { Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(crate::i18n::tr("ui.edit_in_place_refresh_stopped").to_string()), }; let Some(r) = app.edit_in_place.refresh.take() else { return }; - let computed = match result { + let mut computed = match result { Ok(computed) => computed, Err(e) => { app.set_status(e, true); @@ -244,6 +253,11 @@ fn take_refresh(app: &mut SolveApp) { app.set_status(crate::i18n::tr("ui.edit_in_place_refresh_dropped").to_string(), true); return; } + // What was picked or activated in the assembly meanwhile stays as it is. + computed.selection.clone_from(&session.selection); + computed.active_sketch = session.active_sketch; + computed.active_component = session.active_component; + computed.active_occurrence_path.clone_from(&session.active_occurrence_path); session.accept_computed(computed); // Every link was read: coming back to the assembly need not read them again. crate::documents::read_again_at(app, &r.assembly); @@ -261,8 +275,12 @@ fn take_refresh(app: &mut SolveApp) { /// Finish Editing: save the part (and wait for it), go back to the assembly, close the part's /// tab when the edit opened it and read the assembly's links again. pub(crate) fn finish(app: &mut SolveApp) { - let Some(part) = app.edit_in_place.active.as_ref().map(|c| c.part.clone()) else { return }; - if busy(app) { + let Some(part) = app.edit_in_place.active.as_ref().map(|c| c.part.clone()) else { + app.set_status(crate::i18n::tr("ui.edit_in_place_none").to_string(), true); + return; + }; + if !can_finish(app) { + app.set_status(crate::i18n::tr("ui.edit_in_place_busy").to_string(), true); return; } // Saved to another file (Save As, a copy of a read-only design): the assembly still links this one. @@ -289,12 +307,37 @@ pub(crate) fn finish(app: &mut SolveApp) { if context.opened { crate::documents::close(app, part_tab, false); } - // Coming back to its tab already updates what changed (`update_changed_links`). - if !app.preferences.update_changed_links { - crate::network_prompt::update_links(app); + // Coming back to its tab reads what changed, unless it read nothing (`update_changed_links` + // off, the web build without file times): then the part is read here. + if (!app.preferences.update_changed_links || cfg!(target_arch = "wasm32")) && app.file_load.idle() { + let mut request = crate::file_load::Request::new("", crate::file_load::Kind::UpdateLinks); + request.options.insert("component".into(), json!(context.component)); + request.design = Some(context.assembly); + let _ = crate::file_load::begin_request(app, request); } } +/// Nothing is under way in the part that leaving its tab would cut short or that waits for an +/// answer: a dialog or tool, a feature being computed or edited, a sketch, a prompt or Home. +fn can_finish(app: &SolveApp) -> bool { + !busy(app) + && app.dialog.is_none() + && app.applying.is_none() + && app.editing_state.is_none() + && app.pending_feature_edit.is_none() + && app.deferred.is_none() + && app.tool.is_none() + && app.session.active_sketch.is_none() + && app.docs.closing.is_none() + && app.docs.quitting.is_none() + && app.docs.batch.is_none() + && app.network_prompt.is_none() + && app.lock_prompts.is_empty() + && !app.disk_prompt + && app.tree.capture_prompt.is_none() + && !app.home.open +} + /// Each frame: a refresh that finished is taken up; an edit waiting for a part that nothing will /// open any more is dropped; and Finish Editing goes on once the part's save is done, in the /// part's own tab (a save that failed, was cancelled or went elsewhere leaves the edit as it was). @@ -303,19 +346,21 @@ pub(crate) fn tick(app: &mut SolveApp) { if app.edit_in_place.pending.is_some() && !app.file_load.busy() && app.network_prompt.is_none() && app.lock_prompts.is_empty() { app.edit_in_place.pending = None; } - let waiting = app.saving.is_some() || app.file_picker.is_some() || app.disk_prompt; + let waiting = app.saving.is_some() || app.file_picker.is_some() || app.disk_prompt || app.tree.capture_prompt.is_some(); if !waiting && let Some(part) = app.edit_in_place.finish_after_save.take() { let shown = app.session.path.as_deref().is_some_and(|p| crate::documents::same_path(p, &part)); if shown && !app.session.is_dirty() { finish(app); + } else if shown { + app.set_status(crate::i18n::tr("ui.edit_in_place_not_saved").to_string(), true); } } } -/// The mouse's back button (or a keyboard's Back key) pressed: Finish Editing, unless a dialog, a -/// tool or a sketch is open in the part. +/// The mouse's back button (or a keyboard's Back key) pressed while a part is edited in place: +/// Finish Editing, which says why when something open in the part holds it up. pub(crate) fn back(app: &mut SolveApp) { - if app.edit_in_place.active.is_some() && app.dialog.is_none() && app.tool.is_none() && app.session.active_sketch.is_none() { + if app.edit_in_place.active.is_some() { finish(app); } } diff --git a/crates/ui-egui/src/edit_in_place_tests.rs b/crates/ui-egui/src/edit_in_place_tests.rs index 71dc0355c9b..0ec17474581 100644 --- a/crates/ui-egui/src/edit_in_place_tests.rs +++ b/crates/ui-egui/src/edit_in_place_tests.rs @@ -393,6 +393,68 @@ fn the_back_button_finishes_the_edit_unless_a_dialog_is_open() { assert_eq!(f.app.docs.count(), 1); } +#[test] +fn the_assembly_is_not_saved_while_it_reads_its_links_for_the_part() { + let mut f = assembly("save-waits"); + f.app.preferences.update_changed_links = false; + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + save_box(&f.post_file, [10.0, 10.0, 10.0], true); + refresh(&mut f.app); + crate::documents::switch(&mut f.app, 0); + assert!(!crate::save_job::start(&mut f.app, "file.save", json!({}))); + assert!(f.app.saving.is_none()); + assert!(f.app.status.as_ref().is_some_and(|(s, _, error)| *error && s.starts_with("Update Links is running")), "{:?}", f.app.status); + settle(&mut f.app); + assert!((volume(&f.app) - 7250.0).abs() < 1e-6, "{}", volume(&f.app)); + assert!(f.app.session.is_dirty(), "the read is taken up and still to be saved"); +} + +#[test] +fn finish_editing_waits_for_what_is_open_in_the_part() { + let mut f = assembly("waits"); + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + f.app.start("solid.box"); + assert!(f.app.dialog.is_some()); + // As an agent calls it: the command, not the button + f.app.run("component.finish_edit", json!({})).unwrap(); + settle(&mut f.app); + assert!(f.app.edit_in_place.active.is_some() && f.app.dialog.is_some()); + assert!(f.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", f.app.status); + crate::dialogs::cancel(&mut f.app); + f.app.run("component.finish_edit", json!({})).unwrap(); + settle(&mut f.app); + assert!(f.app.edit_in_place.active.is_none()); + assert_eq!(f.app.docs.count(), 1); +} + +#[test] +fn finish_editing_keeps_its_panel_to_itself() { + let mut app = SolveApp::new(Session::default(), Default::default()); + let extrude = crate::toolbar_custom::pinned_on(&app, "MODEL", "solid.extrude"); + crate::toolbar_custom::reorder(&mut app, "MODEL", "solid.extrude", "FINISH EDITING", None); + assert_eq!(crate::toolbar_custom::pinned_on(&app, "MODEL", "solid.extrude"), extrude); + crate::toolbar_custom::reorder(&mut app, "MODEL", "component.finish_edit", "CREATE", None); + assert_ne!(crate::toolbar_custom::pinned_on(&app, "MODEL", "component.finish_edit"), Some("CREATE")); +} + +#[test] +fn entering_again_keeps_the_tab_the_first_edit_opened() { + let mut f = assembly("again"); + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + assert!(context(&f.app).opened); + crate::documents::switch(&mut f.app, 0); + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + assert!(showing(&f.app, &f.plate_file)); + assert!(context(&f.app).opened, "the part's tab is still this edit's to close"); + finish(&mut f.app); + settle(&mut f.app); + assert_eq!(f.app.docs.count(), 1); +} + #[test] fn turned_off_or_unsaved_double_clicking_a_linked_component_does_what_it_did() { let mut f = assembly("off"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9d925b24463..3b99b0f9fa8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -993,6 +993,8 @@ impl SolveApp { if let Ok(v) = &r { match id { "view.fit" | "view.home" => self.frame_view(id == "view.home"), + // The engine has no edit in place to finish; the window does, for every caller. + "component.finish_edit" => edit_in_place::finish(self), "view.tool" => { self.viewport.nav = match v.get("tool").and_then(Value::as_str) { Some("orbit") => Some(viewport::NavMode::Orbit), @@ -1387,10 +1389,6 @@ impl SolveApp { self.finish_sketch(); return; } - if id == "component.finish_edit" { - edit_in_place::finish(self); - return; - } if id == "sketch.cancel" { self.cancel_sketch(); return; @@ -2026,7 +2024,8 @@ impl SolveApp { file_load::tick(self, ctx); save_job::tick(self, false); edit_in_place::tick(self); - if ctx.input(|i| i.pointer.button_clicked(egui::PointerButton::Extra1) || i.key_pressed(egui::Key::BrowserBack)) { + let typing = ctx.egui_wants_keyboard_input(); + if ctx.input(|i| i.pointer.button_clicked(egui::PointerButton::Extra1) || (i.key_pressed(egui::Key::BrowserBack) && !typing)) { edit_in_place::back(self); } if self.saving.is_some() || self.edit_in_place.refreshing() { diff --git a/crates/ui-egui/src/save_job.rs b/crates/ui-egui/src/save_job.rs index 0c5ce06f752..8cfa59b7807 100644 --- a/crates/ui-egui/src/save_job.rs +++ b/crates/ui-egui/src/save_job.rs @@ -18,6 +18,12 @@ pub struct Saving { /// 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 { + // An assembly reading its links for a part edited in place takes them up when the read is + // done: a save before then would record a design that is about to change as saved. + if let Some(name) = crate::edit_in_place::refreshing_assembly(app) { + app.set_status(crate::i18n::format("ui.edit_in_place_save_waits", &[("name", &name)]), true); + return false; + } #[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(); diff --git a/crates/ui-egui/src/toolbar_custom.rs b/crates/ui-egui/src/toolbar_custom.rs index 520a14a9623..b7b948afba0 100644 --- a/crates/ui-egui/src/toolbar_custom.rs +++ b/crates/ui-egui/src/toolbar_custom.rs @@ -241,12 +241,18 @@ fn home_panel(tab: &str, id: &str) -> Option<&'static str> { lists.iter().find(|(_, cmds, _)| cmds.iter().any(|c| c.id == id)).or(lists.first()).map(|(p, ..)| *p) } +/// FINISH EDITING, shown only while a linked design is edited in place, keeps its one button: +/// nothing moves into it, and Finish Editing moves nowhere else. +fn fixed(tab: &str, panel: &str, id: &str) -> bool { + (tab == "MODEL" && panel == "FINISH EDITING") || id == "component.finish_edit" +} + /// Pin a command to the toolbar of a tab (as a button of its panel, at the end). pub fn pin(app: &mut SolveApp, tab: &str, id: &str) -> Result<(), String> { if solidcraft_engine::find_command(id).is_none() { return Err(format!("no command `{id}`")); } - if pinned_on(app, tab, id).is_some() { + if pinned_on(app, tab, id).is_some() || fixed(tab, "", id) { return Ok(()); } let panel = home_panel(tab, id).ok_or_else(|| format!("the {tab} tab has no panels"))?; @@ -258,7 +264,7 @@ pub fn pin(app: &mut SolveApp, tab: &str, id: &str) -> Result<(), String> { /// Remove a command's button from a tab (it stays in its panel's drop-down). pub fn remove(app: &mut SolveApp, tab: &str, id: &str) { - let Some(panel) = pinned_on(app, tab, id) else { return }; + let Some(panel) = pinned_on(app, tab, id).filter(|panel| !fixed(tab, panel, id)) else { return }; let mut ids = own(app, tab, panel); ids.retain(|x| x != id); app.toolbar_custom.panels.insert(key(tab, panel), ids); @@ -266,6 +272,9 @@ pub fn remove(app: &mut SolveApp, tab: &str, id: &str) { /// Move a button before another one (`before`: None puts it at the end of `panel`). pub fn reorder(app: &mut SolveApp, tab: &str, id: &str, panel: &str, before: Option<&str>) { + if fixed(tab, panel, id) { + return; + } // A gallery command dropped on a gallery cell goes (back) into the gallery; dropped anywhere // else it becomes a full-size button. if tab == "SKETCH" && crate::workspace::CONSTRAINT_GALLERY.contains(&id) { From 10108b2c0ac2bc251899f41b56e2cf25e03d053f Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 16:04:52 +0100 Subject: [PATCH 12/20] Edit in place: fixes from the third review component.finish_edit run as a command opens nothing and answers with an error when it cannot finish; engine.batch and engine.script refuse it A double-click or Edit in Place while a dialog, tool or sketch is open in the assembly keeps it open What changes in the assembly while it reads its links without changing its document stays: picks, activation, components dragged but not captured Showing the assembly while it reads its links starts no second read A new or opened design in the part's tab ends the edit Finish Editing keeps the part's tab open while its agent chat runs Co-Authored-By: Claude Opus 5.5 --- assets/locales/pending/edit-in-place.json | 14 +-- crates/ui-egui/src/control.rs | 15 ++- crates/ui-egui/src/documents.rs | 18 ++- crates/ui-egui/src/edit_in_place.rs | 85 ++++++++----- crates/ui-egui/src/edit_in_place_tests.rs | 139 ++++++++++++++++++++-- crates/ui-egui/src/lib.rs | 9 +- 6 files changed, 228 insertions(+), 52 deletions(-) diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json index e2b811e1d9a..af8e24e8157 100644 --- a/assets/locales/pending/edit-in-place.json +++ b/assets/locales/pending/edit-in-place.json @@ -5,7 +5,7 @@ "ui.edit_in_place": "Edit in Place", "ui.edit_in_place_assembly_closed": "{name} is no longer open", "ui.edit_in_place_banner": "Editing in {name}", - "ui.edit_in_place_busy": "Finish or cancel what is open in the part first", + "ui.edit_in_place_busy": "Finish or cancel what is open first", "ui.edit_in_place_none": "No linked design is edited in place", "ui.edit_in_place_not_saved": "The part has changes that are not saved; save it to finish editing", "ui.edit_in_place_refresh_dropped": "The assembly changed while Update Links ran; run it again", @@ -22,7 +22,7 @@ "ui.edit_in_place": "تحرير في المكان", "ui.edit_in_place_assembly_closed": "{name} لم يعد مفتوحًا", "ui.edit_in_place_banner": "تحرير داخل {name}", - "ui.edit_in_place_busy": "أنهِ ما هو مفتوح في الجزء أو ألغِه أولاً", + "ui.edit_in_place_busy": "أنهِ ما هو مفتوح أو ألغِه أولاً", "ui.edit_in_place_none": "لا يُحرَّر أي تصميم مرتبط في مكانه", "ui.edit_in_place_not_saved": "في الجزء تغييرات غير محفوظة؛ احفظه لإنهاء التحرير", "ui.edit_in_place_refresh_dropped": "تغيّر التجميع أثناء تحديث الروابط؛ شغّله مرة أخرى", @@ -39,7 +39,7 @@ "ui.edit_in_place": "An Ort und Stelle bearbeiten", "ui.edit_in_place_assembly_closed": "{name} ist nicht mehr geöffnet", "ui.edit_in_place_banner": "Bearbeitung in {name}", - "ui.edit_in_place_busy": "Zuerst abschließen oder abbrechen, was im Teil offen ist", + "ui.edit_in_place_busy": "Zuerst abschließen oder abbrechen, was offen ist", "ui.edit_in_place_none": "Es wird kein verknüpftes Design an Ort und Stelle bearbeitet", "ui.edit_in_place_not_saved": "Das Teil hat ungespeicherte Änderungen; zum Beenden der Bearbeitung speichern", "ui.edit_in_place_refresh_dropped": "Die Baugruppe wurde während der Aktualisierung der Verknüpfungen geändert; bitte erneut ausführen", @@ -56,7 +56,7 @@ "ui.edit_in_place": "עריכה במקום", "ui.edit_in_place_assembly_closed": "{name} כבר אינו פתוח", "ui.edit_in_place_banner": "עריכה בתוך {name}", - "ui.edit_in_place_busy": "יש לסיים או לבטל קודם את מה שפתוח בחלק", + "ui.edit_in_place_busy": "יש לסיים או לבטל קודם את מה שפתוח", "ui.edit_in_place_none": "אין תכן מקושר בעריכה במקום", "ui.edit_in_place_not_saved": "בחלק יש שינויים שלא נשמרו; יש לשמור כדי לסיים את העריכה", "ui.edit_in_place_refresh_dropped": "ההרכבה השתנתה בזמן עדכון הקישורים; יש להריץ שוב", @@ -73,7 +73,7 @@ "ui.edit_in_place": "その場で編集", "ui.edit_in_place_assembly_closed": "{name} はもう開いていません", "ui.edit_in_place_banner": "{name} 内で編集中", - "ui.edit_in_place_busy": "先に部品で開いているものを終了またはキャンセルしてください", + "ui.edit_in_place_busy": "先に開いているものを終了またはキャンセルしてください", "ui.edit_in_place_none": "その場で編集中のリンクされたデザインはありません", "ui.edit_in_place_not_saved": "部品に保存されていない変更があります。編集を終了するには保存してください", "ui.edit_in_place_refresh_dropped": "リンクの更新中にアセンブリが変更されました。もう一度実行してください", @@ -90,7 +90,7 @@ "ui.edit_in_place": "Chỉnh sửa tại chỗ", "ui.edit_in_place_assembly_closed": "{name} không còn mở", "ui.edit_in_place_banner": "Đang chỉnh sửa trong {name}", - "ui.edit_in_place_busy": "Hãy hoàn tất hoặc hủy những gì đang mở trong chi tiết trước", + "ui.edit_in_place_busy": "Hãy hoàn tất hoặc hủy những gì đang mở trước", "ui.edit_in_place_none": "Không có thiết kế liên kết nào đang được chỉnh sửa tại chỗ", "ui.edit_in_place_not_saved": "Chi tiết có thay đổi chưa lưu; hãy lưu để kết thúc chỉnh sửa", "ui.edit_in_place_refresh_dropped": "Cụm lắp ráp đã thay đổi trong khi cập nhật liên kết; hãy chạy lại", @@ -107,7 +107,7 @@ "ui.edit_in_place": "原位编辑", "ui.edit_in_place_assembly_closed": "{name} 已不再打开", "ui.edit_in_place_banner": "正在 {name} 中编辑", - "ui.edit_in_place_busy": "请先完成或取消零件中打开的操作", + "ui.edit_in_place_busy": "请先完成或取消打开的操作", "ui.edit_in_place_none": "没有正在原位编辑的链接设计", "ui.edit_in_place_not_saved": "零件有未保存的更改;请保存以完成编辑", "ui.edit_in_place_refresh_dropped": "更新链接期间装配体已更改;请再次运行", diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 62750b3152d..c6b4ee48117 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -267,9 +267,16 @@ const MAX_BATCH: usize = 10_000; /// bypass. const LOADS_A_FILE: [&str; 3] = ["doc.open", "file.insert_step", "file.insert_mesh"]; -/// Why `engine.batch` refuses these steps before running any: a step loads a file (send such -/// steps one by one). +/// Finish Editing leaves the part for the assembly's tab: a batch's rollback, or a script's +/// later steps, would land in the wrong design. +const SWITCHES_DESIGN: &str = "component.finish_edit"; + +/// Why `engine.batch` refuses these steps before running any: a step loads a file or switches +/// to another design (send such steps one by one). pub(crate) fn batch_refusal(steps: &[Value]) -> Option { + if let Some(i) = steps.iter().position(|step| command(step) == Some(SWITCHES_DESIGN)) { + return Some(format!("engine.batch unavailable: step {i} ({SWITCHES_DESIGN}) switches to another design")); + } let (i, c) = steps.iter().enumerate().find_map(|(i, step)| command(step).filter(|c| LOADS_A_FILE.contains(c)).map(|c| (i, c)))?; Some(format!("engine.batch unavailable: step {i} ({c}) loads a file")) } @@ -464,6 +471,9 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> } "engine.script" => { let steps = p.as_array().or_else(|| p.get("commands").and_then(Value::as_array)); + if steps.is_some_and(|steps| steps.iter().any(|step| command(step) == Some(SWITCHES_DESIGN))) { + return err(format!("engine.script unavailable: {SWITCHES_DESIGN} switches to another design (send it on its own)")); + } let mut replaced = false; let r = app .session @@ -476,6 +486,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> // A successful replacement still happened if a later script step failed. if replaced { crate::documents::reset_chat(app); + app.edit_in_place.active = None; } app.follow_view_request(false); wrap(r) diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 022d25aae73..95ae1d37cec 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -227,7 +227,12 @@ pub fn switch(app: &mut SolveApp, i: usize) { app.docs.active = i; // Closing several tabs, quitting, or a "save changes?" for this tab goes through them, and a // save then must not wait for a read: what they missed waits for their return. - if app.docs.batch.is_none() && app.docs.quitting.is_none() && app.docs.closing.is_none() { + // An assembly reading its links for a part edited in place takes them all up once it is done. + if app.docs.batch.is_none() + && app.docs.quitting.is_none() + && app.docs.closing.is_none() + && crate::edit_in_place::refreshing_assembly(app).is_none() + { crate::linked_source::update_changed(app); } crate::edit_in_place::attach(app); @@ -242,6 +247,17 @@ pub(crate) fn session_at<'a>(app: &'a SolveApp, path: &str) -> Option<&'a Sessio app.docs.slots.iter().flatten().map(|s| &s.session).find(|s| saved_at(s)) } +/// The design in tab `i` has an agent chat running (closing the tab would end it). +pub(crate) fn chat_running_at(app: &SolveApp, i: usize) -> bool { + let chat = if i == app.docs.active { + &app.agent_chat + } else { + let Some(slot) = app.docs.slots.get(i).and_then(Option::as_ref) else { return false }; + &slot.agent_chat + }; + !matches!(chat.state(), crate::agent_chat::State::Off | crate::agent_chat::State::Exited) +} + /// The open design saved at `path` read every link again without an error: its record of them /// (`Documents::link_stamps`, or its tab's) is now its files as they are. pub(crate) fn read_again_at(app: &mut SolveApp, path: &str) { diff --git a/crates/ui-egui/src/edit_in_place.rs b/crates/ui-egui/src/edit_in_place.rs index 2b2c796f1d2..214a3f6b2d6 100644 --- a/crates/ui-egui/src/edit_in_place.rs +++ b/crates/ui-egui/src/edit_in_place.rs @@ -68,10 +68,11 @@ impl EditInPlace { /// A component double-clicked in the browser: a linked one is edited in place (Preferences: /// `double_click_components`), any other is made the active component (`component.activate` -/// with `params`). Activate itself always does the latter. +/// with `params`), as is a linked one while a dialog or tool is open. Activate itself always +/// does the latter. pub(crate) fn double_click_component(app: &mut SolveApp, params: Value) { let component = params["component"].as_u64().unwrap_or(0); - if app.preferences.double_click_components && app.session.doc.links.contains_key(&component) { + if app.preferences.double_click_components && !working(app) && app.session.doc.links.contains_key(&component) { let path = params["path"].as_array().map(|p| p.iter().filter_map(Value::as_u64).collect::>()); enter(app, component, path); } else { @@ -113,6 +114,17 @@ fn busy(app: &SolveApp) -> bool { app.file_picker_busy() || app.file_load.busy() || app.saving.is_some() || app.edit_in_place.refreshing() } +/// A dialog, tool, sketch or feature edit is open in the design shown: leaving its tab would +/// cancel it. +fn working(app: &SolveApp) -> bool { + app.dialog.is_some() + || app.applying.is_some() + || app.editing_state.is_some() + || app.pending_feature_edit.is_some() + || app.tool.is_some() + || app.session.active_sketch.is_some() +} + /// The bodies of `session` around its linked component `component`, in that component's frame /// at `placement`: how many, their triangles and their extent. `None` when the placement is gone. fn snapshot(session: &Session, component: u64, placement: &[u64]) -> Option<(usize, Vec<([f32; 3], [f32; 3])>, Aabb3)> { @@ -142,6 +154,10 @@ pub(crate) fn enter(app: &mut SolveApp, component: u64, path: Option>) if busy(app) { return; } + if working(app) { + app.set_status(crate::i18n::tr("ui.edit_in_place_busy").to_string(), true); + return; + } let Some(assembly) = app.session.path.clone() else { app.set_status(crate::i18n::tr("ui.edit_in_place_save_first").to_string(), true); return; @@ -253,11 +269,14 @@ fn take_refresh(app: &mut SolveApp) { app.set_status(crate::i18n::tr("ui.edit_in_place_refresh_dropped").to_string(), true); return; } - // What was picked or activated in the assembly meanwhile stays as it is. + // What changed in the assembly meanwhile without changing its document (a pick, an + // activation, a component dragged but not captured) stays, and the revision only moves on. computed.selection.clone_from(&session.selection); computed.active_sketch = session.active_sketch; computed.active_component = session.active_component; computed.active_occurrence_path.clone_from(&session.active_occurrence_path); + computed.pending_moves.clone_from(&session.pending_moves); + computed.revision = computed.revision.max(session.revision) + 1; session.accept_computed(computed); // Every link was read: coming back to the assembly need not read them again. crate::documents::read_again_at(app, &r.assembly); @@ -272,39 +291,55 @@ fn take_refresh(app: &mut SolveApp) { app.set_status(language.format("ui.command_done", &[("command", language.label(crate::command_label("component.update_links")))]), false); } -/// Finish Editing: save the part (and wait for it), go back to the assembly, close the part's -/// tab when the edit opened it and read the assembly's links again. +/// Finish Editing from the window (its button, the back button): a part with changes is saved +/// first, with whatever the save asks, and the edit finishes once the save is done. pub(crate) fn finish(app: &mut SolveApp) { + let _ = finish_with(app, true); +} + +/// `component.finish_edit` run as a command: it opens nothing, so a part with changes is +/// refused (save it first), as is anything else that holds Finish Editing up. +pub(crate) fn finish_command(app: &mut SolveApp) -> Result<(), String> { + finish_with(app, false) +} + +fn refuse(app: &mut SolveApp, why: String) -> Result<(), String> { + app.set_status(why.clone(), true); + Err(why) +} + +/// Save the part (`save`: and wait for it), go back to the assembly, close the part's tab when +/// the edit opened it and read the assembly's links again. +fn finish_with(app: &mut SolveApp, save: bool) -> Result<(), String> { let Some(part) = app.edit_in_place.active.as_ref().map(|c| c.part.clone()) else { - app.set_status(crate::i18n::tr("ui.edit_in_place_none").to_string(), true); - return; + return refuse(app, crate::i18n::tr("ui.edit_in_place_none").to_string()); }; if !can_finish(app) { - app.set_status(crate::i18n::tr("ui.edit_in_place_busy").to_string(), true); - return; + return refuse(app, crate::i18n::tr("ui.edit_in_place_busy").to_string()); } // Saved to another file (Save As, a copy of a read-only design): the assembly still links this one. if !app.session.path.as_deref().is_some_and(|p| crate::documents::same_path(p, &part)) { let name = std::path::Path::new(&part).file_stem().map_or_else(|| part.clone(), |n| n.to_string_lossy().into_owned()); - app.set_status(crate::i18n::format("ui.edit_in_place_saved_elsewhere", &[("name", &name)]), true); - return; + return refuse(app, crate::i18n::format("ui.edit_in_place_saved_elsewhere", &[("name", &name)])); } if app.session.is_dirty() { + if !save { + return refuse(app, crate::i18n::tr("ui.edit_in_place_not_saved").to_string()); + } app.edit_in_place.finish_after_save = Some(part); crate::toolbar::save(app); - return; + return Ok(()); } - let Some(context) = app.edit_in_place.active.take() else { return }; + let Some(context) = app.edit_in_place.active.take() else { return Ok(()) }; let part_tab = app.docs.active; - match crate::documents::reuse_path(app, &context.assembly) { - Ok(true) => {} - _ => { - app.set_status(crate::i18n::format("ui.edit_in_place_assembly_closed", &[("name", &context.assembly_name)]), true); - app.edit_in_place.active = Some(context); - return; - } + if !matches!(crate::documents::reuse_path(app, &context.assembly), Ok(true)) { + let why = crate::i18n::format("ui.edit_in_place_assembly_closed", &[("name", &context.assembly_name)]); + app.edit_in_place.active = Some(context); + return refuse(app, why); } - if context.opened { + // Closing the tab would end the part's agent chat with it: a running chat keeps the tab. + let chat = crate::documents::chat_running_at(app, part_tab); + if context.opened && !chat { crate::documents::close(app, part_tab, false); } // Coming back to its tab reads what changed, unless it read nothing (`update_changed_links` @@ -315,19 +350,15 @@ pub(crate) fn finish(app: &mut SolveApp) { request.design = Some(context.assembly); let _ = crate::file_load::begin_request(app, request); } + Ok(()) } /// Nothing is under way in the part that leaving its tab would cut short or that waits for an /// answer: a dialog or tool, a feature being computed or edited, a sketch, a prompt or Home. fn can_finish(app: &SolveApp) -> bool { !busy(app) - && app.dialog.is_none() - && app.applying.is_none() - && app.editing_state.is_none() - && app.pending_feature_edit.is_none() + && !working(app) && app.deferred.is_none() - && app.tool.is_none() - && app.session.active_sketch.is_none() && app.docs.closing.is_none() && app.docs.quitting.is_none() && app.docs.batch.is_none() diff --git a/crates/ui-egui/src/edit_in_place_tests.rs b/crates/ui-egui/src/edit_in_place_tests.rs index 0ec17474581..49b16cf98c8 100644 --- a/crates/ui-egui/src/edit_in_place_tests.rs +++ b/crates/ui-egui/src/edit_in_place_tests.rs @@ -149,17 +149,21 @@ fn update_links_in_the_part_refreshes_the_assembly_around_it() { #[test] fn looking_at_the_assembly_while_it_refreshes_keeps_the_refresh() { - let mut f = assembly("looked"); - f.app.preferences.update_changed_links = false; - double_click_component(&mut f.app, json!({"component": f.plate})); - settle(&mut f.app); - save_box(&f.post_file, [10.0, 10.0, 10.0], true); - refresh(&mut f.app); - crate::documents::switch(&mut f.app, 0); - crate::documents::switch(&mut f.app, 1); - settle(&mut f.app); - let assembly = crate::documents::session_at(&f.app, &context(&f.app).assembly).unwrap(); - assert!((volume_of(assembly, "") - 7250.0).abs() < 1e-6, "showing the assembly changes nothing in it: {}", volume_of(assembly, "")); + for update_changed_links in [false, true] { + let mut f = assembly(&format!("looked-{update_changed_links}")); + f.app.preferences.update_changed_links = update_changed_links; + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + save_box(&f.post_file, [10.0, 10.0, 10.0], true); + refresh(&mut f.app); + crate::documents::switch(&mut f.app, 0); + assert!(f.app.file_load.idle(), "no second read of the same links"); + crate::documents::switch(&mut f.app, 1); + settle(&mut f.app); + assert!(f.app.status.as_ref().is_some_and(|(_, _, error)| !error), "{:?}", f.app.status); + let assembly = crate::documents::session_at(&f.app, &context(&f.app).assembly).unwrap(); + assert!((volume_of(assembly, "") - 7250.0).abs() < 1e-6, "showing the assembly changes nothing in it: {}", volume_of(assembly, "")); + } } #[test] @@ -417,8 +421,8 @@ fn finish_editing_waits_for_what_is_open_in_the_part() { settle(&mut f.app); f.app.start("solid.box"); assert!(f.app.dialog.is_some()); - // As an agent calls it: the command, not the button - f.app.run("component.finish_edit", json!({})).unwrap(); + // As an agent calls it: the command, not the button, and the refusal is its answer + assert!(f.app.run("component.finish_edit", json!({})).is_err()); settle(&mut f.app); assert!(f.app.edit_in_place.active.is_some() && f.app.dialog.is_some()); assert!(f.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", f.app.status); @@ -427,6 +431,115 @@ fn finish_editing_waits_for_what_is_open_in_the_part() { settle(&mut f.app); assert!(f.app.edit_in_place.active.is_none()); assert_eq!(f.app.docs.count(), 1); + assert!(f.app.run("component.finish_edit", json!({})).is_err(), "nothing is edited in place any more"); +} + +#[test] +fn finish_editing_as_a_command_opens_nothing_for_a_part_with_changes() { + let mut f = assembly("command-dirty"); + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + f.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "operation": "new"})).unwrap(); + let e = f.app.run("component.finish_edit", json!({})).unwrap_err(); + assert!(e.contains("not saved"), "{e}"); + assert!(f.app.saving.is_none() && f.app.file_picker.is_none() && f.app.dialog.is_none() && f.app.edit_in_place.finish_after_save.is_none()); + assert!(showing(&f.app, &f.plate_file) && f.app.edit_in_place.active.is_some()); + f.app.run("file.save", json!({})).unwrap(); + f.app.run("component.finish_edit", json!({})).unwrap(); + settle(&mut f.app); + assert_eq!(f.app.docs.count(), 1); + assert!((volume(&f.app) - 8000.0).abs() < 1e-6, "{}", volume(&f.app)); +} + +#[test] +fn finish_editing_is_sent_on_its_own_not_in_a_batch_or_script() { + let mut f = assembly("control"); + let mut h = crate::scenario::Harness::new(); + h.app = std::mem::replace(&mut f.app, SolveApp::new(Session::default(), Default::default())); + double_click_component(&mut h.app, json!({"component": f.plate})); + settle(&mut h.app); + let steps = json!([{"command": "solid.box", "params": {"length": 1, "width": 1, "height": 1}}, {"command": "component.finish_edit"}]); + for (method, params) in [("engine.batch", json!({"commands": steps})), ("engine.script", json!({"commands": steps}))] { + let reply = h.call(method, params); + assert!(reply.to_string().contains("switches to another design"), "{method}: {reply}"); + assert!(showing(&h.app, &f.plate_file) && h.app.edit_in_place.active.is_some(), "{method}"); + } + assert_eq!(volume(&h.app), 6000.0, "no step ran"); + let reply = h.call("engine.execute", json!({"command": "component.finish_edit"})); + settle(&mut h.app); + assert!(h.app.edit_in_place.active.is_none(), "{reply}"); + assert_eq!(h.app.docs.count(), 1); +} + +#[test] +fn the_mouse_back_button_finishes_the_edit() { + let mut f = assembly("mouse-back"); + let mut h = crate::scenario::Harness::new(); + h.app = std::mem::replace(&mut f.app, SolveApp::new(Session::default(), Default::default())); + h.app.home.open = false; + double_click_component(&mut h.app, json!({"component": f.plate})); + settle(&mut h.app); + h.frames(2); + let pos = egui::pos2(400.0, 300.0); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Extra1, pressed, modifiers: Default::default() }; + h.frame_with(vec![egui::Event::PointerMoved(pos), button(true)]); + h.frame_with(vec![button(false)]); + settle(&mut h.app); + assert!(h.app.edit_in_place.active.is_none()); + assert!(!showing(&h.app, &f.plate_file)); + assert_eq!(h.app.docs.count(), 1); +} + +#[test] +fn a_dialog_open_in_the_assembly_keeps_a_double_click_from_leaving_it() { + use crate::context_menu::{self, Target}; + let mut f = assembly("assembly-dialog"); + f.app.start("solid.box"); + assert!(f.app.dialog.is_some()); + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + assert!(f.app.dialog.is_some(), "the dialog stays"); + assert_eq!(f.app.docs.count(), 1); + assert!(f.app.edit_in_place.active.is_none() && f.app.edit_in_place.pending.is_none()); + let edit = context_menu::items(&f.app, &Target::Component { id: f.plate }).into_iter().find(|i| i.id == "ui.editInPlace").unwrap(); + context_menu::run_item(&mut f.app, &edit, egui::Pos2::ZERO); + settle(&mut f.app); + assert!(f.app.dialog.is_some() && f.app.docs.count() == 1); + assert!(f.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", f.app.status); +} + +#[test] +fn a_new_design_in_the_parts_tab_ends_the_edit() { + let mut f = assembly("replaced"); + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + f.app.run("file.new", json!({})).unwrap(); + assert!(f.app.edit_in_place.active.is_none()); + assert!(bounds(&f.app).is_none(), "no assembly drawn around the new design"); +} + +#[test] +fn what_is_done_in_the_assembly_while_it_refreshes_stays() { + let mut f = assembly("meanwhile"); + f.app.preferences.update_changed_links = false; + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + save_box(&f.post_file, [10.0, 10.0, 10.0], true); + refresh(&mut f.app); + crate::documents::switch(&mut f.app, 0); + // Picked, activated and dragged without capturing: none of it changes the document + let post = f.app.session.doc.occurrences.iter().find(|o| o.component != f.plate).map(|o| o.id).unwrap(); + f.app.run("select.set", json!({"items": [{"type": "occurrence", "path": [post]}]})).unwrap(); + f.app.run("component.activate", json!({"component": f.plate})).unwrap(); + f.app.run("occurrence.move", json!({"occurrence": post, "translate": [0, 0, 5], "capture": false})).unwrap(); + let (picked, moves, revision) = (f.app.session.selection.clone(), f.app.session.pending_moves.clone(), f.app.session.revision); + assert!(!moves.is_empty()); + settle(&mut f.app); + assert!((volume(&f.app) - 7250.0).abs() < 1e-6, "the refresh landed: {}", volume(&f.app)); + assert_eq!(f.app.session.selection, picked); + assert_eq!(f.app.session.active_component, f.plate); + assert_eq!(f.app.session.pending_moves, moves, "the drag stays where it was let go"); + assert!(f.app.session.revision > revision, "the revision only moves on"); } #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3b99b0f9fa8..4251eb72adc 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -990,11 +990,11 @@ impl SolveApp { /// Host effects shared by directly executed and already evaluated commands. pub(crate) fn command_completed(&mut self, id: &str, r: Result) -> Result { + // The engine has no edit in place to finish; the window does, and says when it can't. + let r = if id == "component.finish_edit" { r.and_then(|v| edit_in_place::finish_command(self).map(|()| v)) } else { r }; if let Ok(v) = &r { match id { "view.fit" | "view.home" => self.frame_view(id == "view.home"), - // The engine has no edit in place to finish; the window does, for every caller. - "component.finish_edit" => edit_in_place::finish(self), "view.tool" => { self.viewport.nav = match v.get("tool").and_then(Value::as_str) { Some("orbit") => Some(viewport::NavMode::Orbit), @@ -1119,6 +1119,7 @@ impl SolveApp { } if matches!(id, "file.new" | "doc.open" | "doc.recover") { documents::reset_chat(self); + self.edit_in_place.active = None; render_workspace::reset_document(self); dim_view::cancel(); self.menu.props = None; @@ -1305,6 +1306,10 @@ impl SolveApp { return; } // The picked drawing is placed (position and scale, previewed) before OK adds it. + if id == "component.finish_edit" { + edit_in_place::finish(self); + return; + } if let Some(ext) = id.strip_prefix("sketch.insert_").filter(|e| matches!(*e, "dxf" | "svg")) { let command = id.to_string(); self.pick_open_for(&[ext], move |app, path| { From ca47eea92a8bce81cc17f054d3c23eeac143b3e8 Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 16:24:37 +0100 Subject: [PATCH 13/20] Edit in place: Update Links run as a command in the part refreshes the assembly too Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/edit_in_place_tests.rs | 16 ++++++++++++++++ crates/ui-egui/src/lib.rs | 2 ++ 2 files changed, 18 insertions(+) diff --git a/crates/ui-egui/src/edit_in_place_tests.rs b/crates/ui-egui/src/edit_in_place_tests.rs index 49b16cf98c8..f9fbd8b3ffb 100644 --- a/crates/ui-egui/src/edit_in_place_tests.rs +++ b/crates/ui-egui/src/edit_in_place_tests.rs @@ -147,6 +147,22 @@ fn update_links_in_the_part_refreshes_the_assembly_around_it() { assert!((volume(&f.app) - 7250.0).abs() < 1e-6, "{}", volume(&f.app)); } +#[test] +fn update_links_run_as_a_command_in_the_part_refreshes_the_assembly_too() { + let mut f = assembly("refresh-command"); + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + save_box(&f.post_file, [10.0, 10.0, 10.0], true); + f.app.run("component.update_links", json!({})).unwrap(); + assert!(f.app.edit_in_place.refreshing()); + settle(&mut f.app); + assert!(showing(&f.app, &f.plate_file)); + let after = context(&f.app); + assert!((after.bounds.max.z - 20.0).abs() < 1e-6, "the post's new box shows: {:?}", after.bounds); + let assembly = crate::documents::session_at(&f.app, &after.assembly).unwrap(); + assert!((volume_of(assembly, "") - 7250.0).abs() < 1e-6, "{}", volume_of(assembly, "")); +} + #[test] fn looking_at_the_assembly_while_it_refreshes_keeps_the_refresh() { for update_changed_links in [false, true] { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4251eb72adc..f26708b97f3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -995,6 +995,8 @@ impl SolveApp { if let Ok(v) = &r { match id { "view.fit" | "view.home" => self.frame_view(id == "view.home"), + // Run as a command, it reaches no `start`: the assembly around the part follows here. + "component.update_links" if self.edit_in_place.active.is_some() => edit_in_place::refresh(self), "view.tool" => { self.viewport.nav = match v.get("tool").and_then(Value::as_str) { Some("orbit") => Some(viewport::NavMode::Orbit), From 258ce3b95c46b6d09994b938c409ecb3d38fa34b Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 16:49:31 +0100 Subject: [PATCH 14/20] Edit in place: the ribbon button reads Finish Edit, as Finish Sketch does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A bare "Finish" took the catalogs' surface-finish translation (German "Oberfläche"). Co-Authored-By: Claude Opus 5.5 --- assets/locales/pending/edit-in-place.json | 7 +++++++ crates/ui-egui/src/edit_in_place_tests.rs | 8 ++++++++ crates/ui-egui/src/workspace.rs | 2 +- 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json index af8e24e8157..4b4c4969f18 100644 --- a/assets/locales/pending/edit-in-place.json +++ b/assets/locales/pending/edit-in-place.json @@ -14,6 +14,7 @@ "ui.edit_in_place_save_first": "Save the assembly first: its linked designs are found from its file", "ui.edit_in_place_save_waits": "Update Links is running in {name}; save it once it is done", "ui.edit_in_place_saved_elsewhere": "The part was saved to another file; the assembly still links {name}", + "ui.finish_edit": "Finish Edit", "cmd.component_finish_edit": "Finish Editing" }, "ar": { @@ -31,6 +32,7 @@ "ui.edit_in_place_save_first": "احفظ التجميع أولاً: يُعثر على تصاميمه المرتبطة انطلاقًا من ملفه", "ui.edit_in_place_save_waits": "يجري تحديث الروابط في {name}؛ احفظه بعد انتهائه", "ui.edit_in_place_saved_elsewhere": "حُفظ الجزء في ملف آخر؛ ما زال التجميع مرتبطًا بـ {name}", + "ui.finish_edit": "إنهاء التحرير", "cmd.component_finish_edit": "إنهاء التحرير" }, "de": { @@ -48,6 +50,7 @@ "ui.edit_in_place_save_first": "Zuerst die Baugruppe speichern: ihre verknüpften Designs werden von ihrer Datei aus gefunden", "ui.edit_in_place_save_waits": "In {name} werden die Verknüpfungen aktualisiert; danach speichern", "ui.edit_in_place_saved_elsewhere": "Das Teil wurde in eine andere Datei gespeichert; die Baugruppe verknüpft weiterhin {name}", + "ui.finish_edit": "Bearbeitung beenden", "cmd.component_finish_edit": "Bearbeitung beenden" }, "he": { @@ -65,6 +68,7 @@ "ui.edit_in_place_save_first": "יש לשמור קודם את ההרכבה: התכנים המקושרים שלה נמצאים לפי הקובץ שלה", "ui.edit_in_place_save_waits": "עדכון הקישורים פועל ב-{name}; יש לשמור לאחר שיסתיים", "ui.edit_in_place_saved_elsewhere": "החלק נשמר לקובץ אחר; ההרכבה עדיין מקושרת אל {name}", + "ui.finish_edit": "סיום עריכה", "cmd.component_finish_edit": "סיום עריכה" }, "ja": { @@ -82,6 +86,7 @@ "ui.edit_in_place_save_first": "先にアセンブリを保存してください。リンクされたデザインはそのファイルから見つけます", "ui.edit_in_place_save_waits": "{name} のリンクを更新中です。完了してから保存してください", "ui.edit_in_place_saved_elsewhere": "部品は別のファイルに保存されました。アセンブリは引き続き {name} にリンクしています", + "ui.finish_edit": "編集を終了", "cmd.component_finish_edit": "編集を終了" }, "vi": { @@ -99,6 +104,7 @@ "ui.edit_in_place_save_first": "Hãy lưu cụm lắp ráp trước: các thiết kế liên kết của nó được tìm từ tệp của nó", "ui.edit_in_place_save_waits": "Đang cập nhật liên kết trong {name}; hãy lưu sau khi hoàn tất", "ui.edit_in_place_saved_elsewhere": "Chi tiết đã được lưu vào tệp khác; cụm lắp ráp vẫn liên kết với {name}", + "ui.finish_edit": "Hoàn tất chỉnh sửa", "cmd.component_finish_edit": "Kết thúc chỉnh sửa" }, "zh": { @@ -116,6 +122,7 @@ "ui.edit_in_place_save_first": "请先保存装配体:其链接设计根据其文件查找", "ui.edit_in_place_save_waits": "正在更新 {name} 中的链接;请在完成后保存", "ui.edit_in_place_saved_elsewhere": "零件已保存到其他文件;装配体仍链接 {name}", + "ui.finish_edit": "完成编辑", "cmd.component_finish_edit": "完成编辑" } } diff --git a/crates/ui-egui/src/edit_in_place_tests.rs b/crates/ui-egui/src/edit_in_place_tests.rs index f9fbd8b3ffb..56b1e05442c 100644 --- a/crates/ui-egui/src/edit_in_place_tests.rs +++ b/crates/ui-egui/src/edit_in_place_tests.rs @@ -558,6 +558,14 @@ fn what_is_done_in_the_assembly_while_it_refreshes_stays() { assert!(f.app.session.revision > revision, "the revision only moves on"); } +#[test] +fn the_ribbon_button_reads_finish_edit_in_every_language() { + // A bare "Finish" is a surface finish in other catalogs (German "Oberfläche") + let label = crate::workspace::ribbon_button_label(solidcraft_engine::find_command("component.finish_edit").unwrap()); + assert_eq!(label, "Finish Edit"); + assert_eq!(crate::i18n::Locale::for_language("de").label(label), "Bearbeitung beenden"); +} + #[test] fn finish_editing_keeps_its_panel_to_itself() { let mut app = SolveApp::new(Session::default(), Default::default()); diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index 1f43a2d670d..c714a264260 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -419,7 +419,7 @@ pub const RIBBON_LABELS: &[(&str, &str)] = &[ ("sketch.create", "New Sketch"), ("sketch.dimension", "Dimension"), ("sketch.finish", "Finish Sketch"), - ("component.finish_edit", "Finish"), + ("component.finish_edit", "Finish Edit"), ("sketch.pattern.circular", "Circular"), ("sketch.pattern.rectangular", "Rectangular"), ("sketch.rectangle.two_point", "Rectangle"), From f36d0a8796a5245a81580d013921287755a9c8bf Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 17:16:37 +0100 Subject: [PATCH 15/20] Edit in place: fixes from the fourth review Finish Edit waits while the part's agent is in the middle of its turn, instead of keeping the tab of any chat open A part saved while its assembly refreshes is read again when the edit finishes: the refresh records the files as it found them A double-click on a linked component while something is open in the assembly says so instead of activating it Commands are recognised in any spelling the engine takes, so engine.batch and engine.script cannot slip Finish Edit through Update Links run as a command refreshes the assembly from the control channel only, not for the app's own reads Moves of components the refresh removed are not carried over, and a refusal is one message The command description and the guide say that the command does not save the part Co-Authored-By: Claude Opus 5.5 --- assets/locales/pending/edit-in-place.json | 11 +++- crates/engine/src/cmd/component.rs | 5 +- crates/ui-egui/src/agent_chat/mod.rs | 4 ++ crates/ui-egui/src/control.rs | 13 ++++- crates/ui-egui/src/documents.rs | 32 ++++------- crates/ui-egui/src/edit_in_place.rs | 52 +++++++++--------- crates/ui-egui/src/edit_in_place_tests.rs | 66 +++++++++++++++++++++-- crates/ui-egui/src/lib.rs | 7 ++- docs/book/src/guide/assemblies.md | 5 +- 9 files changed, 133 insertions(+), 62 deletions(-) diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json index 4b4c4969f18..54f70669ad7 100644 --- a/assets/locales/pending/edit-in-place.json +++ b/assets/locales/pending/edit-in-place.json @@ -3,6 +3,7 @@ "settings.double_click_components": "Double-click a component to activate it, or to edit a linked one in place", "ui.heading_finish_editing": "FINISH EDITING", "ui.edit_in_place": "Edit in Place", + "ui.edit_in_place_agent_busy": "The agent is still working in the part; finish editing once its turn is done", "ui.edit_in_place_assembly_closed": "{name} is no longer open", "ui.edit_in_place_banner": "Editing in {name}", "ui.edit_in_place_busy": "Finish or cancel what is open first", @@ -21,6 +22,7 @@ "settings.double_click_components": "انقر نقرًا مزدوجًا على مكوّن لتنشيطه، أو لتحرير مكوّن مرتبط في مكانه", "ui.heading_finish_editing": "إنهاء التحرير", "ui.edit_in_place": "تحرير في المكان", + "ui.edit_in_place_agent_busy": "لا يزال الوكيل يعمل في الجزء؛ أنهِ التحرير بعد انتهاء دوره", "ui.edit_in_place_assembly_closed": "{name} لم يعد مفتوحًا", "ui.edit_in_place_banner": "تحرير داخل {name}", "ui.edit_in_place_busy": "أنهِ ما هو مفتوح أو ألغِه أولاً", @@ -39,6 +41,7 @@ "settings.double_click_components": "Doppelklick auf eine Komponente aktiviert sie oder bearbeitet eine verknüpfte an Ort und Stelle", "ui.heading_finish_editing": "BEARBEITUNG BEENDEN", "ui.edit_in_place": "An Ort und Stelle bearbeiten", + "ui.edit_in_place_agent_busy": "Der Agent arbeitet noch im Teil; die Bearbeitung beenden, sobald er fertig ist", "ui.edit_in_place_assembly_closed": "{name} ist nicht mehr geöffnet", "ui.edit_in_place_banner": "Bearbeitung in {name}", "ui.edit_in_place_busy": "Zuerst abschließen oder abbrechen, was offen ist", @@ -57,6 +60,7 @@ "settings.double_click_components": "לחיצה כפולה על רכיב מפעילה אותו, או עורכת רכיב מקושר במקומו", "ui.heading_finish_editing": "סיום עריכה", "ui.edit_in_place": "עריכה במקום", + "ui.edit_in_place_agent_busy": "הסוכן עדיין עובד בחלק; יש לסיים את העריכה כשתורו יסתיים", "ui.edit_in_place_assembly_closed": "{name} כבר אינו פתוח", "ui.edit_in_place_banner": "עריכה בתוך {name}", "ui.edit_in_place_busy": "יש לסיים או לבטל קודם את מה שפתוח", @@ -75,6 +79,7 @@ "settings.double_click_components": "コンポーネントをダブルクリックしてアクティブにする、またはリンクされたものをその場で編集する", "ui.heading_finish_editing": "編集を終了", "ui.edit_in_place": "その場で編集", + "ui.edit_in_place_agent_busy": "エージェントがまだ部品で作業中です。そのターンが終わってから編集を終了してください", "ui.edit_in_place_assembly_closed": "{name} はもう開いていません", "ui.edit_in_place_banner": "{name} 内で編集中", "ui.edit_in_place_busy": "先に開いているものを終了またはキャンセルしてください", @@ -91,8 +96,9 @@ }, "vi": { "settings.double_click_components": "Nhấp đúp vào một thành phần để kích hoạt nó, hoặc chỉnh sửa tại chỗ một thành phần liên kết", - "ui.heading_finish_editing": "KẾT THÚC CHỈNH SỬA", + "ui.heading_finish_editing": "HOÀN TẤT CHỈNH SỬA", "ui.edit_in_place": "Chỉnh sửa tại chỗ", + "ui.edit_in_place_agent_busy": "Tác tử vẫn đang làm việc trong chi tiết; hãy hoàn tất chỉnh sửa khi lượt của nó kết thúc", "ui.edit_in_place_assembly_closed": "{name} không còn mở", "ui.edit_in_place_banner": "Đang chỉnh sửa trong {name}", "ui.edit_in_place_busy": "Hãy hoàn tất hoặc hủy những gì đang mở trước", @@ -105,12 +111,13 @@ "ui.edit_in_place_save_waits": "Đang cập nhật liên kết trong {name}; hãy lưu sau khi hoàn tất", "ui.edit_in_place_saved_elsewhere": "Chi tiết đã được lưu vào tệp khác; cụm lắp ráp vẫn liên kết với {name}", "ui.finish_edit": "Hoàn tất chỉnh sửa", - "cmd.component_finish_edit": "Kết thúc chỉnh sửa" + "cmd.component_finish_edit": "Hoàn tất chỉnh sửa" }, "zh": { "settings.double_click_components": "双击组件以激活它,或在原位编辑链接组件", "ui.heading_finish_editing": "完成编辑", "ui.edit_in_place": "原位编辑", + "ui.edit_in_place_agent_busy": "代理仍在零件中工作;请在其本轮结束后完成编辑", "ui.edit_in_place_assembly_closed": "{name} 已不再打开", "ui.edit_in_place_banner": "正在 {name} 中编辑", "ui.edit_in_place_busy": "请先完成或取消打开的操作", diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index b7f299f7be8..47a4897707e 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -53,7 +53,10 @@ pub static COMMANDS: &[CommandSpec] = &[ .doc_only() .contract(&FINISH_EDIT_CONTRACT) .output(output_schema_for::) - .params("no parameters → in the app window: save the linked design edited in place and go back to its assembly; elsewhere nothing changes"), + .params( + "no parameters → in the app window: go back from the linked design edited in place to its assembly, which reads it again; \ + fails while the design has unsaved changes (run file.save first) or something is open in it; elsewhere nothing changes", + ), CommandSpec::new("component.list", "List Components", list).icon("list").noundo().params( "compact?: bool (counts of bodies, features, sketches and construction planes instead of their names; occurrences leave out \ identity transforms; children as occurrence ids); bodies?: bool (with compact: body names, not their count)", diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index 866a61a23e6..b000314e095 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -516,6 +516,10 @@ impl AgentChat { pub fn state(&self) -> State { self.state.unwrap_or(State::Off) } + #[cfg(test)] + pub(crate) fn set_state(&mut self, state: State) { + self.state = Some(state); + } fn push(&mut self, item: Item) { if self.items.len() >= MAX_ITEMS { self.items.drain(..MAX_ITEMS / 10); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index c6b4ee48117..48b537ff86d 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -223,6 +223,10 @@ fn execute(app: &mut SolveApp, id: &str, params: Value) -> Result return crate::view_pick::pick_command(app, ¶ms); } let r = app.run(id, params); + // Update Links in a part edited in place reads the assembly around it too, as its button does. + if r.is_ok() && is_command(Some(id), "component.update_links") && app.edit_in_place.active.is_some() { + crate::edit_in_place::refresh(app); + } if r.is_ok() && !matches!( id, @@ -271,10 +275,15 @@ const LOADS_A_FILE: [&str; 3] = ["doc.open", "file.insert_step", "file.insert_me /// later steps, would land in the wrong design. const SWITCHES_DESIGN: &str = "component.finish_edit"; +/// `command` names the command `id`, in any of the spellings the engine takes. +fn is_command(command: Option<&str>, id: &str) -> bool { + command.and_then(solidcraft_engine::find_command).is_some_and(|spec| spec.id == id) +} + /// Why `engine.batch` refuses these steps before running any: a step loads a file or switches /// to another design (send such steps one by one). pub(crate) fn batch_refusal(steps: &[Value]) -> Option { - if let Some(i) = steps.iter().position(|step| command(step) == Some(SWITCHES_DESIGN)) { + if let Some(i) = steps.iter().position(|step| is_command(command(step), SWITCHES_DESIGN)) { return Some(format!("engine.batch unavailable: step {i} ({SWITCHES_DESIGN}) switches to another design")); } let (i, c) = steps.iter().enumerate().find_map(|(i, step)| command(step).filter(|c| LOADS_A_FILE.contains(c)).map(|c| (i, c)))?; @@ -471,7 +480,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> } "engine.script" => { let steps = p.as_array().or_else(|| p.get("commands").and_then(Value::as_array)); - if steps.is_some_and(|steps| steps.iter().any(|step| command(step) == Some(SWITCHES_DESIGN))) { + if steps.is_some_and(|steps| steps.iter().any(|step| is_command(command(step), SWITCHES_DESIGN))) { return err(format!("engine.script unavailable: {SWITCHES_DESIGN} switches to another design (send it on its own)")); } let mut replaced = false; diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 95ae1d37cec..8338fbddd76 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -247,30 +247,18 @@ pub(crate) fn session_at<'a>(app: &'a SolveApp, path: &str) -> Option<&'a Sessio app.docs.slots.iter().flatten().map(|s| &s.session).find(|s| saved_at(s)) } -/// The design in tab `i` has an agent chat running (closing the tab would end it). -pub(crate) fn chat_running_at(app: &SolveApp, i: usize) -> bool { - let chat = if i == app.docs.active { - &app.agent_chat +/// The open design saved at `path` read every link again without an error, from the files as +/// `stamps` found them: its record of them (`Documents::link_stamps`, or its tab's) is now that. +pub(crate) fn record_stamps_at(app: &mut SolveApp, path: &str, stamps: &[(u64, crate::linked_source::Stamp)]) { + let record = if app.session.path.as_deref().is_some_and(|p| same_path(p, path)) { + &mut app.docs.link_stamps } else { - let Some(slot) = app.docs.slots.get(i).and_then(Option::as_ref) else { return false }; - &slot.agent_chat + let saved_at = |s: &DocSlot| s.session.path.as_deref().is_some_and(|p| same_path(p, path)); + let Some(slot) = app.docs.slots.iter_mut().flatten().find(|s| saved_at(s)) else { return }; + &mut slot.link_stamps }; - !matches!(chat.state(), crate::agent_chat::State::Off | crate::agent_chat::State::Exited) -} - -/// The open design saved at `path` read every link again without an error: its record of them -/// (`Documents::link_stamps`, or its tab's) is now its files as they are. -pub(crate) fn read_again_at(app: &mut SolveApp, path: &str) { - if app.session.path.as_deref().is_some_and(|p| same_path(p, path)) { - crate::linked_source::read_again(app, None); - return; - } - let on = app.preferences.update_changed_links; - let saved_at = |s: &DocSlot| s.session.path.as_deref().is_some_and(|p| same_path(p, path)); - if let Some(slot) = app.docs.slots.iter_mut().flatten().find(|s| saved_at(s)) { - for (c, s) in crate::linked_source::stamps_of(&mut slot.session, on) { - crate::linked_source::record(&mut slot.link_stamps, c, s); - } + for (c, s) in stamps { + crate::linked_source::record(record, *c, *s); } } diff --git a/crates/ui-egui/src/edit_in_place.rs b/crates/ui-egui/src/edit_in_place.rs index 214a3f6b2d6..d95c347736b 100644 --- a/crates/ui-egui/src/edit_in_place.rs +++ b/crates/ui-egui/src/edit_in_place.rs @@ -46,6 +46,8 @@ struct Refresh { /// changed since is dropped (showing it changes nothing). assembly: String, base: Arc, + /// The linked files as they were when the run started reading them. + stamps: Vec<(u64, crate::linked_source::Stamp)>, done: Receiver>, } @@ -68,11 +70,10 @@ impl EditInPlace { /// A component double-clicked in the browser: a linked one is edited in place (Preferences: /// `double_click_components`), any other is made the active component (`component.activate` -/// with `params`), as is a linked one while a dialog or tool is open. Activate itself always -/// does the latter. +/// with `params`). Activate itself always does the latter. pub(crate) fn double_click_component(app: &mut SolveApp, params: Value) { let component = params["component"].as_u64().unwrap_or(0); - if app.preferences.double_click_components && !working(app) && app.session.doc.links.contains_key(&component) { + if app.preferences.double_click_components && app.session.doc.links.contains_key(&component) { let path = params["path"].as_array().map(|p| p.iter().filter_map(Value::as_u64).collect::>()); enter(app, component, path); } else { @@ -230,6 +231,7 @@ pub(crate) fn refresh(app: &mut SolveApp) { // Link paths are kept relative to the design's own file. scratch.path.clone_from(&session.path); let base = session.doc.clone(); + let stamps = crate::linked_source::stamps_of(&mut scratch, app.preferences.update_changed_links); let (tx, done) = std::sync::mpsc::channel(); let run = move || { let r = scratch.execute("component.update_links", &json!({})).map(|_| scratch).map_err(|e| e.to_string()); @@ -242,7 +244,7 @@ pub(crate) fn refresh(app: &mut SolveApp) { } #[cfg(target_arch = "wasm32")] run(); - app.edit_in_place.refresh = Some(Refresh { assembly, base, done }); + app.edit_in_place.refresh = Some(Refresh { assembly, base, stamps, done }); let name = app.edit_in_place.active.as_ref().map(|c| c.assembly_name.clone()).unwrap_or_default(); app.set_status(crate::i18n::format("ui.edit_in_place_refreshing", &[("name", &name)]), false); } @@ -270,16 +272,18 @@ fn take_refresh(app: &mut SolveApp) { return; } // What changed in the assembly meanwhile without changing its document (a pick, an - // activation, a component dragged but not captured) stays, and the revision only moves on. + // activation, a component dragged but not captured) stays. computed.selection.clone_from(&session.selection); computed.active_sketch = session.active_sketch; computed.active_component = session.active_component; computed.active_occurrence_path.clone_from(&session.active_occurrence_path); - computed.pending_moves.clone_from(&session.pending_moves); - computed.revision = computed.revision.max(session.revision) + 1; + let occurrences = &computed.doc.occurrences; + computed.pending_moves = + session.pending_moves.iter().filter(|(id, _)| occurrences.iter().any(|o| o.id == **id)).map(|(id, m)| (*id, *m)).collect(); session.accept_computed(computed); - // Every link was read: coming back to the assembly need not read them again. - crate::documents::read_again_at(app, &r.assembly); + // Every link was read as its file was when the run started: one saved since is read again + // when the assembly's tab comes back. + crate::documents::record_stamps_at(app, &r.assembly, &r.stamps); let Some(context) = app.edit_in_place.active.as_ref().filter(|c| crate::documents::same_path(&c.assembly, &r.assembly)) else { return }; let (component, placement) = (context.component, context.placement.clone()); let snap = crate::documents::session_at(app, &r.assembly).and_then(|s| snapshot(s, component, &placement)); @@ -294,37 +298,39 @@ fn take_refresh(app: &mut SolveApp) { /// Finish Editing from the window (its button, the back button): a part with changes is saved /// first, with whatever the save asks, and the edit finishes once the save is done. pub(crate) fn finish(app: &mut SolveApp) { - let _ = finish_with(app, true); + if let Err(why) = finish_with(app, true) { + app.set_status(why, true); + } } /// `component.finish_edit` run as a command: it opens nothing, so a part with changes is -/// refused (save it first), as is anything else that holds Finish Editing up. +/// refused (save it first), as is anything else that holds Finish Editing up. The refusal is +/// its error, which the caller reports. pub(crate) fn finish_command(app: &mut SolveApp) -> Result<(), String> { finish_with(app, false) } -fn refuse(app: &mut SolveApp, why: String) -> Result<(), String> { - app.set_status(why.clone(), true); - Err(why) -} - /// Save the part (`save`: and wait for it), go back to the assembly, close the part's tab when /// the edit opened it and read the assembly's links again. fn finish_with(app: &mut SolveApp, save: bool) -> Result<(), String> { let Some(part) = app.edit_in_place.active.as_ref().map(|c| c.part.clone()) else { - return refuse(app, crate::i18n::tr("ui.edit_in_place_none").to_string()); + return Err(crate::i18n::tr("ui.edit_in_place_none").to_string()); }; + // Leaving the tab would stop the part's agent in the middle of its turn. + if app.agent_chat.state() == crate::agent_chat::State::Busy { + return Err(crate::i18n::tr("ui.edit_in_place_agent_busy").to_string()); + } if !can_finish(app) { - return refuse(app, crate::i18n::tr("ui.edit_in_place_busy").to_string()); + return Err(crate::i18n::tr("ui.edit_in_place_busy").to_string()); } // Saved to another file (Save As, a copy of a read-only design): the assembly still links this one. if !app.session.path.as_deref().is_some_and(|p| crate::documents::same_path(p, &part)) { let name = std::path::Path::new(&part).file_stem().map_or_else(|| part.clone(), |n| n.to_string_lossy().into_owned()); - return refuse(app, crate::i18n::format("ui.edit_in_place_saved_elsewhere", &[("name", &name)])); + return Err(crate::i18n::format("ui.edit_in_place_saved_elsewhere", &[("name", &name)])); } if app.session.is_dirty() { if !save { - return refuse(app, crate::i18n::tr("ui.edit_in_place_not_saved").to_string()); + return Err(crate::i18n::tr("ui.edit_in_place_not_saved").to_string()); } app.edit_in_place.finish_after_save = Some(part); crate::toolbar::save(app); @@ -335,11 +341,9 @@ fn finish_with(app: &mut SolveApp, save: bool) -> Result<(), String> { if !matches!(crate::documents::reuse_path(app, &context.assembly), Ok(true)) { let why = crate::i18n::format("ui.edit_in_place_assembly_closed", &[("name", &context.assembly_name)]); app.edit_in_place.active = Some(context); - return refuse(app, why); + return Err(why); } - // Closing the tab would end the part's agent chat with it: a running chat keeps the tab. - let chat = crate::documents::chat_running_at(app, part_tab); - if context.opened && !chat { + if context.opened { crate::documents::close(app, part_tab, false); } // Coming back to its tab reads what changed, unless it read nothing (`update_changed_links` diff --git a/crates/ui-egui/src/edit_in_place_tests.rs b/crates/ui-egui/src/edit_in_place_tests.rs index 56b1e05442c..8789df1c46f 100644 --- a/crates/ui-egui/src/edit_in_place_tests.rs +++ b/crates/ui-egui/src/edit_in_place_tests.rs @@ -153,8 +153,11 @@ fn update_links_run_as_a_command_in_the_part_refreshes_the_assembly_too() { double_click_component(&mut f.app, json!({"component": f.plate})); settle(&mut f.app); save_box(&f.post_file, [10.0, 10.0, 10.0], true); - f.app.run("component.update_links", json!({})).unwrap(); - assert!(f.app.edit_in_place.refreshing()); + let mut h = crate::scenario::Harness::new(); + h.app = std::mem::replace(&mut f.app, SolveApp::new(Session::default(), Default::default())); + // In any spelling the engine takes; the call may take the refresh up before it answers + h.call("engine.execute", json!({"command": "Component.Update_Links"})); + f.app = std::mem::replace(&mut h.app, SolveApp::new(Session::default(), Default::default())); settle(&mut f.app); assert!(showing(&f.app, &f.plate_file)); let after = context(&f.app); @@ -474,14 +477,15 @@ fn finish_editing_is_sent_on_its_own_not_in_a_batch_or_script() { h.app = std::mem::replace(&mut f.app, SolveApp::new(Session::default(), Default::default())); double_click_component(&mut h.app, json!({"component": f.plate})); settle(&mut h.app); - let steps = json!([{"command": "solid.box", "params": {"length": 1, "width": 1, "height": 1}}, {"command": "component.finish_edit"}]); + let steps = json!([{"command": "solid.box", "params": {"length": 1, "width": 1, "height": 1}}, {"command": "Component.Finish_Edit"}]); for (method, params) in [("engine.batch", json!({"commands": steps})), ("engine.script", json!({"commands": steps}))] { let reply = h.call(method, params); assert!(reply.to_string().contains("switches to another design"), "{method}: {reply}"); assert!(showing(&h.app, &f.plate_file) && h.app.edit_in_place.active.is_some(), "{method}"); } assert_eq!(volume(&h.app), 6000.0, "no step ran"); - let reply = h.call("engine.execute", json!({"command": "component.finish_edit"})); + // Any spelling the engine takes finishes, not just the exact one + let reply = h.call("engine.execute", json!({"command": "Component.Finish_Edit"})); settle(&mut h.app); assert!(h.app.edit_in_place.active.is_none(), "{reply}"); assert_eq!(h.app.docs.count(), 1); @@ -512,9 +516,12 @@ fn a_dialog_open_in_the_assembly_keeps_a_double_click_from_leaving_it() { let mut f = assembly("assembly-dialog"); f.app.start("solid.box"); assert!(f.app.dialog.is_some()); + let active = f.app.session.active_component; double_click_component(&mut f.app, json!({"component": f.plate})); settle(&mut f.app); assert!(f.app.dialog.is_some(), "the dialog stays"); + assert_eq!(f.app.session.active_component, active, "nor is the component activated under it"); + assert!(f.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", f.app.status); assert_eq!(f.app.docs.count(), 1); assert!(f.app.edit_in_place.active.is_none() && f.app.edit_in_place.pending.is_none()); let edit = context_menu::items(&f.app, &Target::Component { id: f.plate }).into_iter().find(|i| i.id == "ui.editInPlace").unwrap(); @@ -559,11 +566,60 @@ fn what_is_done_in_the_assembly_while_it_refreshes_stays() { } #[test] -fn the_ribbon_button_reads_finish_edit_in_every_language() { +fn the_ribbon_button_reads_finish_edit_not_a_surface_finish() { // A bare "Finish" is a surface finish in other catalogs (German "Oberfläche") let label = crate::workspace::ribbon_button_label(solidcraft_engine::find_command("component.finish_edit").unwrap()); assert_eq!(label, "Finish Edit"); assert_eq!(crate::i18n::Locale::for_language("de").label(label), "Bearbeitung beenden"); + for language in ["ar", "he", "ja", "vi", "zh"] { + assert_ne!(crate::i18n::Locale::for_language(language).label(label), label, "{language}"); + } +} + +#[test] +fn finish_editing_waits_for_the_parts_agent_to_end_its_turn() { + let mut f = assembly("agent"); + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + f.app.agent_chat.set_state(crate::agent_chat::State::Busy); + let e = f.app.run("component.finish_edit", json!({})).unwrap_err(); + assert!(e.contains("agent"), "{e}"); + finish(&mut f.app); + assert!(showing(&f.app, &f.plate_file) && f.app.edit_in_place.active.is_some()); + assert!(f.app.status.as_ref().is_some_and(|(s, _, error)| *error && s.contains("agent")), "{:?}", f.app.status); + // An idle chat goes with the tab, as closing it would take it + f.app.agent_chat.set_state(crate::agent_chat::State::Ready); + finish(&mut f.app); + settle(&mut f.app); + assert_eq!(f.app.docs.count(), 1); +} + +#[test] +fn a_refusal_is_one_message() { + let mut f = assembly("one-message"); + crate::messages::control(&mut f.app, &json!({"clear": true})); + assert!(f.app.run("component.finish_edit", json!({})).is_err()); + let messages = crate::messages::control(&mut f.app, &json!({})); + let shown: Vec<_> = + messages["messages"].as_array().unwrap().iter().filter(|m| m["text"].as_str().is_some_and(|t| t.contains("edited in place"))).collect(); + assert!(shown.len() == 1 && shown[0]["count"] == 1, "{shown:?}"); +} + +#[test] +fn a_part_saved_while_the_assembly_refreshes_is_read_when_the_edit_finishes() { + let mut f = assembly("saved-meanwhile"); + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + save_box(&f.post_file, [10.0, 10.0, 10.0], true); + refresh(&mut f.app); + // Saved before the refresh is taken up + f.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "operation": "new"})).unwrap(); + f.app.run("file.save", json!({})).unwrap(); + settle(&mut f.app); + finish(&mut f.app); + settle(&mut f.app); + assert_eq!(f.app.docs.count(), 1); + assert!((volume(&f.app) - 8250.0).abs() < 1e-6, "the post's change and the part's: {}", volume(&f.app)); } #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f26708b97f3..a592cce9806 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -991,12 +991,11 @@ impl SolveApp { /// Host effects shared by directly executed and already evaluated commands. pub(crate) fn command_completed(&mut self, id: &str, r: Result) -> Result { // The engine has no edit in place to finish; the window does, and says when it can't. - let r = if id == "component.finish_edit" { r.and_then(|v| edit_in_place::finish_command(self).map(|()| v)) } else { r }; + let finish_edit = solidcraft_engine::find_command(id).is_some_and(|spec| spec.id == "component.finish_edit"); + let r = if finish_edit { r.and_then(|v| edit_in_place::finish_command(self).map(|()| v)) } else { r }; if let Ok(v) = &r { match id { "view.fit" | "view.home" => self.frame_view(id == "view.home"), - // Run as a command, it reaches no `start`: the assembly around the part follows here. - "component.update_links" if self.edit_in_place.active.is_some() => edit_in_place::refresh(self), "view.tool" => { self.viewport.nav = match v.get("tool").and_then(Value::as_str) { Some("orbit") => Some(viewport::NavMode::Orbit), @@ -1307,11 +1306,11 @@ impl SolveApp { if dialogs_sheet::start_export(self, id) { return; } - // The picked drawing is placed (position and scale, previewed) before OK adds it. if id == "component.finish_edit" { edit_in_place::finish(self); return; } + // The picked drawing is placed (position and scale, previewed) before OK adds it. if let Some(ext) = id.strip_prefix("sketch.insert_").filter(|e| matches!(*e, "dxf" | "svg")) { let command = id.to_string(); self.pick_open_for(&[ext], move |app, path| { diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index 58c9ffb8d43..38f4fef9884 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -370,9 +370,10 @@ To edit a linked part where it sits, double-click it, in the Browser or on one o the view, or choose **Edit in Place** from its menu. Its design opens in a tab of its own with the rest of the assembly drawn faded around it, at the placement you picked, and the part's own history, Browser and commands work as usual. **Update Links** there also reads the assembly's -links again and redraws it. **Finish Editing** (`component.finish_edit`), at the right end of the +links again and redraws it. **Finish Edit** (`component.finish_edit`), at the right end of the **MODEL** tab, or the mouse's back button, saves the part and goes back to the assembly, which -takes up the change; the part's tab closes again when the edit opened it. **Activate** still makes +takes up the change; the part's tab closes again when the edit opened it. Run as a command (by +an agent, for example), it does not save: the part must be saved first. **Activate** still makes a linked component the active one without opening it, and a double-click on a component that is not linked activates it. **Double-click a component to activate it, or to edit a linked one in place** (Preferences, Design, `double_click_components`) turns this off: a double-click in the From 5512d00aad894c59802671eb4ddb5e4f29a23911 Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 17:33:36 +0100 Subject: [PATCH 16/20] Edit in place: the command is Finish Edit, as Finish Sketch is Co-Authored-By: Claude Opus 5.5 --- assets/locales/pending/edit-in-place.json | 9 +-------- crates/engine/src/cmd/component.rs | 2 +- crates/ui-egui/src/control.rs | 2 +- crates/ui-egui/src/edit_in_place.rs | 14 +++++++------- crates/ui-egui/src/edit_in_place_tests.rs | 4 ++-- crates/ui-egui/src/toolbar_custom.rs | 2 +- crates/ui-egui/src/workspace.rs | 1 - 7 files changed, 13 insertions(+), 21 deletions(-) diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json index 54f70669ad7..7c61f9f2d81 100644 --- a/assets/locales/pending/edit-in-place.json +++ b/assets/locales/pending/edit-in-place.json @@ -15,8 +15,7 @@ "ui.edit_in_place_save_first": "Save the assembly first: its linked designs are found from its file", "ui.edit_in_place_save_waits": "Update Links is running in {name}; save it once it is done", "ui.edit_in_place_saved_elsewhere": "The part was saved to another file; the assembly still links {name}", - "ui.finish_edit": "Finish Edit", - "cmd.component_finish_edit": "Finish Editing" + "cmd.component_finish_edit": "Finish Edit" }, "ar": { "settings.double_click_components": "انقر نقرًا مزدوجًا على مكوّن لتنشيطه، أو لتحرير مكوّن مرتبط في مكانه", @@ -34,7 +33,6 @@ "ui.edit_in_place_save_first": "احفظ التجميع أولاً: يُعثر على تصاميمه المرتبطة انطلاقًا من ملفه", "ui.edit_in_place_save_waits": "يجري تحديث الروابط في {name}؛ احفظه بعد انتهائه", "ui.edit_in_place_saved_elsewhere": "حُفظ الجزء في ملف آخر؛ ما زال التجميع مرتبطًا بـ {name}", - "ui.finish_edit": "إنهاء التحرير", "cmd.component_finish_edit": "إنهاء التحرير" }, "de": { @@ -53,7 +51,6 @@ "ui.edit_in_place_save_first": "Zuerst die Baugruppe speichern: ihre verknüpften Designs werden von ihrer Datei aus gefunden", "ui.edit_in_place_save_waits": "In {name} werden die Verknüpfungen aktualisiert; danach speichern", "ui.edit_in_place_saved_elsewhere": "Das Teil wurde in eine andere Datei gespeichert; die Baugruppe verknüpft weiterhin {name}", - "ui.finish_edit": "Bearbeitung beenden", "cmd.component_finish_edit": "Bearbeitung beenden" }, "he": { @@ -72,7 +69,6 @@ "ui.edit_in_place_save_first": "יש לשמור קודם את ההרכבה: התכנים המקושרים שלה נמצאים לפי הקובץ שלה", "ui.edit_in_place_save_waits": "עדכון הקישורים פועל ב-{name}; יש לשמור לאחר שיסתיים", "ui.edit_in_place_saved_elsewhere": "החלק נשמר לקובץ אחר; ההרכבה עדיין מקושרת אל {name}", - "ui.finish_edit": "סיום עריכה", "cmd.component_finish_edit": "סיום עריכה" }, "ja": { @@ -91,7 +87,6 @@ "ui.edit_in_place_save_first": "先にアセンブリを保存してください。リンクされたデザインはそのファイルから見つけます", "ui.edit_in_place_save_waits": "{name} のリンクを更新中です。完了してから保存してください", "ui.edit_in_place_saved_elsewhere": "部品は別のファイルに保存されました。アセンブリは引き続き {name} にリンクしています", - "ui.finish_edit": "編集を終了", "cmd.component_finish_edit": "編集を終了" }, "vi": { @@ -110,7 +105,6 @@ "ui.edit_in_place_save_first": "Hãy lưu cụm lắp ráp trước: các thiết kế liên kết của nó được tìm từ tệp của nó", "ui.edit_in_place_save_waits": "Đang cập nhật liên kết trong {name}; hãy lưu sau khi hoàn tất", "ui.edit_in_place_saved_elsewhere": "Chi tiết đã được lưu vào tệp khác; cụm lắp ráp vẫn liên kết với {name}", - "ui.finish_edit": "Hoàn tất chỉnh sửa", "cmd.component_finish_edit": "Hoàn tất chỉnh sửa" }, "zh": { @@ -129,7 +123,6 @@ "ui.edit_in_place_save_first": "请先保存装配体:其链接设计根据其文件查找", "ui.edit_in_place_save_waits": "正在更新 {name} 中的链接;请在完成后保存", "ui.edit_in_place_saved_elsewhere": "零件已保存到其他文件;装配体仍链接 {name}", - "ui.finish_edit": "完成编辑", "cmd.component_finish_edit": "完成编辑" } } diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index 47a4897707e..bb178da634b 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -47,7 +47,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("component") .params("bodies: [names] → one new component per body, named after it"), CommandSpec::new("component.activate", "Activate Component", activate).icon("activate").noundo().params("component: id or name (0 or \"root\" for the design); occurrence?, path?: exact placement used to author shared geometry"), - CommandSpec::new("component.finish_edit", "Finish Editing", crate::checked!("component.finish_edit", finish_edit)) + CommandSpec::new("component.finish_edit", "Finish Edit", crate::checked!("component.finish_edit", finish_edit)) .icon("finish_edit") .noundo() .doc_only() diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 48b537ff86d..6dce866d3fc 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -271,7 +271,7 @@ const MAX_BATCH: usize = 10_000; /// bypass. const LOADS_A_FILE: [&str; 3] = ["doc.open", "file.insert_step", "file.insert_mesh"]; -/// Finish Editing leaves the part for the assembly's tab: a batch's rollback, or a script's +/// Finish Edit leaves the part for the assembly's tab: a batch's rollback, or a script's /// later steps, would land in the wrong design. const SWITCHES_DESIGN: &str = "component.finish_edit"; diff --git a/crates/ui-egui/src/edit_in_place.rs b/crates/ui-egui/src/edit_in_place.rs index d95c347736b..105e7b114e6 100644 --- a/crates/ui-egui/src/edit_in_place.rs +++ b/crates/ui-egui/src/edit_in_place.rs @@ -1,6 +1,6 @@ //! Edit in place: double-clicking a linked component opens the design it comes from, with the //! rest of the assembly drawn faded around it where the component sits, so its own timeline, -//! browser and commands are at hand. Finish Editing saves the part and goes back to the assembly, +//! browser and commands are at hand. Finish Edit saves the part and goes back to the assembly, //! which reads the link again. //! //! The part is an ordinary tab: saving, autosave, recovery, closing and quitting treat it as any @@ -36,7 +36,7 @@ pub struct PartContext { pub triangles: Arc>, /// Their extent in the part's frame, so fitting the view frames the assembly too. pub bounds: Aabb3, - /// The part's tab was opened for this edit, so Finish Editing closes it again. + /// The part's tab was opened for this edit, so Finish Edit closes it again. pub opened: bool, } @@ -56,7 +56,7 @@ struct Refresh { pub struct EditInPlace { pub active: Option, pending: Option, - /// Finish Editing is waiting for the save of the part at this file. + /// Finish Edit is waiting for the save of the part at this file. finish_after_save: Option, refresh: Option, } @@ -295,7 +295,7 @@ fn take_refresh(app: &mut SolveApp) { app.set_status(language.format("ui.command_done", &[("command", language.label(crate::command_label("component.update_links")))]), false); } -/// Finish Editing from the window (its button, the back button): a part with changes is saved +/// Finish Edit from the window (its button, the back button): a part with changes is saved /// first, with whatever the save asks, and the edit finishes once the save is done. pub(crate) fn finish(app: &mut SolveApp) { if let Err(why) = finish_with(app, true) { @@ -304,7 +304,7 @@ pub(crate) fn finish(app: &mut SolveApp) { } /// `component.finish_edit` run as a command: it opens nothing, so a part with changes is -/// refused (save it first), as is anything else that holds Finish Editing up. The refusal is +/// refused (save it first), as is anything else that holds Finish Edit up. The refusal is /// its error, which the caller reports. pub(crate) fn finish_command(app: &mut SolveApp) -> Result<(), String> { finish_with(app, false) @@ -374,7 +374,7 @@ fn can_finish(app: &SolveApp) -> bool { } /// Each frame: a refresh that finished is taken up; an edit waiting for a part that nothing will -/// open any more is dropped; and Finish Editing goes on once the part's save is done, in the +/// open any more is dropped; and Finish Edit goes on once the part's save is done, in the /// part's own tab (a save that failed, was cancelled or went elsewhere leaves the edit as it was). pub(crate) fn tick(app: &mut SolveApp) { take_refresh(app); @@ -393,7 +393,7 @@ pub(crate) fn tick(app: &mut SolveApp) { } /// The mouse's back button (or a keyboard's Back key) pressed while a part is edited in place: -/// Finish Editing, which says why when something open in the part holds it up. +/// Finish Edit, which says why when something open in the part holds it up. pub(crate) fn back(app: &mut SolveApp) { if app.edit_in_place.active.is_some() { finish(app); diff --git a/crates/ui-egui/src/edit_in_place_tests.rs b/crates/ui-egui/src/edit_in_place_tests.rs index 8789df1c46f..4d5df2393e9 100644 --- a/crates/ui-egui/src/edit_in_place_tests.rs +++ b/crates/ui-egui/src/edit_in_place_tests.rs @@ -116,7 +116,7 @@ fn with_changed_links_left_alone_finish_editing_updates_the_assembly_itself() { finish(&mut f.app); settle(&mut f.app); assert_eq!(f.app.docs.count(), 1); - assert!((volume(&f.app) - 8000.0).abs() < 1e-6, "Finish Editing promises the change: {}", volume(&f.app)); + assert!((volume(&f.app) - 8000.0).abs() < 1e-6, "Finish Edit promises the change: {}", volume(&f.app)); } #[test] @@ -388,7 +388,7 @@ fn finish_editing_is_a_model_tab_button_only_while_a_part_is_edited_in_place() { double_click_component(&mut h.app, json!({"component": f.plate})); settle(&mut h.app); h.frames(3); - assert!(crate::scenario::rect_of("panel:MODEL:FINISH EDITING").is_some(), "the part's MODEL tab ends with Finish Editing"); + assert!(crate::scenario::rect_of("panel:MODEL:FINISH EDITING").is_some(), "the part's MODEL tab ends with Finish Edit"); h.app.start("component.finish_edit"); settle(&mut h.app); h.frames(3); diff --git a/crates/ui-egui/src/toolbar_custom.rs b/crates/ui-egui/src/toolbar_custom.rs index b7b948afba0..71c783081f5 100644 --- a/crates/ui-egui/src/toolbar_custom.rs +++ b/crates/ui-egui/src/toolbar_custom.rs @@ -242,7 +242,7 @@ fn home_panel(tab: &str, id: &str) -> Option<&'static str> { } /// FINISH EDITING, shown only while a linked design is edited in place, keeps its one button: -/// nothing moves into it, and Finish Editing moves nowhere else. +/// nothing moves into it, and Finish Edit moves nowhere else. fn fixed(tab: &str, panel: &str, id: &str) -> bool { (tab == "MODEL" && panel == "FINISH EDITING") || id == "component.finish_edit" } diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index c714a264260..771dc8fc2c2 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -419,7 +419,6 @@ pub const RIBBON_LABELS: &[(&str, &str)] = &[ ("sketch.create", "New Sketch"), ("sketch.dimension", "Dimension"), ("sketch.finish", "Finish Sketch"), - ("component.finish_edit", "Finish Edit"), ("sketch.pattern.circular", "Circular"), ("sketch.pattern.rectangular", "Rectangular"), ("sketch.rectangle.two_point", "Rectangle"), From ff29f328e835d0cfeff38381c9ab3577efd66b35 Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 18:03:27 +0100 Subject: [PATCH 17/20] Edit in place: a command to start it, and fixes from the full review Added component.edit_in_place {component, path?}: the double-click and Edit in Place in the menu run it, and as a command it asks nothing, so a network location not allowed yet or a design open elsewhere makes it fail instead Finish Edit asked by the part's own agent finishes once that agent's turn ends; the button still waits for the turn The parameters and design properties panels, with text typed and not applied yet, hold up entering and finishing an edit A refresh is not taken up under an undo, a queued command or a feature still being computed in the assembly Refusals say what holds them up (a refresh, a file being read or written) instead of nothing The browser strip names the assembly that is refreshing, not any assembly The schema description says the command does not save the part Korean strings for every new message Co-Authored-By: Claude Opus 5.5 --- assets/locales/pending/edit-in-place.json | 52 +++++++- crates/engine/src/cmd/component.rs | 35 ++++- crates/engine/src/schema/component.rs | 38 +++++- crates/engine/src/schema/component_tests.rs | 13 +- crates/ui-egui/src/context_menu.rs | 2 +- crates/ui-egui/src/control.rs | 17 ++- crates/ui-egui/src/edit_in_place.rs | 139 +++++++++++++++----- crates/ui-egui/src/edit_in_place_tests.rs | 70 +++++++++- crates/ui-egui/src/lib.rs | 9 +- 9 files changed, 322 insertions(+), 53 deletions(-) diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json index 7c61f9f2d81..2eb7966be58 100644 --- a/assets/locales/pending/edit-in-place.json +++ b/assets/locales/pending/edit-in-place.json @@ -3,126 +3,176 @@ "settings.double_click_components": "Double-click a component to activate it, or to edit a linked one in place", "ui.heading_finish_editing": "FINISH EDITING", "ui.edit_in_place": "Edit in Place", + "ui.edit_in_place_after_turn": "The edit finishes when the agent's turn ends", "ui.edit_in_place_agent_busy": "The agent is still working in the part; finish editing once its turn is done", "ui.edit_in_place_assembly_closed": "{name} is no longer open", "ui.edit_in_place_banner": "Editing in {name}", "ui.edit_in_place_busy": "Finish or cancel what is open first", "ui.edit_in_place_none": "No linked design is edited in place", "ui.edit_in_place_not_saved": "The part has changes that are not saved; save it to finish editing", + "ui.edit_in_place_open_elsewhere": "{name} is open in another SolidCraft", "ui.edit_in_place_refresh_dropped": "The assembly changed while Update Links ran; run it again", "ui.edit_in_place_refresh_stopped": "Update Links stopped before it was done", "ui.edit_in_place_refreshing": "Updating links in {name}…", "ui.edit_in_place_save_first": "Save the assembly first: its linked designs are found from its file", "ui.edit_in_place_save_waits": "Update Links is running in {name}; save it once it is done", "ui.edit_in_place_saved_elsewhere": "The part was saved to another file; the assembly still links {name}", + "ui.edit_in_place_wait": "Wait for the file that is being read or written", + "cmd.component_edit_in_place": "Edit in Place", "cmd.component_finish_edit": "Finish Edit" }, "ar": { "settings.double_click_components": "انقر نقرًا مزدوجًا على مكوّن لتنشيطه، أو لتحرير مكوّن مرتبط في مكانه", "ui.heading_finish_editing": "إنهاء التحرير", "ui.edit_in_place": "تحرير في المكان", + "ui.edit_in_place_after_turn": "ينتهي التحرير عند انتهاء دور الوكيل", "ui.edit_in_place_agent_busy": "لا يزال الوكيل يعمل في الجزء؛ أنهِ التحرير بعد انتهاء دوره", "ui.edit_in_place_assembly_closed": "{name} لم يعد مفتوحًا", "ui.edit_in_place_banner": "تحرير داخل {name}", "ui.edit_in_place_busy": "أنهِ ما هو مفتوح أو ألغِه أولاً", "ui.edit_in_place_none": "لا يُحرَّر أي تصميم مرتبط في مكانه", "ui.edit_in_place_not_saved": "في الجزء تغييرات غير محفوظة؛ احفظه لإنهاء التحرير", + "ui.edit_in_place_open_elsewhere": "{name} مفتوح في نسخة أخرى من SolidCraft", "ui.edit_in_place_refresh_dropped": "تغيّر التجميع أثناء تحديث الروابط؛ شغّله مرة أخرى", "ui.edit_in_place_refresh_stopped": "توقّف تحديث الروابط قبل أن ينتهي", "ui.edit_in_place_refreshing": "جارٍ تحديث الروابط في {name}…", "ui.edit_in_place_save_first": "احفظ التجميع أولاً: يُعثر على تصاميمه المرتبطة انطلاقًا من ملفه", "ui.edit_in_place_save_waits": "يجري تحديث الروابط في {name}؛ احفظه بعد انتهائه", "ui.edit_in_place_saved_elsewhere": "حُفظ الجزء في ملف آخر؛ ما زال التجميع مرتبطًا بـ {name}", + "ui.edit_in_place_wait": "انتظر حتى تنتهي قراءة الملف أو كتابته", + "cmd.component_edit_in_place": "تحرير في المكان", "cmd.component_finish_edit": "إنهاء التحرير" }, "de": { "settings.double_click_components": "Doppelklick auf eine Komponente aktiviert sie oder bearbeitet eine verknüpfte an Ort und Stelle", "ui.heading_finish_editing": "BEARBEITUNG BEENDEN", "ui.edit_in_place": "An Ort und Stelle bearbeiten", + "ui.edit_in_place_after_turn": "Die Bearbeitung endet, sobald der Agent mit seinem Zug fertig ist", "ui.edit_in_place_agent_busy": "Der Agent arbeitet noch im Teil; die Bearbeitung beenden, sobald er fertig ist", "ui.edit_in_place_assembly_closed": "{name} ist nicht mehr geöffnet", "ui.edit_in_place_banner": "Bearbeitung in {name}", "ui.edit_in_place_busy": "Zuerst abschließen oder abbrechen, was offen ist", "ui.edit_in_place_none": "Es wird kein verknüpftes Design an Ort und Stelle bearbeitet", "ui.edit_in_place_not_saved": "Das Teil hat ungespeicherte Änderungen; zum Beenden der Bearbeitung speichern", + "ui.edit_in_place_open_elsewhere": "{name} ist in einem anderen SolidCraft geöffnet", "ui.edit_in_place_refresh_dropped": "Die Baugruppe wurde während der Aktualisierung der Verknüpfungen geändert; bitte erneut ausführen", "ui.edit_in_place_refresh_stopped": "Die Aktualisierung der Verknüpfungen wurde vorzeitig beendet", "ui.edit_in_place_refreshing": "Verknüpfungen in {name} werden aktualisiert…", "ui.edit_in_place_save_first": "Zuerst die Baugruppe speichern: ihre verknüpften Designs werden von ihrer Datei aus gefunden", "ui.edit_in_place_save_waits": "In {name} werden die Verknüpfungen aktualisiert; danach speichern", "ui.edit_in_place_saved_elsewhere": "Das Teil wurde in eine andere Datei gespeichert; die Baugruppe verknüpft weiterhin {name}", + "ui.edit_in_place_wait": "Warten, bis die Datei gelesen oder geschrieben ist", + "cmd.component_edit_in_place": "An Ort und Stelle bearbeiten", "cmd.component_finish_edit": "Bearbeitung beenden" }, "he": { "settings.double_click_components": "לחיצה כפולה על רכיב מפעילה אותו, או עורכת רכיב מקושר במקומו", "ui.heading_finish_editing": "סיום עריכה", "ui.edit_in_place": "עריכה במקום", + "ui.edit_in_place_after_turn": "העריכה תסתיים כשתור הסוכן יסתיים", "ui.edit_in_place_agent_busy": "הסוכן עדיין עובד בחלק; יש לסיים את העריכה כשתורו יסתיים", "ui.edit_in_place_assembly_closed": "{name} כבר אינו פתוח", "ui.edit_in_place_banner": "עריכה בתוך {name}", "ui.edit_in_place_busy": "יש לסיים או לבטל קודם את מה שפתוח", "ui.edit_in_place_none": "אין תכן מקושר בעריכה במקום", "ui.edit_in_place_not_saved": "בחלק יש שינויים שלא נשמרו; יש לשמור כדי לסיים את העריכה", + "ui.edit_in_place_open_elsewhere": "{name} פתוח במופע אחר של SolidCraft", "ui.edit_in_place_refresh_dropped": "ההרכבה השתנתה בזמן עדכון הקישורים; יש להריץ שוב", "ui.edit_in_place_refresh_stopped": "עדכון הקישורים נעצר לפני שהסתיים", "ui.edit_in_place_refreshing": "מעדכן קישורים ב-{name}…", "ui.edit_in_place_save_first": "יש לשמור קודם את ההרכבה: התכנים המקושרים שלה נמצאים לפי הקובץ שלה", "ui.edit_in_place_save_waits": "עדכון הקישורים פועל ב-{name}; יש לשמור לאחר שיסתיים", "ui.edit_in_place_saved_elsewhere": "החלק נשמר לקובץ אחר; ההרכבה עדיין מקושרת אל {name}", + "ui.edit_in_place_wait": "יש להמתין עד שקריאת הקובץ או כתיבתו תסתיים", + "cmd.component_edit_in_place": "עריכה במקום", "cmd.component_finish_edit": "סיום עריכה" }, "ja": { "settings.double_click_components": "コンポーネントをダブルクリックしてアクティブにする、またはリンクされたものをその場で編集する", "ui.heading_finish_editing": "編集を終了", "ui.edit_in_place": "その場で編集", + "ui.edit_in_place_after_turn": "エージェントのターンが終わると編集を終了します", "ui.edit_in_place_agent_busy": "エージェントがまだ部品で作業中です。そのターンが終わってから編集を終了してください", "ui.edit_in_place_assembly_closed": "{name} はもう開いていません", "ui.edit_in_place_banner": "{name} 内で編集中", "ui.edit_in_place_busy": "先に開いているものを終了またはキャンセルしてください", "ui.edit_in_place_none": "その場で編集中のリンクされたデザインはありません", "ui.edit_in_place_not_saved": "部品に保存されていない変更があります。編集を終了するには保存してください", + "ui.edit_in_place_open_elsewhere": "{name} は別の SolidCraft で開かれています", "ui.edit_in_place_refresh_dropped": "リンクの更新中にアセンブリが変更されました。もう一度実行してください", "ui.edit_in_place_refresh_stopped": "リンクの更新が完了前に停止しました", "ui.edit_in_place_refreshing": "{name} のリンクを更新中…", "ui.edit_in_place_save_first": "先にアセンブリを保存してください。リンクされたデザインはそのファイルから見つけます", "ui.edit_in_place_save_waits": "{name} のリンクを更新中です。完了してから保存してください", "ui.edit_in_place_saved_elsewhere": "部品は別のファイルに保存されました。アセンブリは引き続き {name} にリンクしています", + "ui.edit_in_place_wait": "ファイルの読み込みまたは書き込みが終わるまでお待ちください", + "cmd.component_edit_in_place": "その場で編集", "cmd.component_finish_edit": "編集を終了" }, + "ko": { + "settings.double_click_components": "구성 요소를 두 번 클릭하여 활성화하거나 연결된 구성 요소를 제자리에서 편집", + "ui.heading_finish_editing": "편집 완료", + "ui.edit_in_place": "제자리에서 편집", + "ui.edit_in_place_after_turn": "에이전트의 차례가 끝나면 편집이 완료됩니다", + "ui.edit_in_place_agent_busy": "에이전트가 아직 부품에서 작업 중입니다. 차례가 끝난 후 편집을 완료하세요", + "ui.edit_in_place_assembly_closed": "{name}이(가) 더 이상 열려 있지 않습니다", + "ui.edit_in_place_banner": "{name}에서 편집 중", + "ui.edit_in_place_busy": "먼저 열려 있는 작업을 완료하거나 취소하세요", + "ui.edit_in_place_none": "제자리에서 편집 중인 연결된 디자인이 없습니다", + "ui.edit_in_place_not_saved": "부품에 저장되지 않은 변경 사항이 있습니다. 편집을 완료하려면 저장하세요", + "ui.edit_in_place_open_elsewhere": "{name}이(가) 다른 SolidCraft에서 열려 있습니다", + "ui.edit_in_place_refresh_dropped": "링크 업데이트 중에 어셈블리가 변경되었습니다. 다시 실행하세요", + "ui.edit_in_place_refresh_stopped": "링크 업데이트가 완료되기 전에 중지되었습니다", + "ui.edit_in_place_refreshing": "{name}의 링크 업데이트 중…", + "ui.edit_in_place_save_first": "먼저 어셈블리를 저장하세요. 연결된 디자인은 해당 파일을 기준으로 찾습니다", + "ui.edit_in_place_save_waits": "{name}에서 링크 업데이트가 실행 중입니다. 완료된 후 저장하세요", + "ui.edit_in_place_saved_elsewhere": "부품이 다른 파일에 저장되었습니다. 어셈블리는 여전히 {name}에 연결되어 있습니다", + "ui.edit_in_place_wait": "파일 읽기 또는 쓰기가 끝날 때까지 기다리세요", + "cmd.component_edit_in_place": "제자리에서 편집", + "cmd.component_finish_edit": "편집 완료" + }, "vi": { "settings.double_click_components": "Nhấp đúp vào một thành phần để kích hoạt nó, hoặc chỉnh sửa tại chỗ một thành phần liên kết", "ui.heading_finish_editing": "HOÀN TẤT CHỈNH SỬA", "ui.edit_in_place": "Chỉnh sửa tại chỗ", + "ui.edit_in_place_after_turn": "Việc chỉnh sửa sẽ hoàn tất khi lượt của tác tử kết thúc", "ui.edit_in_place_agent_busy": "Tác tử vẫn đang làm việc trong chi tiết; hãy hoàn tất chỉnh sửa khi lượt của nó kết thúc", "ui.edit_in_place_assembly_closed": "{name} không còn mở", "ui.edit_in_place_banner": "Đang chỉnh sửa trong {name}", "ui.edit_in_place_busy": "Hãy hoàn tất hoặc hủy những gì đang mở trước", "ui.edit_in_place_none": "Không có thiết kế liên kết nào đang được chỉnh sửa tại chỗ", - "ui.edit_in_place_not_saved": "Chi tiết có thay đổi chưa lưu; hãy lưu để kết thúc chỉnh sửa", + "ui.edit_in_place_not_saved": "Chi tiết có thay đổi chưa lưu; hãy lưu để hoàn tất chỉnh sửa", + "ui.edit_in_place_open_elsewhere": "{name} đang mở trong một SolidCraft khác", "ui.edit_in_place_refresh_dropped": "Cụm lắp ráp đã thay đổi trong khi cập nhật liên kết; hãy chạy lại", "ui.edit_in_place_refresh_stopped": "Cập nhật liên kết đã dừng trước khi hoàn tất", "ui.edit_in_place_refreshing": "Đang cập nhật liên kết trong {name}…", "ui.edit_in_place_save_first": "Hãy lưu cụm lắp ráp trước: các thiết kế liên kết của nó được tìm từ tệp của nó", "ui.edit_in_place_save_waits": "Đang cập nhật liên kết trong {name}; hãy lưu sau khi hoàn tất", "ui.edit_in_place_saved_elsewhere": "Chi tiết đã được lưu vào tệp khác; cụm lắp ráp vẫn liên kết với {name}", + "ui.edit_in_place_wait": "Hãy chờ việc đọc hoặc ghi tệp kết thúc", + "cmd.component_edit_in_place": "Chỉnh sửa tại chỗ", "cmd.component_finish_edit": "Hoàn tất chỉnh sửa" }, "zh": { "settings.double_click_components": "双击组件以激活它,或在原位编辑链接组件", "ui.heading_finish_editing": "完成编辑", "ui.edit_in_place": "原位编辑", + "ui.edit_in_place_after_turn": "代理本轮结束后将完成编辑", "ui.edit_in_place_agent_busy": "代理仍在零件中工作;请在其本轮结束后完成编辑", "ui.edit_in_place_assembly_closed": "{name} 已不再打开", "ui.edit_in_place_banner": "正在 {name} 中编辑", "ui.edit_in_place_busy": "请先完成或取消打开的操作", "ui.edit_in_place_none": "没有正在原位编辑的链接设计", "ui.edit_in_place_not_saved": "零件有未保存的更改;请保存以完成编辑", + "ui.edit_in_place_open_elsewhere": "{name} 已在另一个 SolidCraft 中打开", "ui.edit_in_place_refresh_dropped": "更新链接期间装配体已更改;请再次运行", "ui.edit_in_place_refresh_stopped": "更新链接在完成前已停止", "ui.edit_in_place_refreshing": "正在更新 {name} 中的链接…", "ui.edit_in_place_save_first": "请先保存装配体:其链接设计根据其文件查找", "ui.edit_in_place_save_waits": "正在更新 {name} 中的链接;请在完成后保存", "ui.edit_in_place_saved_elsewhere": "零件已保存到其他文件;装配体仍链接 {name}", + "ui.edit_in_place_wait": "请等待文件读取或写入完成", + "cmd.component_edit_in_place": "原位编辑", "cmd.component_finish_edit": "完成编辑" } } diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index bb178da634b..dc12ca10bb2 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -11,10 +11,11 @@ use solidcraft_geom::Vec3; use super::CommandSpec; use crate::params::{bad, bool_, str_, string_list, vec3}; -use crate::schema::component::{FinishEditParams, FinishEditResult}; +use crate::schema::component::{EditInPlaceParams, EditInPlaceResult, FinishEditParams, FinishEditResult}; use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; +const EDIT_IN_PLACE_CONTRACT: TypedContract = TypedContract::new(); const FINISH_EDIT_CONTRACT: TypedContract = TypedContract::new(); #[path = "component_drag.rs"] @@ -47,6 +48,17 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("component") .params("bodies: [names] → one new component per body, named after it"), CommandSpec::new("component.activate", "Activate Component", activate).icon("activate").noundo().params("component: id or name (0 or \"root\" for the design); occurrence?, path?: exact placement used to author shared geometry"), + CommandSpec::new("component.edit_in_place", "Edit in Place", crate::checked!("component.edit_in_place", edit_in_place)) + .icon("edit") + .noundo() + .doc_only() + .contract(&EDIT_IN_PLACE_CONTRACT) + .output(output_schema_for::) + .params( + "component: id or name of a linked component; path?: its placement (occurrence ids, default its first) → in the app \ + window: open the design it links in a tab of its own with the assembly drawn around it (component.finish_edit goes \ + back); fails when it is not linked, the assembly has no file yet or something is open in it; elsewhere it only checks", + ), CommandSpec::new("component.finish_edit", "Finish Edit", crate::checked!("component.finish_edit", finish_edit)) .icon("finish_edit") .noundo() @@ -55,7 +67,8 @@ pub static COMMANDS: &[CommandSpec] = &[ .output(output_schema_for::) .params( "no parameters → in the app window: go back from the linked design edited in place to its assembly, which reads it again; \ - fails while the design has unsaved changes (run file.save first) or something is open in it; elsewhere nothing changes", + fails while the design has unsaved changes (run file.save first) or something is open in it; asked by the part's own \ + agent, it finishes when that agent's turn ends; elsewhere nothing changes", ), CommandSpec::new("component.list", "List Components", list).icon("list").noundo().params( "compact?: bool (counts of bodies, features, sketches and construction planes instead of their names; occurrences leave out \ @@ -207,6 +220,24 @@ fn from_bodies(s: &mut Session, p: &Value) -> Result { transfer::from_bodies(s, p) } +/// The app window opens the edit in place from what this returns; here the component and its +/// placement are only checked. +fn edit_in_place(s: &mut Session, p: &Value) -> Result { + let cmd = "component.edit_in_place"; + let id = component(s, p, "component", cmd)?; + if !s.doc.links.contains_key(&id) { + return Err(bad(cmd, "that component is not linked to a design")); + } + let path = match p.get("path") { + Some(_) => serde_json::from_value::>(p["path"].clone()).map_err(|_| bad(cmd, "`path` must be occurrence ids"))?, + None => s.doc.first_path(id), + }; + if s.occurrence_placement(&path).map_err(|e| bad(cmd, e.to_string()))?.component != id { + return Err(bad(cmd, "`path` is a placement of another component")); + } + serde_json::to_value(EditInPlaceResult { component: id, path, ..Default::default() }).map_err(|e| crate::EngineError::Other(e.to_string())) +} + /// The app window finishes an edit in place (it knows the part's tab and its assembly); here /// there is none, so nothing changes. fn finish_edit(_s: &mut Session, _p: &Value) -> Result { diff --git a/crates/engine/src/schema/component.rs b/crates/engine/src/schema/component.rs index 464f996e8b8..1068096a817 100644 --- a/crates/engine/src/schema/component.rs +++ b/crates/engine/src/schema/component.rs @@ -3,9 +3,41 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -/// Finish editing a linked component's design in place. In the app window: save the part, go back -/// to the assembly around it, which reads the link again, and close the part's tab when the edit -/// opened it. Outside the window nothing is edited in place, so nothing changes. +use super::types::{IdOrName, present}; + +/// Edit a linked component's design in place. In the app window: open the design it links in a +/// tab of its own, with the rest of the assembly drawn faded around it as the placement `path` +/// puts it; `component.finish_edit` goes back. It fails when the component is not linked, the +/// assembly has no file yet, or something is open in it. Outside the window it only checks the +/// component and the placement. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct EditInPlaceParams { + /// The linked component, by id or name. + pub component: IdOrName, + /// The placement to edit it at, as occurrence ids from the top of the assembly down + /// (`component.list`). Default: the component's first placement. + #[serde(default, deserialize_with = "present")] + pub path: Option>, +} + +/// What `component.edit_in_place` returns. +#[derive(Debug, Default, Serialize, JsonSchema)] +pub struct EditInPlaceResult { + /// The component, by id. + pub component: u64, + /// The placement it is edited at. + pub path: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// Finish editing a linked component's design in place. In the app window: go back to the +/// assembly around it, which reads the link again, and close the part's tab when the edit opened +/// it. It fails while the part has unsaved changes (save it first) or something is open in it; +/// asked by the part's own agent, it finishes when that agent's turn ends. Outside the window +/// nothing is edited in place, so nothing changes. #[derive(Debug, Deserialize, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct FinishEditParams {} diff --git a/crates/engine/src/schema/component_tests.rs b/crates/engine/src/schema/component_tests.rs index 5b47f0010b0..08ae137a860 100644 --- a/crates/engine/src/schema/component_tests.rs +++ b/crates/engine/src/schema/component_tests.rs @@ -2,16 +2,27 @@ use std::sync::Arc; use serde_json::json; -use super::FinishEditParams; +use super::{EditInPlaceParams, FinishEditParams}; use crate::Session; use crate::schema::input_schema_for; use crate::schema::tests::assert_keys; #[test] fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["component", "path"]); assert_keys(input_schema_for::(), &[]); } +#[test] +fn editing_in_place_outside_the_window_only_checks_the_component() { + let mut s = Session::default(); + let made = s.execute("component.create", &json!({"name": "Bracket"})).unwrap_or_else(|e| panic!("{e}")); + let e = s.execute("component.edit_in_place", &json!({"component": made["component"]})).unwrap_err().to_string(); + assert!(e.contains("not linked"), "{e}"); + assert!(s.execute("component.edit_in_place", &json!({"component": "nothing"})).is_err()); + assert!(s.execute("component.edit_in_place", &json!({})).is_err(), "the component is required"); +} + #[test] fn finishing_an_edit_outside_the_window_changes_nothing() { let mut s = Session::default(); diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 315d7b64646..2861ce3cba5 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -1387,7 +1387,7 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { "ui.editInPlace" => { if let Some(component) = id_of(&p, "component") { let path = p["path"].as_array().map(|path| path.iter().filter_map(Value::as_u64).collect()); - crate::edit_in_place::enter(app, component, path); + crate::edit_in_place::open(app, component, path); } } "ui.openLinkedDesign" => { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 6dce866d3fc..f7375a35a75 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -271,20 +271,25 @@ const MAX_BATCH: usize = 10_000; /// bypass. const LOADS_A_FILE: [&str; 3] = ["doc.open", "file.insert_step", "file.insert_mesh"]; -/// Finish Edit leaves the part for the assembly's tab: a batch's rollback, or a script's +/// Edit in Place and Finish Edit go to another design's tab: a batch's rollback, or a script's /// later steps, would land in the wrong design. -const SWITCHES_DESIGN: &str = "component.finish_edit"; +const SWITCHES_DESIGN: [&str; 2] = ["component.edit_in_place", "component.finish_edit"]; /// `command` names the command `id`, in any of the spellings the engine takes. fn is_command(command: Option<&str>, id: &str) -> bool { command.and_then(solidcraft_engine::find_command).is_some_and(|spec| spec.id == id) } +/// The command of `step` when it goes to another design's tab. +fn switches_design(step: &Value) -> Option<&'static str> { + SWITCHES_DESIGN.into_iter().find(|id| is_command(command(step), id)) +} + /// Why `engine.batch` refuses these steps before running any: a step loads a file or switches /// to another design (send such steps one by one). pub(crate) fn batch_refusal(steps: &[Value]) -> Option { - if let Some(i) = steps.iter().position(|step| is_command(command(step), SWITCHES_DESIGN)) { - return Some(format!("engine.batch unavailable: step {i} ({SWITCHES_DESIGN}) switches to another design")); + if let Some((i, c)) = steps.iter().enumerate().find_map(|(i, step)| switches_design(step).map(|c| (i, c))) { + return Some(format!("engine.batch unavailable: step {i} ({c}) switches to another design")); } let (i, c) = steps.iter().enumerate().find_map(|(i, step)| command(step).filter(|c| LOADS_A_FILE.contains(c)).map(|c| (i, c)))?; Some(format!("engine.batch unavailable: step {i} ({c}) loads a file")) @@ -480,8 +485,8 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> } "engine.script" => { let steps = p.as_array().or_else(|| p.get("commands").and_then(Value::as_array)); - if steps.is_some_and(|steps| steps.iter().any(|step| is_command(command(step), SWITCHES_DESIGN))) { - return err(format!("engine.script unavailable: {SWITCHES_DESIGN} switches to another design (send it on its own)")); + if let Some(c) = steps.and_then(|steps| steps.iter().find_map(switches_design)) { + return err(format!("engine.script unavailable: {c} switches to another design (send it on its own)")); } let mut replaced = false; let r = app diff --git a/crates/ui-egui/src/edit_in_place.rs b/crates/ui-egui/src/edit_in_place.rs index 105e7b114e6..674851f14cc 100644 --- a/crates/ui-egui/src/edit_in_place.rs +++ b/crates/ui-egui/src/edit_in_place.rs @@ -58,7 +58,11 @@ pub struct EditInPlace { pending: Option, /// Finish Edit is waiting for the save of the part at this file. finish_after_save: Option, + /// The part's own agent asked to finish the edit of the part at this file during its turn. + finish_after_turn: Option, refresh: Option, + /// `component.edit_in_place` is run by the window ([`open`]), not as a command: its open may ask. + ask: bool, } impl EditInPlace { @@ -75,7 +79,7 @@ pub(crate) fn double_click_component(app: &mut SolveApp, params: Value) { let component = params["component"].as_u64().unwrap_or(0); if app.preferences.double_click_components && app.session.doc.links.contains_key(&component) { let path = params["path"].as_array().map(|p| p.iter().filter_map(Value::as_u64).collect::>()); - enter(app, component, path); + open(app, component, path); } else { let _ = app.run("component.activate", params); } @@ -98,7 +102,7 @@ pub(crate) fn double_click_face(app: &mut SolveApp, body: &str) -> bool { .map(|(_, path, _)| path) .find(|path| app.session.occurrence_bodies(path, true).is_ok_and(|bodies| bodies.iter().any(|b| b == body))); if app.session.doc.links.contains_key(&component) { - enter(app, component, placement); + open(app, component, placement); return true; } let active = app.session.active_component == component @@ -115,8 +119,20 @@ fn busy(app: &SolveApp) -> bool { app.file_picker_busy() || app.file_load.busy() || app.saving.is_some() || app.edit_in_place.refreshing() } -/// A dialog, tool, sketch or feature edit is open in the design shown: leaving its tab would -/// cancel it. +/// Why [`busy`]: the assembly's refresh, or a file being read, written or picked. +fn busy_reason(app: &SolveApp) -> String { + match &app.edit_in_place.refresh { + Some(r) => crate::i18n::format("ui.edit_in_place_refreshing", &[("name", &file_name(&r.assembly))]), + None => crate::i18n::tr("ui.edit_in_place_wait").to_string(), + } +} + +fn file_name(path: &str) -> String { + std::path::Path::new(path).file_stem().map_or_else(|| path.to_string(), |n| n.to_string_lossy().into_owned()) +} + +/// A dialog, tool, sketch or feature edit, or the parameters or design properties panel (with +/// text typed and not applied yet) is open in the design shown: leaving its tab would drop it. fn working(app: &SolveApp) -> bool { app.dialog.is_some() || app.applying.is_some() @@ -124,6 +140,8 @@ fn working(app: &SolveApp) -> bool { || app.pending_feature_edit.is_some() || app.tool.is_some() || app.session.active_sketch.is_some() + || app.params.is_some() + || app.design_properties.is_some() } /// The bodies of `session` around its linked component `component`, in that component's frame @@ -149,34 +167,66 @@ fn snapshot(session: &Session, component: u64, placement: &[u64]) -> Option<(usi Some((bodies, triangles, bounds)) } +/// Edit the linked component `component` in place at its placement `path` (default: its first), +/// as the window does it (a double-click, Edit in Place in its menu): `component.edit_in_place`, +/// with the questions an open can ask (a network location, a design open elsewhere) asked. +pub(crate) fn open(app: &mut SolveApp, component: u64, path: Option>) { + let mut params = json!({ "component": component }); + if let Some(path) = path { + params["path"] = json!(path); + } + app.edit_in_place.ask = true; + let _ = app.run("component.edit_in_place", params); + app.edit_in_place.ask = false; +} + +/// `component.edit_in_place` ran: `result` names the component and its placement, and the window +/// opens the edit. Run as a command, it asks nothing: what would need a question fails instead. +pub(crate) fn command_ran(app: &mut SolveApp, result: &Value) -> Result<(), String> { + let component = result["component"].as_u64().unwrap_or(0); + let path = result["path"].as_array().map(|p| p.iter().filter_map(Value::as_u64).collect::>()); + let ask = app.edit_in_place.ask; + enter(app, component, path, ask) +} + /// Open the design the linked component `component` comes from, with the assembly around it as -/// its placement `path` (default: its first) puts it. -pub(crate) fn enter(app: &mut SolveApp, component: u64, path: Option>) { +/// its placement `path` (default: its first) puts it (`ask`: with the open's questions). +fn enter(app: &mut SolveApp, component: u64, path: Option>, ask: bool) -> Result<(), String> { if busy(app) { - return; + return Err(busy_reason(app)); } if working(app) { - app.set_status(crate::i18n::tr("ui.edit_in_place_busy").to_string(), true); - return; + return Err(crate::i18n::tr("ui.edit_in_place_busy").to_string()); } let Some(assembly) = app.session.path.clone() else { - app.set_status(crate::i18n::tr("ui.edit_in_place_save_first").to_string(), true); - return; - }; - let links = match app.session.execute("component.links", &json!({})) { - Ok(links) => links, - Err(e) => { - app.set_status(e.to_string(), true); - return; - } + return Err(crate::i18n::tr("ui.edit_in_place_save_first").to_string()); }; + let links = app.session.execute("component.links", &json!({})).map_err(|e| e.to_string())?; let Some(link) = links["links"].as_array().into_iter().flatten().find(|l| l["component"].as_u64() == Some(component)).cloned() else { - app.set_status(app.tr_label("ui.relink_not_linked").to_string(), true); - return; + return Err(app.tr_label("ui.relink_not_linked").to_string()); }; - let Some(part) = link["file"].as_str().map(str::to_string) else { return }; + let Some(part) = link["file"].as_str().map(str::to_string) else { + return Err(app.tr_label("ui.relink_not_linked").to_string()); + }; + if !ask { + // A network location not allowed yet, a missing file or one open in another SolidCraft + // would ask or stop the open: as a command, that is its answer. + if link["found"] != true { + return Err(format!("{part}: {}", link["reason"].as_str().or(link["host"].as_str()).unwrap_or("not found"))); + } + #[cfg(not(target_arch = "wasm32"))] + if app.locks.is_some() + && crate::documents::session_at(app, &part).is_none() + && solidcraft_engine::io::design_lock::held_elsewhere(std::path::Path::new(&part), solidcraft_engine::io::design_lock::now_secs()) + .is_some() + { + return Err(crate::i18n::format("ui.edit_in_place_open_elsewhere", &[("name", &file_name(&part))])); + } + } let placement = path.unwrap_or_else(|| app.session.doc.first_path(component)); - let Some((bodies, triangles, bounds)) = snapshot(&app.session, component, &placement) else { return }; + let Some((bodies, triangles, bounds)) = snapshot(&app.session, component, &placement) else { + return Err(app.tr_label("ui.relink_not_linked").to_string()); + }; let opened = crate::documents::session_at(app, &part).is_none(); app.edit_in_place.pending = Some(PartContext { assembly, @@ -190,6 +240,7 @@ pub(crate) fn enter(app: &mut SolveApp, component: u64, path: Option>) opened, }); crate::network_prompt::open_linked(app, &link); + Ok(()) } /// The design shown has become the part an edit waits for: the edit starts there. An edit whose @@ -218,7 +269,12 @@ pub(crate) fn refreshing_assembly(app: &SolveApp) -> Option { /// Update Links pressed while a part is edited in place: the assembly's tab reads its links again /// (off the window thread), and the picture around the part follows. pub(crate) fn refresh(app: &mut SolveApp) { + // A refresh already running is the one asked for. + if app.edit_in_place.refreshing() { + return; + } if busy(app) { + app.set_status(busy_reason(app), true); return; } let Some(assembly) = app.edit_in_place.active.as_ref().map(|c| c.assembly.clone()) else { return }; @@ -253,6 +309,12 @@ pub(crate) fn refresh(app: &mut SolveApp) { /// run started from, and the picture around the part is taken again. fn take_refresh(app: &mut SolveApp) { let Some(r) = &app.edit_in_place.refresh else { return }; + // An undo, a command or a feature still being computed in the assembly goes first: taken up + // under it, the refresh would be what it undoes or what it is refused for. + let shown = app.session.path.as_deref().is_some_and(|p| crate::documents::same_path(p, &r.assembly)); + if shown && (app.deferred.is_some() || !app.deferred_queue.is_empty() || app.applying.is_some()) { + return; + } let result = match r.done.try_recv() { Ok(result) => result, Err(std::sync::mpsc::TryRecvError::Empty) => return, @@ -316,17 +378,15 @@ fn finish_with(app: &mut SolveApp, save: bool) -> Result<(), String> { let Some(part) = app.edit_in_place.active.as_ref().map(|c| c.part.clone()) else { return Err(crate::i18n::tr("ui.edit_in_place_none").to_string()); }; - // Leaving the tab would stop the part's agent in the middle of its turn. - if app.agent_chat.state() == crate::agent_chat::State::Busy { - return Err(crate::i18n::tr("ui.edit_in_place_agent_busy").to_string()); + if busy(app) { + return Err(busy_reason(app)); } if !can_finish(app) { return Err(crate::i18n::tr("ui.edit_in_place_busy").to_string()); } // Saved to another file (Save As, a copy of a read-only design): the assembly still links this one. if !app.session.path.as_deref().is_some_and(|p| crate::documents::same_path(p, &part)) { - let name = std::path::Path::new(&part).file_stem().map_or_else(|| part.clone(), |n| n.to_string_lossy().into_owned()); - return Err(crate::i18n::format("ui.edit_in_place_saved_elsewhere", &[("name", &name)])); + return Err(crate::i18n::format("ui.edit_in_place_saved_elsewhere", &[("name", &file_name(&part))])); } if app.session.is_dirty() { if !save { @@ -336,6 +396,16 @@ fn finish_with(app: &mut SolveApp, save: bool) -> Result<(), String> { crate::toolbar::save(app); return Ok(()); } + // Leaving the tab would stop the part's agent in the middle of its turn. Asked by that agent + // (a command, which it can only send during its turn), the edit finishes once the turn ends. + if app.agent_chat.state() == crate::agent_chat::State::Busy { + if save { + return Err(crate::i18n::tr("ui.edit_in_place_agent_busy").to_string()); + } + app.edit_in_place.finish_after_turn = Some(part); + app.set_status(crate::i18n::tr("ui.edit_in_place_after_turn").to_string(), false); + return Ok(()); + } let Some(context) = app.edit_in_place.active.take() else { return Ok(()) }; let part_tab = app.docs.active; if !matches!(crate::documents::reuse_path(app, &context.assembly), Ok(true)) { @@ -360,8 +430,7 @@ fn finish_with(app: &mut SolveApp, save: bool) -> Result<(), String> { /// Nothing is under way in the part that leaving its tab would cut short or that waits for an /// answer: a dialog or tool, a feature being computed or edited, a sketch, a prompt or Home. fn can_finish(app: &SolveApp) -> bool { - !busy(app) - && !working(app) + !working(app) && app.deferred.is_none() && app.docs.closing.is_none() && app.docs.quitting.is_none() @@ -390,6 +459,15 @@ pub(crate) fn tick(app: &mut SolveApp) { app.set_status(crate::i18n::tr("ui.edit_in_place_not_saved").to_string(), true); } } + // The agent's turn ended: the finish it asked for goes on, as the command would have, in the + // part's own tab (shown elsewhere, or edited differently since, it is dropped). + if app.agent_chat.state() != crate::agent_chat::State::Busy + && let Some(part) = app.edit_in_place.finish_after_turn.take() + && app.edit_in_place.active.as_ref().is_some_and(|c| crate::documents::same_path(&c.part, &part)) + && let Err(why) = finish_with(app, false) + { + app.set_status(why, true); + } } /// The mouse's back button (or a keyboard's Back key) pressed while a part is edited in place: @@ -424,7 +502,8 @@ pub(crate) fn draw_context(app: &SolveApp, sc: &mut GpuScene) { pub(crate) fn browser_strip(app: &SolveApp, ui: &mut egui::Ui) { let Some(context) = &app.edit_in_place.active else { return }; let t = Tokens::get(); - let key = if app.edit_in_place.refreshing() { "ui.edit_in_place_refreshing" } else { "ui.edit_in_place_banner" }; + let refreshing = app.edit_in_place.refresh.as_ref().is_some_and(|r| crate::documents::same_path(&r.assembly, &context.assembly)); + let key = if refreshing { "ui.edit_in_place_refreshing" } else { "ui.edit_in_place_banner" }; let text = crate::i18n::format(key, &[("name", &context.assembly_name)]); ui.horizontal(|ui| { ui.add_space(t.space_6); diff --git a/crates/ui-egui/src/edit_in_place_tests.rs b/crates/ui-egui/src/edit_in_place_tests.rs index 4d5df2393e9..41d88d06494 100644 --- a/crates/ui-egui/src/edit_in_place_tests.rs +++ b/crates/ui-egui/src/edit_in_place_tests.rs @@ -417,7 +417,7 @@ fn the_back_button_finishes_the_edit_unless_a_dialog_is_open() { } #[test] -fn the_assembly_is_not_saved_while_it_reads_its_links_for_the_part() { +fn saving_the_assembly_from_the_window_waits_while_it_reads_its_links_for_the_part() { let mut f = assembly("save-waits"); f.app.preferences.update_changed_links = false; double_click_component(&mut f.app, json!({"component": f.plate})); @@ -582,16 +582,74 @@ fn finish_editing_waits_for_the_parts_agent_to_end_its_turn() { double_click_component(&mut f.app, json!({"component": f.plate})); settle(&mut f.app); f.app.agent_chat.set_state(crate::agent_chat::State::Busy); - let e = f.app.run("component.finish_edit", json!({})).unwrap_err(); - assert!(e.contains("agent"), "{e}"); + // The button would stop the agent mid-turn: refused finish(&mut f.app); assert!(showing(&f.app, &f.plate_file) && f.app.edit_in_place.active.is_some()); assert!(f.app.status.as_ref().is_some_and(|(s, _, error)| *error && s.contains("agent")), "{:?}", f.app.status); - // An idle chat goes with the tab, as closing it would take it + // The agent itself asks: the edit finishes once its turn is over + f.app.run("component.finish_edit", json!({})).unwrap(); + settle(&mut f.app); + assert!(showing(&f.app, &f.plate_file) && f.app.edit_in_place.active.is_some(), "not during the turn"); f.app.agent_chat.set_state(crate::agent_chat::State::Ready); - finish(&mut f.app); settle(&mut f.app); - assert_eq!(f.app.docs.count(), 1); + assert!(f.app.edit_in_place.active.is_none()); + assert_eq!(f.app.docs.count(), 1, "an idle chat goes with the tab, as closing it would take it"); +} + +#[test] +fn edit_in_place_is_a_command_the_double_click_runs() { + let mut f = assembly("command-enter"); + let mut h = crate::scenario::Harness::new(); + h.app = std::mem::replace(&mut f.app, SolveApp::new(Session::default(), Default::default())); + // Not linked, or not a placement of it: refused, nothing opens + let base = h.app.run("component.create", json!({"name": "Bracket"})).unwrap()["component"].as_u64().unwrap(); + h.app.run("component.activate", json!({"component": "root"})).unwrap(); + assert!(h.app.run("component.edit_in_place", json!({"component": base})).is_err()); + assert!(h.app.run("component.edit_in_place", json!({"component": f.plate, "path": [999]})).is_err()); + // In a batch or script it would switch designs under the other steps + let reply = h.call("engine.batch", json!({"commands": [{"command": "component.edit_in_place", "params": {"component": f.plate}}]})); + assert!(reply.to_string().contains("switches to another design"), "{reply}"); + assert_eq!(h.app.docs.count(), 1); + let reply = h.call("engine.execute", json!({"command": "component.edit_in_place", "params": {"component": f.plate}})); + settle(&mut h.app); + assert_eq!(reply["result"]["component"], json!(f.plate), "{reply}"); + assert!(showing(&h.app, &f.plate_file), "{reply}"); + assert!((context(&h.app).bounds.min.x - -150.0).abs() < 1e-6, "the assembly around it, as the double-click draws it"); +} + +#[test] +fn an_open_panel_with_typed_text_holds_the_edit_up() { + let mut f = assembly("panels"); + crate::params_dialog::open(&mut f.app); + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + assert_eq!(f.app.docs.count(), 1, "the assembly's parameters panel stays"); + f.app.params = None; + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + crate::design_properties::open(&mut f.app); + assert!(f.app.run("component.finish_edit", json!({})).is_err()); + assert!(f.app.design_properties.is_some() && showing(&f.app, &f.plate_file)); +} + +#[test] +fn a_refresh_waits_for_a_command_still_queued_in_the_assembly() { + let mut f = assembly("queued"); + f.app.preferences.update_changed_links = false; + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + save_box(&f.post_file, [10.0, 10.0, 10.0], true); + refresh(&mut f.app); + crate::documents::switch(&mut f.app, 0); + f.app.deferred_queue.push(("view.fit".into(), json!({}))); + for _ in 0..200 { + tick(&mut f.app); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(f.app.edit_in_place.refreshing(), "not taken up under the queued command"); + f.app.deferred_queue.clear(); + settle(&mut f.app); + assert!((volume(&f.app) - 7250.0).abs() < 1e-6, "{}", volume(&f.app)); } #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a592cce9806..ca194d784be 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -990,9 +990,12 @@ impl SolveApp { /// Host effects shared by directly executed and already evaluated commands. pub(crate) fn command_completed(&mut self, id: &str, r: Result) -> Result { - // The engine has no edit in place to finish; the window does, and says when it can't. - let finish_edit = solidcraft_engine::find_command(id).is_some_and(|spec| spec.id == "component.finish_edit"); - let r = if finish_edit { r.and_then(|v| edit_in_place::finish_command(self).map(|()| v)) } else { r }; + // The engine has no edit in place to start or finish; the window does, and says when it can't. + let r = match solidcraft_engine::find_command(id).map(|spec| spec.id) { + Some("component.edit_in_place") => r.and_then(|v| edit_in_place::command_ran(self, &v).map(|()| v)), + Some("component.finish_edit") => r.and_then(|v| edit_in_place::finish_command(self).map(|()| v)), + _ => r, + }; if let Ok(v) = &r { match id { "view.fit" | "view.home" => self.frame_view(id == "view.home"), From f98a1b0ba22a7a1383a973b39ea69e397e50b3f9 Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 18:41:45 +0100 Subject: [PATCH 18/20] Edit in place: fixes from the second full review The MCP batch tool refuses component.edit_in_place and component.finish_edit as steps instead of sending them one by one Edit in Place asked while the assembly's agent is in its turn opens the part once the turn ends; a double-click then is refused rather than stopping the agent Both commands answer queued: true when they wait for the agent's turn, and stopping the agent forgets what it queued An undo, a queued command or a delete check running in the design holds up entering and finishing an edit A refresh redraws every edit of the assembly, the parts in other tabs too In an assembly never saved, a double-click activates the linked component as before The control and MCP docs list the new batch and script refusals, and the commands list every way they fail Co-Authored-By: Claude Opus 5.5 --- assets/locales/pending/edit-in-place.json | 42 ++++---- crates/engine/src/cmd/component.rs | 8 +- crates/engine/src/schema/component.rs | 16 +++- crates/mcp/src/tests.rs | 6 ++ crates/mcp/src/tools.rs | 5 + crates/ui-egui/src/agent_chat/mod.rs | 1 + crates/ui-egui/src/documents.rs | 7 ++ crates/ui-egui/src/edit_in_place.rs | 111 ++++++++++++++++------ crates/ui-egui/src/edit_in_place_tests.rs | 64 ++++++++++++- crates/ui-egui/src/lib.rs | 13 ++- docs/control-protocol.md | 2 +- docs/mcp.md | 2 +- 12 files changed, 221 insertions(+), 56 deletions(-) diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json index 2eb7966be58..8f7db407ca9 100644 --- a/assets/locales/pending/edit-in-place.json +++ b/assets/locales/pending/edit-in-place.json @@ -4,20 +4,21 @@ "ui.heading_finish_editing": "FINISH EDITING", "ui.edit_in_place": "Edit in Place", "ui.edit_in_place_after_turn": "The edit finishes when the agent's turn ends", - "ui.edit_in_place_agent_busy": "The agent is still working in the part; finish editing once its turn is done", + "ui.edit_in_place_agent_busy": "The agent is still working in this design; try again once its turn is done", "ui.edit_in_place_assembly_closed": "{name} is no longer open", "ui.edit_in_place_banner": "Editing in {name}", "ui.edit_in_place_busy": "Finish or cancel what is open first", "ui.edit_in_place_none": "No linked design is edited in place", "ui.edit_in_place_not_saved": "The part has changes that are not saved; save it to finish editing", "ui.edit_in_place_open_elsewhere": "{name} is open in another SolidCraft", + "ui.edit_in_place_opens_after_turn": "The part opens when the agent's turn ends", "ui.edit_in_place_refresh_dropped": "The assembly changed while Update Links ran; run it again", "ui.edit_in_place_refresh_stopped": "Update Links stopped before it was done", "ui.edit_in_place_refreshing": "Updating links in {name}…", "ui.edit_in_place_save_first": "Save the assembly first: its linked designs are found from its file", "ui.edit_in_place_save_waits": "Update Links is running in {name}; save it once it is done", "ui.edit_in_place_saved_elsewhere": "The part was saved to another file; the assembly still links {name}", - "ui.edit_in_place_wait": "Wait for the file that is being read or written", + "ui.edit_in_place_wait": "Wait until what is running in the design is done", "cmd.component_edit_in_place": "Edit in Place", "cmd.component_finish_edit": "Finish Edit" }, @@ -26,20 +27,21 @@ "ui.heading_finish_editing": "إنهاء التحرير", "ui.edit_in_place": "تحرير في المكان", "ui.edit_in_place_after_turn": "ينتهي التحرير عند انتهاء دور الوكيل", - "ui.edit_in_place_agent_busy": "لا يزال الوكيل يعمل في الجزء؛ أنهِ التحرير بعد انتهاء دوره", + "ui.edit_in_place_agent_busy": "لا يزال الوكيل يعمل في هذا التصميم؛ حاول مرة أخرى بعد انتهاء دوره", "ui.edit_in_place_assembly_closed": "{name} لم يعد مفتوحًا", "ui.edit_in_place_banner": "تحرير داخل {name}", "ui.edit_in_place_busy": "أنهِ ما هو مفتوح أو ألغِه أولاً", "ui.edit_in_place_none": "لا يُحرَّر أي تصميم مرتبط في مكانه", "ui.edit_in_place_not_saved": "في الجزء تغييرات غير محفوظة؛ احفظه لإنهاء التحرير", "ui.edit_in_place_open_elsewhere": "{name} مفتوح في نسخة أخرى من SolidCraft", + "ui.edit_in_place_opens_after_turn": "يُفتح الجزء عند انتهاء دور الوكيل", "ui.edit_in_place_refresh_dropped": "تغيّر التجميع أثناء تحديث الروابط؛ شغّله مرة أخرى", "ui.edit_in_place_refresh_stopped": "توقّف تحديث الروابط قبل أن ينتهي", "ui.edit_in_place_refreshing": "جارٍ تحديث الروابط في {name}…", "ui.edit_in_place_save_first": "احفظ التجميع أولاً: يُعثر على تصاميمه المرتبطة انطلاقًا من ملفه", "ui.edit_in_place_save_waits": "يجري تحديث الروابط في {name}؛ احفظه بعد انتهائه", "ui.edit_in_place_saved_elsewhere": "حُفظ الجزء في ملف آخر؛ ما زال التجميع مرتبطًا بـ {name}", - "ui.edit_in_place_wait": "انتظر حتى تنتهي قراءة الملف أو كتابته", + "ui.edit_in_place_wait": "انتظر حتى ينتهي ما يجري في التصميم", "cmd.component_edit_in_place": "تحرير في المكان", "cmd.component_finish_edit": "إنهاء التحرير" }, @@ -47,21 +49,22 @@ "settings.double_click_components": "Doppelklick auf eine Komponente aktiviert sie oder bearbeitet eine verknüpfte an Ort und Stelle", "ui.heading_finish_editing": "BEARBEITUNG BEENDEN", "ui.edit_in_place": "An Ort und Stelle bearbeiten", - "ui.edit_in_place_after_turn": "Die Bearbeitung endet, sobald der Agent mit seinem Zug fertig ist", - "ui.edit_in_place_agent_busy": "Der Agent arbeitet noch im Teil; die Bearbeitung beenden, sobald er fertig ist", + "ui.edit_in_place_after_turn": "Die Bearbeitung endet, sobald der Agent seine Antwort beendet hat", + "ui.edit_in_place_agent_busy": "Der Agent arbeitet noch in diesem Design; erneut versuchen, sobald er seine Antwort beendet hat", "ui.edit_in_place_assembly_closed": "{name} ist nicht mehr geöffnet", "ui.edit_in_place_banner": "Bearbeitung in {name}", "ui.edit_in_place_busy": "Zuerst abschließen oder abbrechen, was offen ist", "ui.edit_in_place_none": "Es wird kein verknüpftes Design an Ort und Stelle bearbeitet", "ui.edit_in_place_not_saved": "Das Teil hat ungespeicherte Änderungen; zum Beenden der Bearbeitung speichern", "ui.edit_in_place_open_elsewhere": "{name} ist in einem anderen SolidCraft geöffnet", + "ui.edit_in_place_opens_after_turn": "Das Teil öffnet sich, sobald der Agent seine Antwort beendet hat", "ui.edit_in_place_refresh_dropped": "Die Baugruppe wurde während der Aktualisierung der Verknüpfungen geändert; bitte erneut ausführen", "ui.edit_in_place_refresh_stopped": "Die Aktualisierung der Verknüpfungen wurde vorzeitig beendet", "ui.edit_in_place_refreshing": "Verknüpfungen in {name} werden aktualisiert…", "ui.edit_in_place_save_first": "Zuerst die Baugruppe speichern: ihre verknüpften Designs werden von ihrer Datei aus gefunden", "ui.edit_in_place_save_waits": "In {name} werden die Verknüpfungen aktualisiert; danach speichern", "ui.edit_in_place_saved_elsewhere": "Das Teil wurde in eine andere Datei gespeichert; die Baugruppe verknüpft weiterhin {name}", - "ui.edit_in_place_wait": "Warten, bis die Datei gelesen oder geschrieben ist", + "ui.edit_in_place_wait": "Warten, bis abgeschlossen ist, was im Design läuft", "cmd.component_edit_in_place": "An Ort und Stelle bearbeiten", "cmd.component_finish_edit": "Bearbeitung beenden" }, @@ -70,20 +73,21 @@ "ui.heading_finish_editing": "סיום עריכה", "ui.edit_in_place": "עריכה במקום", "ui.edit_in_place_after_turn": "העריכה תסתיים כשתור הסוכן יסתיים", - "ui.edit_in_place_agent_busy": "הסוכן עדיין עובד בחלק; יש לסיים את העריכה כשתורו יסתיים", + "ui.edit_in_place_agent_busy": "הסוכן עדיין עובד בתכן הזה; יש לנסות שוב כשתורו יסתיים", "ui.edit_in_place_assembly_closed": "{name} כבר אינו פתוח", "ui.edit_in_place_banner": "עריכה בתוך {name}", "ui.edit_in_place_busy": "יש לסיים או לבטל קודם את מה שפתוח", "ui.edit_in_place_none": "אין תכן מקושר בעריכה במקום", "ui.edit_in_place_not_saved": "בחלק יש שינויים שלא נשמרו; יש לשמור כדי לסיים את העריכה", "ui.edit_in_place_open_elsewhere": "{name} פתוח במופע אחר של SolidCraft", + "ui.edit_in_place_opens_after_turn": "החלק ייפתח כשתור הסוכן יסתיים", "ui.edit_in_place_refresh_dropped": "ההרכבה השתנתה בזמן עדכון הקישורים; יש להריץ שוב", "ui.edit_in_place_refresh_stopped": "עדכון הקישורים נעצר לפני שהסתיים", "ui.edit_in_place_refreshing": "מעדכן קישורים ב-{name}…", "ui.edit_in_place_save_first": "יש לשמור קודם את ההרכבה: התכנים המקושרים שלה נמצאים לפי הקובץ שלה", "ui.edit_in_place_save_waits": "עדכון הקישורים פועל ב-{name}; יש לשמור לאחר שיסתיים", "ui.edit_in_place_saved_elsewhere": "החלק נשמר לקובץ אחר; ההרכבה עדיין מקושרת אל {name}", - "ui.edit_in_place_wait": "יש להמתין עד שקריאת הקובץ או כתיבתו תסתיים", + "ui.edit_in_place_wait": "יש להמתין עד שמה שפועל בתכן יסתיים", "cmd.component_edit_in_place": "עריכה במקום", "cmd.component_finish_edit": "סיום עריכה" }, @@ -92,20 +96,21 @@ "ui.heading_finish_editing": "編集を終了", "ui.edit_in_place": "その場で編集", "ui.edit_in_place_after_turn": "エージェントのターンが終わると編集を終了します", - "ui.edit_in_place_agent_busy": "エージェントがまだ部品で作業中です。そのターンが終わってから編集を終了してください", + "ui.edit_in_place_agent_busy": "エージェントがまだこのデザインで作業中です。そのターンが終わってから再度お試しください", "ui.edit_in_place_assembly_closed": "{name} はもう開いていません", "ui.edit_in_place_banner": "{name} 内で編集中", "ui.edit_in_place_busy": "先に開いているものを終了またはキャンセルしてください", "ui.edit_in_place_none": "その場で編集中のリンクされたデザインはありません", "ui.edit_in_place_not_saved": "部品に保存されていない変更があります。編集を終了するには保存してください", "ui.edit_in_place_open_elsewhere": "{name} は別の SolidCraft で開かれています", + "ui.edit_in_place_opens_after_turn": "エージェントのターンが終わると部品が開きます", "ui.edit_in_place_refresh_dropped": "リンクの更新中にアセンブリが変更されました。もう一度実行してください", "ui.edit_in_place_refresh_stopped": "リンクの更新が完了前に停止しました", "ui.edit_in_place_refreshing": "{name} のリンクを更新中…", "ui.edit_in_place_save_first": "先にアセンブリを保存してください。リンクされたデザインはそのファイルから見つけます", "ui.edit_in_place_save_waits": "{name} のリンクを更新中です。完了してから保存してください", "ui.edit_in_place_saved_elsewhere": "部品は別のファイルに保存されました。アセンブリは引き続き {name} にリンクしています", - "ui.edit_in_place_wait": "ファイルの読み込みまたは書き込みが終わるまでお待ちください", + "ui.edit_in_place_wait": "デザインで実行中の処理が終わるまでお待ちください", "cmd.component_edit_in_place": "その場で編集", "cmd.component_finish_edit": "編集を終了" }, @@ -114,20 +119,21 @@ "ui.heading_finish_editing": "편집 완료", "ui.edit_in_place": "제자리에서 편집", "ui.edit_in_place_after_turn": "에이전트의 차례가 끝나면 편집이 완료됩니다", - "ui.edit_in_place_agent_busy": "에이전트가 아직 부품에서 작업 중입니다. 차례가 끝난 후 편집을 완료하세요", + "ui.edit_in_place_agent_busy": "에이전트가 아직 이 디자인에서 작업 중입니다. 차례가 끝난 후 다시 시도하세요", "ui.edit_in_place_assembly_closed": "{name}이(가) 더 이상 열려 있지 않습니다", "ui.edit_in_place_banner": "{name}에서 편집 중", "ui.edit_in_place_busy": "먼저 열려 있는 작업을 완료하거나 취소하세요", "ui.edit_in_place_none": "제자리에서 편집 중인 연결된 디자인이 없습니다", "ui.edit_in_place_not_saved": "부품에 저장되지 않은 변경 사항이 있습니다. 편집을 완료하려면 저장하세요", "ui.edit_in_place_open_elsewhere": "{name}이(가) 다른 SolidCraft에서 열려 있습니다", + "ui.edit_in_place_opens_after_turn": "에이전트의 차례가 끝나면 부품이 열립니다", "ui.edit_in_place_refresh_dropped": "링크 업데이트 중에 어셈블리가 변경되었습니다. 다시 실행하세요", "ui.edit_in_place_refresh_stopped": "링크 업데이트가 완료되기 전에 중지되었습니다", "ui.edit_in_place_refreshing": "{name}의 링크 업데이트 중…", "ui.edit_in_place_save_first": "먼저 어셈블리를 저장하세요. 연결된 디자인은 해당 파일을 기준으로 찾습니다", "ui.edit_in_place_save_waits": "{name}에서 링크 업데이트가 실행 중입니다. 완료된 후 저장하세요", "ui.edit_in_place_saved_elsewhere": "부품이 다른 파일에 저장되었습니다. 어셈블리는 여전히 {name}에 연결되어 있습니다", - "ui.edit_in_place_wait": "파일 읽기 또는 쓰기가 끝날 때까지 기다리세요", + "ui.edit_in_place_wait": "디자인에서 실행 중인 작업이 끝날 때까지 기다리세요", "cmd.component_edit_in_place": "제자리에서 편집", "cmd.component_finish_edit": "편집 완료" }, @@ -136,20 +142,21 @@ "ui.heading_finish_editing": "HOÀN TẤT CHỈNH SỬA", "ui.edit_in_place": "Chỉnh sửa tại chỗ", "ui.edit_in_place_after_turn": "Việc chỉnh sửa sẽ hoàn tất khi lượt của tác tử kết thúc", - "ui.edit_in_place_agent_busy": "Tác tử vẫn đang làm việc trong chi tiết; hãy hoàn tất chỉnh sửa khi lượt của nó kết thúc", + "ui.edit_in_place_agent_busy": "Tác tử vẫn đang làm việc trong thiết kế này; hãy thử lại khi lượt của nó kết thúc", "ui.edit_in_place_assembly_closed": "{name} không còn mở", "ui.edit_in_place_banner": "Đang chỉnh sửa trong {name}", "ui.edit_in_place_busy": "Hãy hoàn tất hoặc hủy những gì đang mở trước", "ui.edit_in_place_none": "Không có thiết kế liên kết nào đang được chỉnh sửa tại chỗ", "ui.edit_in_place_not_saved": "Chi tiết có thay đổi chưa lưu; hãy lưu để hoàn tất chỉnh sửa", "ui.edit_in_place_open_elsewhere": "{name} đang mở trong một SolidCraft khác", + "ui.edit_in_place_opens_after_turn": "Chi tiết sẽ mở khi lượt của tác tử kết thúc", "ui.edit_in_place_refresh_dropped": "Cụm lắp ráp đã thay đổi trong khi cập nhật liên kết; hãy chạy lại", "ui.edit_in_place_refresh_stopped": "Cập nhật liên kết đã dừng trước khi hoàn tất", "ui.edit_in_place_refreshing": "Đang cập nhật liên kết trong {name}…", "ui.edit_in_place_save_first": "Hãy lưu cụm lắp ráp trước: các thiết kế liên kết của nó được tìm từ tệp của nó", "ui.edit_in_place_save_waits": "Đang cập nhật liên kết trong {name}; hãy lưu sau khi hoàn tất", "ui.edit_in_place_saved_elsewhere": "Chi tiết đã được lưu vào tệp khác; cụm lắp ráp vẫn liên kết với {name}", - "ui.edit_in_place_wait": "Hãy chờ việc đọc hoặc ghi tệp kết thúc", + "ui.edit_in_place_wait": "Hãy chờ những gì đang chạy trong thiết kế hoàn tất", "cmd.component_edit_in_place": "Chỉnh sửa tại chỗ", "cmd.component_finish_edit": "Hoàn tất chỉnh sửa" }, @@ -158,20 +165,21 @@ "ui.heading_finish_editing": "完成编辑", "ui.edit_in_place": "原位编辑", "ui.edit_in_place_after_turn": "代理本轮结束后将完成编辑", - "ui.edit_in_place_agent_busy": "代理仍在零件中工作;请在其本轮结束后完成编辑", + "ui.edit_in_place_agent_busy": "代理仍在此设计中工作;请在其本轮结束后重试", "ui.edit_in_place_assembly_closed": "{name} 已不再打开", "ui.edit_in_place_banner": "正在 {name} 中编辑", "ui.edit_in_place_busy": "请先完成或取消打开的操作", "ui.edit_in_place_none": "没有正在原位编辑的链接设计", "ui.edit_in_place_not_saved": "零件有未保存的更改;请保存以完成编辑", "ui.edit_in_place_open_elsewhere": "{name} 已在另一个 SolidCraft 中打开", + "ui.edit_in_place_opens_after_turn": "代理本轮结束后将打开零件", "ui.edit_in_place_refresh_dropped": "更新链接期间装配体已更改;请再次运行", "ui.edit_in_place_refresh_stopped": "更新链接在完成前已停止", "ui.edit_in_place_refreshing": "正在更新 {name} 中的链接…", "ui.edit_in_place_save_first": "请先保存装配体:其链接设计根据其文件查找", "ui.edit_in_place_save_waits": "正在更新 {name} 中的链接;请在完成后保存", "ui.edit_in_place_saved_elsewhere": "零件已保存到其他文件;装配体仍链接 {name}", - "ui.edit_in_place_wait": "请等待文件读取或写入完成", + "ui.edit_in_place_wait": "请等待设计中正在运行的操作完成", "cmd.component_edit_in_place": "原位编辑", "cmd.component_finish_edit": "完成编辑" } diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index dc12ca10bb2..3ad97fe6560 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -57,7 +57,9 @@ pub static COMMANDS: &[CommandSpec] = &[ .params( "component: id or name of a linked component; path?: its placement (occurrence ids, default its first) → in the app \ window: open the design it links in a tab of its own with the assembly drawn around it (component.finish_edit goes \ - back); fails when it is not linked, the assembly has no file yet or something is open in it; elsewhere it only checks", + back); fails when it is not linked, the assembly has no file yet, something is open or running in it, or the file is \ + missing, on a network location not allowed yet or open in another SolidCraft; asked during the agent's turn it opens \ + once the turn ends (queued: true); elsewhere it only checks", ), CommandSpec::new("component.finish_edit", "Finish Edit", crate::checked!("component.finish_edit", finish_edit)) .icon("finish_edit") @@ -67,8 +69,8 @@ pub static COMMANDS: &[CommandSpec] = &[ .output(output_schema_for::) .params( "no parameters → in the app window: go back from the linked design edited in place to its assembly, which reads it again; \ - fails while the design has unsaved changes (run file.save first) or something is open in it; asked by the part's own \ - agent, it finishes when that agent's turn ends; elsewhere nothing changes", + fails while the design has unsaved changes (run file.save first) or something is open in it; asked during the agent's \ + turn it finishes once the turn ends (queued: true); elsewhere nothing changes", ), CommandSpec::new("component.list", "List Components", list).icon("list").noundo().params( "compact?: bool (counts of bodies, features, sketches and construction planes instead of their names; occurrences leave out \ diff --git a/crates/engine/src/schema/component.rs b/crates/engine/src/schema/component.rs index 1068096a817..8129a0fac7e 100644 --- a/crates/engine/src/schema/component.rs +++ b/crates/engine/src/schema/component.rs @@ -8,8 +8,10 @@ use super::types::{IdOrName, present}; /// Edit a linked component's design in place. In the app window: open the design it links in a /// tab of its own, with the rest of the assembly drawn faded around it as the placement `path` /// puts it; `component.finish_edit` goes back. It fails when the component is not linked, the -/// assembly has no file yet, or something is open in it. Outside the window it only checks the -/// component and the placement. +/// assembly has no file yet, something is open or running in it, or the linked file is missing, +/// on a network location not allowed yet or open in another SolidCraft. Asked while the +/// assembly's agent is in its turn, the part opens once the turn ends (`queued`). Outside the +/// window it only checks the component and the placement. #[derive(Debug, Deserialize, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct EditInPlaceParams { @@ -24,6 +26,10 @@ pub struct EditInPlaceParams { /// What `component.edit_in_place` returns. #[derive(Debug, Default, Serialize, JsonSchema)] pub struct EditInPlaceResult { + /// In the app window, asked while the design's agent is in its turn: the part opens once the + /// turn ends (Stop cancels it). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub queued: bool, /// The component, by id. pub component: u64, /// The placement it is edited at. @@ -36,7 +42,7 @@ pub struct EditInPlaceResult { /// Finish editing a linked component's design in place. In the app window: go back to the /// assembly around it, which reads the link again, and close the part's tab when the edit opened /// it. It fails while the part has unsaved changes (save it first) or something is open in it; -/// asked by the part's own agent, it finishes when that agent's turn ends. Outside the window +/// asked while the part's agent is in its turn, it finishes once the turn ends (`queued`). Outside the window /// nothing is edited in place, so nothing changes. #[derive(Debug, Deserialize, JsonSchema)] #[schemars(deny_unknown_fields)] @@ -45,6 +51,10 @@ pub struct FinishEditParams {} /// What `component.finish_edit` returns. #[derive(Debug, Default, Serialize, JsonSchema)] pub struct FinishEditResult { + /// In the app window, asked while the part's agent is in its turn: the edit finishes once the + /// turn ends (Stop cancels it). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub queued: bool, /// In the warn parameter-check mode: what the call's parameters got wrong. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub param_warnings: Vec, diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index bde44a91229..3959de54d2e 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -2140,6 +2140,12 @@ fn batch_steps_may_name_tools() { assert!(body["failed"]["error"].as_str().is_some_and(|e| e.contains("screenshot")), "{body}"); let (_, body, _) = recorded_batch(Ok(json!({})), json!({"commands": [{"command": "body_topology", "params": {"body": "Body1"}}]})); assert!(body["failed"]["error"].as_str().is_some_and(|e| e.contains("model.edges") && e.contains("model.faces")), "{body}"); + // Editing in place goes to another design's tab: never a step, not even one by one + for command in ["component.edit_in_place", "Component.Finish_Edit"] { + let (b, body, is_error) = recorded_batch(Ok(json!({})), json!({"commands": [{"command": "solid.box"}, {"command": command}]})); + assert!(is_error && b.calls.is_empty(), "{command}: {body}"); + assert!(body["failed"]["error"].as_str().is_some_and(|e| e.contains("on its own")), "{body}"); + } // Headless, step by step. let mut s = server(); diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index dbf3ce6efbc..87c3dd3a061 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -644,6 +644,11 @@ fn batch_step(step: &Value) -> Result<(String, Value, Option), String> { "screenshot" => Err("`screenshot` is a tool, not a command: call it after the batch".into()), "batch" => Err("batches don't nest: put the steps in this batch".into()), "pending" => Err("`pending` is a tool, not a command: call it on its own".into()), + // The window switches to another design's tab for these: the batch's later steps and its + // rollback would land in the wrong design. + c if solidcraft_engine::find_command(c).is_some_and(|spec| matches!(spec.id, "component.edit_in_place" | "component.finish_edit")) => { + Err(format!("`{c}` goes to another design's tab: send it on its own with execute")) + } "running" => Err("`running` is a tool, not a command: call it on its own".into()), "skill_reference" => Err("`skill_reference` is a tool, not a command: call it on its own".into()), // An engine command: the step goes as it is. diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index b000314e095..23ce6d7c175 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -1417,6 +1417,7 @@ pub(crate) fn attach_dropped(app: &mut SolveApp, paths: impl Iterator(app: &'a SolveApp, path: &str) -> Option<&'a Sessio app.docs.slots.iter().flatten().map(|s| &s.session).find(|s| saved_at(s)) } +/// Every edit in place: of the tab shown, and of the tabs in the background. +pub(crate) fn edits_mut(app: &mut SolveApp) -> Vec<&mut crate::edit_in_place::PartContext> { + let mut edits: Vec<_> = app.docs.slots.iter_mut().flatten().filter_map(|s| s.edit_in_place.as_mut()).collect(); + edits.extend(app.edit_in_place.active.as_mut()); + edits +} + /// The open design saved at `path` read every link again without an error, from the files as /// `stamps` found them: its record of them (`Documents::link_stamps`, or its tab's) is now that. pub(crate) fn record_stamps_at(app: &mut SolveApp, path: &str, stamps: &[(u64, crate::linked_source::Stamp)]) { diff --git a/crates/ui-egui/src/edit_in_place.rs b/crates/ui-egui/src/edit_in_place.rs index 674851f14cc..c52e1445046 100644 --- a/crates/ui-egui/src/edit_in_place.rs +++ b/crates/ui-egui/src/edit_in_place.rs @@ -60,6 +60,9 @@ pub struct EditInPlace { finish_after_save: Option, /// The part's own agent asked to finish the edit of the part at this file during its turn. finish_after_turn: Option, + /// The assembly's own agent asked to edit this component of the assembly at this file, at + /// this placement, during its turn. + enter_after_turn: Option<(String, u64, Option>)>, refresh: Option, /// `component.edit_in_place` is run by the window ([`open`]), not as a command: its open may ask. ask: bool, @@ -72,12 +75,18 @@ impl EditInPlace { } } +/// A linked component the window edits in place when it is double-clicked: in a saved design +/// (its links are found from its file) with `double_click_components` on. +fn edits_on_double_click(app: &SolveApp, component: u64) -> bool { + app.preferences.double_click_components && app.session.path.is_some() && app.session.doc.links.contains_key(&component) +} + /// A component double-clicked in the browser: a linked one is edited in place (Preferences: -/// `double_click_components`), any other is made the active component (`component.activate` -/// with `params`). Activate itself always does the latter. +/// `double_click_components`), any other, or any in a design not saved yet, is made the active +/// component (`component.activate` with `params`). Activate itself always does the latter. pub(crate) fn double_click_component(app: &mut SolveApp, params: Value) { let component = params["component"].as_u64().unwrap_or(0); - if app.preferences.double_click_components && app.session.doc.links.contains_key(&component) { + if edits_on_double_click(app, component) { let path = params["path"].as_array().map(|p| p.iter().filter_map(Value::as_u64).collect::>()); open(app, component, path); } else { @@ -101,7 +110,7 @@ pub(crate) fn double_click_face(app: &mut SolveApp, body: &str) -> bool { .filter(|(c, _, _)| *c == component) .map(|(_, path, _)| path) .find(|path| app.session.occurrence_bodies(path, true).is_ok_and(|bodies| bodies.iter().any(|b| b == body))); - if app.session.doc.links.contains_key(&component) { + if edits_on_double_click(app, component) { open(app, component, placement); return true; } @@ -114,12 +123,20 @@ pub(crate) fn double_click_face(app: &mut SolveApp, body: &str) -> bool { app.run("component.activate", json!({"component": component, "occurrence": occurrence, "path": placement})).is_ok() } -/// Something runs that a change of the design shown would spoil. +/// Something runs that a change of the design shown would spoil: a file being read, written or +/// picked, the assembly's refresh, or an undo, a queued command or a delete check, which would +/// land in the other design. fn busy(app: &SolveApp) -> bool { - app.file_picker_busy() || app.file_load.busy() || app.saving.is_some() || app.edit_in_place.refreshing() + app.file_picker_busy() + || app.file_load.busy() + || app.saving.is_some() + || app.edit_in_place.refreshing() + || app.deferred.is_some() + || !app.deferred_queue.is_empty() + || app.delete_check.is_some() } -/// Why [`busy`]: the assembly's refresh, or a file being read, written or picked. +/// Why [`busy`]: the assembly's refresh, or something else that has to finish first. fn busy_reason(app: &SolveApp) -> String { match &app.edit_in_place.refresh { Some(r) => crate::i18n::format("ui.edit_in_place_refreshing", &[("name", &file_name(&r.assembly))]), @@ -182,22 +199,43 @@ pub(crate) fn open(app: &mut SolveApp, component: u64, path: Option>) { /// `component.edit_in_place` ran: `result` names the component and its placement, and the window /// opens the edit. Run as a command, it asks nothing: what would need a question fails instead. -pub(crate) fn command_ran(app: &mut SolveApp, result: &Value) -> Result<(), String> { +pub(crate) fn command_ran(app: &mut SolveApp, result: &Value) -> Result { let component = result["component"].as_u64().unwrap_or(0); let path = result["path"].as_array().map(|p| p.iter().filter_map(Value::as_u64).collect::>()); let ask = app.edit_in_place.ask; - enter(app, component, path, ask) + // Leaving the tab would stop the design's agent in the middle of its turn. Asked by that agent + // (a command, which it sends during its turn), the part opens once the turn ends. + if app.agent_chat.state() == crate::agent_chat::State::Busy { + if ask { + return Err(crate::i18n::tr("ui.edit_in_place_agent_busy").to_string()); + } + check_enter(app)?; + let assembly = app.session.path.clone().unwrap_or_default(); + app.edit_in_place.enter_after_turn = Some((assembly, component, path)); + app.set_status(crate::i18n::tr("ui.edit_in_place_opens_after_turn").to_string(), false); + return Ok(true); + } + enter(app, component, path, ask).map(|()| false) } -/// Open the design the linked component `component` comes from, with the assembly around it as -/// its placement `path` (default: its first) puts it (`ask`: with the open's questions). -fn enter(app: &mut SolveApp, component: u64, path: Option>, ask: bool) -> Result<(), String> { +/// What holds up entering an edit from the design shown. +fn check_enter(app: &SolveApp) -> Result<(), String> { if busy(app) { return Err(busy_reason(app)); } if working(app) { return Err(crate::i18n::tr("ui.edit_in_place_busy").to_string()); } + if app.session.path.is_none() { + return Err(crate::i18n::tr("ui.edit_in_place_save_first").to_string()); + } + Ok(()) +} + +/// Open the design the linked component `component` comes from, with the assembly around it as +/// its placement `path` (default: its first) puts it (`ask`: with the open's questions). +fn enter(app: &mut SolveApp, component: u64, path: Option>, ask: bool) -> Result<(), String> { + check_enter(app)?; let Some(assembly) = app.session.path.clone() else { return Err(crate::i18n::tr("ui.edit_in_place_save_first").to_string()); }; @@ -346,12 +384,18 @@ fn take_refresh(app: &mut SolveApp) { // Every link was read as its file was when the run started: one saved since is read again // when the assembly's tab comes back. crate::documents::record_stamps_at(app, &r.assembly, &r.stamps); - let Some(context) = app.edit_in_place.active.as_ref().filter(|c| crate::documents::same_path(&c.assembly, &r.assembly)) else { return }; - let (component, placement) = (context.component, context.placement.clone()); - let snap = crate::documents::session_at(app, &r.assembly).and_then(|s| snapshot(s, component, &placement)); - let Some((bodies, triangles, bounds)) = snap else { return }; - if let Some(context) = app.edit_in_place.active.as_mut() { - (context.bodies, context.triangles, context.bounds) = (bodies, Arc::new(triangles), bounds); + // Every edit of a part of this assembly, in the tab shown or another, is drawn around anew. + let of_assembly = |c: &&mut PartContext| crate::documents::same_path(&c.assembly, &r.assembly); + let placements: Vec<(u64, Vec)> = + crate::documents::edits_mut(app).into_iter().filter(of_assembly).map(|c| (c.component, c.placement.clone())).collect(); + let snaps: Vec<_> = placements + .iter() + .map(|(component, placement)| crate::documents::session_at(app, &r.assembly).and_then(|s| snapshot(s, *component, placement))) + .collect(); + for (context, snap) in crate::documents::edits_mut(app).into_iter().filter(of_assembly).zip(snaps) { + if let Some((bodies, triangles, bounds)) = snap { + (context.bodies, context.triangles, context.bounds) = (bodies, Arc::new(triangles), bounds); + } } let language = crate::i18n::Locale::for_language(&app.preferences.language); app.set_status(language.format("ui.command_done", &[("command", language.label(crate::command_label("component.update_links")))]), false); @@ -367,14 +411,14 @@ pub(crate) fn finish(app: &mut SolveApp) { /// `component.finish_edit` run as a command: it opens nothing, so a part with changes is /// refused (save it first), as is anything else that holds Finish Edit up. The refusal is -/// its error, which the caller reports. -pub(crate) fn finish_command(app: &mut SolveApp) -> Result<(), String> { +/// its error, which the caller reports; `true`: it waits for the end of the agent's turn. +pub(crate) fn finish_command(app: &mut SolveApp) -> Result { finish_with(app, false) } /// Save the part (`save`: and wait for it), go back to the assembly, close the part's tab when -/// the edit opened it and read the assembly's links again. -fn finish_with(app: &mut SolveApp, save: bool) -> Result<(), String> { +/// the edit opened it and read the assembly's links again. `true`: it waits for the agent. +fn finish_with(app: &mut SolveApp, save: bool) -> Result { let Some(part) = app.edit_in_place.active.as_ref().map(|c| c.part.clone()) else { return Err(crate::i18n::tr("ui.edit_in_place_none").to_string()); }; @@ -394,7 +438,7 @@ fn finish_with(app: &mut SolveApp, save: bool) -> Result<(), String> { } app.edit_in_place.finish_after_save = Some(part); crate::toolbar::save(app); - return Ok(()); + return Ok(false); } // Leaving the tab would stop the part's agent in the middle of its turn. Asked by that agent // (a command, which it can only send during its turn), the edit finishes once the turn ends. @@ -404,9 +448,9 @@ fn finish_with(app: &mut SolveApp, save: bool) -> Result<(), String> { } app.edit_in_place.finish_after_turn = Some(part); app.set_status(crate::i18n::tr("ui.edit_in_place_after_turn").to_string(), false); - return Ok(()); + return Ok(true); } - let Some(context) = app.edit_in_place.active.take() else { return Ok(()) }; + let Some(context) = app.edit_in_place.active.take() else { return Ok(false) }; let part_tab = app.docs.active; if !matches!(crate::documents::reuse_path(app, &context.assembly), Ok(true)) { let why = crate::i18n::format("ui.edit_in_place_assembly_closed", &[("name", &context.assembly_name)]); @@ -424,14 +468,13 @@ fn finish_with(app: &mut SolveApp, save: bool) -> Result<(), String> { request.design = Some(context.assembly); let _ = crate::file_load::begin_request(app, request); } - Ok(()) + Ok(false) } /// Nothing is under way in the part that leaving its tab would cut short or that waits for an /// answer: a dialog or tool, a feature being computed or edited, a sketch, a prompt or Home. fn can_finish(app: &SolveApp) -> bool { !working(app) - && app.deferred.is_none() && app.docs.closing.is_none() && app.docs.quitting.is_none() && app.docs.batch.is_none() @@ -468,6 +511,20 @@ pub(crate) fn tick(app: &mut SolveApp) { { app.set_status(why, true); } + // Likewise the edit the assembly's agent asked for, from the assembly's tab. + if app.agent_chat.state() != crate::agent_chat::State::Busy + && let Some((assembly, component, path)) = app.edit_in_place.enter_after_turn.take() + && app.session.path.as_deref().is_some_and(|p| crate::documents::same_path(p, &assembly)) + && let Err(why) = enter(app, component, path, false) + { + app.set_status(why, true); + } +} + +/// The agent's turn was stopped: what it asked to do once the turn ended is not done. +pub(crate) fn forget_after_turn(app: &mut SolveApp) { + app.edit_in_place.finish_after_turn = None; + app.edit_in_place.enter_after_turn = None; } /// The mouse's back button (or a keyboard's Back key) pressed while a part is edited in place: diff --git a/crates/ui-egui/src/edit_in_place_tests.rs b/crates/ui-egui/src/edit_in_place_tests.rs index 41d88d06494..177383e7cad 100644 --- a/crates/ui-egui/src/edit_in_place_tests.rs +++ b/crates/ui-egui/src/edit_in_place_tests.rs @@ -715,11 +715,71 @@ fn turned_off_or_unsaved_double_clicking_a_linked_component_does_what_it_did() { assert_eq!(f.app.session.active_component, f.plate); assert_eq!(f.app.docs.count(), 1); assert!(f.app.edit_in_place.active.is_none()); - // An assembly never saved has no folder to find its links from + // An assembly never saved has no folder to find its links from: the double-click activates let mut fresh = SolveApp::new(Session::default(), Default::default()); let linked = fresh.run("component.insert_design", json!({"path": f.plate_file})).unwrap()["component"].as_u64().unwrap(); + fresh.run("component.activate", json!({"component": "root"})).unwrap(); double_click_component(&mut fresh, json!({"component": linked})); settle(&mut fresh); assert!(fresh.edit_in_place.active.is_none() && fresh.edit_in_place.pending.is_none()); - assert!(fresh.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", fresh.status); + assert_eq!(fresh.session.active_component, linked); + // Asked as a command, it says why + let e = fresh.run("component.edit_in_place", json!({"component": linked})).unwrap_err(); + assert!(e.contains("Save the assembly first"), "{e}"); +} + +#[test] +fn the_assemblys_agent_opens_the_part_once_its_turn_ends() { + let mut f = assembly("enter-agent"); + f.app.agent_chat.set_state(crate::agent_chat::State::Busy); + // A double-click would stop the agent mid-turn: refused + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + assert_eq!(f.app.docs.count(), 1); + assert!(f.app.status.as_ref().is_some_and(|(s, _, error)| *error && s.contains("agent")), "{:?}", f.app.status); + // The agent asks: queued, and said so + let r = f.app.run("component.edit_in_place", json!({"component": f.plate})).unwrap(); + assert_eq!(r["queued"], json!(true), "{r}"); + settle(&mut f.app); + assert_eq!(f.app.docs.count(), 1, "not during the turn"); + f.app.agent_chat.set_state(crate::agent_chat::State::Ready); + settle(&mut f.app); + assert!(showing(&f.app, &f.plate_file) && f.app.edit_in_place.active.is_some()); +} + +#[test] +fn stopping_the_agent_forgets_what_it_queued() { + let mut f = assembly("stopped"); + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + f.app.agent_chat.set_state(crate::agent_chat::State::Busy); + assert_eq!(f.app.run("component.finish_edit", json!({})).unwrap()["queued"], json!(true)); + crate::agent_chat::cancel(&mut f.app); + f.app.agent_chat.set_state(crate::agent_chat::State::Ready); + settle(&mut f.app); + assert!(showing(&f.app, &f.plate_file) && f.app.edit_in_place.active.is_some(), "Stop means stop"); +} + +#[test] +fn a_command_queued_in_the_assembly_holds_up_entering() { + let mut f = assembly("queued-enter"); + f.app.deferred_queue.push(("view.fit".into(), json!({}))); + let e = f.app.run("component.edit_in_place", json!({"component": f.plate})).unwrap_err(); + assert!(e.contains("Wait"), "{e}"); + settle(&mut f.app); + assert_eq!(f.app.docs.count(), 1, "the queued command lands in the assembly, not the part"); +} + +#[test] +fn a_refresh_taken_up_in_the_assemblys_tab_redraws_the_parts_tab_too() { + let mut f = assembly("watched"); + f.app.preferences.update_changed_links = false; + double_click_component(&mut f.app, json!({"component": f.plate})); + settle(&mut f.app); + save_box(&f.post_file, [10.0, 10.0, 10.0], true); + refresh(&mut f.app); + crate::documents::switch(&mut f.app, 0); + settle(&mut f.app); + crate::documents::switch(&mut f.app, 1); + assert!((context(&f.app).bounds.max.z - 20.0).abs() < 1e-6, "the post's new box shows: {:?}", context(&f.app).bounds); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ca194d784be..ff31be2f2a4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -992,8 +992,9 @@ impl SolveApp { pub(crate) fn command_completed(&mut self, id: &str, r: Result) -> Result { // The engine has no edit in place to start or finish; the window does, and says when it can't. let r = match solidcraft_engine::find_command(id).map(|spec| spec.id) { - Some("component.edit_in_place") => r.and_then(|v| edit_in_place::command_ran(self, &v).map(|()| v)), - Some("component.finish_edit") => r.and_then(|v| edit_in_place::finish_command(self).map(|()| v)), + // `queued`: it waits for the end of the agent's turn. + Some("component.edit_in_place") => r.and_then(|v| edit_in_place::command_ran(self, &v).map(|queued| with_queued(v, queued))), + Some("component.finish_edit") => r.and_then(|v| edit_in_place::finish_command(self).map(|queued| with_queued(v, queued))), _ => r, }; if let Ok(v) = &r { @@ -2528,6 +2529,14 @@ fn window_hidden(ctx: &egui::Context) -> bool { ctx.input(|i| i.viewport().visible()) == Some(false) } +/// An edit in place command's result, saying when it waits for the end of the agent's turn. +fn with_queued(mut result: Value, queued: bool) -> Value { + if queued && let Some(o) = result.as_object_mut() { + o.insert("queued".into(), Value::Bool(true)); + } + result +} + /// A command's name as people see it (its label), for the status bar. pub fn command_label(id: &str) -> &str { solidcraft_engine::find_command(id).map_or(id, |c| c.label) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8a99c08ba47..fd7685d391a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -134,7 +134,7 @@ MCP server sends its folders this way on every request ([mcp.md](mcp.md)). Witho |---|---|---| | `engine.execute` | `command`: command id, `params`: JSON object | the command's result | | `engine.script` | `commands`: `[{command, params}, …]` | results, stops at the first error | -| `engine.batch` | `commands`: `[{command, params}, …]` (at most 10 000), `rollback?`: bool (default true), `timings?`, `profile?`, `coalesce_parameters?`: bool (default false) | `{completed, results, undone}`, plus `failed: {index, command, error}` when a step fails, and with `timings` `timings: [{index, command, ms}]` (the failing step included) and `total_ms`; `profile` adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`. Runs the steps in one request, so within one frame, each as `engine.execute` runs it. The first failure stops the batch, and with `rollback` the design goes back to how it was before it (`undone`: the steps taken back, `rolled_back`: whether the design is back as it was, `false` only when the checkpoint could not restore it). Refused before anything runs, with an error starting `engine.batch unavailable`, while the agent cursor is shown or when a step loads a file (`doc.open`, `file.insert_step`, `file.insert_mesh`). Send such steps one by one. A step the batch would certainly refuse at its turn is found before the first step runs (#5853): a step without a command, an unknown command id (with the closest ids) or, with strict parameter checking, a call that breaks its command's contract. The reply is then that step's failure with `completed: 0`, `undone: 0`, `not_run` listing every step and a `note`; nothing has run. With `coalesce_parameters`, each run of consecutive plain parameter edits (`parameters.change` with only a name and an expression, or with `changes`) is set as one `parameters.change {changes}`, so the design rebuilds once for the run. Every step still gets its own result (with `coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits: an edit that would be refused on its own, but not once the run's later edits are in, goes through. A run whose combined edit is refused (a new parameter, a bad expression) runs step by step, so the refused step is named. Answered when done, for up to 3600 s | +| `engine.batch` | `commands`: `[{command, params}, …]` (at most 10 000), `rollback?`: bool (default true), `timings?`, `profile?`, `coalesce_parameters?`: bool (default false) | `{completed, results, undone}`, plus `failed: {index, command, error}` when a step fails, and with `timings` `timings: [{index, command, ms}]` (the failing step included) and `total_ms`; `profile` adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`. Runs the steps in one request, so within one frame, each as `engine.execute` runs it. The first failure stops the batch, and with `rollback` the design goes back to how it was before it (`undone`: the steps taken back, `rolled_back`: whether the design is back as it was, `false` only when the checkpoint could not restore it). Refused before anything runs, with an error starting `engine.batch unavailable`, while the agent cursor is shown, when a step loads a file (`doc.open`, `file.insert_step`, `file.insert_mesh`) or when it goes to another design's tab (`component.edit_in_place`, `component.finish_edit`, which `engine.script` refuses too). Send such steps one by one. A step the batch would certainly refuse at its turn is found before the first step runs (#5853): a step without a command, an unknown command id (with the closest ids) or, with strict parameter checking, a call that breaks its command's contract. The reply is then that step's failure with `completed: 0`, `undone: 0`, `not_run` listing every step and a `note`; nothing has run. With `coalesce_parameters`, each run of consecutive plain parameter edits (`parameters.change` with only a name and an expression, or with `changes`) is set as one `parameters.change {changes}`, so the design rebuilds once for the run. Every step still gets its own result (with `coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits: an edit that would be refused on its own, but not once the run's later edits are in, goes through. A run whose combined edit is refused (a new parameter, a bad expression) runs step by step, so the refused step is named. Answered when done, for up to 3600 s | | `engine.commands` | — | every command: id, label, tab, panel, icon, shortcut, params doc, enabled | | `document.revision` | — | `{document_id, revision}`: the active design's id and a number that moves whenever the design changes, for programs that follow it ([Following the design](#following-the-design)) | | `control.subscribe` | — | `{document_id, revision}`, as `document.revision`; the connection is then sent a `design.changed` line whenever they change ([Following the design](#following-the-design)) | diff --git a/docs/mcp.md b/docs/mcp.md index d7e50c2c30a..0a273ffb466 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -261,7 +261,7 @@ The `skill_reference` tool returns these documents from the copies built into So | `list_commands` | `filter?` | The command catalog: id, label, tab/panel, shortcut, parameter docs, enabled now. `filter` matches id, label, tab and panel. | | `describe_command` | `id` | One command's parameter docs (`params`) and, for commands with a typed contract (every new command, and more of the older ones as they are converted), the JSON Schemas (2020-12) of its parameters (`input`) and of a successful result (`output`); `null` for the others. The same as `execute` `engine.describe {command}`. | | `execute` | `command`, `params?`, `verbose?` (default true) | Run any command with JSON parameters (`list_commands` shows them). Failures leave the design unchanged. A feature command replies with the feature (`feature`, `name`), every body (`bodies`) and the bodies it created, changed and removed (`created_bodies`, `changed_bodies`, `removed_bodies`). `verbose: false` uses the same compact reply as `batch`. | -| `batch` | `commands: [{command, params}]`, `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?`, `coalesce_parameters?` (default false) | Run steps in order, stop at the first error and undo the completed steps. The reply names the failing step (`failed.index`, `failed.command`, `failed.error`), every result before it, `rolled_back` (true only when the design really went back to where the batch started), `undone`, `applied` (the indices of the steps whose changes are in the design) and `not_run` (the steps never sent). A step may name a tool instead of a command, with that tool's arguments as `params`: `set_parameter` (runs `parameters.change`; `value` or `expression`), `list_commands` (`engine.commands`, filtered by `filter` as the tool filters it), `describe_command` (`engine.describe`), `execute` (`{command, params}`), `measure`, `inspect_design` (`document.inspect`: each sketch as its counts, not its full contents, and no joints), `undo`, `redo`, `export`, `save`, `open`, `new_design` and `crash_reports`. `screenshot`, `body_topology` (use `model.edges` and `model.faces`), `batch`, `pending`, `running` and `skill_reference` can't be steps: such a batch fails before anything is sent. So does a step the batch would certainly refuse at its turn (#5853): a step without a command, an unknown command id (the error names the closest ids) or, with `--param-check strict`, parameters that break a command's contract. A headless session checks this itself; an app checks it against its own commands when it gets the batch. `verbose: false` keeps the reply small in large designs: feature steps leave out the full body list (`created_bodies`, `changed_bodies`, `removed_bodies` stay) and sketch steps the ids they repeat outside `created`. Bridged to an app that has `engine.batch`, the whole batch is one control request (one frame of the app). Older apps, and apps showing the agent cursor, get the steps one by one. `timings: true` adds `timings: [{index, command, ms}]` for every step run, the failing one included, and `total_ms`. `profile: true` also adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`, its time in kernel booleans, in tessellation and the rest. Steps are timed where they run: in the app when bridged. An app without `engine.batch` is timed step by step, without `profile`. `coalesce_parameters: true` sets each run of consecutive plain parameter edits (`parameters.change` or `set_parameter` with a name and a value, or `changes`) together, so the design rebuilds once per run instead of once per edit. Steps between runs see the design up to date. Each step keeps its own result (`coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits, so an edit refused on its own can go through with the run's later ones. A refused run goes step by step, naming the refused step. | +| `batch` | `commands: [{command, params}]`, `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?`, `coalesce_parameters?` (default false) | Run steps in order, stop at the first error and undo the completed steps. The reply names the failing step (`failed.index`, `failed.command`, `failed.error`), every result before it, `rolled_back` (true only when the design really went back to where the batch started), `undone`, `applied` (the indices of the steps whose changes are in the design) and `not_run` (the steps never sent). A step may name a tool instead of a command, with that tool's arguments as `params`: `set_parameter` (runs `parameters.change`; `value` or `expression`), `list_commands` (`engine.commands`, filtered by `filter` as the tool filters it), `describe_command` (`engine.describe`), `execute` (`{command, params}`), `measure`, `inspect_design` (`document.inspect`: each sketch as its counts, not its full contents, and no joints), `undo`, `redo`, `export`, `save`, `open`, `new_design` and `crash_reports`. `screenshot`, `body_topology` (use `model.edges` and `model.faces`), `batch`, `pending`, `running` and `skill_reference` can't be steps, nor can `component.edit_in_place` and `component.finish_edit`, which go to another design's tab (send them with `execute`): such a batch fails before anything is sent. So does a step the batch would certainly refuse at its turn (#5853): a step without a command, an unknown command id (the error names the closest ids) or, with `--param-check strict`, parameters that break a command's contract. A headless session checks this itself; an app checks it against its own commands when it gets the batch. `verbose: false` keeps the reply small in large designs: feature steps leave out the full body list (`created_bodies`, `changed_bodies`, `removed_bodies` stay) and sketch steps the ids they repeat outside `created`. Bridged to an app that has `engine.batch`, the whole batch is one control request (one frame of the app). Older apps, and apps showing the agent cursor, get the steps one by one. `timings: true` adds `timings: [{index, command, ms}]` for every step run, the failing one included, and `total_ms`. `profile: true` also adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`, its time in kernel booleans, in tessellation and the rest. Steps are timed where they run: in the app when bridged. An app without `engine.batch` is timed step by step, without `profile`. `coalesce_parameters: true` sets each run of consecutive plain parameter edits (`parameters.change` or `set_parameter` with a name and a value, or `changes`) together, so the design rebuilds once per run instead of once per edit. Steps between runs see the design up to date. Each step keeps its own result (`coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits, so an edit refused on its own can go through with the run's later ones. A refused run goes step by step, naming the refused step. | | `inspect_design` | `measure?` (default true), `sketches?` (default true), `joints?` (default true) | Design properties (`metadata`: project, author… and other tools' keys; set them with `execute` `document.metadata.set`), parameters, timeline (type, suppressed, rolled back, error, warning, timing), bodies (volume, area, centre of mass, bbox, face/edge/vertex counts, visible; `removed_later: true` while a sketch is being edited on a rolled-back timeline and a later feature deletes the body, which is then not shown), sketches (curves, points, constraints, profiles, DOF, solve status, visible), joints when the design has any (as `joint.inspect` gives them: each origin's occurrence, component and path, the snap as saved, the feature, face, edge or sketch curve (`sketch: {id, name, curve}`) its persistent names refer to, `resolves` and the `error` when it is lost; kind, offset, angle, flip, values, limits, expressions, motion links; `execute` `joint.inspect {joint}` gives one joint), selection, undo depth. Hide helper sketches, bodies or construction planes with `execute` `browser.visibility` (`{items, visible}` or `{folder, visible}`), and joint glyphs with `{joints: [id or name], visible}` or `{folder: "joints", visible}` (a hidden joint still constrains and drives; `joint.list` reports each joint's `visible`). | | `measure` | `body?` or `items?` | Area (mm²), bbox, topology counts and `closed` per body. Volume (mm³), volume centre of mass, density and mass are reported only for closed, consistently oriented bodies (null or omitted for open surfaces). Volume/mass totals skip open bodies; `total.open_bodies_skipped` gives their count. Area and topology totals include all bodies. With `items` (one or two selections as `execute` takes them: `face`, `edge`, `vertex`, `sketch_curve`, `profile`), the picked geometry instead: faces and edges need only `type`, `body` and `point`; `index` is optional. See below. | | `body_topology` | `body` | Edges (index, midpoint, length, ends) and faces (index, name, area, centroid, normal, `point`, and for a cylindrical face its `cylinder`: `origin`, `axis`, `radius`). An edge midpoint is the `[x,y,z]` that picks that edge for fillet and chamfer. A face's `point` lies on it and picks it (its centroid may not: that of a face with a hole is in the hole); a face's `name` picks it for the commands that take faces (`face.delete`, `solid.shell`, `solid.draft`, `solid.offset_face`, `solid.split_face`, `solid.replace_face`, and `face` of `sheet.convert`). | From 844c6d9950e127a594fc850cb15d3babc755a5e5 Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Tue, 27 Oct 2026 19:11:42 +0100 Subject: [PATCH 19/20] Edit in place: fixes from the third full review The MCP batch tool refuses the two commands however a step names them, an execute step too A queued Edit in Place is checked fully when asked for, a second one is refused, and both queued requests wait for what runs in the design instead of being dropped Disconnecting the agent forgets what it queued, as stopping it does Co-Authored-By: Claude Opus 5.5 --- assets/locales/pending/edit-in-place.json | 8 ++++++ crates/mcp/src/tests.rs | 9 ++++-- crates/mcp/src/tools.rs | 18 ++++++++---- crates/ui-egui/src/agent_chat/mod.rs | 1 + crates/ui-egui/src/edit_in_place.rs | 34 ++++++++++++++++------- crates/ui-egui/src/edit_in_place_tests.rs | 32 +++++++++++++++++++++ docs/mcp.md | 2 +- 7 files changed, 85 insertions(+), 19 deletions(-) diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json index 8f7db407ca9..47d488f23b6 100644 --- a/assets/locales/pending/edit-in-place.json +++ b/assets/locales/pending/edit-in-place.json @@ -5,6 +5,7 @@ "ui.edit_in_place": "Edit in Place", "ui.edit_in_place_after_turn": "The edit finishes when the agent's turn ends", "ui.edit_in_place_agent_busy": "The agent is still working in this design; try again once its turn is done", + "ui.edit_in_place_already_queued": "An edit already waits for the end of the agent's turn", "ui.edit_in_place_assembly_closed": "{name} is no longer open", "ui.edit_in_place_banner": "Editing in {name}", "ui.edit_in_place_busy": "Finish or cancel what is open first", @@ -28,6 +29,7 @@ "ui.edit_in_place": "تحرير في المكان", "ui.edit_in_place_after_turn": "ينتهي التحرير عند انتهاء دور الوكيل", "ui.edit_in_place_agent_busy": "لا يزال الوكيل يعمل في هذا التصميم؛ حاول مرة أخرى بعد انتهاء دوره", + "ui.edit_in_place_already_queued": "هناك تحرير ينتظر بالفعل انتهاء دور الوكيل", "ui.edit_in_place_assembly_closed": "{name} لم يعد مفتوحًا", "ui.edit_in_place_banner": "تحرير داخل {name}", "ui.edit_in_place_busy": "أنهِ ما هو مفتوح أو ألغِه أولاً", @@ -51,6 +53,7 @@ "ui.edit_in_place": "An Ort und Stelle bearbeiten", "ui.edit_in_place_after_turn": "Die Bearbeitung endet, sobald der Agent seine Antwort beendet hat", "ui.edit_in_place_agent_busy": "Der Agent arbeitet noch in diesem Design; erneut versuchen, sobald er seine Antwort beendet hat", + "ui.edit_in_place_already_queued": "Eine Bearbeitung wartet bereits auf das Ende der Antwort des Agenten", "ui.edit_in_place_assembly_closed": "{name} ist nicht mehr geöffnet", "ui.edit_in_place_banner": "Bearbeitung in {name}", "ui.edit_in_place_busy": "Zuerst abschließen oder abbrechen, was offen ist", @@ -74,6 +77,7 @@ "ui.edit_in_place": "עריכה במקום", "ui.edit_in_place_after_turn": "העריכה תסתיים כשתור הסוכן יסתיים", "ui.edit_in_place_agent_busy": "הסוכן עדיין עובד בתכן הזה; יש לנסות שוב כשתורו יסתיים", + "ui.edit_in_place_already_queued": "עריכה כבר ממתינה לסיום תור הסוכן", "ui.edit_in_place_assembly_closed": "{name} כבר אינו פתוח", "ui.edit_in_place_banner": "עריכה בתוך {name}", "ui.edit_in_place_busy": "יש לסיים או לבטל קודם את מה שפתוח", @@ -97,6 +101,7 @@ "ui.edit_in_place": "その場で編集", "ui.edit_in_place_after_turn": "エージェントのターンが終わると編集を終了します", "ui.edit_in_place_agent_busy": "エージェントがまだこのデザインで作業中です。そのターンが終わってから再度お試しください", + "ui.edit_in_place_already_queued": "エージェントのターンの終了を待っている編集がすでにあります", "ui.edit_in_place_assembly_closed": "{name} はもう開いていません", "ui.edit_in_place_banner": "{name} 内で編集中", "ui.edit_in_place_busy": "先に開いているものを終了またはキャンセルしてください", @@ -120,6 +125,7 @@ "ui.edit_in_place": "제자리에서 편집", "ui.edit_in_place_after_turn": "에이전트의 차례가 끝나면 편집이 완료됩니다", "ui.edit_in_place_agent_busy": "에이전트가 아직 이 디자인에서 작업 중입니다. 차례가 끝난 후 다시 시도하세요", + "ui.edit_in_place_already_queued": "에이전트의 차례가 끝나기를 기다리는 편집이 이미 있습니다", "ui.edit_in_place_assembly_closed": "{name}이(가) 더 이상 열려 있지 않습니다", "ui.edit_in_place_banner": "{name}에서 편집 중", "ui.edit_in_place_busy": "먼저 열려 있는 작업을 완료하거나 취소하세요", @@ -143,6 +149,7 @@ "ui.edit_in_place": "Chỉnh sửa tại chỗ", "ui.edit_in_place_after_turn": "Việc chỉnh sửa sẽ hoàn tất khi lượt của tác tử kết thúc", "ui.edit_in_place_agent_busy": "Tác tử vẫn đang làm việc trong thiết kế này; hãy thử lại khi lượt của nó kết thúc", + "ui.edit_in_place_already_queued": "Đã có một thao tác chỉnh sửa đang chờ lượt của tác tử kết thúc", "ui.edit_in_place_assembly_closed": "{name} không còn mở", "ui.edit_in_place_banner": "Đang chỉnh sửa trong {name}", "ui.edit_in_place_busy": "Hãy hoàn tất hoặc hủy những gì đang mở trước", @@ -166,6 +173,7 @@ "ui.edit_in_place": "原位编辑", "ui.edit_in_place_after_turn": "代理本轮结束后将完成编辑", "ui.edit_in_place_agent_busy": "代理仍在此设计中工作;请在其本轮结束后重试", + "ui.edit_in_place_already_queued": "已有编辑在等待代理本轮结束", "ui.edit_in_place_assembly_closed": "{name} 已不再打开", "ui.edit_in_place_banner": "正在 {name} 中编辑", "ui.edit_in_place_busy": "请先完成或取消打开的操作", diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 3959de54d2e..2ce6fef67b8 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -2141,8 +2141,13 @@ fn batch_steps_may_name_tools() { let (_, body, _) = recorded_batch(Ok(json!({})), json!({"commands": [{"command": "body_topology", "params": {"body": "Body1"}}]})); assert!(body["failed"]["error"].as_str().is_some_and(|e| e.contains("model.edges") && e.contains("model.faces")), "{body}"); // Editing in place goes to another design's tab: never a step, not even one by one - for command in ["component.edit_in_place", "Component.Finish_Edit"] { - let (b, body, is_error) = recorded_batch(Ok(json!({})), json!({"commands": [{"command": "solid.box"}, {"command": command}]})); + for step in [ + json!({"command": "component.edit_in_place"}), + json!({"command": "Component.Finish_Edit"}), + json!({"command": "execute", "params": {"command": "component.finish_edit"}}), + ] { + let command = step.to_string(); + let (b, body, is_error) = recorded_batch(Ok(json!({})), json!({"commands": [{"command": "solid.box"}, step]})); assert!(is_error && b.calls.is_empty(), "{command}: {body}"); assert!(body["failed"]["error"].as_str().is_some_and(|e| e.contains("on its own")), "{body}"); } diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 87c3dd3a061..c5ede837091 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -644,11 +644,6 @@ fn batch_step(step: &Value) -> Result<(String, Value, Option), String> { "screenshot" => Err("`screenshot` is a tool, not a command: call it after the batch".into()), "batch" => Err("batches don't nest: put the steps in this batch".into()), "pending" => Err("`pending` is a tool, not a command: call it on its own".into()), - // The window switches to another design's tab for these: the batch's later steps and its - // rollback would land in the wrong design. - c if solidcraft_engine::find_command(c).is_some_and(|spec| matches!(spec.id, "component.edit_in_place" | "component.finish_edit")) => { - Err(format!("`{c}` goes to another design's tab: send it on its own with execute")) - } "running" => Err("`running` is a tool, not a command: call it on its own".into()), "skill_reference" => Err("`skill_reference` is a tool, not a command: call it on its own".into()), // An engine command: the step goes as it is. @@ -767,7 +762,18 @@ fn batch(b: &mut dyn Backend, a: &Map) -> Value { let mut mapped: Vec = Vec::with_capacity(steps.len()); let mut filters: Vec<(usize, String)> = Vec::new(); for (i, step) in steps.iter().enumerate() { - match batch_step(step) { + // The window goes to another design's tab for these, however the step names them: the + // batch's later steps and its rollback would land in the wrong design. + let step_result = batch_step(step).and_then(|(command, params, filter)| { + let id = if command.is_empty() { step.get("command").or_else(|| step.get("id")).and_then(Value::as_str).unwrap_or("") } else { &command }; + match solidcraft_engine::find_command(id).map(|spec| spec.id) { + Some(c @ ("component.edit_in_place" | "component.finish_edit")) => { + Err(format!("`{c}` goes to another design's tab: send it on its own, not in a batch")) + } + _ => Ok((command, params, filter)), + } + }); + match step_result { Ok((command, _, _)) if command.is_empty() => mapped.push(step.clone()), Ok((command, params, filter)) => { if let Some(f) = filter { diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index 23ce6d7c175..2fd57e3ea18 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -980,6 +980,7 @@ fn connect_at_start(app: &mut SolveApp, ctx: &egui::Context) { /// Stop the agent (and everything it started); the conversation stays. pub fn disconnect(app: &mut SolveApp) { + crate::edit_in_place::forget_after_turn(app); app.agent_chat.disconnect_document(&mut app.session, false); } diff --git a/crates/ui-egui/src/edit_in_place.rs b/crates/ui-egui/src/edit_in_place.rs index c52e1445046..ba1a586fca2 100644 --- a/crates/ui-egui/src/edit_in_place.rs +++ b/crates/ui-egui/src/edit_in_place.rs @@ -209,9 +209,12 @@ pub(crate) fn command_ran(app: &mut SolveApp, result: &Value) -> Result Result<(), String> { /// Open the design the linked component `component` comes from, with the assembly around it as /// its placement `path` (default: its first) puts it (`ask`: with the open's questions). fn enter(app: &mut SolveApp, component: u64, path: Option>, ask: bool) -> Result<(), String> { + let (context, link) = prepare(app, component, path, ask)?; + app.edit_in_place.pending = Some(context); + crate::network_prompt::open_linked(app, &link); + Ok(()) +} + +/// The edit [`enter`] would start, and the link it opens, or why it can't: everything is checked +/// and nothing changes. +fn prepare(app: &mut SolveApp, component: u64, path: Option>, ask: bool) -> Result<(PartContext, Value), String> { check_enter(app)?; let Some(assembly) = app.session.path.clone() else { return Err(crate::i18n::tr("ui.edit_in_place_save_first").to_string()); @@ -266,7 +278,7 @@ fn enter(app: &mut SolveApp, component: u64, path: Option>, ask: bool) return Err(app.tr_label("ui.relink_not_linked").to_string()); }; let opened = crate::documents::session_at(app, &part).is_none(); - app.edit_in_place.pending = Some(PartContext { + let context = PartContext { assembly, assembly_name: app.session.doc.name.clone(), part, @@ -276,9 +288,8 @@ fn enter(app: &mut SolveApp, component: u64, path: Option>, ask: bool) triangles: Arc::new(triangles), bounds, opened, - }); - crate::network_prompt::open_linked(app, &link); - Ok(()) + }; + Ok((context, link)) } /// The design shown has become the part an edit waits for: the edit starts there. An edit whose @@ -503,8 +514,10 @@ pub(crate) fn tick(app: &mut SolveApp) { } } // The agent's turn ended: the finish it asked for goes on, as the command would have, in the - // part's own tab (shown elsewhere, or edited differently since, it is dropped). - if app.agent_chat.state() != crate::agent_chat::State::Busy + // part's own tab (shown elsewhere, or edited differently since, it is dropped). What runs in + // the design meanwhile (an undo, a file being written) is waited for, not a reason to drop it. + let after_turn = app.agent_chat.state() != crate::agent_chat::State::Busy && !busy(app); + if after_turn && let Some(part) = app.edit_in_place.finish_after_turn.take() && app.edit_in_place.active.as_ref().is_some_and(|c| crate::documents::same_path(&c.part, &part)) && let Err(why) = finish_with(app, false) @@ -512,7 +525,8 @@ pub(crate) fn tick(app: &mut SolveApp) { app.set_status(why, true); } // Likewise the edit the assembly's agent asked for, from the assembly's tab. - if app.agent_chat.state() != crate::agent_chat::State::Busy + if after_turn + && !busy(app) && let Some((assembly, component, path)) = app.edit_in_place.enter_after_turn.take() && app.session.path.as_deref().is_some_and(|p| crate::documents::same_path(p, &assembly)) && let Err(why) = enter(app, component, path, false) diff --git a/crates/ui-egui/src/edit_in_place_tests.rs b/crates/ui-egui/src/edit_in_place_tests.rs index 177383e7cad..305cbc68a91 100644 --- a/crates/ui-egui/src/edit_in_place_tests.rs +++ b/crates/ui-egui/src/edit_in_place_tests.rs @@ -747,6 +747,38 @@ fn the_assemblys_agent_opens_the_part_once_its_turn_ends() { assert!(showing(&f.app, &f.plate_file) && f.app.edit_in_place.active.is_some()); } +#[test] +fn a_queued_edit_is_checked_when_asked_for_and_waits_for_what_runs() { + let mut f = assembly("queued-checks"); + f.app.agent_chat.set_state(crate::agent_chat::State::Busy); + // What would fail at the turn's end fails now, where the agent sees it + let gone = f.folder.join("post.solidcraft"); + std::fs::rename(&gone, f.folder.join("moved.solidcraft")).unwrap(); + let post = f.app.session.doc.links.keys().copied().find(|c| *c != f.plate).unwrap(); + assert!(f.app.run("component.edit_in_place", json!({"component": post})).is_err()); + assert_eq!(f.app.run("component.edit_in_place", json!({"component": f.plate})).unwrap()["queued"], json!(true)); + let e = f.app.run("component.edit_in_place", json!({"component": f.plate})).unwrap_err(); + assert!(e.contains("already"), "one at a time: {e}"); + // The turn ends while a command still waits in the design: the edit waits too + f.app.agent_chat.set_state(crate::agent_chat::State::Ready); + f.app.deferred_queue.push(("view.fit".into(), json!({}))); + tick(&mut f.app); + assert!(f.app.edit_in_place.enter_after_turn.is_some() && f.app.docs.count() == 1); + f.app.deferred_queue.clear(); + settle(&mut f.app); + assert!(showing(&f.app, &f.plate_file)); +} + +#[test] +fn disconnecting_the_agent_forgets_what_it_queued() { + let mut f = assembly("disconnected"); + f.app.agent_chat.set_state(crate::agent_chat::State::Busy); + assert_eq!(f.app.run("component.edit_in_place", json!({"component": f.plate})).unwrap()["queued"], json!(true)); + crate::agent_chat::disconnect(&mut f.app); + settle(&mut f.app); + assert_eq!(f.app.docs.count(), 1); +} + #[test] fn stopping_the_agent_forgets_what_it_queued() { let mut f = assembly("stopped"); diff --git a/docs/mcp.md b/docs/mcp.md index 0a273ffb466..22e2711bd9e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -261,7 +261,7 @@ The `skill_reference` tool returns these documents from the copies built into So | `list_commands` | `filter?` | The command catalog: id, label, tab/panel, shortcut, parameter docs, enabled now. `filter` matches id, label, tab and panel. | | `describe_command` | `id` | One command's parameter docs (`params`) and, for commands with a typed contract (every new command, and more of the older ones as they are converted), the JSON Schemas (2020-12) of its parameters (`input`) and of a successful result (`output`); `null` for the others. The same as `execute` `engine.describe {command}`. | | `execute` | `command`, `params?`, `verbose?` (default true) | Run any command with JSON parameters (`list_commands` shows them). Failures leave the design unchanged. A feature command replies with the feature (`feature`, `name`), every body (`bodies`) and the bodies it created, changed and removed (`created_bodies`, `changed_bodies`, `removed_bodies`). `verbose: false` uses the same compact reply as `batch`. | -| `batch` | `commands: [{command, params}]`, `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?`, `coalesce_parameters?` (default false) | Run steps in order, stop at the first error and undo the completed steps. The reply names the failing step (`failed.index`, `failed.command`, `failed.error`), every result before it, `rolled_back` (true only when the design really went back to where the batch started), `undone`, `applied` (the indices of the steps whose changes are in the design) and `not_run` (the steps never sent). A step may name a tool instead of a command, with that tool's arguments as `params`: `set_parameter` (runs `parameters.change`; `value` or `expression`), `list_commands` (`engine.commands`, filtered by `filter` as the tool filters it), `describe_command` (`engine.describe`), `execute` (`{command, params}`), `measure`, `inspect_design` (`document.inspect`: each sketch as its counts, not its full contents, and no joints), `undo`, `redo`, `export`, `save`, `open`, `new_design` and `crash_reports`. `screenshot`, `body_topology` (use `model.edges` and `model.faces`), `batch`, `pending`, `running` and `skill_reference` can't be steps, nor can `component.edit_in_place` and `component.finish_edit`, which go to another design's tab (send them with `execute`): such a batch fails before anything is sent. So does a step the batch would certainly refuse at its turn (#5853): a step without a command, an unknown command id (the error names the closest ids) or, with `--param-check strict`, parameters that break a command's contract. A headless session checks this itself; an app checks it against its own commands when it gets the batch. `verbose: false` keeps the reply small in large designs: feature steps leave out the full body list (`created_bodies`, `changed_bodies`, `removed_bodies` stay) and sketch steps the ids they repeat outside `created`. Bridged to an app that has `engine.batch`, the whole batch is one control request (one frame of the app). Older apps, and apps showing the agent cursor, get the steps one by one. `timings: true` adds `timings: [{index, command, ms}]` for every step run, the failing one included, and `total_ms`. `profile: true` also adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`, its time in kernel booleans, in tessellation and the rest. Steps are timed where they run: in the app when bridged. An app without `engine.batch` is timed step by step, without `profile`. `coalesce_parameters: true` sets each run of consecutive plain parameter edits (`parameters.change` or `set_parameter` with a name and a value, or `changes`) together, so the design rebuilds once per run instead of once per edit. Steps between runs see the design up to date. Each step keeps its own result (`coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits, so an edit refused on its own can go through with the run's later ones. A refused run goes step by step, naming the refused step. | +| `batch` | `commands: [{command, params}]`, `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?`, `coalesce_parameters?` (default false) | Run steps in order, stop at the first error and undo the completed steps. The reply names the failing step (`failed.index`, `failed.command`, `failed.error`), every result before it, `rolled_back` (true only when the design really went back to where the batch started), `undone`, `applied` (the indices of the steps whose changes are in the design) and `not_run` (the steps never sent). A step may name a tool instead of a command, with that tool's arguments as `params`: `set_parameter` (runs `parameters.change`; `value` or `expression`), `list_commands` (`engine.commands`, filtered by `filter` as the tool filters it), `describe_command` (`engine.describe`), `execute` (`{command, params}`), `measure`, `inspect_design` (`document.inspect`: each sketch as its counts, not its full contents, and no joints), `undo`, `redo`, `export`, `save`, `open`, `new_design` and `crash_reports`. `screenshot`, `body_topology` (use `model.edges` and `model.faces`), `batch`, `pending`, `running` and `skill_reference` can't be steps, nor can `component.edit_in_place` and `component.finish_edit`, however a step names them, as they go to another design's tab (send them with the `execute` tool on their own): such a batch fails before anything is sent. So does a step the batch would certainly refuse at its turn (#5853): a step without a command, an unknown command id (the error names the closest ids) or, with `--param-check strict`, parameters that break a command's contract. A headless session checks this itself; an app checks it against its own commands when it gets the batch. `verbose: false` keeps the reply small in large designs: feature steps leave out the full body list (`created_bodies`, `changed_bodies`, `removed_bodies` stay) and sketch steps the ids they repeat outside `created`. Bridged to an app that has `engine.batch`, the whole batch is one control request (one frame of the app). Older apps, and apps showing the agent cursor, get the steps one by one. `timings: true` adds `timings: [{index, command, ms}]` for every step run, the failing one included, and `total_ms`. `profile: true` also adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`, its time in kernel booleans, in tessellation and the rest. Steps are timed where they run: in the app when bridged. An app without `engine.batch` is timed step by step, without `profile`. `coalesce_parameters: true` sets each run of consecutive plain parameter edits (`parameters.change` or `set_parameter` with a name and a value, or `changes`) together, so the design rebuilds once per run instead of once per edit. Steps between runs see the design up to date. Each step keeps its own result (`coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits, so an edit refused on its own can go through with the run's later ones. A refused run goes step by step, naming the refused step. | | `inspect_design` | `measure?` (default true), `sketches?` (default true), `joints?` (default true) | Design properties (`metadata`: project, author… and other tools' keys; set them with `execute` `document.metadata.set`), parameters, timeline (type, suppressed, rolled back, error, warning, timing), bodies (volume, area, centre of mass, bbox, face/edge/vertex counts, visible; `removed_later: true` while a sketch is being edited on a rolled-back timeline and a later feature deletes the body, which is then not shown), sketches (curves, points, constraints, profiles, DOF, solve status, visible), joints when the design has any (as `joint.inspect` gives them: each origin's occurrence, component and path, the snap as saved, the feature, face, edge or sketch curve (`sketch: {id, name, curve}`) its persistent names refer to, `resolves` and the `error` when it is lost; kind, offset, angle, flip, values, limits, expressions, motion links; `execute` `joint.inspect {joint}` gives one joint), selection, undo depth. Hide helper sketches, bodies or construction planes with `execute` `browser.visibility` (`{items, visible}` or `{folder, visible}`), and joint glyphs with `{joints: [id or name], visible}` or `{folder: "joints", visible}` (a hidden joint still constrains and drives; `joint.list` reports each joint's `visible`). | | `measure` | `body?` or `items?` | Area (mm²), bbox, topology counts and `closed` per body. Volume (mm³), volume centre of mass, density and mass are reported only for closed, consistently oriented bodies (null or omitted for open surfaces). Volume/mass totals skip open bodies; `total.open_bodies_skipped` gives their count. Area and topology totals include all bodies. With `items` (one or two selections as `execute` takes them: `face`, `edge`, `vertex`, `sketch_curve`, `profile`), the picked geometry instead: faces and edges need only `type`, `body` and `point`; `index` is optional. See below. | | `body_topology` | `body` | Edges (index, midpoint, length, ends) and faces (index, name, area, centroid, normal, `point`, and for a cylindrical face its `cylinder`: `origin`, `axis`, `radius`). An edge midpoint is the `[x,y,z]` that picks that edge for fillet and chamfer. A face's `point` lies on it and picks it (its centroid may not: that of a face with a hole is in the hole); a face's `name` picks it for the commands that take faces (`face.delete`, `solid.shell`, `solid.draft`, `solid.offset_face`, `solid.split_face`, `solid.replace_face`, and `face` of `sheet.convert`). | From b8f7e9e7d7044ccf93f87273c4b9233cf8973e8c Mon Sep 17 00:00:00 2001 From: Christian Hammacher Date: Wed, 28 Oct 2026 12:18:04 +0100 Subject: [PATCH 20/20] Edit in place: help text for the Finish Edit button main now requires help for every toolbar command (#7134), and Finish Edit is one. Written in every language the branch's catalog carries. Co-Authored-By: Claude Opus 5.5 --- assets/locales/pending/edit-in-place.json | 24 +++++++++++++++-------- crates/ui-egui/src/command_help.rs | 1 + 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json index 47d488f23b6..ba58264455c 100644 --- a/assets/locales/pending/edit-in-place.json +++ b/assets/locales/pending/edit-in-place.json @@ -21,7 +21,8 @@ "ui.edit_in_place_saved_elsewhere": "The part was saved to another file; the assembly still links {name}", "ui.edit_in_place_wait": "Wait until what is running in the design is done", "cmd.component_edit_in_place": "Edit in Place", - "cmd.component_finish_edit": "Finish Edit" + "cmd.component_finish_edit": "Finish Edit", + "help.component.finish_edit": "Saves the part you are editing in place, returns to its assembly and updates the assembly from it. Use it when your changes to the linked part are done." }, "ar": { "settings.double_click_components": "انقر نقرًا مزدوجًا على مكوّن لتنشيطه، أو لتحرير مكوّن مرتبط في مكانه", @@ -45,7 +46,8 @@ "ui.edit_in_place_saved_elsewhere": "حُفظ الجزء في ملف آخر؛ ما زال التجميع مرتبطًا بـ {name}", "ui.edit_in_place_wait": "انتظر حتى ينتهي ما يجري في التصميم", "cmd.component_edit_in_place": "تحرير في المكان", - "cmd.component_finish_edit": "إنهاء التحرير" + "cmd.component_finish_edit": "إنهاء التحرير", + "help.component.finish_edit": "يحفظ الجزء الذي تحرّره في مكانه، ويعود إلى تجميعه ويحدّث التجميع منه. استخدمه عند الانتهاء من تغييراتك على الجزء المرتبط." }, "de": { "settings.double_click_components": "Doppelklick auf eine Komponente aktiviert sie oder bearbeitet eine verknüpfte an Ort und Stelle", @@ -69,7 +71,8 @@ "ui.edit_in_place_saved_elsewhere": "Das Teil wurde in eine andere Datei gespeichert; die Baugruppe verknüpft weiterhin {name}", "ui.edit_in_place_wait": "Warten, bis abgeschlossen ist, was im Design läuft", "cmd.component_edit_in_place": "An Ort und Stelle bearbeiten", - "cmd.component_finish_edit": "Bearbeitung beenden" + "cmd.component_finish_edit": "Bearbeitung beenden", + "help.component.finish_edit": "Speichert das an Ort und Stelle bearbeitete Teil, kehrt zu seiner Baugruppe zurück und aktualisiert die Baugruppe daraus. Verwenden Sie es, wenn Ihre Änderungen am verknüpften Teil fertig sind." }, "he": { "settings.double_click_components": "לחיצה כפולה על רכיב מפעילה אותו, או עורכת רכיב מקושר במקומו", @@ -93,7 +96,8 @@ "ui.edit_in_place_saved_elsewhere": "החלק נשמר לקובץ אחר; ההרכבה עדיין מקושרת אל {name}", "ui.edit_in_place_wait": "יש להמתין עד שמה שפועל בתכן יסתיים", "cmd.component_edit_in_place": "עריכה במקום", - "cmd.component_finish_edit": "סיום עריכה" + "cmd.component_finish_edit": "סיום עריכה", + "help.component.finish_edit": "שומר את החלק שנערך במקומו, חוזר להרכבה שלו ומעדכן ממנו את ההרכבה. יש להשתמש בו כשהשינויים בחלק המקושר הושלמו." }, "ja": { "settings.double_click_components": "コンポーネントをダブルクリックしてアクティブにする、またはリンクされたものをその場で編集する", @@ -117,7 +121,8 @@ "ui.edit_in_place_saved_elsewhere": "部品は別のファイルに保存されました。アセンブリは引き続き {name} にリンクしています", "ui.edit_in_place_wait": "デザインで実行中の処理が終わるまでお待ちください", "cmd.component_edit_in_place": "その場で編集", - "cmd.component_finish_edit": "編集を終了" + "cmd.component_finish_edit": "編集を終了", + "help.component.finish_edit": "その場で編集中の部品を保存し、アセンブリに戻って、その部品でアセンブリを更新します。リンクされた部品への変更が終わったときに使います。" }, "ko": { "settings.double_click_components": "구성 요소를 두 번 클릭하여 활성화하거나 연결된 구성 요소를 제자리에서 편집", @@ -141,7 +146,8 @@ "ui.edit_in_place_saved_elsewhere": "부품이 다른 파일에 저장되었습니다. 어셈블리는 여전히 {name}에 연결되어 있습니다", "ui.edit_in_place_wait": "디자인에서 실행 중인 작업이 끝날 때까지 기다리세요", "cmd.component_edit_in_place": "제자리에서 편집", - "cmd.component_finish_edit": "편집 완료" + "cmd.component_finish_edit": "편집 완료", + "help.component.finish_edit": "제자리에서 편집 중인 부품을 저장하고 어셈블리로 돌아가 그 부품으로 어셈블리를 업데이트합니다. 연결된 부품의 변경을 마쳤을 때 사용하세요." }, "vi": { "settings.double_click_components": "Nhấp đúp vào một thành phần để kích hoạt nó, hoặc chỉnh sửa tại chỗ một thành phần liên kết", @@ -165,7 +171,8 @@ "ui.edit_in_place_saved_elsewhere": "Chi tiết đã được lưu vào tệp khác; cụm lắp ráp vẫn liên kết với {name}", "ui.edit_in_place_wait": "Hãy chờ những gì đang chạy trong thiết kế hoàn tất", "cmd.component_edit_in_place": "Chỉnh sửa tại chỗ", - "cmd.component_finish_edit": "Hoàn tất chỉnh sửa" + "cmd.component_finish_edit": "Hoàn tất chỉnh sửa", + "help.component.finish_edit": "Lưu chi tiết đang được chỉnh sửa tại chỗ, quay lại cụm lắp ráp của nó và cập nhật cụm lắp ráp từ chi tiết đó. Dùng khi bạn đã hoàn tất các thay đổi cho chi tiết liên kết." }, "zh": { "settings.double_click_components": "双击组件以激活它,或在原位编辑链接组件", @@ -189,6 +196,7 @@ "ui.edit_in_place_saved_elsewhere": "零件已保存到其他文件;装配体仍链接 {name}", "ui.edit_in_place_wait": "请等待设计中正在运行的操作完成", "cmd.component_edit_in_place": "原位编辑", - "cmd.component_finish_edit": "完成编辑" + "cmd.component_finish_edit": "完成编辑", + "help.component.finish_edit": "保存正在原位编辑的零件,返回其装配体,并用该零件更新装配体。对链接零件的更改完成后使用。" } } diff --git a/crates/ui-egui/src/command_help.rs b/crates/ui-egui/src/command_help.rs index 635f7300912..481730fb7b2 100644 --- a/crates/ui-egui/src/command_help.rs +++ b/crates/ui-egui/src/command_help.rs @@ -9,6 +9,7 @@ use crate::i18n; /// The commands that have help text. Each one needs a `help.` message in the catalogs. pub const DOCUMENTED: &[&str] = &[ "appearance.assign", + "component.finish_edit", "face.delete", "material.assign", "parameters.change",