Keep linked components valid through Undo after Save As (#6860) (#6877)

* claim: #6860

* fix: preserve linked component targets across Save As history (#6860)
This commit is contained in:
Colin Faulkingham authored and GitHub committed 2026-10-26 11:08:32 +00:00
1 parent 25ad6c7266
commit 03bf992bc1
8 files changed
+183 -44

No files matched your search

+2 -3
View File
@@ -262,8 +262,7 @@ fn load_checked(path: &str, check: solidcraft_engine::schema::ParamCheck) -> Res
let bytes = solidcraft_engine::io::vfs::read(path, solidcraft_engine::io::MAX_DESIGN_BYTES).map_err(|e| format!("{path}: {e}"))?;
if solidcraft_engine::io::is_design_container(&bytes) {
let doc = solidcraft_engine::io::read_design(&bytes).map_err(|e| format!("{path}: {e}"))?;
let mut session = Session::new(doc);
session.path = Some(path.to_owned());
let mut session = Session::opened_at(doc, None, Some(path));
session.param_check = check;
return Ok(session);
}
@@ -845,7 +844,7 @@ pub(crate) fn cmd_bench_open(args: &[String]) -> Result<(), String> {
return Ok(());
}
let t = std::time::Instant::now();
let s = Session::opened(doc, saved.as_ref());
let s = Session::opened_at(doc, saved.as_ref(), (!step).then_some(path.as_str()));
drop(read);
// Taken from the file: nothing evaluated (SOLIDCRAFT_NO_MODEL_CACHE evaluates anyway), or
// only the features whose state a thinned file left out.
+12
View File
@@ -448,6 +448,18 @@ pub fn recovery_path() -> String {
format!("{OPFS}{RECOVERY}")
}
/// A recovery file lives in OPFS, but its relative links belong to the original design's
/// folder (which can be on disk). Resolve them before Open sees the temporary file location.
pub fn prepare_recovery(original_path: Option<&str>) -> Result<String, String> {
let path = recovery_path();
let bytes = vfs::read(&path, solidcraft_engine::io::MAX_DESIGN_BYTES).map_err(|e| e.to_string())?;
let mut doc = solidcraft_engine::io::read_design(&bytes).map_err(|e| e.to_string())?;
solidcraft_engine::resolve_design_links(&mut doc, original_path);
let bytes = solidcraft_engine::io::write_design_container(&doc).map_err(|e| e.to_string())?;
vfs::insert(&path, bytes);
Ok(path)
}
/// Pick files on the computer: the File System Access picker where there is one, else an
/// `<input type=file>`. Read files arrive in `files.incoming`.
pub fn pick_from_disk(files: &Rc<Files>, intent: Intent) {
+12 -2
View File
@@ -498,15 +498,25 @@ mod web {
});
});
let Some(recover) = answer else { return };
*self.files.recovery.borrow_mut() = None;
if recover {
self.app.open_path(&files::recovery_path());
let recovery = match files::prepare_recovery(path.as_deref()) {
Ok(recovery) => recovery,
Err(error) => {
self.app.set_status(error, true);
return;
}
};
self.app.open_path(&recovery);
if self.app.session.path.as_deref() != Some(recovery.as_str()) {
return;
}
// It belongs to its own file again (saving goes there); it is unsaved.
self.app.session.path = path;
self.app.session.doc_mut().name = name;
self.app.session.mark_unsaved();
self.app.home.open = false;
}
*self.files.recovery.borrow_mut() = None;
files::autosave(&self.files, None);
}
+1 -1
View File
@@ -592,7 +592,7 @@ pub(super) fn extract(s: &mut Session, p: &Value) -> Result<Value> {
f.link_faces = faces;
}
let path = stored(s.path.as_deref(), &file);
s.doc_mut().links.insert(comp, DesignLink { path: path.clone(), feature: id });
s.doc_mut().links.insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), feature: id });
s.refresh();
rename_joint_faces(s, &state, id, &sc.own);
if let Some(e) = s.model.result(id).and_then(|r| r.error.clone()) {
+108 -9
View File
@@ -2,9 +2,9 @@
//!
//! The linked design is opened and evaluated on its own, and its solid bodies, as placed in it,
//! join a new component through an Import feature (exact B-rep, kept in this design so it opens
//! without the part file). The link remembers the file, relative to this design's folder once it
//! is saved; Update Links reads the file again and replaces the Import feature's bodies, and
//! Break Link keeps the bodies and forgets the file. The bodies' faces are named after the names
//! without the part file). The link remembers the absolute file in a session and a path relative
//! to the design's folder on disk; Update Links reads it again and replaces the Import feature's
//! bodies, and Break Link keeps the bodies and forgets the file. The bodies' faces are named after the names
//! the design gives them (`Feature::link_faces`), so a joint on a linked face stays on that face
//! when the design changes, as it would inside the design, and reports it when the face is gone.
@@ -124,6 +124,14 @@ pub(super) fn rebased(doc: &Document, from: Option<&str>, to: &str) -> std::coll
doc.links.iter().map(|(c, l)| (*c, DesignLink { path: stored(Some(to), &resolve(from, &l.path)), feature: l.feature })).collect()
}
/// Resolve a design's component links against its original file, before opening it from a
/// different location (for example a recovery file) or keeping it in session history.
pub fn resolve_design_links(doc: &mut Document, from: Option<&str>) {
for link in doc.links.values_mut() {
link.path = absolute(&resolve(from, &link.path)).to_string_lossy().into_owned();
}
}
/// The bodies of a linked design: its name, the Import feature that holds them and the names
/// the design gives their faces (`Feature::link_faces`).
type Linked = (String, solidcraft_io::StepFeature, Vec<Vec<String>>);
@@ -136,7 +144,7 @@ fn linked_bodies(file: &Path, own: Option<&str>) -> Result<Linked> {
}
let bytes = solidcraft_io::vfs::read(&shown, solidcraft_io::MAX_DESIGN_BYTES).map_err(|e| EngineError::Other(format!("{shown}: {e}")))?;
let doc = solidcraft_io::read_design(&bytes).map_err(|e| EngineError::Other(format!("{shown}: {e}")))?;
session_bodies(&Session::new(doc), &shown)
session_bodies(&Session::opened_at(doc, None, Some(&shown)), &shown)
}
/// The solid bodies of `part`, the design saved as `shown`, as an Import feature.
@@ -212,7 +220,7 @@ fn insert_design(s: &mut Session, p: &Value) -> Result<Value> {
o.transform[3] = [translate.x, translate.y, translate.z, 1.0];
}
let path = stored(s.path.as_deref(), &file);
s.doc_mut().links.insert(comp, DesignLink { path: path.clone(), feature: id });
s.doc_mut().links.insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), feature: id });
s.refresh();
if let Some(e) = s.model.result(id).and_then(|r| r.error.clone()) {
return Err(EngineError::Other(e));
@@ -354,7 +362,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
f.kind = sf.kind;
f.link_faces = faces;
}
s.doc_mut().links.insert(comp, DesignLink { path: path.clone(), feature: link.feature });
s.doc_mut().links.insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), 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));
@@ -367,7 +375,8 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
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,
let previous_path = stored(s.path.as_deref(), &resolve(s.path.as_deref(), &link.path));
Ok(json!({"component": comp, "feature": link.feature, "path": path, "previous_path": previous_path, "geometry_changed": geometry_changed,
"warnings": warnings, "joint_errors": diagnostics(&sol.errors), "joint_conflicts": diagnostics(&sol.conflicts)}))
}
@@ -375,7 +384,7 @@ fn break_link(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "component.break_link";
let comp = component_key(s, p, "component", cmd)?;
let link = s.doc_mut().links.remove(&comp).ok_or_else(|| bad(cmd, "that component is not linked to a design"))?;
Ok(json!({"component": comp, "path": link.path}))
Ok(json!({"component": comp, "path": stored(s.path.as_deref(), &resolve(s.path.as_deref(), &link.path))}))
}
fn list_links(s: &mut Session, _p: &Value) -> Result<Value> {
@@ -386,8 +395,9 @@ fn list_links(s: &mut Session, _p: &Value) -> Result<Value> {
.map(|(c, l)| {
let file = resolve(s.path.as_deref(), &l.path);
let name = s.doc.components.iter().find(|x| x.id == *c).map(|x| x.name.clone());
let path = stored(s.path.as_deref(), &file);
let file = file.to_string_lossy();
json!({"component": c, "name": name, "path": l.path, "file": file, "found": solidcraft_io::vfs::is_file(&file)})
json!({"component": c, "name": name, "path": path, "file": file, "found": solidcraft_io::vfs::is_file(&file)})
})
.collect();
Ok(json!({"links": links}))
@@ -436,6 +446,95 @@ mod tests {
run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN)
}
/// #6860: Save As changes the file's folder, not the targets kept in the edit history.
#[test]
fn save_as_keeps_link_targets_through_undo_redo_and_checkpoints() {
for on_copy in [false, true] {
let dir = std::env::temp_dir().join(format!("solidcraft-link-save-as-{}-{on_copy}", std::process::id()));
std::fs::create_dir_all(dir.join("parts")).unwrap();
std::fs::create_dir_all(dir.join("asm/sub/deeper")).unwrap();
let part = dir.join("parts/plate.solidcraft");
let case = dir.join("asm/case.solidcraft");
save_box(&part, 30.0);
let mut s = Session::default();
run(&mut s, "component.insert_design", json!({"path": part}));
run(&mut s, "file.save", json!({"path": case}));
// Opening starts from the relative paths actually written to disk.
run(&mut s, "doc.open", json!({"path": case}));
run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [60, 0, 0]}));
let checkpoint = s.checkpoint();
run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [80, 0, 0]}));
run(&mut s, "edit.undo", json!({}));
let before = s.doc.clone();
let undo_before = s.undo.last().unwrap().doc.clone();
let missing = dir.join("missing/case.solidcraft");
assert!(s.execute("file.save_as", &json!({"path": missing})).is_err());
assert_eq!(s.path.as_deref(), case.to_str());
for folder in ["asm/sub", "asm/sub/deeper"] {
let path = dir.join(folder).join("case.solidcraft");
if on_copy {
let mut copy = s.scratch();
run(&mut copy, "file.save_as", json!({"path": path}));
s.adopt_save(&copy);
} else {
run(&mut s, "file.save_as", json!({"path": path}));
}
assert!(!s.is_dirty());
for command in ["edit.redo", "edit.undo", "edit.undo", "edit.redo"] {
run(&mut s, command, json!({}));
let links = run(&mut s, "component.links", json!({}));
assert_eq!(links["links"][0]["found"], true, "{on_copy}, {folder}, {command}: {links}");
assert_eq!(absolute(Path::new(links["links"][0]["file"].as_str().unwrap())), absolute(&part));
}
}
assert!(std::sync::Arc::ptr_eq(&s.doc, &before), "saving does not rewrite the live document");
assert!(std::sync::Arc::ptr_eq(&s.undo.last().unwrap().doc, &undo_before), "saving does not copy the edit history");
s.restore_checkpoint(checkpoint).unwrap();
assert_eq!(run(&mut s, "component.links", json!({}))["links"][0]["found"], true);
let path = s.path.clone().unwrap();
for format in ["json", "container"] {
run(&mut s, "file.save", json!({"format": format}));
let disk = solidcraft_io::read_design(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(disk.links.values().next().unwrap().path, "../../../parts/plate.solidcraft");
run(&mut s, "doc.open", json!({"path": path}));
assert!(!s.is_dirty());
assert_eq!(run(&mut s, "component.links", json!({}))["links"][0]["found"], true);
}
save_box(&part, 45.0);
assert_eq!(run(&mut s, "component.update_links", json!({}))["updated"], json!(["plate"]));
assert!((volume(&mut s) - 9125.0).abs() < 1e-6);
let _ = std::fs::remove_dir_all(&dir);
}
}
#[test]
fn recovered_relative_links_keep_their_targets_after_save_as() {
let dir = std::env::temp_dir().join(format!("solidcraft-link-recovery-{}", std::process::id()));
std::fs::create_dir_all(dir.join("parts")).unwrap();
std::fs::create_dir_all(dir.join("asm/sub")).unwrap();
let part = dir.join("parts/plate.solidcraft");
save_box(&part, 30.0);
let mut s = Session::default();
run(&mut s, "component.insert_design", json!({"path": part}));
run(&mut s, "file.save", json!({"path": dir.join("asm/case.solidcraft")}));
run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [60, 0, 0]}));
let recovery = dir.join("recovery");
let mut autosaver = crate::recovery::Autosaver::new(&recovery, std::time::Duration::ZERO).unwrap();
assert!(autosaver.save(&s).unwrap());
drop(autosaver);
let entry = crate::recovery::orphans(&recovery).pop().unwrap();
// Older autosaves hold paths relative to the design, not the recovery folder.
std::fs::write(recovery.join(format!("{}.solidcraft", entry.id)), solidcraft_io::write_design(&s.design())).unwrap();
let mut recovered = Session::default();
run(&mut recovered, "doc.recover", json!({"dir": recovery, "id": entry.id}));
assert_eq!(run(&mut recovered, "component.links", json!({}))["links"][0]["found"], true);
run(&mut recovered, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [80, 0, 0]}));
run(&mut recovered, "file.save_as", json!({"path": dir.join("asm/sub/case.solidcraft")}));
run(&mut recovered, "edit.undo", json!({}));
assert_eq!(run(&mut recovered, "component.links", json!({}))["links"][0]["found"], true);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_saved_assembly_reopens_with_its_link_updates_it_and_breaks_it() {
let dir = std::env::temp_dir().join(format!("solidcraft-link-reopen-{}", std::process::id()));
+41 -21
View File
@@ -304,8 +304,7 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(stem) = default_name_for(&doc.name, path) {
doc.name = stem;
}
s.replace_design(Session::opened(doc, saved.as_ref()));
s.path = Some(path.to_string());
s.replace_design(Session::opened_at(doc, saved.as_ref(), Some(path)));
s.disk = disk;
s.read_only = read_only;
let errors = s.model.results.iter().filter(|r| r.error.is_some()).count();
@@ -402,16 +401,7 @@ fn write_file(s: &mut Session, path: &str, format: &str, compression: &str, prev
"compact" => solidcraft_io::DesignCompression::Compact,
_ => return Err(bad("file.save", "compression must be fast or compact")),
};
// Linked designs are kept relative to the folder the design is saved in.
let links = super::component_link::rebased(&s.doc, s.path.as_deref(), path);
let old_links = (links != s.doc.links).then(|| std::mem::replace(&mut s.doc_mut().links, links));
let r = write_bytes(s, path, format, compression, preview, cache);
if r.is_err()
&& let Some(old) = old_links
{
s.doc_mut().links = old;
}
r
write_bytes(s, path, format, compression, preview, cache)
}
fn write_bytes(
@@ -423,8 +413,8 @@ fn write_bytes(
cache: bool,
) -> Result<Value> {
let bytes = match format {
"container" => s.design_container(compression, preview, cache)?,
"json" => solidcraft_io::write_design(&s.design()),
"container" => s.design_container_at(Some(path), compression, preview, cache)?,
"json" => solidcraft_io::write_design(&s.design_at(Some(path))),
_ => return Err(bad("file.save", "format must be container or json")),
};
// Atomic, keeping the version being replaced as `<file>.bak`.
@@ -437,18 +427,39 @@ fn write_bytes(
}
impl Session {
/// Open a design with its file location, resolving component links before history keeps
/// them. Absolute in-memory targets survive Save As, undo, redo and recovery unchanged.
pub fn opened_at(mut doc: Document, saved: Option<&solidcraft_doc::SavedModel>, path: Option<&str>) -> Self {
super::component_link::resolve_design_links(&mut doc, path);
let mut session = Self::opened(doc, saved);
session.path = path.map(str::to_owned);
session
}
/// Prepare only the file's copy with relative paths; saving never rewrites live history.
pub(crate) fn design_at(&self, path: Option<&str>) -> std::borrow::Cow<'_, Document> {
let mut design = std::borrow::Cow::Borrowed(&*self.doc);
if let Some(path) = path {
let links = super::component_link::rebased(&self.doc, self.path.as_deref(), path);
if links != self.doc.links {
design.to_mut().links = links;
}
}
if !self.visibility.is_empty() {
design.to_mut().visibility = self.visibility.clone();
}
design
}
/// Take up a save that ran on `done`, a [`Session::scratch`] copy of this session that
/// `file.save` or `file.save_as` ran on (on another thread, so the window keeps drawing)
/// while this one did not change: the name and link paths the save gave the design, its
/// while this one did not change: the name the save gave the design, its
/// file, and its saved state, as running the command here would have left them.
pub fn adopt_save(&mut self, done: &Session) {
if done.doc.name != self.doc.name {
let (from, to) = (self.doc.name.clone(), done.doc.name.clone());
rename_design(self, &from, &to);
}
if done.doc.links != self.doc.links {
self.doc_mut().links.clone_from(&done.doc.links);
}
self.path.clone_from(&done.path);
self.disk = done.disk;
self.read_only = done.read_only;
@@ -467,7 +478,17 @@ impl Session {
/// Container bytes for desktop and browser saves. Only already evaluated bodies
/// and warm meshes are eligible; saving never forces evaluation or tessellation.
pub fn design_container(&self, compression: solidcraft_io::DesignCompression, preview: bool, cache: bool) -> solidcraft_io::Result<Vec<u8>> {
let design = self.design();
self.design_container_at(self.path.as_deref(), compression, preview, cache)
}
fn design_container_at(
&self,
path: Option<&str>,
compression: solidcraft_io::DesignCompression,
preview: bool,
cache: bool,
) -> solidcraft_io::Result<Vec<u8>> {
let design = self.design_at(path);
let geometry = cache.then(|| saved_geometry(self, &design)).flatten();
let preview = preview.then(|| saved_preview(self)).flatten();
let thumbnail = cache.then(|| thumbnail::saved(self)).flatten();
@@ -708,8 +729,7 @@ fn recover(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(stem) = entry.path.as_deref().and_then(|path| default_name_for(&doc.name, path)) {
doc.name = stem;
}
s.replace_design(Session::new(doc));
s.path = entry.path.clone();
s.replace_design(Session::opened_at(doc, None, entry.path.as_deref()));
s.mark_unsaved();
if bool_(p, "discard").unwrap_or(false) {
crate::recovery::remove(&dir, id)?;
+1
View File
@@ -44,6 +44,7 @@ pub use sketch_modify::{extend_arc_preview, extend_preview, trim_piece};
pub use view_dxf::sketch::exportable as view_dxf_exportable;
pub use view_navigation::standard_view;
mod component_link;
pub use component_link::resolve_design_links;
mod config;
mod file;
mod frame;
+6 -8
View File
@@ -38,7 +38,7 @@ use serde_json::Value;
use solidcraft_doc::{Document, Model, ModelState};
use solidcraft_geom::Vec3;
pub use cmd::{CommandInfo, CommandSpec, auto_operation, command_specs, extrude_reach, find_command, standard_view};
pub use cmd::{CommandInfo, CommandSpec, auto_operation, command_specs, extrude_reach, find_command, resolve_design_links, standard_view};
pub use solidcraft_doc as doc;
pub use solidcraft_doc::Visibility;
pub use solidcraft_geom as geom;
@@ -444,12 +444,15 @@ impl Default for Session {
}
impl Session {
/// A session on an in-memory document. For a document read from a file, use
/// [`Self::opened_at`] so relative component links are resolved against that file.
pub fn new(doc: Document) -> Self {
Self::opened(doc, None)
}
/// A session on `doc` whose evaluation is the model its file kept (`saved`), when that is
/// `doc`'s evaluation ([`Model::adopt`]); otherwise the timeline is evaluated.
/// Use [`Self::opened_at`] when the document's file location is known.
/// `SOLIDCRAFT_NO_MODEL_CACHE` set always evaluates.
pub fn opened(mut doc: Document, saved: Option<&solidcraft_doc::SavedModel>) -> Self {
// The session keeps what is hidden (an undo step of its own); the design file carries it.
@@ -608,14 +611,9 @@ impl Session {
Ok(())
}
/// The design as a file holds it: the document with what is hidden in it.
/// The design as its current file holds it, including visibility and relative link paths.
pub fn design(&self) -> std::borrow::Cow<'_, Document> {
if self.visibility.is_empty() {
return std::borrow::Cow::Borrowed(&*self.doc);
}
let mut doc = (*self.doc).clone();
doc.visibility = self.visibility.clone();
std::borrow::Cow::Owned(doc)
self.design_at(self.path.as_deref())
}
/// The design has changes not in its file (a recovered design).
pub fn mark_unsaved(&mut self) {