Thanks @amolinari-autotex.
This commit is contained in:
committed by
GitHub
parent
852d364d5f
commit
aaa35a94d8
@@ -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<Value> {
|
||||
Ok(json!({"updated": updated, "unchanged": unchanged, "warnings": warnings}))
|
||||
}
|
||||
|
||||
fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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::<Vec<_>>();
|
||||
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<Value> {
|
||||
let cmd = "component.break_link";
|
||||
let comp = component_key(s, p, "component", cmd)?;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
Reference in New Issue
Block a user