SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Engine: one module for the design-link path helpers (no behaviour change) (#5420)
CarelT13f650b69529
diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rsindex 7fd4cb5fc6..011c6b8316 100644--- a/crates/engine/src/cmd/component_link.rs+++ b/crates/engine/src/cmd/component_link.rs@@ -8,12 +8,13 @@//! 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.-use std::path::{Component as PathPart, Path, PathBuf};+use std::path::Path;use serde_json::{Value, json};use solidcraft_doc::{DesignLink, Document, FeatureKind};use super::CommandSpec;+use super::design_link::{absolute, resolve, stored};use crate::params::{bad, str_, vec3};use crate::{EngineError, Result, Session};@@ -60,65 +61,6 @@ pub static COMMANDS: &[CommandSpec] = &[),];-/// The folder relative link paths are kept against: the design's own, once it has a file.-fn base_dir(path: Option<&str>) -> Option<PathBuf> {- path.and_then(|p| absolute(Path::new(p)).parent().map(Path::to_path_buf))-}--/// A path as given, made absolute when the platform can, with `.` and `..` worked out.-fn absolute(p: &Path) -> PathBuf {- let full = std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf());- let mut out = PathBuf::new();- for c in full.components() {- match c {- PathPart::CurDir => {}- PathPart::ParentDir if matches!(out.components().next_back(), Some(PathPart::Normal(_))) => {- out.pop();- }- c => out.push(c.as_os_str()),- }- }- out-}--/// `target` relative to the folder `base` (both absolute), when they share a root.-fn relative(base: &Path, target: &Path) -> Option<PathBuf> {- let (b, t): (Vec<_>, Vec<_>) = (base.components().collect(), target.components().collect());- let root = |c: &[PathPart]| c.iter().take_while(|x| matches!(x, PathPart::Prefix(_) | PathPart::RootDir)).count();- if root(&b) == 0 || b.get(..root(&b)) != t.get(..root(&b)) {- return None;- }- let common = b.iter().zip(&t).take_while(|(x, y)| x == y).count();- let mut out = PathBuf::new();- for _ in common..b.len() {- out.push("..");- }- for c in t.iter().skip(common) {- out.push(c.as_os_str());- }- Some(out)-}--/// How a link stores `file` for a design saved at `design` (`None`: not saved yet).-fn stored(design: Option<&str>, file: &Path) -> String {- let file = absolute(file);- match base_dir(design).and_then(|d| relative(&d, &file)) {- // Relative paths are written with `/`, so a design moves between systems with its parts.- Some(rel) => rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect::<Vec<_>>().join("/"),- None => file.to_string_lossy().into_owned(),- }-}--/// The file a stored link path names, for a design saved at `design`.-fn resolve(design: Option<&str>, link: &str) -> PathBuf {- let p = Path::new(link);- match base_dir(design) {- // Browser storage keys do not let the OS resolve `..` for us.- Some(d) if p.is_relative() => absolute(&d.join(p)),- _ => p.to_path_buf(),- }-}-/// Why the file a stored link names may not be reached, from its text alone (`None`: it may): a/// device, or a network location not allowed (`vfs::design_path_refusal`). Both the link as/// stored and the file it resolves to are judged, before anything asks the disk or the network.@@ -134,11 +76,6 @@ fn link_refused(design: Option<&str>, link: &str) -> Result<()> {solidcraft_io::vfs::check_design_path(&file.to_string_lossy(), design).map_err(|e| EngineError::Other(e.to_string()))}-/// The links of `doc` stored for a design saved at `to` instead of at `from`.-pub(super) fn rebased(doc: &Document, from: Option<&str>, to: &str) -> std::collections::BTreeMap<u64, DesignLink> {- 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>) {@@ -446,30 +383,6 @@ fn list_links(s: &mut Session, _p: &Value) -> Result<Value> {mod tests {use super::*;- #[test]- fn link_paths_are_kept_relative_to_the_design_and_follow_save_as() {- let root = absolute(Path::new("projects"));- let part = root.join("parts").join("plate.solidcraft");- let design = root.join("assembly").join("case.solidcraft");- let design = design.to_string_lossy().into_owned();- assert_eq!(stored(Some(&design), &part), "../parts/plate.solidcraft");- assert_eq!(resolve(Some(&design), "../parts/plate.solidcraft"), part);- // A design path given relative to the working folder works the same.- assert_eq!(stored(Some("case.solidcraft"), &absolute(Path::new("parts/plate.solidcraft"))), "parts/plate.solidcraft");- // Before the design has a file the path is kept whole; saving it makes it relative.- let unsaved = stored(None, &part);- assert!(Path::new(&unsaved).is_absolute(), "{unsaved}");- let mut doc = Document::default();- doc.links.insert(7, DesignLink { path: unsaved, feature: 3 });- let moved = rebased(&doc, None, &design);- assert_eq!(moved.get(&7).map(|l| l.path.as_str()), Some("../parts/plate.solidcraft"));- let beside = root.join("parts").join("asm.solidcraft").to_string_lossy().into_owned();- assert_eq!(- rebased(&Document { links: moved, ..Document::default() }, Some(&design), &beside).get(&7).map(|l| l.path.as_str()),- Some("plate.solidcraft")- );- }-fn run(s: &mut Session, id: &str, p: Value) -> Value {s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))}diff --git a/crates/engine/src/cmd/design_link.rs b/crates/engine/src/cmd/design_link.rsnew file mode 100644index 0000000000..8844a37a04--- /dev/null+++ b/crates/engine/src/cmd/design_link.rs@@ -0,0 +1,102 @@+//! Links from a design to other design files (Insert Design's linked components, and the kinds of+//! link to come): where a link keeps its file and how it finds it again. A link keeps the file+//! relative to the linking design's folder once that design is saved, so a folder of designs can+//! move together; before the design has a file the path is kept whole.++use std::path::{Component as PathPart, Path, PathBuf};++use solidcraft_doc::{DesignLink, Document};++/// The folder relative link paths are kept against: the design's own, once it has a file.+fn base_dir(path: Option<&str>) -> Option<PathBuf> {+ path.and_then(|p| absolute(Path::new(p)).parent().map(Path::to_path_buf))+}++/// A path as given, made absolute when the platform can, with `.` and `..` worked out.+pub(super) fn absolute(p: &Path) -> PathBuf {+ let full = std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf());+ let mut out = PathBuf::new();+ for c in full.components() {+ match c {+ PathPart::CurDir => {}+ PathPart::ParentDir if matches!(out.components().next_back(), Some(PathPart::Normal(_))) => {+ out.pop();+ }+ c => out.push(c.as_os_str()),+ }+ }+ out+}++/// `target` relative to the folder `base` (both absolute), when they share a root.+fn relative(base: &Path, target: &Path) -> Option<PathBuf> {+ let (b, t): (Vec<_>, Vec<_>) = (base.components().collect(), target.components().collect());+ let root = |c: &[PathPart]| c.iter().take_while(|x| matches!(x, PathPart::Prefix(_) | PathPart::RootDir)).count();+ if root(&b) == 0 || b.get(..root(&b)) != t.get(..root(&b)) {+ return None;+ }+ let common = b.iter().zip(&t).take_while(|(x, y)| x == y).count();+ let mut out = PathBuf::new();+ for _ in common..b.len() {+ out.push("..");+ }+ for c in t.iter().skip(common) {+ out.push(c.as_os_str());+ }+ Some(out)+}++/// How a link stores `file` for a design saved at `design` (`None`: not saved yet).+pub(super) fn stored(design: Option<&str>, file: &Path) -> String {+ let file = absolute(file);+ match base_dir(design).and_then(|d| relative(&d, &file)) {+ // Relative paths are written with `/`, so a design moves between systems with its parts.+ Some(rel) => rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect::<Vec<_>>().join("/"),+ None => file.to_string_lossy().into_owned(),+ }+}++/// The file a stored link path names, for a design saved at `design`.+pub(super) fn resolve(design: Option<&str>, link: &str) -> PathBuf {+ let p = Path::new(link);+ match base_dir(design) {+ // Browser storage keys do not let the OS resolve `..` for us.+ Some(d) if p.is_relative() => absolute(&d.join(p)),+ _ => p.to_path_buf(),+ }+}++/// The links of `doc` stored for a design saved at `to` instead of at `from`.+pub(super) fn rebased(doc: &Document, from: Option<&str>, to: &str) -> std::collections::BTreeMap<u64, DesignLink> {+ doc.links.iter().map(|(c, l)| (*c, DesignLink { path: stored(Some(to), &resolve(from, &l.path)), feature: l.feature })).collect()+}++#[cfg(test)]+#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]+mod tests {+ use super::*;++ #[test]+ fn link_paths_are_kept_relative_to_the_design_and_follow_save_as() {+ let root = absolute(Path::new("projects"));+ let part = root.join("parts").join("plate.solidcraft");+ let design = root.join("assembly").join("case.solidcraft");+ let design = design.to_string_lossy().into_owned();+ assert_eq!(stored(Some(&design), &part), "../parts/plate.solidcraft");+ assert_eq!(resolve(Some(&design), "../parts/plate.solidcraft"), part);+ // A design path given relative to the working folder works the same.+ assert_eq!(stored(Some("case.solidcraft"), &absolute(Path::new("parts/plate.solidcraft"))), "parts/plate.solidcraft");+ // Before the design has a file the path is kept whole; saving it makes it relative.+ let unsaved = stored(None, &part);+ assert!(Path::new(&unsaved).is_absolute(), "{unsaved}");+ let mut doc = Document::default();+ doc.links.insert(7, DesignLink { path: unsaved, feature: 3 });+ let moved = rebased(&doc, None, &design);+ assert_eq!(moved.get(&7).map(|l| l.path.as_str()), Some("../parts/plate.solidcraft"));+ let beside = root.join("parts").join("asm.solidcraft").to_string_lossy().into_owned();+ assert_eq!(+ rebased(&Document { links: moved, ..Document::default() }, Some(&design), &beside).get(&7).map(|l| l.path.as_str()),+ Some("plate.solidcraft")+ );+ }+}diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rsindex 739b90a8d3..02c6e4e279 100644--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@ -458,7 +458,7 @@ impl Session {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);+ let links = super::design_link::rebased(&self.doc, self.path.as_deref(), path);if links != self.doc.links {design.to_mut().links = links;}diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex 553854dea6..cf4e472072 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -46,6 +46,7 @@ pub use view_navigation::standard_view;mod component_link;pub use component_link::resolve_design_links;mod config;+mod design_link;mod file;mod frame;pub(crate) mod inspect;