From d6d6c7d9ee020cb4859210c859844f654fff1295 Mon Sep 17 00:00:00 2001 From: N3MI-DG <129717180+N3MI-DG@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:31:09 +0000 Subject: [PATCH] Copy and paste bodies and components between designs (#3511) (#3512) * Components: copy and paste bodies and components between designs and components (#3390) Squashed for the rebase onto main. Co-Authored-By: Claude Opus 5.5 * claim: #3511 Co-Authored-By: Claude Opus 5.5 * Paste New: copy from a design other than the one pasted into `component_clone::paste` read the design it copies from through the session it pastes into. `build` now takes the source (document, evaluated model, unapplied moves) apart from the target session; Paste New within one design passes the session as both, as before. Names are numbered against the target's names. From another design (`Source::copied`, a `ForeignCopy` snapshot taken at copy time): - names are kept where the target doesn't have them, else numbered; - the user parameters the copy uses come along, `w_2` where the target has a `w`, with the copied expressions following; - a copy whose features use what isn't in it (bodies, sketches, faces, parameters outside it) is refused with a list of what; `FeatureKind::input_bodies` lists the bodies a feature uses; - configurations stay with their design, and the target's timeline marker must be at the end; - a body moved in from outside comes as an imported base named `BodyImport1`. Body transfers are pointed at the copy's components before they are added: `add_feature` checks that the components they name exist, which another design's don't. Co-Authored-By: Claude Opus 5.5 * Engine: paste bodies and components copied in another design `component.paste_from_design` pastes what `Session::foreign_copy` holds, at the same world coordinates as in its design, into the active component or `component` (placed by `component_path`; a component placed more than once gets it in every instance), as one step to undo: - bodies as imported bodies, without their history, in one Import feature (named as any import is, "Import1"); a body seen in another placement ("Cube (B:2)") pastes as "Cube"; names the target has are numbered; - components as independent copies (Paste New from the snapshot): with their history, appearances, materials, joints and motion inside them; joints to the outside stay behind. Tests: bodies (position, naming, target component, undo; a body of another placement) and components (history, appearances, a part placed twice, editing independently, save and reopen, undo; user parameters renamed; refused when using a body outside it; bodies moved in). Co-Authored-By: Claude Opus 5.5 * Clipboard: copy in one design, paste in another Copying or cutting bodies or components also keeps a snapshot of them (`ForeignCopy`); another tab pastes it with `component.paste_from_design`: bodies as imported bodies, components as independent copies (Paste and Paste New alike), folded and selected. Cut pastes as a copy there, the original staying; Esc on the cut leaves nothing to paste anywhere. The last copy in any design is what pastes: each copy or cut is numbered, and a tab whose own copy is older empties its clipboard when it is switched to (`drop_stale`). A failed copy anywhere leaves nothing to paste in any tab. Tests: bodies and components pasted in another tab, the last copy winning across tabs, cut as a copy. `copied_bodies_stay_with_their_design` gave way to the cross-design test. Co-Authored-By: Claude Opus 5.5 * Clipboard: what is selected wins over a design row picked earlier Copy copied the whole design as a linked component whenever the design's browser row was still picked, even after a component, body or feature had been selected in the view or another tab, and failed in an unsaved design. The design row now gives way to anything selected, and switching tabs drops the picked components of the design left. Co-Authored-By: Claude Opus 5.5 * Put the Paste from Another Design label in the pending locale file Co-Authored-By: Claude Opus 5.5 * Tests: unground the placement before moving it (a design's first part is grounded) Co-Authored-By: Claude Opus 5.5 * Drop locale keys main already folded into en.json Co-Authored-By: Claude Opus 5.5 * Pending locale: Paste from Another Design in the complete catalogs Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- .../pending/paste-bodies-and-components.json | 20 ++ crates/doc/src/feature_refs.rs | 11 + crates/engine/src/cmd/component.rs | 10 + crates/engine/src/cmd/component_clone.rs | 267 ++++++++++++++---- crates/engine/src/cmd/component_foreign.rs | 107 +++++++ .../engine/src/cmd/component_foreign_tests.rs | 134 +++++++++ crates/engine/src/cmd/occurrence_tests.rs | 56 ++++ crates/engine/src/lib.rs | 51 ++++ crates/ui-egui/src/documents.rs | 10 +- crates/ui-egui/src/edit_clipboard.rs | 96 ++++++- crates/ui-egui/src/edit_clipboard_tests.rs | 101 ++++++- crates/ui-egui/src/lib.rs | 11 + 12 files changed, 799 insertions(+), 75 deletions(-) create mode 100644 assets/locales/pending/paste-bodies-and-components.json create mode 100644 crates/engine/src/cmd/component_foreign.rs create mode 100644 crates/engine/src/cmd/component_foreign_tests.rs diff --git a/assets/locales/pending/paste-bodies-and-components.json b/assets/locales/pending/paste-bodies-and-components.json new file mode 100644 index 000000000..57fb54b50 --- /dev/null +++ b/assets/locales/pending/paste-bodies-and-components.json @@ -0,0 +1,20 @@ +{ + "en": { + "cmd.component_paste_from_design": "Paste from Another Design" + }, + "ja": { + "cmd.component_paste_from_design": "別のデザインから貼り付け" + }, + "zh": { + "cmd.component_paste_from_design": "从其他设计粘贴" + }, + "ar": { + "cmd.component_paste_from_design": "لصق من تصميم آخر" + }, + "he": { + "cmd.component_paste_from_design": "הדבק מעיצוב אחר" + }, + "vi": { + "cmd.component_paste_from_design": "Dán từ thiết kế khác" + } +} diff --git a/crates/doc/src/feature_refs.rs b/crates/doc/src/feature_refs.rs index 6408871a6..f5a6d649d 100644 --- a/crates/doc/src/feature_refs.rs +++ b/crates/doc/src/feature_refs.rs @@ -46,6 +46,17 @@ impl FeatureKind { found } + /// Bodies the feature works on (by name). + pub fn input_bodies(&self) -> Vec { + let mut v = Vec::new(); + self.walk_refs(&mut |r| { + if let Ref::Body(name) = r { + v.push(name.as_ref().to_string()); + } + }); + v + } + /// Point references to sketches and features (both by id) at their copies, and references /// that are still keyed by name at a feature's new name (`timeline.rename`). pub fn remap_refs(&mut self, ids: &BTreeMap, names: &BTreeMap) { diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index c31fc295a..68d829968 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -24,6 +24,8 @@ const FINISH_EDIT_CONTRACT: TypedContract = TypedContract::new mod align; #[path = "component_drag.rs"] mod drag; +#[path = "component_foreign.rs"] +mod foreign; #[path = "component_matrix.rs"] pub(super) mod matrix; #[path = "component_placing.rs"] @@ -103,6 +105,14 @@ pub static COMMANDS: &[CommandSpec] = &[ by (default: its only one, else the active one; a component placed more than once gets them in every instance). Each \ copy stays where its body is in the world; the copies' names come back as `bodies`", ), + CommandSpec::new("component.paste_from_design", "Paste from Another Design", foreign::paste_from_design).icon("paste").params( + "component?: where it goes (default: the active one); component_path?: its placement (default: the active one, else its \ + only one). Pastes what was copied in another design, at the same world coordinates: its bodies as imported bodies \ + (no history) in one Import feature, or its components as independent copies with their history, appearances, \ + joints and motion (as `component.paste_new`); the user parameters they use come along, renamed `w_2` when taken. \ + A component that uses what isn't in it (another body, sketch or parameter) is refused, saying what. Returns \ + `bodies` and `feature`, or the pasted components' `paths`", + ), CommandSpec::new("component.move_sketches", "Move Sketches to Component", move_sketches).icon("move").params("sketches: [ids or names], component"), CommandSpec::new("occurrence.copy", "Paste (Instance)", copy_occurrence).icon("copy") .params("component (or occurrence): what to place again; path?: validates selected occurrence; parent?: component (default: the same parent); translate?: [x,y,z]; in_place?: bool (default false: the selected transform within the parent; true: where the selected placement is in the world, translate in world axes; a parent placed more than once is placed by parent_path?, else the active placement, and every instance gets the copy). Copies the selected effective transform, including pending moves"), diff --git a/crates/engine/src/cmd/component_clone.rs b/crates/engine/src/cmd/component_clone.rs index d244cc26f..60ea12ebc 100644 --- a/crates/engine/src/cmd/component_clone.rs +++ b/crates/engine/src/cmd/component_clone.rs @@ -83,8 +83,10 @@ fn cloned_path(source: &Document, path: &[u64], root: u64, destination: &[u64], Ok(mapped) } -fn unique(base: &str, used: &mut BTreeSet) -> String { - let name = solidcraft_doc::copy_name(base, |n| used.contains(n)); +/// A name for a copy of `base` that isn't in `used` (and then is): numbered, or with `keep` +/// (pasting into another design, where the original isn't) `base` itself while it is free. +fn unique(base: &str, used: &mut BTreeSet, keep: bool) -> String { + let name = if keep && !used.contains(base.trim()) { base.trim().to_string() } else { solidcraft_doc::copy_name(base, |n| used.contains(n)) }; used.insert(name.clone()); name } @@ -182,6 +184,32 @@ fn graph(doc: &Document, root: u64) -> Result> { Ok(sorted) } +/// The design Paste New copies from: its document, its evaluated model and its placements moved +/// but not yet applied. The session pasted into is the target; they are the same design for a +/// paste within one design. +pub(super) struct Source<'a> { + pub doc: &'a Document, + pub model: &'a solidcraft_doc::Model, + pub pending_moves: &'a BTreeMap, + /// Another design than the target: the copy can't point at anything outside it (it is + /// refused, saying what), and the user parameters it uses come along. + pub other_design: bool, +} + +impl<'a> Source<'a> { + /// The session's own design. + pub fn of(s: &'a Session) -> Source<'a> { + Source { doc: &s.doc, model: &s.model, pending_moves: &s.pending_moves, other_design: false } + } + + /// What was copied in another design. + pub fn copied(copy: &'a crate::ForeignCopy) -> Source<'a> { + Source { doc: ©.doc, model: ©.model, pending_moves: ©.pending_moves, other_design: true } + } +} + +/// An independent copy of `component` (and what it holds), from the session's own design, into +/// `parent`. pub(super) fn paste( s: &mut Session, component: u64, @@ -190,7 +218,26 @@ pub(super) fn paste( parent: u64, params: &Value, ) -> Result { - let source = s.doc.clone(); + let (scratch, out) = build(s, &Source::of(s), component, source_occurrence, transform, parent, None, params)?; + s.accept_computed(scratch); + Ok(out) +} + +/// [`paste`] from `origin` into `s`: the computed session to accept, and what the paste made. +/// `parent_path`: the placement of `parent` the copy is placed by (default: the source +/// placement's parent's). +#[allow(clippy::too_many_arguments)] +pub(super) fn build( + s: &Session, + origin: &Source<'_>, + component: u64, + source_occurrence: Option, + transform: Mat, + parent: u64, + parent_path: Option>, + params: &Value, +) -> Result<(Session, Value)> { + let source = origin.doc; let source_parameters: BTreeMap<_, _> = source.params.iter().map(|p| (p.name.as_str(), p)).collect(); let generated_parameters: BTreeSet<_> = source .params @@ -199,22 +246,25 @@ pub(super) fn paste( .map(|p| p.name.as_str()) .chain(source.features.iter().flat_map(|f| f.param_names.iter().map(String::as_str))) .collect(); - let definitions = graph(&source, component)?; + let definitions = graph(source, component)?; let definition_records: BTreeMap<_, _> = source.components.iter().map(|c| (c.id, c)).collect(); let selected: BTreeSet<_> = definitions.iter().copied().collect(); if source.marker.is_some_and(|m| m < source.features.len()) { return Err(bad(CMD, "move the timeline marker to the end before Paste New")); } + if origin.other_design && s.doc.marker.is_some_and(|m| m < s.doc.features.len()) { + return Err(bad(CMD, "move the timeline marker to the end in this design before pasting")); + } let feats: Vec = source.features.iter().filter(|f| selected.contains(&f.component)).cloned().collect(); if feats.len() + source.features.len() > MAX_WORK { return Err(bad(CMD, "too many features to copy")); } for f in &feats { - if s.model.result(f.id).is_some_and(|r| r.error.is_some()) { + if origin.model.result(f.id).is_some_and(|r| r.error.is_some()) { return Err(bad(CMD, format!("source feature {} has an evaluation error", f.name))); } } - let state = s.model.state(); + let state = origin.model.state(); if state.bodies.len() > MAX_WORK { return Err(bad(CMD, "body set exceeds copy work limit")); } @@ -228,11 +278,12 @@ pub(super) fn paste( let mut names = BTreeMap::new(); let mut bodies = BTreeMap::new(); let mut parameters = BTreeMap::new(); - // Names are numbered among their own kind: a component named after its body takes the same - // number as the body's copy, and neither skips one the other took. - let mut used_components: BTreeSet = source.components.iter().map(|c| c.name.clone()).collect(); - let mut used_features: BTreeSet = source.features.iter().map(|f| f.name.clone()).collect(); - let mut used_bodies: BTreeSet = state.bodies.iter().map(|b| b.name.clone()).collect(); + // Names are numbered among their own kind, against the names the target has: a component + // named after its body takes the same number as the body's copy, and neither skips one the + // other took. + let mut used_components: BTreeSet = s.doc.components.iter().map(|c| c.name.clone()).collect(); + let mut used_features: BTreeSet = s.doc.features.iter().map(|f| f.name.clone()).collect(); + let mut used_bodies: BTreeSet = s.model.state().bodies.iter().map(|b| b.name.clone()).collect(); let mut new_ids = Vec::new(); let mut frozen = Vec::new(); // Allocate definitions, discarding their automatic placeholder occurrence except root. @@ -243,7 +294,7 @@ pub(super) fn paste( } else { components.get(&c.parent).copied().unwrap_or(*components.get(&component).ok_or_else(|| bad(CMD, "missing clone root"))?) }; - let name = unique(&c.name, &mut used_components); + let name = unique(&c.name, &mut used_components, origin.other_design); let new = scratch.doc_mut().add_component(Some(&name), mapped_parent)?; // A copy keeps the definition's part properties. if let Some(added) = scratch.doc_mut().components.iter_mut().find(|x| x.id == new) { @@ -258,12 +309,14 @@ pub(super) fn paste( } let root = *components.get(&component).ok_or_else(|| bad(CMD, "missing clone root"))?; let root_occurrence = scratch.doc.occurrence_of(root).map(|o| o.id).ok_or_else(|| bad(CMD, "missing cloned placement"))?; - let mut clone_path = if let Some(o) = &source_occurrence { + let mut clone_path = if let Some(path) = parent_path { + path + } else if let Some(o) = &source_occurrence { let mut path = super::component::occurrence_path(s, params, o.id, CMD)?; path.pop(); path } else { - source.first_path(parent) + s.doc.first_path(parent) }; clone_path.push(root_occurrence); if let Some(o) = scratch.doc_mut().occurrences.iter_mut().find(|o| o.id == root_occurrence) { @@ -277,7 +330,7 @@ pub(super) fn paste( for old in source.occurrences.iter().filter(|o| selected.contains(&o.parent)) { let child = *components.get(&old.component).ok_or_else(|| bad(CMD, "missing child definition"))?; let owner = *components.get(&old.parent).ok_or_else(|| bad(CMD, "missing parent definition"))?; - let pose = s.pending_moves.get(&old.id).copied().unwrap_or(old.transform); + let pose = origin.pending_moves.get(&old.id).copied().unwrap_or(old.transform); if !super::component::valid_position(&pose) { return Err(bad(CMD, "invalid internal pending occurrence transform")); } @@ -292,10 +345,10 @@ pub(super) fn paste( // The names the bodies of a feature have in the model, where they are its stored names, numbered. let mut shown: BTreeMap> = BTreeMap::new(); for f in &feats { - if let Some(result) = s.model.result(f.id) { + if let Some(result) = origin.model.result(f.id) { let created: Vec<_> = result.state.bodies.iter().filter(|b| b.feature == f.id).map(|b| b.name.clone()).collect(); for name in &created { - bodies.entry(name.clone()).or_insert_with(|| unique(name, &mut used_bodies)); + bodies.entry(name.clone()).or_insert_with(|| unique(name, &mut used_bodies, origin.other_design)); } if named_by(&f.body_names, &created) { shown.insert(f.id, created.clone()); @@ -307,7 +360,7 @@ pub(super) fn paste( if !shown.contains_key(&f.id) { for name in &f.body_names { if !name.is_empty() { - bodies.entry(name.clone()).or_insert_with(|| unique(name, &mut used_bodies)); + bodies.entry(name.clone()).or_insert_with(|| unique(name, &mut used_bodies, origin.other_design)); } } } @@ -328,23 +381,32 @@ pub(super) fn paste( !f.suppressed && matches!(&f.kind, FeatureKind::BodyTransfer { bodies, from, to, .. } if !selected.contains(from) && bodies.iter().any(|b| *b == body.name) - && s.model.result(f.id).is_some_and(|result| !result.skipped && result.error.is_none() + && origin.model.result(f.id).is_some_and(|result| !result.skipped && result.error.is_none() && result.state.body(&body.name).is_some_and(|entered| source.model_body_component(entered) == *to))) }); let before = feats.iter().find_map(|f| { - let before = s.model.state_before(f.id); + let before = origin.model.state_before(f.id); let prior = before.body(&body.name)?; - let after = s.model.result(f.id)?.state.body(&body.name); + let after = origin.model.result(f.id)?.state.body(&body.name); if after.is_none_or(|after| !prior.body.same(&after.body)) { Some(before) } else { None } }); - let entered = entry.and_then(|f| s.model.result(f.id)).map(|r| r.state.clone()); + let entered = entry.and_then(|f| origin.model.result(f.id)).map(|r| r.state.clone()); let base = entered.as_ref().and_then(|st| st.body(&body.name)).or_else(|| before.as_ref().and_then(|st| st.body(&body.name))).unwrap_or(body); let baseline_component = source.model_body_component(base); let geometry = solidcraft_kernel::transform_matrix(&base.body, offset)?; let step = solidcraft_kernel::step_export(&[&geometry], "SolidCraft independent reassigned body")?; - let new_name = unique(&body.name, &mut used_bodies); + let new_name = unique(&body.name, &mut used_bodies, origin.other_design); bodies.insert(body.name.clone(), new_name.clone()); - let feature_name = unique(&format!("{} Base", body.name), &mut used_features); + // From another design it is named as what it is there, an imported body, numbered as + // the timeline numbers its features ("BodyImport1"). + let feature_name = if origin.other_design { + let name = + (1..=MAX_WORK + 1).map(|n| format!("BodyImport{n}")).find(|n| !used_features.contains(n)).unwrap_or_else(|| "BodyImport".into()); + used_features.insert(name.clone()); + name + } else { + unique(&format!("{} Base", body.name), &mut used_features, false) + }; let id = scratch.doc_mut().add_feature( FeatureKind::Import { file: format!("{} independent base", body.name), step: step.into(), components: Vec::new(), skip: Vec::new() }, Some(&feature_name), @@ -358,8 +420,12 @@ pub(super) fn paste( } // Allocate all history IDs before rewriting any forward reference. for f in &feats { - let name = unique(&f.name, &mut used_features); - let id = scratch.doc_mut().add_feature(f.kind.clone(), Some(&name))?; + let name = unique(&f.name, &mut used_features, origin.other_design); + // A transfer is checked as it is added: it names the copy's components (another design + // has none of the original ones). + let mut kind = f.kind.clone(); + transfer_into_copy(&mut kind, &components)?; + let id = scratch.doc_mut().add_feature(kind, Some(&name))?; if let Some(new) = scratch.doc.feature(id) { for (old, pn) in f.param_names.iter().zip(&new.param_names) { parameters.insert(old.clone(), pn.clone()); @@ -387,6 +453,11 @@ pub(super) fn paste( } } } + // From another design, the user parameters the copy uses come along (and the ones they use), + // renamed `w_2` where this design has a `w` already. + if origin.other_design { + copy_user_parameters(&mut scratch, source, &feats, &mut parameters)?; + } for (old, new) in ¶meters { if let Some(comment) = source.param_comments.get(old) { scratch.doc_mut().param_comments.insert(new.clone(), comment.clone()); @@ -414,26 +485,18 @@ pub(super) fn paste( f.body_names = outputs.get(&old.id).cloned().unwrap_or_default(); } f.remap_clone(&features, &names, &bodies, ¶meters)?; - if let FeatureKind::BodyTransfer { from, to, transform, .. } = &mut f.kind { - *to = *components.get(to).ok_or_else(|| bad(CMD, "transfer destination is outside the copied graph"))?; - if let Some(mapped) = components.get(from) { - *from = *mapped; - } else { - *from = *to; - *transform = solidcraft_doc::IDENTITY; - } - } + transfer_into_copy(&mut f.kind, &components)?; if let FeatureKind::Emboss { face: Some(face), .. } = &mut f.kind && !face.path.is_empty() && let FeatureKind::Emboss { face: Some(old_face), .. } = &old.kind && bodies.contains_key(old_face.body.as_ref()) { - face.path = cloned_path(&source, &old_face.path, component, &clone_path, &occurrences)?; + face.path = cloned_path(source, &old_face.path, component, &clone_path, &occurrences)?; } if let FeatureKind::Emboss { face: Some(face), .. } = &mut f.kind && !face.author_path.is_empty() { - face.author_path = cloned_path(&source, &face.author_path, component, &clone_path, &occurrences)?; + face.author_path = cloned_path(source, &face.author_path, component, &clone_path, &occurrences)?; } if let (FeatureKind::Sketch { plane, .. }, FeatureKind::Sketch { plane: old_plane, .. }) = (&mut f.kind, &old.kind) && let (Some(anchor), Some(original)) = (super::sketch::face::anchor_mut(plane), super::sketch::face::anchor(old_plane)) @@ -441,9 +504,9 @@ pub(super) fn paste( if bodies.contains_key(&original.target.body) { anchor.component = *components.get(&original.component).ok_or_else(|| bad(CMD, "anchored source component is outside copied graph"))?; - anchor.path = cloned_path(&source, &original.path, component, &clone_path, &occurrences)?; + anchor.path = cloned_path(source, &original.path, component, &clone_path, &occurrences)?; } - anchor.author_path = cloned_path(&source, &original.author_path, component, &clone_path, &occurrences)?; + anchor.author_path = cloned_path(source, &original.author_path, component, &clone_path, &occurrences)?; } if let Some(slot) = scratch.doc_mut().feature_mut(f.id) { *slot = f; @@ -482,7 +545,7 @@ pub(super) fn paste( .filter_map(|b| bodies.get(&b.name).cloned()) .collect(); if !moved_out.is_empty() { - let name = unique("Assigned-out bodies", &mut used_features); + let name = unique("Assigned-out bodies", &mut used_features, origin.other_design); let id = scratch.doc_mut().add_feature(FeatureKind::Remove { bodies: moved_out.into_iter().map(BodyName).collect() }, Some(&name))?; if let Some(f) = scratch.doc_mut().feature_mut(id) { f.component = root; @@ -514,14 +577,20 @@ pub(super) fn paste( scratch.doc_mut().appearances.faces.push(face); } } - // Typed configuration and assembly helpers preserve original targets. - scratch.doc_mut().configs.clone_targets(&solidcraft_doc::config::ConfigCloneMaps { - features: features.clone(), - components: components.clone(), - bodies: bodies.clone(), - parameters: parameters.clone(), - })?; - let mut notices = super::component_clone_assembly::clone_assembly(scratch.doc_mut(), &source, &occurrences, &features, &bodies)?; + // Typed configuration and assembly helpers preserve original targets (another design's + // configurations stay with it: this design's table has its own targets). + if !origin.other_design { + scratch.doc_mut().configs.clone_targets(&solidcraft_doc::config::ConfigCloneMaps { + features: features.clone(), + components: components.clone(), + bodies: bodies.clone(), + parameters: parameters.clone(), + })?; + } + let mut notices = super::component_clone_assembly::clone_assembly(scratch.doc_mut(), source, &occurrences, &features, &bodies)?; + // Joints and motion to the outside are left behind (those notices); what follows is what + // the copied features point at outside it. + let assembly_notices = notices.len(); let mut reference_work = 0usize; for feature in &feats { if let FeatureKind::Emboss { face: Some(face), .. } = &feature.kind @@ -605,12 +674,22 @@ pub(super) fn paste( } } } + if origin.other_design { + // What the copy points at outside itself isn't in this design. + let mut outside = outside_references(notices.get(assembly_notices..).unwrap_or_default(), &feats, &bodies); + if !outside.is_empty() { + outside.sort(); + outside.dedup(); + let name = definition_records.get(&component).map(|c| c.name.clone()).unwrap_or_default(); + return Err(bad(CMD, format!("{name} uses what isn't in it, so it can't be pasted into another design: {}", outside.join("; ")))); + } + } notices.sort(); notices.dedup(); scratch.refresh(); let original_errors: BTreeMap<_, _> = s.model.results.iter().map(|result| (result.id, result.error.as_ref())).collect(); let refreshed_errors: BTreeMap<_, _> = scratch.model.results.iter().map(|result| (result.id, result.error.as_ref())).collect(); - if source.features.iter().any(|feature| original_errors.get(&feature.id) != refreshed_errors.get(&feature.id)) { + if s.doc.features.iter().any(|feature| original_errors.get(&feature.id) != refreshed_errors.get(&feature.id)) { return Err(bad(CMD, "copy would change an original feature's error state")); } // Base imports acquire new face identities. Resolve copied face overrides against the @@ -640,14 +719,14 @@ pub(super) fn paste( let copied_bodies: BTreeMap<_, _> = copied.bodies.iter().map(|body| (body.name.as_str(), body)).collect(); // Adding placements can invalidate cached source evaluation. Compare clone effects // against that same evaluation's source prefix, not older shared B-rep pointers. - if scratch.doc.features.get(..source.features.len()) != Some(source.features.as_slice()) - || scratch.doc.params.get(..source.params.len()) != Some(source.params.as_slice()) + if scratch.doc.features.get(..s.doc.features.len()) != Some(s.doc.features.as_slice()) + || scratch.doc.params.get(..s.doc.params.len()) != Some(s.doc.params.as_slice()) { return Err(bad(CMD, "copy would change original feature history or parameters")); } let original_state = new_ids.first().map(|id| scratch.model.state_before(*id)).unwrap_or_else(|| copied.clone()); let all_columns = std::mem::take(&mut scratch.doc_mut().configs.columns); - scratch.doc_mut().configs.columns = all_columns.iter().skip(source.configs.columns.len()).cloned().collect(); + scratch.doc_mut().configs.columns = all_columns.iter().skip(s.doc.configs.columns.len()).cloned().collect(); let style_validation = scratch.doc.configuration_style_status(&copied); scratch.doc_mut().configs.columns = all_columns; style_validation?; @@ -714,10 +793,86 @@ pub(super) fn paste( } } scratch.selection = vec![Sel::Occurrence { path: clone_path }]; - s.accept_computed(scratch); - Ok( - json!({"component":root,"occurrence":root_occurrence,"features":new_ids,"components":components.len(),"bodies":expected_count,"frozen_bodies":frozen,"notices":notices}), - ) + let out = json!({"component":root,"occurrence":root_occurrence,"features":new_ids,"components":components.len(),"bodies":expected_count,"frozen_bodies":frozen,"notices":notices}); + Ok((scratch, out)) +} + +/// A copied body transfer moves its bodies between the copies of its components; one from +/// outside the copy is where the copy starts (it stays in place, in its destination). +fn transfer_into_copy(kind: &mut FeatureKind, components: &BTreeMap) -> Result<()> { + if let FeatureKind::BodyTransfer { from, to, transform, .. } = kind { + *to = *components.get(to).ok_or_else(|| bad(CMD, "transfer destination is outside the copied graph"))?; + if let Some(mapped) = components.get(from) { + *from = *mapped; + } else { + *from = *to; + *transform = solidcraft_doc::IDENTITY; + } + } + Ok(()) +} + +/// What copied features point at outside the copy, in words: the external references Paste New +/// keeps within one design (`notices`), and the bodies they work on that aren't copied. +fn outside_references(notices: &[String], feats: &[Feature], bodies: &BTreeMap) -> Vec { + let mut out: Vec = + notices.iter().map(|n| n.replace(" retains an external ", " uses a ").replace(" retains external ", " uses ")).collect(); + for f in feats { + for body in f.kind.input_bodies() { + if !bodies.contains_key(&body) { + out.push(format!("{} uses body {body}", f.name)); + } + } + } + out +} + +/// The user parameters copied features use (their expressions and their dimensions'), and the +/// ones those use, copied from `source` into `scratch`: named as they were where that name is +/// free, else `w_2`, `w_3`…; `parameters` maps each to its copy. +fn copy_user_parameters(scratch: &mut Session, source: &Document, feats: &[Feature], parameters: &mut BTreeMap) -> Result<()> { + let user: BTreeMap<&str, &solidcraft_doc::Param> = source.params.iter().filter(|p| !p.model).map(|p| (p.name.as_str(), p)).collect(); + let mut pending: Vec = feats.iter().flat_map(|f| f.kind.expressions()).map(str::to_string).collect(); + pending.extend(parameters.keys().filter_map(|old| source.params.iter().find(|p| p.model && p.name == *old)).map(|p| p.expr.clone())); + let mut used: BTreeSet<&str> = BTreeSet::new(); + let mut work = 0usize; + while let Some(expr) = pending.pop() { + for name in solidcraft_doc::expr::references(&expr) { + work += 1; + if work > 100_000 { + return Err(bad(CMD, "parameter references exceed copy work limit")); + } + if let Some((key, p)) = user.get_key_value(name.as_str()) + && used.insert(key) + { + pending.push(p.expr.clone()); + } + } + } + let copied: Vec<&solidcraft_doc::Param> = source.params.iter().filter(|p| used.contains(p.name.as_str())).collect(); + if scratch.doc.params.len() + copied.len() > solidcraft_doc::MAX_PARAMS { + return Err(bad(CMD, "too many copied parameters")); + } + let mut taken: BTreeSet = scratch.doc.params.iter().map(|p| p.name.clone()).collect(); + for p in &copied { + let mut name = p.name.clone(); + let mut n = 2; + while taken.contains(&name) || Document::param_name_problem(&name).is_some() { + name = format!("{}_{n}", p.name); + n += 1; + if n > 10_000 { + return Err(bad(CMD, format!("no free name for parameter {}", p.name))); + } + } + taken.insert(name.clone()); + parameters.insert(p.name.clone(), name); + } + for p in copied { + let name = parameters.get(&p.name).cloned().unwrap_or_default(); + let expr = solidcraft_doc::clone_expression(&p.expr, parameters); + scratch.doc_mut().params.push(solidcraft_doc::Param { name, expr, unit: p.unit.clone(), comment: p.comment.clone(), model: false }); + } + Ok(()) } #[cfg(test)] diff --git a/crates/engine/src/cmd/component_foreign.rs b/crates/engine/src/cmd/component_foreign.rs new file mode 100644 index 000000000..38916848b --- /dev/null +++ b/crates/engine/src/cmd/component_foreign.rs @@ -0,0 +1,107 @@ +//! Pasting what was copied in another design (`Session::foreign_copy`). Bodies come as an +//! imported body each, without their history (that stays with the design they were made in), at +//! the same world coordinates as in their design, in one Import base feature in the target +//! component. Components come as a Paste New does: an independent copy of each with what it +//! holds, its history, appearances, joints and motion, where it is in the world. + +use super::*; + +pub(super) fn paste_from_design(s: &mut Session, p: &Value) -> Result { + let cmd = "component.paste_from_design"; + let copy = s.foreign_copy.clone().ok_or_else(|| bad(cmd, "nothing was copied in another design"))?; + if copy.bodies.is_empty() && copy.placed.is_empty() { + return Err(bad(cmd, "nothing was copied in another design")); + } + let to = if p.get("component").is_some() { component(s, p, "component", cmd)? } else { s.active_component }; + let given = match p.get("component_path") { + None => None, + Some(v) => Some( + v.as_array() + .filter(|a| a.len() <= 64) + .and_then(|a| a.iter().map(Value::as_u64).collect::>>()) + .ok_or_else(|| bad(cmd, "`component_path` must list 0..64 occurrence ids"))?, + ), + }; + let path = match given { + Some(path) => path, + None if to == s.active_component => s.active_occurrence_path.clone().unwrap_or_else(|| s.doc.first_path(to)), + None => placing::placement_of(s, &s.placed_document(), to, None, "component_path", cmd)?.0, + }; + let frame = s.placed_document().path_transform(to, &path).ok_or_else(|| bad(cmd, "that path is not a placement of the target"))?; + let into_target = solidcraft_doc::mat_inverse(&frame).ok_or_else(|| bad(cmd, "the target's frame is not invertible"))?; + if copy.bodies.is_empty() { + return paste_components(s, ©, to, path, into_target, p); + } + // Each body at its world coordinates in its design, in the target's frame, named as in its + // component (a body seen in another placement without that placement) where that name is + // free here, else numbered. + let state = s.model.state(); + let mut names: Vec = Vec::new(); + let mut shapes = Vec::new(); + for (i, seen) in copy.bodies.iter().enumerate() { + let body = copy.world.body(seen).ok_or_else(|| bad(cmd, format!("no body `{seen}` in {}", copy.design)))?; + let name = copy.names.get(i).unwrap_or(seen); + let taken = |n: &str| state.body(n).is_some() || names.iter().any(|x| x == n); + let new = if taken(name) { solidcraft_doc::copy_name(name, taken) } else { name.clone() }; + shapes.push(solidcraft_kernel::transform_matrix(&body.body, into_target)?); + names.push(new); + } + drop(state); + let list: Vec = + names.iter().zip(&shapes).map(|(name, body)| solidcraft_kernel::ExportBody { name: name.clone(), body, color: body.color() }).collect(); + let header = solidcraft_kernel::StepHeader { organization: "SolidCraft".into(), ..Default::default() }; + let step = solidcraft_kernel::step_export_bodies(&list, &header)?; + let mut scratch = s.scratch(); + let kind = FeatureKind::Import { file: format!("{} (pasted)", copy.design), step: step.into(), components: Vec::new(), skip: Vec::new() }; + // Named as any import is ("Import1"); the design they came from stays on it as its file. + let id = scratch.doc_mut().add_feature(kind, None)?; + let feature = scratch.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default(); + if let Some(f) = scratch.doc_mut().feature_mut(id) { + f.component = to; + f.body_names = names.clone(); + } + scratch.refresh(); + if let Some(error) = scratch.model.result(id).and_then(|r| r.error.as_ref()) { + return Err(bad(cmd, format!("the pasted bodies didn't import: {error}"))); + } + scratch.selection = names.iter().map(|name| crate::Sel::Body { name: name.clone() }).collect(); + s.accept_computed(scratch); + Ok(json!({"bodies": names, "feature": feature, "component": to})) +} + +/// Independent copies of the components copied in another design, each with what it holds, in +/// `to` (placed by `path`; `into_target` takes world coordinates into it), where each is in the +/// world; one step to undo. They are selected. +fn paste_components( + s: &mut Session, + copy: &crate::ForeignCopy, + to: u64, + path: Vec, + into_target: solidcraft_doc::Mat, + p: &Value, +) -> Result { + let origin = crate::cmd::component_clone::Source::copied(copy); + let mut computed: Option = None; + let mut made = Vec::new(); + for (component, occurrence, world) in ©.placed { + let source_occurrence = copy.doc.occurrences.iter().find(|o| o.id == *occurrence).cloned(); + let transform = solidcraft_doc::mat_mul(&into_target, world); + if !super::valid_position(&transform) { + return Err(bad("component.paste_from_design", "copy transform exceeds supported numeric range")); + } + let target = computed.as_ref().unwrap_or(s); + let (next, out) = crate::cmd::component_clone::build(target, &origin, *component, source_occurrence, transform, to, Some(path.clone()), p)?; + if let Some(id) = out.get("occurrence").and_then(Value::as_u64) { + made.push(path.iter().copied().chain([id]).collect::>()); + } + computed = Some(next); + } + let Some(mut scratch) = computed else { return Err(bad("component.paste_from_design", "the copied components are gone")) }; + scratch.selection = made.iter().map(|path| crate::Sel::Occurrence { path: path.clone() }).collect(); + s.accept_computed(scratch); + Ok(json!({"paths": made, "component": to})) +} + +#[cfg(test)] +#[path = "component_foreign_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/component_foreign_tests.rs b/crates/engine/src/cmd/component_foreign_tests.rs new file mode 100644 index 000000000..a566a1b1d --- /dev/null +++ b/crates/engine/src/cmd/component_foreign_tests.rs @@ -0,0 +1,134 @@ +#![allow(clippy::unwrap_used)] +use crate::{ForeignCopy, Session}; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap() +} +fn created(s: &mut Session, name: &str) -> (u64, u64) { + let c = run(s, "component.create", json!({"name": name})); + (c["component"].as_u64().unwrap(), c["occurrence"].as_u64().unwrap()) +} +fn volume(s: &mut Session, id: u64) -> f64 { + run(s, "component.properties", json!({"component": id}))["total"]["volume_mm3"].as_f64().unwrap() +} +fn design(name: &str) -> Session { + let mut s = Session::default(); + s.doc_mut().name = name.into(); + s +} +/// `s` copies its placement `path` for another design. +fn copied(s: &Session, path: Vec) -> Option> { + Some(Arc::new(ForeignCopy::of(s, Vec::new(), vec![path]))) +} + +/// A component copied in another design pastes as an independent copy of it and what it holds: +/// its history, its appearances, a part placed twice in it still one component placed twice, +/// where it is in the world, named "(2)" where the name is taken, as one step to undo. +#[test] +fn a_component_from_another_design_pastes_with_its_history() { + let mut source = design("Bracket"); + let (assembly, at) = created(&mut source, "Assembly"); + let (child, _) = created(&mut source, "Child"); + run(&mut source, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"})); + run(&mut source, "appearance.assign", json!({"bodies": ["Cube"], "color": "#abcdef"})); + run(&mut source, "occurrence.copy", json!({"component": child})); + run(&mut source, "component.activate", json!({"component": 0})); + run(&mut source, "occurrence.ground", json!({"occurrence": at, "grounded": false})); + run(&mut source, "occurrence.move", json!({"occurrence": at, "translate": [0, 30, 0]})); + let was = source.world_state().body("Cube").unwrap().mesh().bounds(); + let box_features = source.doc.features.len(); + + let mut s = design("Frame"); + created(&mut s, "Assembly"); + run(&mut s, "component.activate", json!({"component": 0})); + s.foreign_copy = copied(&source, vec![at]); + let undo = s.undo.len(); + let out = run(&mut s, "component.paste_from_design", json!({})); + assert_eq!(s.undo.len(), undo + 1); + let new = s.doc.components.iter().find(|c| c.name == "Assembly (2)").expect("named (2)").id; + assert_eq!(out["paths"], json!([[s.doc.occurrence_of(new).unwrap().id]])); + let kids: Vec<_> = s.doc.occurrences.iter().filter(|o| o.parent == new).collect(); + assert_eq!(kids.len(), 2); + assert_eq!(kids[0].component, kids[1].component, "still one component placed twice"); + assert_eq!(s.doc.features.len(), box_features, "the box's history came along"); + assert!((volume(&mut s, new) - 16.0).abs() < 1e-6); + assert_eq!(s.doc.appearances.bodies["Cube"].color, [0xab, 0xcd, 0xef]); + let is = s.world_state().body("Cube").unwrap().mesh().bounds(); + assert!(was.min.dist(is.min) < 1e-6 && was.max.dist(is.max) < 1e-6, "{was:?} vs {is:?}"); + // Its history is its own: changing it here leaves the original as it was. + let copy = s.doc.features.iter().find(|f| matches!(f.kind, solidcraft_doc::FeatureKind::Box { .. })).unwrap(); + let parameter = copy.param_names[0].clone(); + run(&mut s, "parameters.change", json!({"name": parameter, "expression": "3 mm"})); + assert!((volume(&mut s, new) - 24.0).abs() < 1e-6); + assert!((volume(&mut source, assembly) - 16.0).abs() < 1e-6); + let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + assert_eq!(reopened.occurrences.iter().filter(|o| o.parent == new).count(), 2); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert!(s.doc.components.iter().all(|c| c.name != "Assembly (2)")); +} + +/// The user parameters a pasted component uses come along: as they were where the name is +/// free, else renamed `w_2`, its features following; this design's own `w` stays as it is. +#[test] +fn user_parameters_come_along_renamed_where_taken() { + let mut source = design("Bracket"); + run(&mut source, "parameters.add", json!({"name": "w", "expression": "4 mm"})); + let (_, at) = created(&mut source, "Part"); + let feature = run(&mut source, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"}))["feature"].as_u64().unwrap(); + let length = source.doc.feature(feature).unwrap().param_names[0].clone(); + run(&mut source, "parameters.change", json!({"name": length, "expression": "w"})); + + let mut s = design("Frame"); + run(&mut s, "parameters.add", json!({"name": "w", "expression": "10 mm"})); + s.foreign_copy = copied(&source, vec![at]); + run(&mut s, "component.paste_from_design", json!({})); + let w2 = s.doc.params.iter().find(|p| p.name == "w_2").expect("w came along as w_2"); + assert_eq!(w2.expr, "4 mm"); + assert_eq!(s.doc.params.iter().find(|p| p.name == "w").unwrap().expr, "10 mm"); + let part = s.doc.components.iter().find(|c| c.name == "Part").unwrap().id; + assert!((volume(&mut s, part) - 16.0).abs() < 1e-6); + run(&mut s, "parameters.change", json!({"name": "w_2", "expression": "1 mm"})); + assert!((volume(&mut s, part) - 4.0).abs() < 1e-6, "the copy follows w_2"); +} + +/// A component whose features use what isn't in it (here a body outside it) isn't pasted into +/// another design: it is refused, saying what, and the design is left as it was. +#[test] +fn a_component_using_what_is_outside_it_is_refused_saying_what() { + let mut source = design("Bracket"); + run(&mut source, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"})); + let (_, at) = created(&mut source, "Part"); + run(&mut source, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Pin"})); + run(&mut source, "solid.move", json!({"bodies": ["Cube"], "translate": [10, 0, 0]})); + + let mut s = design("Frame"); + s.foreign_copy = copied(&source, vec![at]); + let saved = s.doc.to_json(); + let error = s.execute("component.paste_from_design", &json!({})).unwrap_err().to_string(); + assert!(error.contains("uses body Cube"), "{error}"); + assert_eq!(s.doc.to_json(), saved); +} + +/// A component that bodies were moved into (a body transfer, as Create Components from Bodies +/// makes) pastes into another design, which has none of the components the transfer names. +#[test] +fn a_component_bodies_were_moved_into_pastes_into_another_design() { + let mut source = design("Bracket"); + run(&mut source, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"})); + let (part, at) = created(&mut source, "Part"); + run(&mut source, "component.move_bodies", json!({"bodies": ["Cube"], "component": part})); + run(&mut source, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Pin"})); + + let mut s = design("Frame"); + s.foreign_copy = copied(&source, vec![at]); + run(&mut s, "component.paste_from_design", json!({})); + let new = s.doc.components.iter().find(|c| c.name == "Part").unwrap().id; + let state = s.model.state(); + assert_eq!(s.doc.model_body_component(state.body("Cube").unwrap()), new); + assert_eq!(s.doc.model_body_component(state.body("Pin").unwrap()), new); + // The body moved in from outside comes as an imported body. + assert!(s.doc.find_feature("BodyImport1").is_some_and(|f| f.component == new)); +} diff --git a/crates/engine/src/cmd/occurrence_tests.rs b/crates/engine/src/cmd/occurrence_tests.rs index 42503da4c..e259e017b 100644 --- a/crates/engine/src/cmd/occurrence_tests.rs +++ b/crates/engine/src/cmd/occurrence_tests.rs @@ -1638,3 +1638,59 @@ fn occurrence_align_keeps_every_pick_and_reports_shared_definitions() { let r = run(&mut s, "occurrence.align", json!({"paths": [[b]], "from": [0, 0, 0], "to": [1, 0, 0]})); assert!(r.get("shared").is_none(), "{r}"); } + +/// A body copied in another design pastes here as an imported body: at the world coordinates it +/// had there, into the component asked for (placed elsewhere), named as it was or numbered when +/// that name is taken, from one Import feature named as any import is, as one step to undo. +#[test] +fn a_body_copied_in_another_design_pastes_as_an_imported_body() { + let mut source = Session::default(); + source.doc_mut().name = "Bracket".into(); + let (_, holder) = created(&mut source, "Holder"); + run(&mut source, "occurrence.move", json!({"occurrence": holder, "translate": [0,50,0]})); + run(&mut source, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"})); + let was = source.world_state().body("Cube").unwrap().mesh().bounds(); + let copy = crate::ForeignCopy::of(&source, vec!["Cube".into()], Vec::new()); + + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Cube"})); + let (a, a_at) = created(&mut s, "A"); + run(&mut s, "occurrence.move", json!({"occurrence": a_at, "translate": [100,0,0]})); + s.foreign_copy = Some(std::sync::Arc::new(copy)); + let undo = s.undo.len(); + let out = run(&mut s, "component.paste_from_design", json!({"component": a, "component_path": [a_at]})); + assert_eq!(out["bodies"], json!(["Cube (2)"])); + assert_eq!(out["feature"], "Import1"); + assert_eq!(s.undo.len(), undo + 1); + let is = s.world_state().body("Cube (2)").unwrap().mesh().bounds(); + assert!(was.min.dist(is.min) < 1e-6 && was.max.dist(is.max) < 1e-6, "{was:?} vs {is:?}"); + let state = s.model.state(); + assert_eq!(s.doc.model_body_component(state.body("Cube (2)").unwrap()), a); + assert!(matches!(&s.doc.find_feature("Import1").unwrap().kind, solidcraft_doc::FeatureKind::Import { file, .. } if file == "Bracket (pasted)")); + run(&mut s, "edit.undo", json!({})); + assert!(s.model.state().body("Cube (2)").is_none()); +} + +/// A body seen in another placement of its component ("Cube (Holder:2)") pastes into another +/// design under its own name, at that placement's position. +#[test] +fn a_body_seen_in_another_placement_pastes_into_another_design_under_its_own_name() { + let mut source = Session::default(); + source.doc_mut().name = "Bracket".into(); + let (holder, first) = created(&mut source, "Holder"); + run(&mut source, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"})); + run(&mut source, "component.activate", json!({"component": 0})); + let second = run(&mut source, "occurrence.copy", json!({"occurrence": first}))["occurrence"].as_u64().unwrap(); + run(&mut source, "occurrence.move", json!({"occurrence": second, "translate": [0,40,0]})); + let seen = source.placed_document().world_body_name(&source.model.state(), "Cube", holder, &[second]); + assert_ne!(seen, "Cube"); + let was = source.world_state().body(&seen).unwrap().mesh().bounds(); + let copy = crate::ForeignCopy::of(&source, vec![seen], Vec::new()); + assert_eq!(copy.names, vec!["Cube".to_string()]); + + let mut s = Session { foreign_copy: Some(std::sync::Arc::new(copy)), ..Default::default() }; + let out = run(&mut s, "component.paste_from_design", json!({})); + assert_eq!(out["bodies"], json!(["Cube"])); + let is = s.world_state().body("Cube").unwrap().mesh().bounds(); + assert!(was.min.dist(is.min) < 1e-6 && was.max.dist(is.max) < 1e-6, "{was:?} vs {is:?}"); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 296bd3630..797142b7e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -183,6 +183,52 @@ struct BodyRename { names_only: bool, } +/// Bodies or component placements copied in one design, for pasting into another +/// (`component.paste_from_design`): that design's placed model as it was when they were copied, +/// so the copy is what was copied, whatever happens to that design (or its tab) after. +#[derive(Clone, Debug)] +pub struct ForeignCopy { + /// The design's name (it names what the paste adds). + pub design: String, + /// Its placed model: what its Browser and view showed. + pub world: Arc, + /// The bodies copied, as its Browser names them (a body seen in another placement under the + /// name it has there). + pub bodies: Vec, + /// The name each of `bodies` has in its component (without the placement a body seen in + /// another placement is named after): the name it pastes as. + pub names: Vec, + /// The component placements copied, by path. + pub placements: Vec>, + /// Each of `placements`: the component placed, the occurrence and where it is in the world. + pub placed: Vec<(u64, u64, solidcraft_doc::Mat)>, + /// The design, its evaluated model and its placements moved but not yet applied: what a + /// pasted component's history is copied from. + pub doc: Arc, + pub model: Model, + pub pending_moves: std::collections::BTreeMap, +} + +impl ForeignCopy { + /// What `session` copies when `bodies` and `placements` are copied in it now. + pub fn of(session: &Session, bodies: Vec, placements: Vec>) -> ForeignCopy { + let frames = session.placed_document().body_frames_with_source(&session.model.state()); + let names = bodies.iter().map(|b| frames.iter().find(|f| f.0 == *b).map_or_else(|| b.clone(), |f| f.1.clone())).collect(); + let placed = placements.iter().filter_map(|p| session.occurrence_placement(p).ok()).map(|p| (p.component, p.occurrence, p.world)).collect(); + ForeignCopy { + design: session.doc.name.clone(), + world: session.world_state(), + bodies, + names, + placements, + placed, + doc: session.doc.clone(), + model: session.model.clone(), + pending_moves: session.pending_moves.clone(), + } + } +} + /// One undo step. #[derive(Clone, Debug)] pub struct Snapshot { @@ -410,6 +456,9 @@ pub struct Session { pub sketch_clipboard: Option, /// Resolved appearance copied by appearance.copy; transient, outside design/history. pub appearance_clipboard: Option, + /// What was copied in another design, to paste here (`component.paste_from_design`). The + /// host puts it here; each design's own copies stay in its own clipboard. + pub foreign_copy: Option>, /// Section Analysis: a view cut by a plane (origin, unit normal; the normal side is hidden). pub section: Option<(Vec3, Vec3)>, /// Whether the section's cut faces are hatched (`inspect.section`'s `hatch`; on by default). @@ -594,6 +643,7 @@ impl Session { clipboard: Vec::new(), sketch_clipboard: None, appearance_clipboard: None, + foreign_copy: None, section: None, section_hatch: true, colored_components: None, @@ -1437,6 +1487,7 @@ impl Session { clipboard: self.clipboard.clone(), sketch_clipboard: self.sketch_clipboard.clone(), appearance_clipboard: self.appearance_clipboard.clone(), + foreign_copy: self.foreign_copy.clone(), section: None, section_hatch: true, colored_components: None, diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 05743aaa5..8743451df 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -42,11 +42,14 @@ pub struct DocSlot { struct DocView { render: crate::render_workspace::ViewState, /// Bodies and components copied or cut in this design: their names and paths mean nothing - /// in another one (copied features stay with the session the same way). + /// in another one (copied features stay with the session the same way). Another design + /// pastes them from `SolveApp::foreign_copy`. copied_bodies: Vec, copied_placements: Vec>, cut_bodies: Vec, cut_placements: Vec>, + /// `SolveApp::own_clipboard_stamp`. + own_clipboard_stamp: u64, } impl DocSlot { @@ -116,6 +119,7 @@ fn take_view(app: &mut SolveApp) -> DocView { copied_placements: std::mem::take(&mut app.copied_placements), cut_bodies: std::mem::take(&mut app.cut_bodies), cut_placements: std::mem::take(&mut app.cut_placements), + own_clipboard_stamp: app.own_clipboard_stamp, } } @@ -128,6 +132,8 @@ fn put_view(app: &mut SolveApp, v: DocView) { app.copied_placements = v.copied_placements; app.cut_bodies = v.cut_bodies; app.cut_placements = v.cut_placements; + app.own_clipboard_stamp = v.own_clipboard_stamp; + crate::edit_clipboard::drop_stale(app); } /// Put `slot` into the app and return what was there. @@ -172,6 +178,8 @@ fn swap_in(app: &mut SolveApp, mut slot: DocSlot) -> DocSlot { app.session.crash_journal = out.session.crash_journal; out.session.crash_journal = false; put_view(app, slot.view); + // Components picked in the browser are the outgoing design's: Copy must not copy them here. + app.tree.picked_components.clear(); // Preferences the session holds go with the user, not the tab (#680). app.session.auto_project = out.session.auto_project; // Views cache by revision: the incoming design must not look unchanged. diff --git a/crates/ui-egui/src/edit_clipboard.rs b/crates/ui-egui/src/edit_clipboard.rs index 495e930a2..73febe7e0 100644 --- a/crates/ui-egui/src/edit_clipboard.rs +++ b/crates/ui-egui/src/edit_clipboard.rs @@ -12,6 +12,12 @@ //! the component (`component.move_bodies`, `occurrence.reparent`, where they are), and a copy or //! Esc before that leaves them be. A component placed more than once (an instance) isn't cut. //! +//! Copied bodies paste into another design (tab) too, as imported bodies without their history, +//! and copied components as independent copies with their history (Paste and Paste New alike), +//! where they were in the world (`component.paste_from_design`); cut ones paste there as copies, +//! the originals staying. The last copy or cut in any design is what pastes: a design's own +//! clipboard empties when another design copied after it. +//! //! The window system turns Ctrl+C / Ctrl+V into clipboard events, not key presses, and only sends //! the paste event while the system clipboard holds text. So a copy also puts a short line of //! text on the system clipboard (a menu's Copy leaves it for the next frame, which has the @@ -50,18 +56,52 @@ fn body_selection(app: &SolveApp) -> Vec { app.session.selection.iter().filter_map(|s| if let Sel::Body { name } = s { Some(name.clone()) } else { None }).collect() } +/// Does Copy copy the whole design (its row picked in the browser)? Features, bodies or +/// components selected since then are what was meant, so the design gives way to them. +fn copying_design(app: &SolveApp) -> bool { + app.session.active_sketch.is_none() + && app.tree.picked_components == [0] + && crate::timeline::selected_feature_ids(app).is_empty() + && body_selection(app).is_empty() + && placement_selection(app).is_empty() +} + /// Is there something Copy would copy? pub fn something_to_copy(app: &SolveApp) -> bool { if app.session.active_sketch.is_some() { !sketch_selection(app).is_empty() } else { - app.tree.picked_components == [0] + copying_design(app) || !crate::timeline::selected_feature_ids(app).is_empty() || !body_selection(app).is_empty() || !placement_selection(app).is_empty() } } +/// What another design copied or cut last, when that is what pastes here (this design's own +/// clipboard is older). +fn foreign(app: &SolveApp) -> Option<&std::sync::Arc> { + app.foreign_copy.as_ref().filter(|_| app.own_clipboard_stamp != app.clipboard_stamp) +} + +/// Bodies another design copied or cut last: they paste here as imported bodies. +fn foreign_bodies(app: &SolveApp) -> bool { + foreign(app).is_some_and(|c| !c.bodies.is_empty()) +} + +/// This design's clipboard, when another design has copied or cut since (switching to this +/// design): it empties, so the last copy is what pastes. +pub(crate) fn drop_stale(app: &mut SolveApp) { + if app.own_clipboard_stamp != app.clipboard_stamp { + app.session.clipboard.clear(); + app.session.sketch_clipboard = None; + app.copied_bodies.clear(); + app.copied_placements.clear(); + app.cut_bodies.clear(); + app.cut_placements.clear(); + } +} + /// Is there something Paste would paste here? pub fn can_paste(app: &SolveApp) -> bool { if app.session.active_sketch.is_some() { @@ -70,7 +110,8 @@ pub fn can_paste(app: &SolveApp) -> bool { // A copied design is what pastes, and never into itself. !design_copied_here(app) } else { - !app.session.clipboard.is_empty() + foreign(app).is_some() + || !app.session.clipboard.is_empty() || !app.cut_bodies.is_empty() || !app.cut_placements.is_empty() || !app.copied_bodies.is_empty() @@ -88,7 +129,7 @@ pub fn pasting_components(app: &SolveApp) -> bool { app.session.active_sketch.is_none() && app.session.clipboard.is_empty() && app.linked_design_clipboard.is_none() - && !app.copied_placements.is_empty() + && (!app.copied_placements.is_empty() || foreign(app).is_some_and(|c| !c.placed.is_empty())) } /// Whether copied features (sketches, …) are what Paste pastes now (a Sketches folder's menu @@ -102,7 +143,7 @@ pub fn pasting_bodies(app: &SolveApp) -> bool { app.session.active_sketch.is_none() && app.session.clipboard.is_empty() && app.linked_design_clipboard.is_none() - && (!app.copied_bodies.is_empty() || !app.cut_bodies.is_empty()) + && (!app.copied_bodies.is_empty() || !app.cut_bodies.is_empty() || foreign_bodies(app)) } /// [`paste_into`], then what was pasted into `group` of the component's `folder`: a group's menu @@ -162,8 +203,12 @@ fn clear_clipboard(app: &mut SolveApp) { } /// A new copy or cut replaces the copied bodies, components, cut bodies and design (copied -/// features and sketch geometry are replaced by the commands that copy them). +/// features and sketch geometry are replaced by the commands that copy them), in this design and +/// for the others: it is the last one. fn replace_clipboard(app: &mut SolveApp) { + app.clipboard_stamp += 1; + app.own_clipboard_stamp = app.clipboard_stamp; + app.foreign_copy = None; app.copied_bodies.clear(); app.copied_placements.clear(); app.cut_bodies.clear(); @@ -171,8 +216,12 @@ fn replace_clipboard(app: &mut SolveApp) { app.linked_design_clipboard = None; } -/// Leave bodies that were cut where they are (Esc, or another copy). +/// Leave bodies that were cut where they are (Esc, or another copy): another design has nothing +/// of them to paste either. pub fn drop_cut(app: &mut SolveApp) { + if !app.cut_bodies.is_empty() || !app.cut_placements.is_empty() { + app.foreign_copy = None; + } app.cut_bodies.clear(); app.cut_placements.clear(); } @@ -200,7 +249,7 @@ pub fn copy_design(app: &mut SolveApp) -> bool { /// Copy the selection: sketch geometry in a sketch, otherwise timeline features. pub fn copy(app: &mut SolveApp) -> bool { - if app.session.active_sketch.is_none() && app.tree.picked_components == [0] { + if copying_design(app) { return copy_design(app); } if app.session.active_sketch.is_some() { @@ -229,6 +278,7 @@ pub fn copy(app: &mut SolveApp) -> bool { let names: Vec = placements.iter().filter_map(|p| app.session.occurrence_placement(p).ok()).map(|p| p.name).collect(); app.set_status(format!("Copied {} (Ctrl+V pastes an instance, Ctrl+Shift+V a new copy)", names.join(", ")), false); leave_text(app, format!("SolidCraft components: {}", names.join(", "))); + app.foreign_copy = Some(std::sync::Arc::new(solidcraft_engine::ForeignCopy::of(&app.session, Vec::new(), placements.clone()))); app.copied_placements = placements; return true; } @@ -238,6 +288,7 @@ pub fn copy(app: &mut SolveApp) -> bool { replace_clipboard(app); app.set_status(format!("Copied {}", bodies.join(", ")), false); leave_text(app, format!("SolidCraft bodies: {}", bodies.join(", "))); + app.foreign_copy = Some(std::sync::Arc::new(solidcraft_engine::ForeignCopy::of(&app.session, bodies.clone(), Vec::new()))); app.copied_bodies = bodies; return true; } @@ -303,6 +354,7 @@ pub fn cut(app: &mut SolveApp) -> bool { let names: Vec = placements.iter().filter_map(|p| app.session.occurrence_placement(p).ok()).map(|p| p.name).collect(); app.set_status(format!("Cut {}: paste to move it into a component (Esc leaves it)", names.join(", ")), false); leave_text(app, format!("SolidCraft components: {}", names.join(", "))); + app.foreign_copy = Some(std::sync::Arc::new(solidcraft_engine::ForeignCopy::of(&app.session, Vec::new(), placements.clone()))); app.cut_placements = placements; return true; } @@ -313,6 +365,8 @@ pub fn cut(app: &mut SolveApp) -> bool { clear_clipboard(app); app.set_status(format!("Cut {}: paste to move it into a component (Esc leaves it)", bodies.join(", ")), false); leave_text(app, format!("SolidCraft bodies: {}", bodies.join(", "))); + // Another design pastes copies of them. + app.foreign_copy = Some(std::sync::Arc::new(solidcraft_engine::ForeignCopy::of(&app.session, bodies.clone(), Vec::new()))); app.cut_bodies = bodies; return true; } @@ -397,6 +451,9 @@ pub fn paste_into(app: &mut SolveApp, at: Option, new_copy: bool, into: Op app.set_status("Pasted linked component: use Move/Copy to position it", false); return true; } + if let Some(copy) = foreign(app).cloned() { + return paste_from_design(app, copy, into); + } // Features copied later replace bodies and components (copying those empties the features). if app.session.clipboard.is_empty() && !app.cut_bodies.is_empty() { return paste_cut_bodies(app, into); @@ -459,6 +516,27 @@ fn paste_placement(app: &SolveApp, at: Option) -> (Vec, [f64; 3]) { (path, [local.x, local.y, local.z]) } +/// The bodies another design copied or cut, into `into` (a component, placed by its placement) +/// as imported bodies, or its components as independent copies, where they were in the world; +/// they are selected. +fn paste_from_design(app: &mut SolveApp, copy: std::sync::Arc, (component, path): (u64, Vec)) -> bool { + let design = copy.design.clone(); + app.session.foreign_copy = Some(copy); + let Ok(out) = app.run("component.paste_from_design", json!({ "component": component, "component_path": path })) else { return false }; + if let Some(paths) = out.get("paths").and_then(Value::as_array) { + // Pasted components arrive folded. + for path in paths { + let path: Vec = path.as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(); + crate::browser::close_placement(app, &path); + } + app.set_status(format!("Pasted independent copies of the components copied in {design}"), false); + return true; + } + let made: Vec<&str> = out.get("bodies").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + app.set_status(format!("Pasted {} as imported bodies (without their history)", made.join(", ")), false); + true +} + /// Move the cut bodies into `into` (a component, placed by its placement), where they are; they /// are selected and the clipboard empties. Bodies already in it stay as they are. A move that /// can't be done says why and keeps the cut, to paste somewhere else. @@ -472,12 +550,14 @@ fn paste_cut_bodies(app: &mut SolveApp, (component, path): (u64, Vec)) -> b .collect(); drop(state); let cut = std::mem::take(&mut app.cut_bodies); + let foreign = app.foreign_copy.take(); if moving.is_empty() { app.set_status("Already in that component: nothing to move", false); return true; } if app.run("component.move_bodies", json!({ "bodies": moving, "component": component, "component_path": path })).is_err() { app.cut_bodies = cut; + app.foreign_copy = foreign; return false; } let _ = app.run("select.set", json!({ "items": moving.iter().map(|b| json!({"type": "body", "name": b})).collect::>() })); @@ -490,6 +570,7 @@ fn paste_cut_bodies(app: &mut SolveApp, (component, path): (u64, Vec)) -> b /// as they are. A move that can't be done (into itself) says why and keeps the cut. fn paste_cut_placements(app: &mut SolveApp, (component, path): (u64, Vec)) -> bool { let cut = std::mem::take(&mut app.cut_placements); + let foreign = app.foreign_copy.take(); let mut moved = Vec::new(); for from in &cut { let Some(&occurrence) = from.last() else { continue }; @@ -499,6 +580,7 @@ fn paste_cut_placements(app: &mut SolveApp, (component, path): (u64, Vec)) let params = json!({ "occurrence": occurrence, "path": from, "parent": component, "parent_path": path }); let Ok(out) = app.run("occurrence.reparent", params) else { app.cut_placements = cut; + app.foreign_copy = foreign; return false; }; let to: Vec = out.get("path").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(); diff --git a/crates/ui-egui/src/edit_clipboard_tests.rs b/crates/ui-egui/src/edit_clipboard_tests.rs index 6d15a184b..dfefdaf92 100644 --- a/crates/ui-egui/src/edit_clipboard_tests.rs +++ b/crates/ui-egui/src/edit_clipboard_tests.rs @@ -530,24 +530,103 @@ fn select(app: &mut crate::SolveApp, item: Value) { app.run("select.set", json!({"items": [item]})).unwrap(); } -/// Copied bodies belong to the design they were copied in: another tab has nothing of them to -/// paste, and their own design still pastes them when it is back. +/// A session named `name` with a 2 mm cube "Cube", raised 10 mm. +fn design_with_cube(name: &str) -> solidcraft_engine::Session { + let mut s = solidcraft_engine::Session::default(); + s.doc_mut().name = name.into(); + s.execute("solid.box", &json!({"length":2,"width":2,"height":2,"body_name":"Cube","translate":[0,0,10]})).unwrap(); + s +} + +/// Bodies copied in one design paste into another (tab) as imported bodies, where they were in +/// the world, numbered when the name is taken there; their own design still pastes them as +/// copies with history when it is back. #[test] -fn copied_bodies_stay_with_their_design() { - let mut app = plain_app(); - app.run("solid.box", json!({"length":2,"width":2,"height":2,"body_name":"Cube"})).unwrap(); +fn copied_bodies_paste_into_another_design_as_imported_bodies() { + let mut app = crate::SolveApp::new(design_with_cube("Bracket"), crate::Services::default()); + let was = app.session.world_state().body("Cube").unwrap().mesh().bounds(); select(&mut app, json!({"type": "body", "name": "Cube"})); assert!(super::copy(&mut app)); - crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap(); - assert!(!super::can_paste(&app), "nothing of the other design pastes here"); - assert!(!super::paste(&mut app, None)); - assert!(app.session.model.state().bodies.is_empty()); - crate::documents::switch(&mut app, 0); - assert!(super::can_paste(&app)); + crate::documents::open_tab(&mut app, design_with_cube("Frame")).unwrap(); + assert!(super::can_paste(&app) && super::pasting_bodies(&app)); assert!(super::paste(&mut app, None)); + let is = app.session.world_state().body("Cube (2)").unwrap().mesh().bounds(); + assert!(was.min.dist(is.min) < 1e-6 && was.max.dist(is.max) < 1e-6, "{was:?} vs {is:?}"); + let feature = app.session.doc.find_feature("Import1").expect("one Import feature"); + assert!(matches!(feature.kind, solidcraft_engine::doc::FeatureKind::Import { .. })); + assert!(app.session.selection.contains(&Sel::Body { name: "Cube (2)".into() })); + crate::documents::switch(&mut app, 0); + assert!(super::paste(&mut app, None)); + assert!(app.session.doc.find_feature("Import1").is_none(), "its own design pastes a copy with history"); assert!(app.session.model.state().body("Cube (2)").is_some()); } +/// The last copy in any design is what pastes: a copy in another tab replaces this tab's own. +#[test] +fn the_last_copy_in_any_design_is_what_pastes() { + let mut app = crate::SolveApp::new(design_with_cube("Bracket"), crate::Services::default()); + select(&mut app, json!({"type": "body", "name": "Cube"})); + assert!(super::copy(&mut app)); + let mut frame = solidcraft_engine::Session::default(); + frame.doc_mut().name = "Frame".into(); + frame.execute("solid.box", &json!({"length":1,"width":1,"height":1,"body_name":"Pin"})).unwrap(); + crate::documents::open_tab(&mut app, frame).unwrap(); + select(&mut app, json!({"type": "body", "name": "Pin"})); + assert!(super::copy(&mut app)); + crate::documents::switch(&mut app, 0); + assert!(app.copied_bodies.is_empty(), "Bracket's own copy is stale"); + assert!(super::paste(&mut app, None)); + assert!(app.session.model.state().body("Pin").is_some(), "Frame's body pasted"); + assert!(app.session.model.state().body("Cube (2)").is_none()); + // A copy that fails anywhere leaves nothing for any design. + app.run("select.clear", json!({})).unwrap(); + assert!(!super::copy(&mut app)); + crate::documents::switch(&mut app, 1); + assert!(!super::can_paste(&app)); +} + +/// Bodies cut in one design paste into another as copies: the originals stay. Esc on the cut +/// leaves nothing to paste anywhere. +#[test] +fn bodies_cut_in_another_design_paste_as_copies() { + let mut app = crate::SolveApp::new(design_with_cube("Bracket"), crate::Services::default()); + select(&mut app, json!({"type": "body", "name": "Cube"})); + assert!(super::cut(&mut app)); + crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap(); + assert!(super::paste(&mut app, None)); + assert!(app.session.model.state().body("Cube").is_some()); + crate::documents::switch(&mut app, 0); + assert!(app.session.model.state().body("Cube").is_some(), "the original stays"); + super::drop_cut(&mut app); + crate::documents::switch(&mut app, 1); + assert!(!super::can_paste(&app), "Esc left nothing to paste"); +} + +/// Components copied in one design paste into another as independent copies with their history +/// (Paste and Paste New alike), named as they were, folded and selected; the original stays. +#[test] +fn components_copied_in_another_design_paste_as_independent_copies() { + let mut app = plain_app(); + app.session.doc_mut().name = "Bracket".into(); + let at = app.run("component.create", json!({"name":"Part"})).unwrap()["occurrence"].as_u64().unwrap(); + app.run("solid.box", json!({"length":2,"width":2,"height":2,"body_name":"Cube"})).unwrap(); + app.run("component.activate", json!({"component": 0})).unwrap(); + select(&mut app, json!({"type": "occurrence", "path": [at]})); + assert!(super::copy(&mut app)); + crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap(); + assert!(super::can_paste(&app) && super::pasting_components(&app)); + let features = app.session.doc.features.len(); + assert!(super::paste_as(&mut app, None, true)); + let part = app.session.doc.components.iter().find(|c| c.name == "Part").expect("the pasted component").id; + assert!(app.session.doc.features.len() > features, "with its history"); + let state = app.session.model.state(); + assert_eq!(app.session.doc.model_body_component(state.body("Cube").expect("its body")), part); + drop(state); + assert!(matches!(app.session.selection.as_slice(), [Sel::Occurrence { .. }])); + crate::documents::switch(&mut app, 0); + assert_eq!(app.session.doc.components.len(), 1, "the original stays as it was"); +} + /// Whatever was copied last is what pastes: a component copied after a body replaces it, and a /// body copied after that replaces the component. #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 886239139..02bb3d410 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -557,6 +557,14 @@ pub struct SolveApp { pub copied_placements: Vec>, /// Bodies cut with Cut (by name): they stay until Paste moves them into a component. pub cut_bodies: Vec, + /// Counts copies and cuts in every open design: the last one is what pastes. + pub clipboard_stamp: u64, + /// The copy or cut this design made last (`clipboard_stamp` then): when it isn't the last + /// one, what this design copied is stale and another design's copy pastes. + pub own_clipboard_stamp: u64, + /// The bodies (or components) the last copy or cut took, with the design they were in, to + /// paste into another design (`component.paste_from_design`). + pub foreign_copy: Option>, /// Component placements cut with Cut (by path): they stay until Paste moves them. pub cut_placements: Vec>, /// Esc was already acted on this frame (by the shortcuts), so later handlers skip it. @@ -750,6 +758,9 @@ impl SolveApp { clipboard_text: None, copied_placements: Vec::new(), cut_bodies: Vec::new(), + clipboard_stamp: 0, + own_clipboard_stamp: 0, + foreign_copy: None, cut_placements: Vec::new(), esc_handled: false, last_escape: None,