Skip to content

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

Update Links: linked designs that changed while the tab was away come back as one undo step (#9743) (#9753)

froglemonade204761549738a
diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rs
index 3c3b28ed8e..8c1cc99927 100644
--- a/crates/engine/src/cmd/component_link.rs
+++ b/crates/engine/src/cmd/component_link.rs
@@ -35,8 +35,10 @@ pub static COMMANDS: &[CommandSpec] = &[
reuse?: bool (default false): insert a free occurrence, reusing an existing link to the same file when available",
),
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; \
- → updated, unchanged, warnings (also joints whose faces are gone or that no longer solve)",
+ "component?: id or name (default: every linked component); components?: a list of ids or names, which goes on past a design it \
+ cannot read (that one keeps its bodies, is named in failed and gets a warning) — reads the linked designs again and replaces \
+ their bodies where they changed, as one undo step; → updated, unchanged, failed ([{component, name, error}]), warnings (also \
+ joints whose faces are gone or that no longer solve)",
),
CommandSpec::new("component.relink", "Relink Source", relink).icon("update").params(
"component: id or name of a linked component; path: a saved .sc 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",
@@ -553,14 +555,25 @@ fn insert_design(s: &mut Session, p: &Value) -> Result<Value> {
fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "component.update_links";
- let only = if p.get("component").is_some() { Some(component_key(s, p, "component", cmd)?) } else { None };
- if let Some(c) = only
- && !s.doc.links.contains_key(&c)
- {
- return Err(bad(cmd, "that component is not linked to a design"));
+ let only = match (p.get("component"), p.get("components")) {
+ (Some(_), Some(_)) => return Err(bad(cmd, "give `component` or `components`, not both")),
+ (Some(_), None) => Some(vec![component_key(s, p, "component", cmd)?]),
+ (None, Some(Value::Array(list))) if !list.is_empty() && list.len() <= 10_000 => {
+ Some(list.iter().map(|c| component_key(s, &json!({"component": c}), "component", cmd)).collect::<Result<Vec<_>>>()?)
+ }
+ (None, Some(_)) => return Err(bad(cmd, "`components` must be a list of component ids or names")),
+ (None, None) => None,
+ };
+ if let Some(c) = only.iter().flatten().find(|c| !s.doc.links.contains_key(c)) {
+ let name = s.doc.components.iter().find(|x| x.id == *c).map_or_else(|| c.to_string(), |x| x.name.clone());
+ return Err(bad(cmd, format!("{name}: that component is not linked to a design")));
}
- let links: Vec<(u64, DesignLink)> = s.doc.links.iter().filter(|(c, _)| only.is_none_or(|o| o == **c)).map(|(c, l)| (*c, l.clone())).collect();
- let (mut updated, mut unchanged, mut warnings) = (Vec::new(), Vec::new(), Vec::new());
+ // A list goes on past a design it cannot read: that link keeps its bodies and is named in
+ // `failed`, so the others still come in as one step (#9743).
+ let go_on = p.get("components").is_some();
+ let links: Vec<(u64, DesignLink)> =
+ s.doc.links.iter().filter(|(c, _)| only.as_ref().is_none_or(|o| o.contains(c))).map(|(c, l)| (*c, l.clone())).collect();
+ let (mut updated, mut unchanged, mut warnings, mut failed) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
let count = links.len();
for (index, (comp, link)) in links.into_iter().enumerate() {
let cname = s.doc.components.iter().find(|c| c.id == comp).map(|c| c.name.clone());
@@ -571,16 +584,15 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
};
// A window running this off its thread names the design being read again (#5329).
solidcraft_doc::progress::item(Some((&cname, index, count)));
- let Some(FeatureKind::Import { step: old, .. }) = s.doc.feature(link.feature).filter(|f| f.component == comp).map(|f| &f.kind) else {
- return Err(bad(
- cmd,
- format!("{cname}: its linked bodies (feature {}) are gone; break the link or insert the design again", link.feature),
- ));
+ let (old, file, bytes) = match read_linked(s, comp, &link) {
+ Ok(read) => read,
+ Err(e) if go_on => {
+ failed.push(json!({"component": comp, "name": cname, "error": e}));
+ warnings.push(format!("{cname} keeps its bodies: {e}"));
+ continue;
+ }
+ Err(e) => return Err(bad(cmd, format!("{cname}: {e}"))),
};
- let old = old.clone();
- link_refused(s.path.as_deref(), &link.path).map_err(|e| bad(cmd, format!("{cname}: {e}")))?;
- let file = resolve(s.path.as_deref(), &link.path);
- let bytes = read_link(&file, s.path.as_deref()).map_err(|e| bad(cmd, format!("{cname}: {e}")))?;
// The link keeps what it read, so opening this design again knows whether the file
// changed while it was closed (#9739).
let read = DesignLink::file_digest(&bytes);
@@ -607,7 +619,19 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
}
continue;
}
- let (_, sf, faces, _, properties) = design_bodies(&file, &bytes).map_err(|e| bad(cmd, format!("{cname}: {e}")))?;
+ let (_, sf, faces, _, properties) = match design_bodies(&file, &bytes) {
+ Ok(read) => read,
+ Err(e) if go_on => {
+ // It keeps its bodies, so it has not taken this file in yet.
+ if let Some(kept) = s.doc_mut().links.get_mut(&comp) {
+ kept.file_sha256.clone_from(&link.file_sha256);
+ }
+ failed.push(json!({"component": comp, "name": cname, "error": e.to_string()}));
+ warnings.push(format!("{cname} keeps its bodies: {e}"));
+ continue;
+ }
+ Err(e) => return Err(bad(cmd, format!("{cname}: {e}"))),
+ };
warnings.extend(sf.warnings.iter().cloned());
let same = matches!(&sf.kind, FeatureKind::Import { step, .. } if *step == old);
let kept = s.doc.feature(link.feature).map(|f| &f.link_faces);
@@ -645,6 +669,11 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
if changed { updated.push(cname) } else { unchanged.push(cname) }
}
solidcraft_doc::progress::item(None);
+ // None could be read: nothing to take back either.
+ if updated.is_empty() && unchanged.is_empty() && !failed.is_empty() {
+ let (name, why) = (failed[0]["name"].as_str().unwrap_or_default(), failed[0]["error"].as_str().unwrap_or_default());
+ return Err(bad(cmd, format!("{name}: {why}")));
+ }
s.refresh();
if let Some(e) = s.doc.links.values().find_map(|l| s.model.result(l.feature).and_then(|r| r.error.clone())) {
return Err(EngineError::Other(e));
@@ -654,7 +683,19 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
let sol = solidcraft_doc::joints::solve(&s.doc, &s.model.state());
warnings.extend(sol.errors.iter().chain(&sol.conflicts).map(|(_, name, why)| format!("joint {name}: {why}")));
}
- Ok(json!({"updated": updated, "unchanged": unchanged, "warnings": warnings}))
+ Ok(json!({"updated": updated, "unchanged": unchanged, "warnings": warnings, "failed": failed}))
+}
+
+/// `comp`'s linked design as it was last read (its bodies) and as its file is now, read before
+/// anything in the design changes.
+fn read_linked(s: &Session, comp: u64, link: &DesignLink) -> std::result::Result<(std::sync::Arc<str>, PathBuf, Vec<u8>), String> {
+ let Some(FeatureKind::Import { step: old, .. }) = s.doc.feature(link.feature).filter(|f| f.component == comp).map(|f| &f.kind) else {
+ return Err(format!("its linked bodies (feature {}) are gone; break the link or insert the design again", link.feature));
+ };
+ link_refused(s.path.as_deref(), &link.path).map_err(|e| e.to_string())?;
+ let file = resolve(s.path.as_deref(), &link.path);
+ let bytes = read_link(&file, s.path.as_deref()).map_err(|e| e.to_string())?;
+ Ok((old.clone(), file, bytes))
}
/// The joints and joint origins on occurrences of `comp` that name its linked faces by their
@@ -997,6 +1038,49 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
+ /// #9743: a list of links is read in one step that goes on past a design it can't read.
+ #[test]
+ fn update_links_given_a_list_reads_them_in_one_step_past_a_design_it_cannot_read() {
+ let dir = std::env::temp_dir().join(format!("solidcraft-link-list-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let (plate, block) = (dir.join("plate.solidcraft"), dir.join("block.solidcraft"));
+ save_box(&plate, 30.0);
+ save_box(&block, 10.0);
+ let mut a = Session::default();
+ let first = run(&mut a, "component.insert_design", json!({"path": plate}))["component"].clone();
+ let second = run(&mut a, "component.insert_design", json!({"path": plate, "translate": [50, 0, 0]}))["component"].clone();
+ let third = run(&mut a, "component.insert_design", json!({"path": block, "translate": [100, 0, 0]}))["component"].clone();
+ assert!((volume(&mut a) - 14000.0).abs() < 1e-6, "{}", volume(&mut a));
+ // Two links to the same changed file come in together, and one Undo takes both back.
+ save_box(&plate, 45.0);
+ let r = run(&mut a, "component.update_links", json!({"components": [first, second]}));
+ assert_eq!((r["updated"].as_array().map(Vec::len), r["failed"].clone()), (Some(2), json!([])), "{r}");
+ assert!((volume(&mut a) - 20000.0).abs() < 1e-6, "{}", volume(&mut a));
+ run(&mut a, "edit.undo", json!({}));
+ assert!((volume(&mut a) - 14000.0).abs() < 1e-6, "{}", volume(&mut a));
+ // A design it can't read keeps its bodies and is named; the others still come in.
+ std::fs::write(&block, b"not a design").unwrap();
+ let r = run(&mut a, "component.update_links", json!({"components": [first, third]}));
+ assert_eq!(r["updated"].as_array().map(Vec::len), Some(1), "{r}");
+ assert_eq!((r["failed"][0]["component"].clone(), r["failed"][0]["name"].clone()), (third.clone(), json!("block")), "{r}");
+ assert!(r["warnings"].as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("block")))), "{r}");
+ assert!((volume(&mut a) - 17000.0).abs() < 1e-6, "{}", volume(&mut a));
+ // Not taken in, it still says its file changed (#9739).
+ let links = run(&mut a, "component.links", json!({}));
+ let block_link = links["links"].as_array().and_then(|l| l.iter().find(|l| l["component"] == third)).cloned();
+ assert_eq!(block_link.map(|l| l["changed"].clone()), Some(json!(true)), "{links}");
+ // None it can read: an error, and nothing to undo.
+ let err = a.execute("component.update_links", &json!({"components": [third]})).unwrap_err().to_string();
+ assert!(err.contains("block"), "{err}");
+ // Malformed lists are refused.
+ for bad in
+ [json!({"components": []}), json!({"components": 3}), json!({"components": [first], "component": first}), json!({"components": ["nope"]})]
+ {
+ assert!(a.execute("component.update_links", &bad).is_err(), "{bad}");
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[test]
fn inserting_a_missing_file_or_bad_parameters_changes_nothing() {
let mut s = Session::default();
diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs
index e4fe198065..b5dc74bdb3 100644
--- a/crates/ui-egui/src/file_load.rs
+++ b/crates/ui-egui/src/file_load.rs
@@ -38,7 +38,7 @@ pub enum Kind {
/// 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`, with the
- /// request's options: `component` reads only that link).
+ /// request's options: `component` or `components` reads only those links).
UpdateLinks,
}
@@ -942,11 +942,16 @@ 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));
+ crate::linked_source::read_again(app, &request.options, &made.result);
let r = Ok(made.result);
app.finish_command(id, &r);
let language = crate::i18n::Locale::for_language(&app.preferences.language);
app.set_status(language.format("ui.command_done", &[("command", language.label(crate::command_label(id)))]), false);
+ // A design it could not read is said as when that was all it was asked.
+ if let Some(f) = r.as_ref().ok().and_then(|v| v["failed"].as_array()).and_then(|f| f.first()) {
+ let (name, why) = (f["name"].as_str().unwrap_or_default(), f["error"].as_str().unwrap_or_default());
+ app.set_status(format!("{name}: {why}"), true);
+ }
request.answer(r);
}
Ok(_) if reuse_open(app, request) => {}
diff --git a/crates/ui-egui/src/linked_source.rs b/crates/ui-egui/src/linked_source.rs
index b83bdecfaa..b3c39c22bb 100644
--- a/crates/ui-egui/src/linked_source.rs
+++ b/crates/ui-egui/src/linked_source.rs
@@ -3,7 +3,7 @@
use std::sync::Arc;
-use serde_json::json;
+use serde_json::{Value, json};
use crate::SolveApp;
@@ -94,7 +94,7 @@ pub(crate) fn extract(app: &mut SolveApp, component: u64) {
}
/// The status line after a command: `done`, then its warnings and notices.
-fn report(app: &mut SolveApp, result: &serde_json::Value, done: &str) {
+fn report(app: &mut SolveApp, result: &Value, done: &str) {
let notes: Vec<&str> =
["warnings", "notices"].iter().flat_map(|k| result[*k].as_array().into_iter().flatten()).filter_map(|w| w.as_str()).collect();
if notes.is_empty() {
@@ -180,9 +180,9 @@ pub(crate) fn note_unread(app: &mut SolveApp) {
}
/// The shown design came back to its tab, or was just opened: 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.
+/// as Update Links does, the linked designs whose files changed since it last read them. All in
+/// one run, so they come in as one undo step (#9743); one that cannot be read holds up no other,
+/// keeps its bodies and is tried again next time.
pub(crate) fn update_changed(app: &mut SolveApp) {
let now = disk_stamps(app);
// Links met here for the first time: those whose files changed since the design last read
@@ -199,20 +199,26 @@ pub(crate) fn update_changed(app: &mut SolveApp) {
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);
+ // No room to wait: they are still changed when the tab next comes back.
+ if changed.is_empty() || app.file_load.room() == 0 {
+ return;
}
+ let mut request = crate::file_load::Request::new("", crate::file_load::Kind::UpdateLinks);
+ request.options.insert("components".into(), json!(changed));
+ 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)) {
+/// Update Links (`options` as it was asked) read the shown design's links again: those it read
+/// without an error (`result`'s `failed` names the others) are now as their files are.
+pub(crate) fn read_again(app: &mut SolveApp, options: &serde_json::Map<String, Value>, result: &Value) {
+ let asked: Option<Vec<u64>> = match (options.get("component"), options.get("components")) {
+ (Some(c), _) => Some(c.as_u64().into_iter().collect()),
+ (None, Some(list)) => Some(list.as_array().into_iter().flatten().filter_map(Value::as_u64).collect()),
+ (None, None) => None,
+ };
+ let failed: Vec<u64> = result["failed"].as_array().into_iter().flatten().filter_map(|f| f["component"].as_u64()).collect();
+ for (c, s) in disk_stamps(app).into_iter().filter(|(c, _)| asked.as_ref().is_none_or(|a| a.contains(c)) && !failed.contains(c)) {
record(&mut app.docs.link_stamps, c, s);
}
}
@@ -562,6 +568,24 @@ mod tests {
let _ = std::fs::remove_dir_all(folder);
}
+ /// #9743: the links that changed while the tab was away come back as one undo step.
+ #[test]
+ fn links_to_a_changed_design_come_back_together_and_one_undo_takes_them_back() {
+ let (mut app, folder, plate, cube) = two_links("one-step");
+ app.run("component.insert_design", json!({"path": plate, "translate": [0, 100, 0]})).unwrap();
+ app.run("file.save", json!({})).unwrap();
+ assert!((volume(&app) - 13000.0).abs() < 1e-6, "{}", volume(&app));
+ crate::documents::switch(&mut app, 1);
+ 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, 0);
+ settle(&mut app);
+ assert!((volume(&app) - 13750.0).abs() < 1e-6, "{}", volume(&app));
+ assert_eq!(app.run("edit.undo", json!({})).unwrap()["undone"], "Update Links");
+ assert!((volume(&app) - 13000.0).abs() < 1e-6, "every copy of the part goes back together: {}", volume(&app));
+ 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");
diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md
index f5b11c5e57..59a5a82f96 100644
--- a/docs/book/src/guide/assemblies.md
+++ b/docs/book/src/guide/assemblies.md
@@ -387,7 +387,8 @@ part file. The link is stored relative to the assembly's folder once the assembl
After the part file changes, **Update Links** (`component.update_links`) reads it again.
An assembly that opens, or 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.
+a checkout. The parts it reads come in as one step, so one **Undo** takes them all back. A part
+that cannot be read keeps its bodies, 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