Skip to content

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

Assemblies: edit a linked component in place, with the assembly around it (#7672) (#7819)

Christian Hammacheraae2c5e4171f
diff --git a/assets/icons/ui/design/requested_icons.txt b/assets/icons/ui/design/requested_icons.txt
index 125ac1f9ee..ed748590e5 100644
--- a/assets/icons/ui/design/requested_icons.txt
+++ b/assets/icons/ui/design/requested_icons.txt
@@ -105,6 +105,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 0000000000..60de721977
--- /dev/null
+++ b/assets/icons/ui/design/svg/model/finish_edit.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
+ <title>Finish Edit</title>
+ <path d="M50 32L14 32M25 21L14 32L25 43" fill="none" stroke="#236ead" stroke-width="5.6" stroke-linejoin="round" stroke-linecap="round"/>
+</svg>
diff --git a/assets/locales/pending/edit-in-place.json b/assets/locales/pending/edit-in-place.json
new file mode 100644
index 0000000000..ba58264455
--- /dev/null
+++ b/assets/locales/pending/edit-in-place.json
@@ -0,0 +1,202 @@
+{
+ "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_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",
+ "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 until what is running in the design is done",
+ "cmd.component_edit_in_place": "Edit in Place",
+ "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": "انقر نقرًا مزدوجًا على مكوّن لتنشيطه، أو لتحرير مكوّن مرتبط في مكانه",
+ "ui.heading_finish_editing": "إنهاء التحرير",
+ "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": "أنهِ ما هو مفتوح أو ألغِه أولاً",
+ "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": "انتظر حتى ينتهي ما يجري في التصميم",
+ "cmd.component_edit_in_place": "تحرير في المكان",
+ "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",
+ "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 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",
+ "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 abgeschlossen ist, was im Design läuft",
+ "cmd.component_edit_in_place": "An Ort und Stelle bearbeiten",
+ "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": "לחיצה כפולה על רכיב מפעילה אותו, או עורכת רכיב מקושר במקומו",
+ "ui.heading_finish_editing": "סיום עריכה",
+ "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": "יש לסיים או לבטל קודם את מה שפתוח",
+ "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": "יש להמתין עד שמה שפועל בתכן יסתיים",
+ "cmd.component_edit_in_place": "עריכה במקום",
+ "cmd.component_finish_edit": "סיום עריכה",
+ "help.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_already_queued": "エージェントのターンの終了を待っている編集がすでにあります",
+ "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": "デザインで実行中の処理が終わるまでお待ちください",
+ "cmd.component_edit_in_place": "その場で編集",
+ "cmd.component_finish_edit": "編集を終了",
+ "help.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_already_queued": "에이전트의 차례가 끝나기를 기다리는 편집이 이미 있습니다",
+ "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": "디자인에서 실행 중인 작업이 끝날 때까지 기다리세요",
+ "cmd.component_edit_in_place": "제자리에서 편집",
+ "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",
+ "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 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",
+ "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ờ 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",
+ "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": "双击组件以激活它,或在原位编辑链接组件",
+ "ui.heading_finish_editing": "完成编辑",
+ "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": "请先完成或取消打开的操作",
+ "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": "请等待设计中正在运行的操作完成",
+ "cmd.component_edit_in_place": "原位编辑",
+ "cmd.component_finish_edit": "完成编辑",
+ "help.component.finish_edit": "保存正在原位编辑的零件,返回其装配体,并用该零件更新装配体。对链接零件的更改完成后使用。"
+ }
+}
diff --git a/assets/locales/pending/update-changed-links.json b/assets/locales/pending/update-changed-links.json
new file mode 100644
index 0000000000..464c6937d6
--- /dev/null
+++ b/assets/locales/pending/update-changed-links.json
@@ -0,0 +1,30 @@
+{
+ "en": {
+ "prefs.linked_designs": "Linked designs",
+ "settings.update_changed_links": "Update changed linked designs when a tab comes back"
+ },
+ "ar": {
+ "prefs.linked_designs": "التصاميم المرتبطة",
+ "settings.update_changed_links": "تحديث التصاميم المرتبطة التي تغيّرت عند العودة إلى علامة التبويب"
+ },
+ "de": {
+ "prefs.linked_designs": "Verknüpfte Designs",
+ "settings.update_changed_links": "Geänderte verknüpfte Designs aktualisieren, wenn ein Tab wieder angezeigt wird"
+ },
+ "he": {
+ "prefs.linked_designs": "תכנים מקושרים",
+ "settings.update_changed_links": "עדכון תכנים מקושרים שהשתנו כשלשונית מוצגת שוב"
+ },
+ "ja": {
+ "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 khi quay lại một thẻ"
+ },
+ "zh": {
+ "prefs.linked_designs": "链接设计",
+ "settings.update_changed_links": "返回标签页时更新已更改的链接设计"
+ }
+}
diff --git a/attribution/pending/finish-edit-icon.md b/attribution/pending/finish-edit-icon.md
new file mode 100644
index 0000000000..636d522e03
--- /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 de89316298..3ad97fe656 100644
--- a/crates/engine/src/cmd/component.rs
+++ b/crates/engine/src/cmd/component.rs
@@ -11,8 +11,13 @@ use solidcraft_geom::Vec3;
use super::CommandSpec;
use crate::params::{bad, bool_, str_, string_list, vec3};
+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<EditInPlaceParams> = TypedContract::new();
+const FINISH_EDIT_CONTRACT: TypedContract<FinishEditParams> = TypedContract::new();
+
#[path = "component_drag.rs"]
mod drag;
#[path = "component_matrix.rs"]
@@ -43,6 +48,30 @@ 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::<EditInPlaceResult>)
+ .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, 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")
+ .noundo()
+ .doc_only()
+ .contract(&FINISH_EDIT_CONTRACT)
+ .output(output_schema_for::<FinishEditResult>)
+ .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 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 \
identity transforms; children as occurrence ids); bodies?: bool (with compact: body names, not their count)",
@@ -193,6 +222,30 @@ fn from_bodies(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
+ 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::<Vec<u64>>(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<Value> {
+ serde_json::to_value(FinishEditResult::default()).map_err(|e| crate::EngineError::Other(e.to_string()))
+}
+
fn activate(s: &mut Session, p: &Value) -> Result<Value> {
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 0000000000..8129a0fac7
--- /dev/null
+++ b/crates/engine/src/schema/component.rs
@@ -0,0 +1,65 @@
+//! Contracts and result types for the commands in `cmd/component.rs`.
+
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+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, 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 {
+ /// 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<Vec<u64>>,
+}
+
+/// 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.
+ pub path: Vec<u64>,
+ /// 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<String>,
+}
+
+/// 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 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)]
+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<String>,
+}
+
+#[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 0000000000..08ae137a86
--- /dev/null
+++ b/crates/engine/src/schema/component_tests.rs
@@ -0,0 +1,34 @@
+use std::sync::Arc;
+
+use serde_json::json;
+
+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::<EditInPlaceParams>(), &["component", "path"]);
+ assert_keys(input_schema_for::<FinishEditParams>(), &[]);
+}
+
+#[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();
+ 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 809035c312..eda6b72537 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/gpu/src/view.rs b/crates/gpu/src/view.rs
index 8cd223ee6b..6daf6550a6 100644
--- a/crates/gpu/src/view.rs
+++ b/crates/gpu/src/view.rs
@@ -3626,6 +3626,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/mcp/src/tests.rs b/crates/mcp/src/tests.rs
index 2643964a00..db89875ebb 100644
--- a/crates/mcp/src/tests.rs
+++ b/crates/mcp/src/tests.rs
@@ -2252,6 +2252,17 @@ 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 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}");
+ }
// Headless, step by step.
let mut s = server();
diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs
index 353f1bfa91..9a673b1f6c 100644
--- a/crates/mcp/src/tools.rs
+++ b/crates/mcp/src/tools.rs
@@ -765,7 +765,18 @@ fn batch(b: &mut dyn Backend, a: &Map<String, Value>) -> Value {
let mut mapped: Vec<Value> = 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 866a61a23e..2fd57e3ea1 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);
@@ -976,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);
}
@@ -1413,6 +1418,7 @@ pub(crate) fn attach_dropped(app: &mut SolveApp, paths: impl Iterator<Item = std
pub fn cancel(app: &mut SolveApp) {
app.agent_chat.steering = false;
app.agent_chat.stopped = true;
+ crate::edit_in_place::forget_after_turn(app);
interrupt(app);
}
diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs
index 899d8369e6..cde4b678b1 100644
--- a/crates/ui-egui/src/browser.rs
+++ b/crates/ui-egui/src/browser.rs
@@ -1009,6 +1009,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 {
@@ -1323,7 +1324,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::double_click_component(app, json!({ "component": id }));
}
}
if r.hovered {
@@ -1469,8 +1470,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)) {
- let _ = app.run("component.activate", 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/command_help.rs b/crates/ui-egui/src/command_help.rs
index 635f730091..481730fb7b 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.<id>` message in the catalogs.
pub const DOCUMENTED: &[&str] = &[
"appearance.assign",
+ "component.finish_edit",
"face.delete",
"material.assign",
"parameters.change",
diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs
index 8e9e0ad5e9..c982e9126e 100644
--- a/crates/ui-egui/src/context_menu.rs
+++ b/crates/ui-egui/src/context_menu.rs
@@ -818,6 +818,7 @@ fn occurrence_items(app: &SolveApp, path: &[u64]) -> Vec<Item> {
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}));
@@ -892,6 +893,7 @@ fn component_items(app: &SolveApp, id: u64) -> Vec<Item> {
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 })));
@@ -1429,6 +1431,12 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) {
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::open(app, component, path);
+ }
+ }
"ui.openLinkedDesign" => {
let Some(component) = id_of(&p, "component") else { return };
let links = match app.session.execute("component.links", &json!({})) {
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 212947daa2..4386ecd02a 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<Value, String>
return crate::view_pick::pick_command(app, &params);
}
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,
@@ -268,9 +272,26 @@ 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).
+/// 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; 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<String> {
+ 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"))
}
@@ -475,6 +496,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 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
.session
@@ -487,6 +511,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 449af1df42..1c5d2c458c 100644
--- a/crates/ui-egui/src/documents.rs
+++ b/crates/ui-egui/src/documents.rs
@@ -31,6 +31,9 @@ pub struct DocSlot {
view: DocView,
occurrence_move: Option<crate::browser::OccMove>,
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<crate::edit_in_place::PartContext>,
}
/// The per-design part of the UI state the session doesn't keep (what is hidden, shown or locked
@@ -60,6 +63,8 @@ impl DocSlot {
view: DocView::default(),
occurrence_move: None,
agent_chat: Default::default(),
+ link_stamps: Vec::new(),
+ edit_in_place: None,
}
}
}
@@ -81,6 +86,11 @@ 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<Vec<usize>>,
+ /// 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 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)>,
}
impl Documents {
@@ -154,6 +164,8 @@ 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: 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;
@@ -209,12 +221,64 @@ pub fn switch(app: &mut SolveApp, i: usize) {
return;
}
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;
+ // 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.
+ // 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);
+}
+
+/// 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))
+}
+
+/// 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)]) {
+ let record = if app.session.path.as_deref().is_some_and(|p| same_path(p, path)) {
+ &mut app.docs.link_stamps
+ } else {
+ 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
+ };
+ for (c, s) in stamps {
+ crate::linked_source::record(record, *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));
+ 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
@@ -239,7 +303,7 @@ pub(crate) fn reuse_path(app: &mut SolveApp, path: &str) -> Result<bool, String>
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;
}
@@ -293,6 +357,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();
@@ -386,6 +453,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;
}
@@ -441,18 +509,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
@@ -1004,6 +1077,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);
@@ -1020,12 +1095,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/edit_in_place.rs b/crates/ui-egui/src/edit_in_place.rs
new file mode 100644
index 0000000000..ba1a586fca
--- /dev/null
+++ b/crates/ui-egui/src/edit_in_place.rs
@@ -0,0 +1,589 @@
+//! 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 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
+//! 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::{apply_point, apply_vector, mat_inverse, mat_mul};
+use solidcraft_engine::geom::Aabb3;
+
+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<u64>,
+ /// 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<Vec<([f32; 3], [f32; 3])>>,
+ /// 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 Edit closes it again.
+ pub opened: bool,
+}
+
+/// Update Links run on the assembly while its part is edited in place.
+struct Refresh {
+ /// 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<solidcraft_engine::doc::Document>,
+ /// The linked files as they were when the run started reading them.
+ stamps: Vec<(u64, crate::linked_source::Stamp)>,
+ done: Receiver<Result<Session, String>>,
+}
+
+/// The edit in place of the tab shown, and one waiting for its part to open.
+#[derive(Default)]
+pub struct EditInPlace {
+ pub active: Option<PartContext>,
+ pending: Option<PartContext>,
+ /// Finish Edit is waiting for the save of the part at this file.
+ finish_after_save: Option<String>,
+ /// The part's own agent asked to finish the edit of the part at this file during its turn.
+ finish_after_turn: Option<String>,
+ /// 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<Vec<u64>>)>,
+ refresh: Option<Refresh>,
+ /// `component.edit_in_place` is run by the window ([`open`]), not as a command: its open may ask.
+ ask: bool,
+}
+
+impl EditInPlace {
+ /// Update Links is running on an assembly whose part is edited in place.
+ pub fn refreshing(&self) -> bool {
+ self.refresh.is_some()
+ }
+}
+
+/// 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, 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 edits_on_double_click(app, component) {
+ let path = params["path"].as_array().map(|p| p.iter().filter_map(Value::as_u64).collect::<Vec<_>>());
+ open(app, component, path);
+ } else {
+ let _ = app.run("component.activate", params);
+ }
+}
+
+/// 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.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
+ .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)));
+ if edits_on_double_click(app, component) {
+ open(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: 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.deferred.is_some()
+ || !app.deferred_queue.is_empty()
+ || app.delete_check.is_some()
+}
+
+/// 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))]),
+ 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()
+ || app.editing_state.is_some()
+ || 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
+/// 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 (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<Vec<_>> = 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, 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<Vec<u64>>) {
+ 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<bool, 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::<Vec<_>>());
+ let ask = app.edit_in_place.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());
+ }
+ if app.edit_in_place.enter_after_turn.is_some() {
+ return Err(crate::i18n::tr("ui.edit_in_place_already_queued").to_string());
+ }
+ // Everything that would make it fail at the turn's end fails it now.
+ let (context, _) = prepare(app, component, path.clone(), false)?;
+ app.edit_in_place.enter_after_turn = Some((context.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)
+}
+
+/// 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<Vec<u64>>, 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<Vec<u64>>, 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());
+ };
+ 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 {
+ return Err(app.tr_label("ui.relink_not_linked").to_string());
+ };
+ 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 Err(app.tr_label("ui.relink_not_linked").to_string());
+ };
+ let opened = crate::documents::session_at(app, &part).is_none();
+ let context = PartContext {
+ assembly,
+ assembly_name: app.session.doc.name.clone(),
+ part,
+ component,
+ placement,
+ bodies,
+ triangles: Arc::new(triangles),
+ bounds,
+ opened,
+ };
+ Ok((context, link))
+}
+
+/// 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 {
+ return;
+ };
+ // 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<String> {
+ 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) {
+ // 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 };
+ 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 = 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());
+ 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(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, 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);
+}
+
+/// 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 };
+ // 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,
+ 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 mut 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) {
+ app.set_status(crate::i18n::tr("ui.edit_in_place_refresh_dropped").to_string(), true);
+ return;
+ }
+ // What changed in the assembly meanwhile without changing its document (a pick, an
+ // 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);
+ 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 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);
+ // 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<u64>)> =
+ 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);
+}
+
+/// 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) {
+ 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 Edit up. The refusal is
+/// 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<bool, String> {
+ 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. `true`: it waits for the agent.
+fn finish_with(app: &mut SolveApp, save: bool) -> Result<bool, 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());
+ };
+ 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)) {
+ return Err(crate::i18n::format("ui.edit_in_place_saved_elsewhere", &[("name", &file_name(&part))]));
+ }
+ if app.session.is_dirty() {
+ if !save {
+ 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);
+ 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.
+ 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(true);
+ }
+ 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)]);
+ app.edit_in_place.active = Some(context);
+ return Err(why);
+ }
+ 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`
+ // 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);
+ }
+ 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.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 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);
+ 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 || 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 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). 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)
+ {
+ app.set_status(why, true);
+ }
+ // Likewise the edit the assembly's agent asked for, from the assembly's tab.
+ 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)
+ {
+ 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:
+/// 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);
+ }
+}
+
+/// 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)
+}
+
+/// The extent of the assembly around the part, when one is shown.
+pub(crate) fn bounds(app: &SolveApp) -> Option<Aabb3> {
+ 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 (p, n) in context.triangles.iter() {
+ sc.ghost_tri(*p, *n, col);
+ }
+}
+
+/// 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.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);
+ crate::ui_kit::text(ui, &text, crate::ui_kit::Text::Hint("edit_in_place"));
+ });
+ ui.add_space(t.space_3);
+}
+
+#[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 0000000000..305cbc68a9
--- /dev/null
+++ b/crates/ui-egui/src/edit_in_place_tests.rs
@@ -0,0 +1,817 @@
+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, 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();
+ 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));
+ }
+}
+
+/// 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");
+ 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);
+ assert!(showing(&f.app, &f.plate_file));
+ let c = context(&f.app);
+ assert!(c.opened);
+ 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
+ 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;
+ 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);
+ settle(&mut f.app);
+ assert_eq!(f.app.docs.count(), 1);
+ assert!((volume(&f.app) - 8000.0).abs() < 1e-6, "Finish Edit promises the change: {}", volume(&f.app));
+}
+
+#[test]
+fn update_links_in_the_part_refreshes_the_assembly_around_it() {
+ let mut f = assembly("refresh");
+ 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
+ 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.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 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 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);
+ 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);
+ 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] {
+ 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]
+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");
+ // 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;
+ 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);
+ // 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");
+ 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);
+ 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);
+ 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));
+ 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();
+ 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;
+ 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();
+ 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, 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 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_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");
+ 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.double_click_components = 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 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 Edit");
+ 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 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}));
+ 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, 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);
+ 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);
+ 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");
+ // 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);
+}
+
+#[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());
+ 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();
+ 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]
+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);
+ // 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);
+ // 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);
+ settle(&mut f.app);
+ 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]
+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]
+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");
+ 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);
+ 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: 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_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 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");
+ 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/file_load.rs b/crates/ui-egui/src/file_load.rs
index 496f7e5c84..49b03233ef 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<String> },
/// Export a snapshot of the current design without adopting the worker's session.
ExportDxf,
- /// Read the active design's linked designs again (`component.update_links`).
+ /// Read the active design's linked designs again (`component.update_links`, with the
+ /// request's options: `component` reads only that link).
UpdateLinks,
}
@@ -54,6 +55,9 @@ pub struct Request {
pub options: serde_json::Map<String, Value>,
/// Network servers the user allowed for this one request ("Allow once", `network_prompt`).
pub allow_hosts: Vec<String>,
+ /// 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<String>,
}
impl Request {
@@ -65,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 {
@@ -83,7 +88,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<Value, String>) {
@@ -194,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()
@@ -248,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 { .. } => {
@@ -359,7 +370,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
}
@@ -395,6 +407,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)
@@ -889,6 +905,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/lib.rs b/crates/ui-egui/src/lib.rs
index 3424c4aaf1..55a911026e 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;
@@ -515,6 +516,8 @@ pub struct SolveApp {
/// OK pressed on a feature that takes a while: its evaluation runs off the window thread.
pub applying: Option<dialogs::Applying>,
pub(crate) editing_state: Option<dialogs::EditingState>,
+ /// 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<feature_edit::PendingFeatureEdit>,
/// A command recomputing the history (the marker moved, undo) computing off the window
/// thread, and those asked for meanwhile ([`deferred`]).
@@ -712,6 +715,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(),
@@ -1020,6 +1024,13 @@ impl SolveApp {
/// Host effects shared by directly executed and already evaluated commands.
pub(crate) fn command_completed(&mut self, id: &str, r: Result<Value, String>) -> Result<Value, String> {
+ // 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) {
+ // `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 {
match id {
"view.fit" | "view.home" => self.frame_view(id == "view.home"),
@@ -1194,6 +1205,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;
@@ -1405,6 +1417,10 @@ impl SolveApp {
if dialogs_sheet::start_export(self, id) {
return;
}
+ 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();
@@ -1415,6 +1431,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
@@ -2154,7 +2177,12 @@ 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);
+ 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() {
ctx.request_repaint_after(std::time::Duration::from_millis(16));
}
open_meshing::tick(self, ctx);
@@ -2652,6 +2680,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/crates/ui-egui/src/linked_source.rs b/crates/ui-egui/src/linked_source.rs
index 2b409e46a2..dbfe57197d 100644
--- a/crates/ui-egui/src/linked_source.rs
+++ b/crates/ui-egui/src/linked_source.rs
@@ -106,6 +106,99 @@ 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 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)> {
+ 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) = session.execute("component.links", &json!({})) else { return Vec::new() };
+ links["links"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .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()
+}
+
+/// Set `component`'s entry in `stamps` (each link's file as the design last read it).
+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)),
+ }
+}
+
+/// 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<u64> =
+ 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));
+ }
+ }
+ // 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);
+ }
+}
+
+/// 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<u64>) {
+ 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.
#[derive(Clone, Debug)]
pub struct Copies {
@@ -318,6 +411,259 @@ 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::<f64>()
+ };
+ 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);
+ }
+
+ /// 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 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");
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index 6c96b95bde..156ac82811 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -823,6 +823,14 @@ 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 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");
+ /// 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 162cf1632e..7ea8f28c65 100644
--- a/crates/ui-egui/src/prefs/design.rs
+++ b/crates/ui-egui/src/prefs/design.rs
@@ -78,6 +78,10 @@ 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);
+ 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| {
setting::network_locations(app, ui);
diff --git a/crates/ui-egui/src/save_job.rs b/crates/ui-egui/src/save_job.rs
index 0c5ce06f75..8cfa59b780 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.rs b/crates/ui-egui/src/toolbar.rs
index 3bca3159ae..030283ffb2 100644
--- a/crates/ui-egui/src/toolbar.rs
+++ b/crates/ui-egui/src/toolbar.rs
@@ -1297,8 +1297,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.
@@ -1341,7 +1343,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);
@@ -1364,7 +1367,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 {
@@ -3736,7 +3739,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/toolbar_custom.rs b/crates/ui-egui/src/toolbar_custom.rs
index dd84d39fad..b5b21c1971 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 Edit 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) {
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 5b7c8bd17d..8f00aac488 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -390,7 +390,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
@@ -464,6 +465,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.
@@ -1463,6 +1465,7 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene {
}
}
}
+ crate::edit_in_place::draw_context(app, &mut sc);
sc
}
@@ -1713,7 +1716,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()
}
@@ -4225,6 +4228,18 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
.collect();
let _ = app.run("select.set", json!({ "items": items, "add": add }));
}
+ // 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()
+ && 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. egui's click
// already allows the pointer a few points of travel, as a mouse moves while it is clicked.
if resp.secondary_clicked() && !crate::mouse_gesture::took_press(app) {
diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs
index 2632a7fea3..28b2a4c91d 100644
--- a/crates/ui-egui/src/workspace.rs
+++ b/crates/ui-egui/src/workspace.rs
@@ -119,6 +119,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"] },
diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md
index 5053876745..0a67afe5a3 100644
--- a/docs/book/src/guide/assemblies.md
+++ b/docs/book/src/guide/assemblies.md
@@ -357,6 +357,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 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
@@ -364,6 +369,19 @@ 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 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. 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
+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 `.sc` design
to use. Relinking updates that component's stored path and solid bodies for **all its
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 8139dc8cfd..ce37b326fe 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -136,7 +136,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 44ed5736d3..f61470d317 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -277,7 +277,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`, 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`). |