From aaa35a94d8fd753fac02e6403f5ce7ef8403c5fd Mon Sep 17 00:00:00 2001 From: amolinari-autotex Date: Mon, 19 Oct 2026 13:14:33 +0200 Subject: [PATCH] Relink a linked assembly source from the Browser (#2772) (#2773) Thanks @amolinari-autotex. --- assets/locales/en.json | 6 + assets/locales/it.json | 6 + assets/locales/ja.json | 6 + assets/locales/ms.json | 1 + assets/locales/zh.json | 6 + crates/engine/src/cmd/component_link.rs | 68 +++++++ .../engine/src/cmd/component_relink_tests.rs | 147 ++++++++++++++ crates/ui-egui/src/context_menu.rs | 8 + crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/linked_source.rs | 180 ++++++++++++++++++ docs/book/src/guide/assemblies.md | 16 ++ 11 files changed, 449 insertions(+) create mode 100644 crates/engine/src/cmd/component_relink_tests.rs create mode 100644 crates/ui-egui/src/linked_source.rs diff --git a/assets/locales/en.json b/assets/locales/en.json index 6c2253456..55f762924 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -350,6 +350,7 @@ "cmd.component_move_sketches": "Move Sketches to Component", "cmd.component_paste_new": "Paste New", "cmd.component_properties": "Component Physical Properties", + "cmd.component_relink": "Relink Source", "cmd.component_rename": "Rename Component", "cmd.component_revert_position": "Revert Position", "cmd.component_unlock": "Unlock Contents", @@ -1408,6 +1409,11 @@ "ui.rectangle": "Rectangle", "ui.rectangular_pattern": "Rectangular Pattern", "ui.redo": "Redo", + "ui.relink_design_changed": "The assembly changed while choosing a source. Start Relink Source again.", + "ui.relink_done": "Source relinked for all instances.", + "ui.relink_not_linked": "This component is not linked to a source design.", + "ui.relink_select_one": "Select one linked component or one of its instances first.", + "ui.relink_source_all": "Relink Source (All Instances)…", "ui.removeFromToolbar": "Remove from Toolbar", "ui.removeSection": "Remove Section", "ui.render": "Render", diff --git a/assets/locales/it.json b/assets/locales/it.json index e28daca5e..0d3784dc4 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -345,6 +345,7 @@ "cmd.component_move_sketches": "Sposta schizzi nel componente", "cmd.component_paste_new": "Incolla come nuovo", "cmd.component_properties": "Proprietà fisiche del componente", + "cmd.component_relink": "Ricollega sorgente", "cmd.component_rename": "Rinomina componente", "cmd.component_revert_position": "Ripristina posizione", "cmd.component_unlock": "Sblocca contenuto", @@ -1342,6 +1343,11 @@ "ui.rectangle": "Rettangolo", "ui.rectangular_pattern": "Ripetizione rettangolare", "ui.redo": "Ripeti", + "ui.relink_design_changed": "L'assieme è cambiato durante la scelta del sorgente. Avvia di nuovo Ricollega sorgente.", + "ui.relink_done": "Sorgente ricollegato per tutte le istanze.", + "ui.relink_not_linked": "Questo componente non è collegato a un progetto sorgente.", + "ui.relink_select_one": "Seleziona un componente collegato o una delle sue istanze.", + "ui.relink_source_all": "Ricollega sorgente (tutte le istanze)…", "ui.removeFromToolbar": "Rimuovi dalla barra degli strumenti", "ui.removeSection": "Rimuovi sezione", "ui.render": "Rendering", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 396aebaee..b40c29bc1 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -350,6 +350,7 @@ "cmd.component_move_sketches": "スケッチをコンポーネントに移動", "cmd.component_paste_new": "新規として貼り付け", "cmd.component_properties": "コンポーネントの物理的プロパティ", + "cmd.component_relink": "参照元を再リンク", "cmd.component_rename": "コンポーネントの名前を変更", "cmd.component_revert_position": "位置を元に戻す", "cmd.component_unlock": "内容のロックを解除", @@ -1408,6 +1409,11 @@ "ui.rectangle": "長方形", "ui.rectangular_pattern": "矩形パターン", "ui.redo": "やり直す", + "ui.relink_design_changed": "参照元の選択中にアセンブリが変更されました。再リンクをやり直してください。", + "ui.relink_done": "すべてのインスタンスの参照元を再リンクしました。", + "ui.relink_not_linked": "このコンポーネントは参照元の設計にリンクされていません。", + "ui.relink_select_one": "リンクされたコンポーネントまたはそのインスタンスを1つ選択してください。", + "ui.relink_source_all": "参照元を再リンク(すべてのインスタンス)…", "ui.removeFromToolbar": "ツールバーから削除", "ui.removeSection": "セクションを解除", "ui.render": "レンダリング", diff --git a/assets/locales/ms.json b/assets/locales/ms.json index 9c5ad68a1..11765f89a 100644 --- a/assets/locales/ms.json +++ b/assets/locales/ms.json @@ -1067,6 +1067,7 @@ "ui.continuity_g0": "Lipatan G0", "ui.continuity_g1": "Tangen G1", "ui.continuity_g2": "Kelengkungan G2", + "ui.continuity_gap": "Sela", "ui.copy": "Salin", "ui.corner": "Sudut", "ui.corners": "Sudut", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index c9eafe6ec..b4d664675 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -350,6 +350,7 @@ "cmd.component_move_sketches": "将草图移至组件", "cmd.component_paste_new": "粘贴为新对象", "cmd.component_properties": "组件物理属性", + "cmd.component_relink": "重新链接源文件", "cmd.component_rename": "重命名组件", "cmd.component_revert_position": "恢复位置", "cmd.component_unlock": "解锁内容", @@ -1408,6 +1409,11 @@ "ui.rectangle": "矩形", "ui.rectangular_pattern": "矩形阵列", "ui.redo": "重做", + "ui.relink_design_changed": "选择源文件时装配已更改。请重新开始链接。", + "ui.relink_done": "已为所有实例重新链接源文件。", + "ui.relink_not_linked": "此组件未链接到源设计。", + "ui.relink_select_one": "请先选择一个链接组件或其实例。", + "ui.relink_source_all": "重新链接源文件(所有实例)…", "ui.removeFromToolbar": "从工具栏移除", "ui.removeSection": "移除剖面", "ui.render": "渲染", diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rs index c5e3d6baa..343c67491 100644 --- a/crates/engine/src/cmd/component_link.rs +++ b/crates/engine/src/cmd/component_link.rs @@ -15,6 +15,11 @@ use super::CommandSpec; use crate::params::{bad, str_, vec3}; use crate::{EngineError, Result, Session}; +#[cfg(test)] +#[path = "component_relink_tests.rs"] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod relink_tests; + pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("component.insert_design", "Insert Design", insert_design).at("SOLID", "ASSEMBLE").icon("component").params( "path: a .solidcraft design → a new component linked to it, holding its solid bodies as placed in that design; \ @@ -23,6 +28,9 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("component.update_links", "Update Links", update_links).icon("update").params( "component?: id or name (default: every linked component) — reads the linked designs again and replaces their bodies where they changed", ), + CommandSpec::new("component.relink", "Relink Source", relink).icon("update").params( + "component: id or name of a linked component; path: a saved .solidcraft design — replaces the source and linked bodies for all its occurrences, preserving identities and placements; returns path, previous_path, warnings, joint_errors and joint_conflicts", + ), CommandSpec::new("component.break_link", "Break Link", break_link) .icon("break") .params("component: id or name of a linked component — keeps its bodies as they are and forgets the design file"), @@ -216,6 +224,66 @@ fn update_links(s: &mut Session, p: &Value) -> Result { Ok(json!({"updated": updated, "unchanged": unchanged, "warnings": warnings})) } +fn relink(s: &mut Session, p: &Value) -> Result { + let cmd = "component.relink"; + let comp = component_key(s, p, "component", cmd)?; + let link = s.doc.links.get(&comp).cloned().ok_or_else(|| bad(cmd, "that component is not linked to a design"))?; + if !matches!(s.doc.feature(link.feature), Some(f) if f.component == comp && matches!(f.kind, FeatureKind::Import { .. })) { + return Err(bad(cmd, "the linked bodies are gone; break the link or insert the design again")); + } + let given = str_(p, "path").filter(|x| !x.trim().is_empty() && x.len() < 4096).ok_or_else(|| bad(cmd, "`path` is required"))?; + let file = absolute(Path::new(given)); + if !file.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("solidcraft")) { + return Err(bad(cmd, "choose a saved .solidcraft design")); + } + // The ordinary lexical check in linked_bodies also works in the browser VFS. On native + // hosts, reject an alias of this assembly too (a symlink or a path with different case). + if let (Ok(candidate), Some(Ok(own))) = (file.canonicalize(), s.path.as_deref().map(std::fs::canonicalize)) + && candidate == own + { + return Err(bad(cmd, "a design can't be linked into itself")); + } + // Read/evaluate the candidate before changing anything. Session::execute owns the single + // undo step and restores both the document and evaluated state on any later failure. + let (_, sf) = linked_bodies(&file, s.path.as_deref()).map_err(|e| bad(cmd, e.to_string()))?; + let geometry_changed = match (s.doc.feature(link.feature).map(|f| &f.kind), &sf.kind) { + (Some(FeatureKind::Import { step: old, .. }), FeatureKind::Import { step, .. }) => old != step, + _ => true, + }; + let path = stored(s.path.as_deref(), &file); + let mut warnings = sf.warnings; + if geometry_changed + && s.doc + .assembly + .joints + .iter() + .any(|j| s.doc.occurrences.iter().any(|o| o.component == comp && (j.a.occurrence == o.id || j.b.occurrence == o.id))) + { + warnings.push("the linked geometry changed; check this component's joints, even when the solver reports no error".to_string()); + } + if let Some(f) = s.doc_mut().feature_mut(link.feature) { + if f.body_names.len() != sf.body_names.len() { + f.body_names = sf.body_names; + } + f.kind = sf.kind; + } + s.doc_mut().links.insert(comp, DesignLink { path: path.clone(), feature: link.feature }); + s.refresh(); + if let Some(error) = s.model.result(link.feature).and_then(|r| r.error.clone()) { + return Err(bad(cmd, error)); + } + // Report the solver's diagnostics. A resolved joint can still describe the wrong + // connection after a source edit; the reminder above does not depend on solve errors. + let sol = solidcraft_doc::joints::solve(&s.doc, &s.model.state()); + let diagnostics = + |rows: &[(u64, String, String)]| rows.iter().map(|(id, name, why)| json!({"joint": id, "name": name, "why": why})).collect::>(); + for (_, name, why) in sol.errors.iter().chain(&sol.conflicts) { + warnings.push(format!("joint {name}: {why}")); + } + Ok(json!({"component": comp, "feature": link.feature, "path": path, "previous_path": link.path, "geometry_changed": geometry_changed, + "warnings": warnings, "joint_errors": diagnostics(&sol.errors), "joint_conflicts": diagnostics(&sol.conflicts)})) +} + fn break_link(s: &mut Session, p: &Value) -> Result { let cmd = "component.break_link"; let comp = component_key(s, p, "component", cmd)?; diff --git a/crates/engine/src/cmd/component_relink_tests.rs b/crates/engine/src/cmd/component_relink_tests.rs new file mode 100644 index 000000000..31b78c5a8 --- /dev/null +++ b/crates/engine/src/cmd/component_relink_tests.rs @@ -0,0 +1,147 @@ +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::Session; + +fn run(s: &mut Session, command: &str, params: Value) -> Value { + s.execute(command, ¶ms).unwrap_or_else(|e| panic!("{command}: {e}")) +} + +fn folder(case: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("solidcraft-relink-{case}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn part(path: &Path, height: u32) { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": height, "corner": [0,0,0]})); + run(&mut s, "file.save", json!({"path": path})); +} + +fn volume(s: &mut Session) -> f64 { + run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap() +} + +#[test] +fn relink_repairs_a_moved_source_for_every_instance_in_one_undo_step() { + let dir = folder("moved"); + let old = dir.join("old.solidcraft"); + let moved = dir.join("moved.solidcraft"); + let assembly = dir.join("assembly.solidcraft"); + part(&old, 30); + let mut s = Session::default(); + run(&mut s, "file.save", json!({"path": assembly})); + let inserted = run(&mut s, "component.insert_design", json!({"path": old})); + let component = inserted["component"].as_u64().unwrap(); + let first = inserted["occurrence"].as_u64().unwrap(); + let second = run(&mut s, "occurrence.copy", json!({"occurrence": first, "translate": [70,30,10]}))["occurrence"].as_u64().unwrap(); + run(&mut s, "occurrence.move", json!({"occurrence": second, "translate": [0,12,0], "capture": false})); + let occurrences = s.doc.occurrences.clone(); + let pending = s.pending_moves.clone(); + let before = serde_json::to_value(&*s.doc).unwrap(); + let undo = s.undo.len(); + std::fs::rename(&old, &moved).unwrap(); + part(&moved, 45); + let result = run(&mut s, "component.relink", json!({"component": component, "path": moved})); + assert_eq!(result["previous_path"], "old.solidcraft"); + assert_eq!(result["path"], "moved.solidcraft"); + assert_eq!(result["geometry_changed"], true); + assert_eq!(result["warnings"], json!([])); + assert_eq!(s.doc.occurrences, occurrences); + assert_eq!(s.pending_moves, pending); + assert_eq!(s.undo.len(), undo + 1); + assert!((volume(&mut s) - 18000.0).abs() < 1e-5); + let after = serde_json::to_value(&*s.doc).unwrap(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(serde_json::to_value(&*s.doc).unwrap(), before); + assert_eq!(s.pending_moves, pending); + assert!((volume(&mut s) - 12000.0).abs() < 1e-5); + run(&mut s, "edit.redo", json!({})); + assert_eq!(serde_json::to_value(&*s.doc).unwrap(), after); + run(&mut s, "file.save", json!({})); + let mut reopened = Session::default(); + run(&mut reopened, "doc.open", json!({"path": assembly})); + assert_eq!(run(&mut reopened, "component.links", json!({}))["links"][0]["path"], "moved.solidcraft"); + assert_eq!(run(&mut reopened, "component.links", json!({}))["links"][0]["found"], true); + assert!((volume(&mut reopened) - 18000.0).abs() < 1e-5); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn relink_rejects_bad_sources_and_targets_without_touching_the_design_or_undo() { + let dir = folder("failures"); + let source = dir.join("source.solidcraft"); + let assembly = dir.join("assembly.solidcraft"); + let empty = dir.join("empty.solidcraft"); + let corrupt = dir.join("corrupt.solidcraft"); + part(&source, 30); + let mut s = Session::default(); + let component = run(&mut s, "component.insert_design", json!({"path": source}))["component"].as_u64().unwrap(); + run(&mut s, "file.save", json!({"path": assembly})); + run(&mut Session::default(), "file.save", json!({"path": empty})); + std::fs::write(&corrupt, b"not a design").unwrap(); + let before = serde_json::to_value(&*s.doc).unwrap(); + let undo = s.undo.len(); + for params in [ + json!({}), + json!({"component": component}), + json!({"component": false, "path": source}), + json!({"component": 0, "path": source}), + json!({"component": "unknown", "path": source}), + json!({"component": component, "path": " "}), + json!({"component": component, "path": false}), + json!({"component": component, "path": dir.join("missing.solidcraft")}), + json!({"component": component, "path": dir.join("source.step")}), + json!({"component": component, "path": empty}), + json!({"component": component, "path": corrupt}), + json!({"component": component, "path": assembly}), + ] { + assert!(s.execute("component.relink", ¶ms).is_err(), "{params}"); + assert_eq!(serde_json::to_value(&*s.doc).unwrap(), before, "{params}"); + assert_eq!(s.undo.len(), undo); + assert!((volume(&mut s) - 6000.0).abs() < 1e-5); + } + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn relink_keeps_joint_definitions_and_reports_solver_diagnostics() { + let dir = folder("joints"); + let original = dir.join("original.solidcraft"); + let replacement = dir.join("replacement.solidcraft"); + part(&original, 30); + part(&replacement, 45); + let mut s = Session::default(); + let inserted = run(&mut s, "component.insert_design", json!({"path": original})); + let component = inserted["component"].as_u64().unwrap(); + let occurrence = inserted["occurrence"].as_u64().unwrap(); + // Explicit points can keep solving after the source changes, even if the intended + // connection no longer exists. The source-change warning must still be present. + run( + &mut s, + "joint.create", + json!({"name": "Seat", "type": "rigid", "a": {"occurrence": 0, "point": [0,0,0]}, "b": {"occurrence": occurrence, "point": [0,0,0]}}), + ); + let joints = s.doc.assembly.joints.clone(); + let identical = dir.join("identical.solidcraft"); + std::fs::copy(&original, &identical).unwrap(); + let result = run(&mut s, "component.relink", json!({"component": component, "path": identical})); + assert_eq!(result["geometry_changed"], false, "renaming a source is not a geometry change"); + assert_eq!(result["warnings"], json!([])); + assert_eq!(s.doc.assembly.joints, joints); + let result = run(&mut s, "component.relink", json!({"component": component, "path": replacement})); + assert_eq!(s.doc.assembly.joints, joints); + assert!(result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("check this component's joints")))); + // A deliberately lost named face exercises the ordinary solver diagnostics, without + // requiring relink to guess which face of a different design was intended. + let joint = s.doc_mut().assembly.joints.first_mut().unwrap(); + joint.b.snap = + solidcraft_doc::joints::Snap::FaceCenter { pick: solidcraft_geom::Vec3::ZERO, face: Some("no-such-linked-face".to_string()), x: None }; + s.refresh(); + let result = run(&mut s, "component.relink", json!({"component": component, "path": replacement})); + assert!(result["joint_errors"].as_array().unwrap().iter().any(|e| e["name"] == "Seat")); + assert!(result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("joint Seat:")))); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 59b7e777a..ec50701d7 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -703,6 +703,9 @@ fn component_items(app: &SolveApp, id: u64) -> Vec { .on(id != 0 || !bodies.is_empty()), ); v.push(act("ui.properties", "Properties", "measure").with(json!({ "component": id }))); + if doc.links.contains_key(&id) { + v.push(act("ui.relinkSource", "Relink Source (All Instances)…", "update").with(json!({"component": id}))); + } if id == 0 { v.push(act("ui.designProperties", "Design Properties", "settings")); } @@ -888,6 +891,11 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { "ui.delete" if item.params.is_some() => crate::delete::request(app, p), "ui.delete" => delete(app), "ui.finishSketch" => app.finish_sketch(), + "ui.relinkSource" => { + if let Some(component) = id_of(&p, "component") { + crate::linked_source::start(app, component); + } + } "ui.copy" => drop(crate::edit_clipboard::copy(app)), "ui.cut" => drop(crate::edit_clipboard::cut(app)), "ui.paste" => drop(crate::edit_clipboard::paste(app, Some(at))), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3ca76af58..29b6fb11e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -69,6 +69,7 @@ pub mod install; pub mod issue_report; pub mod joint_drag; pub mod keymap; +mod linked_source; mod material_card_review; #[cfg(test)] mod measurement_ui_tests; @@ -785,6 +786,10 @@ impl SolveApp { }); return; } + if id == "component.relink" { + linked_source::start_selected(self); + return; + } if matches!(id, "file.insert_step" | "file.insert_mesh") { self.pick_open(|app, path| { if let Some(path) = path { diff --git a/crates/ui-egui/src/linked_source.rs b/crates/ui-egui/src/linked_source.rs new file mode 100644 index 000000000..da5052881 --- /dev/null +++ b/crates/ui-egui/src/linked_source.rs @@ -0,0 +1,180 @@ +//! Explicitly choose a linked component's source; all its instances share that source. + +use std::sync::Arc; + +use serde_json::json; + +use crate::SolveApp; + +pub(crate) fn start_selected(app: &mut SolveApp) { + let mut components = app.tree.picked_components.clone(); + for selection in &app.session.selection { + if let solidcraft_engine::Sel::Occurrence { path } = selection + && let Ok(placement) = app.session.occurrence_placement(path) + { + components.push(placement.component); + } + } + components.sort_unstable(); + components.dedup(); + if let [component] = components.as_slice() + && app.session.doc.links.contains_key(component) + { + start(app, *component); + } else { + app.set_status(app.tr("ui.relink_select_one").to_string(), true); + } +} + +pub(crate) fn start(app: &mut SolveApp, component: u64) { + if app.file_picker_busy() || app.file_load.busy() { + return; + } + if !app.session.doc.links.contains_key(&component) { + app.set_status(app.tr_label("ui.relink_not_linked").to_string(), true); + return; + } + let document = app.session.doc.clone(); + app.pick_open_for(&["solidcraft"], move |app, path| { + let Some(path) = path else { return }; + // A host or programmatic caller can replace/edit a design while a native picker is + // pending. Never apply that old component id to a different design or newer revision. + if !Arc::ptr_eq(&document, &app.session.doc) { + app.set_status(app.tr_label("ui.relink_design_changed").to_string(), true); + return; + } + if let Ok(result) = app.run("component.relink", json!({"component": component, "path": path})) { + let warnings: Vec<&str> = result["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str()).collect(); + if warnings.is_empty() { + app.set_status(app.tr_label("ui.relink_done").to_string(), false); + } else { + let text = format!("{} {}", app.tr_label("ui.relink_done"), warnings.join("; ")); + app.session.echo(text.clone()); + app.set_status(text, true); + } + } + }); +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use crate::context_menu::{self, Target}; + use solidcraft_engine::Session; + use std::path::PathBuf; + + fn fixture(name: &str) -> (SolveApp, u64, u64, PathBuf, PathBuf) { + let folder = std::env::temp_dir().join(format!("solidcraft-relink-ui-{name}-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let source = folder.join("source.solidcraft"); + let moved = folder.join("moved.solidcraft"); + let mut part = Session::default(); + part.execute("solid.box", &json!({"length": 10, "width": 20, "height": 30})).unwrap(); + part.execute("file.save", &json!({"path": source})).unwrap(); + let mut app = SolveApp::new(Session::default(), Default::default()); + let inserted = app.run("component.insert_design", json!({"path": source})).unwrap(); + let component = inserted["component"].as_u64().unwrap(); + let occurrence = inserted["occurrence"].as_u64().unwrap(); + std::fs::rename(&source, &moved).unwrap(); + (app, component, occurrence, folder, moved) + } + + fn menu(app: &SolveApp, target: Target) -> Option { + context_menu::items(app, &target).into_iter().find(|i| i.id == "ui.relinkSource") + } + + fn answer(app: &mut SolveApp, path: Option) { + app.services.pick_open = Some(Box::new(move |extensions| { + assert_eq!(extensions, &["solidcraft"]); + let result = path.clone(); + Box::pin(async move { result }) + })); + } + + #[test] + fn relink_menu_uses_the_selected_link_from_components_and_occurrences() { + let (mut app, component, occurrence, folder, moved) = fixture("menu"); + let second = app.run("occurrence.copy", json!({"occurrence": occurrence, "translate": [90,0,0]})).unwrap()["occurrence"].as_u64().unwrap(); + let occurrences = app.session.doc.occurrences.clone(); + let item = menu(&app, Target::Component { id: component }).unwrap(); + assert!(item.label.contains("All Instances")); + assert_eq!(menu(&app, Target::Occurrence { path: vec![second] }).unwrap().params, Some(json!({"component": component}))); + assert!(menu(&app, Target::Component { id: 0 }).is_none()); + answer(&mut app, Some(moved.to_string_lossy().into_owned())); + let before = app.session.doc.clone(); + context_menu::run_item(&mut app, &item, egui::Pos2::ZERO); + assert!(app.file_picker_busy()); + assert!(Arc::ptr_eq(&before, &app.session.doc), "choosing is not an edit"); + crate::file_picker::tick(&mut app, &egui::Context::default()); + assert!(!app.file_picker_busy()); + assert!(app.session.doc.links[&component].path.ends_with("moved.solidcraft")); + assert_eq!(app.session.doc.occurrences, occurrences); + assert!(app.status.as_ref().is_some_and(|(s, _, error)| s.contains("all instances") && !error)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(serde_json::to_value(&*app.session.doc).unwrap(), serde_json::to_value(&*before).unwrap()); + let _ = std::fs::remove_dir_all(folder); + } + + #[test] + fn relink_picker_cancel_bad_file_and_changed_document_keep_the_link() { + let (mut app, component, _, folder, moved) = fixture("cancel"); + let before = serde_json::to_value(&*app.session.doc).unwrap(); + let undo = app.session.undo.len(); + answer(&mut app, None); + start(&mut app, component); + crate::file_picker::tick(&mut app, &egui::Context::default()); + assert_eq!(serde_json::to_value(&*app.session.doc).unwrap(), before); + assert_eq!(app.session.undo.len(), undo); + answer(&mut app, Some(folder.join("missing.solidcraft").to_string_lossy().into_owned())); + start(&mut app, component); + crate::file_picker::tick(&mut app, &egui::Context::default()); + assert_eq!(serde_json::to_value(&*app.session.doc).unwrap(), before); + assert_eq!(app.session.undo.len(), undo); + assert!(app.status.as_ref().is_some_and(|(_, _, error)| *error)); + answer(&mut app, Some(moved.to_string_lossy().into_owned())); + start(&mut app, component); + // The ordinary UI blocks edits while picking. Simulate a host replacing/editing the + // session directly to exercise the continuation's independent stale-target guard. + app.session.execute("component.rename", &json!({"component": component, "name": "Changed"})).unwrap(); + let changed = serde_json::to_value(&*app.session.doc).unwrap(); + crate::file_picker::tick(&mut app, &egui::Context::default()); + assert_eq!(serde_json::to_value(&*app.session.doc).unwrap(), changed); + assert!(app.status.as_ref().is_some_and(|(s, _, error)| s.contains("assembly changed") && *error)); + let _ = std::fs::remove_dir_all(folder); + } + + #[test] + fn relink_start_requires_one_linked_selection_and_opens_its_picker() { + let (mut app, component, occurrence, folder, moved) = fixture("start"); + answer(&mut app, Some(moved.to_string_lossy().into_owned())); + app.start("component.relink"); + assert!(!app.file_picker_busy()); + assert!(app.status.as_ref().is_some_and(|(s, _, error)| s.contains("Select one linked") && *error)); + app.session.selection = vec![solidcraft_engine::Sel::Occurrence { path: vec![occurrence] }]; + app.start("component.relink"); + assert!(app.file_picker_busy()); + crate::file_picker::tick(&mut app, &egui::Context::default()); + assert!(app.session.doc.links[&component].path.ends_with("moved.solidcraft")); + 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"); + app.run( + "joint.create", + json!({"name": "Seat", "type": "rigid", "a": {"occurrence": 0, "point": [0,0,0]}, "b": {"occurrence": occurrence, "point": [0,0,0]}}), + ) + .unwrap(); + let mut changed = Session::default(); + changed.execute("solid.box", &json!({"length": 10, "width": 20, "height": 45})).unwrap(); + changed.execute("file.save", &json!({"path": moved})).unwrap(); + answer(&mut app, Some(moved.to_string_lossy().into_owned())); + start(&mut app, component); + crate::file_picker::tick(&mut app, &egui::Context::default()); + assert!(app.status.as_ref().is_some_and(|(s, _, error)| s.contains("check this component's joints") && *error)); + assert!(app.session.log.iter().any(|s| s.contains("check this component's joints"))); + let _ = std::fs::remove_dir_all(folder); + } +} diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index bbd40dda8..5c20f1d9c 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -250,6 +250,22 @@ After the part file changes, **Update Links** (`component.update_links`) reads i the part's bodies only: its timeline, parameters and sheet-metal data (flat pattern, bend table) stay in the part's own design. +If a source file moves or is renamed, right-click its linked component or occurrence in the +Browser and choose **Relink Source (All Instances)…**. Choose the saved `.solidcraft` design +to use. Relinking updates that component's stored path and solid bodies for **all its +instances**, keeping their identities and placements. Cancelling or choosing a missing, +invalid, empty or self-referencing design leaves the assembly unchanged. The operation is +one undo step and the new path is saved relative to the assembly when possible. + +Scripts use `component.relink {component, path}`. The reply includes `previous_path`, `path`, +`warnings`, `joint_errors` and `joint_conflicts`. Changed geometry can invalidate a joint's +face reference: relinking reports those joints in the reply and UI status/message history; +repair the joint or undo the relink. Relink does not repair or verify the intended meaning of +existing joints. +When linked geometry changes and the component has joints, a reminder to check those joints +is also shown even if the solver reports no error: a successful solve does not prove that a +joint still describes the intended connection. + STEP export writes the component tree as an assembly. Right-click a component in the Browser and choose **Properties** to inspect