Sketch: copy completed sketches between designs (#5427) (#8962)

* claim: #5427

* Sketch: paste completed sketches across design tabs
This commit is contained in:
Colin Faulkingham authored and GitHub committed 2026-10-30 14:09:37 +00:00
1 parent 332f96c26a
commit 085853315d
6 files changed
+607 -6

No files matched your search

+214 -1
View File
@@ -16,7 +16,8 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("timeline.paste", "Paste Features", paste).icon("paste").params(
"translate?: [x,y,z] (moves the copies' geometry); component?: where the copies go (default: the active one), \
component_path?: its placement (default: the active one, else its only one); the copies go at the marker, each where \
its original is in the world (copies into their own component keep its coordinates); body transfers are left out",
its original is in the world (copies into their own component keep its coordinates); body transfers are left out; \
from_design?: true to paste sketch features from the host's cross-design clipboard snapshot",
),
];
@@ -35,6 +36,7 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
let copied: Vec<solidcraft_doc::Feature> = s.doc.features.iter().filter(|f| ids.contains(&f.id)).cloned().collect();
let names: Vec<String> = copied.iter().map(|f| f.name.clone()).collect();
s.clipboard = copied;
s.foreign_copy = Some(std::sync::Arc::new(crate::ForeignCopy::of_features(s)));
Ok(json!({"copied": names}))
}
@@ -55,6 +57,11 @@ pub(in crate::cmd) fn explicit_planes(p: &mut PlaneRef) {
fn paste(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "timeline.paste";
match p.get("from_design") {
Some(Value::Bool(true)) => return super::clipboard_foreign::paste(s, p),
None | Some(Value::Bool(false)) => {}
_ => return Err(bad(cmd, "`from_design` must be true or false")),
}
if s.clipboard.is_empty() {
return Err(bad(cmd, "nothing copied (timeline.copy first)"));
}
@@ -249,6 +256,212 @@ mod tests {
run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN)
}
fn dimensioned_sketch() -> Session {
let mut s = Session::default();
run(&mut s, "parameters.change", json!({"name": "base", "expression": "5 mm"}));
run(&mut s, "parameters.change", json!({"name": "width", "expression": "base * 4"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]}));
run(&mut s, "sketch.constraint.coincident", json!({"a": "p1", "b": "origin"}));
let width = run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": "width"}))["param"].as_str().unwrap().to_string();
run(&mut s, "sketch.dimension", json!({"entities": ["l2"], "value": format!("{width} / 2")}));
run(&mut s, "sketch.finish", json!({}));
s
}
fn sketch_area(s: &Session, id: u64) -> f64 {
s.model.state().sketch(id).unwrap().profiles.iter().map(|p| p.area).sum()
}
#[test]
fn foreign_sketch_paste_keeps_parameter_graph_snapshot_and_undo() {
let mut source = dimensioned_sketch();
run(&mut source, "timeline.copy", json!({"features": ["S"]}));
let mut target = dimensioned_sketch();
run(&mut target, "document.units", json!({"units": "in"}));
run(&mut target, "parameters.change", json!({"name": "base", "expression": "7 mm"}));
target.foreign_copy = source.foreign_copy.clone();
run(&mut source, "parameters.change", json!({"name": "base", "expression": "30 mm"}));
drop(source);
let before = target.doc.to_json();
let undo = target.undo.len();
let result = run(&mut target, "timeline.paste", json!({"from_design": true}));
let id = result["pasted"][0]["id"].as_u64().unwrap();
assert_eq!(result["pasted"][0]["name"], "S (2)");
assert!((sketch_area(&target, id) - 200.).abs() < 1e-6);
assert_eq!(target.doc.param("base").unwrap().expr, "7 mm");
assert_eq!(target.doc.param("base_2").unwrap().expr, "5 mm");
assert_eq!(target.doc.param("width_2").unwrap().expr, "base_2 * 4");
assert_eq!(target.undo.len(), undo + 1);
let after = target.doc.to_json();
run(&mut target, "edit.undo", json!({}));
assert_eq!(target.doc.to_json(), before);
run(&mut target, "edit.redo", json!({}));
assert_eq!(target.doc.to_json(), after);
let second = run(&mut target, "timeline.paste", json!({"from_design": true}))["pasted"][0]["id"].as_u64().unwrap();
assert!((sketch_area(&target, second) - 200.).abs() < 1e-6);
run(&mut target, "parameters.change", json!({"name": "base_2", "expression": "10 mm"}));
assert!((sketch_area(&target, id) - 800.).abs() < 1e-6);
assert!((sketch_area(&target, second) - 200.).abs() < 1e-6, "each paste owns its parameters");
assert!(solidcraft_doc::Document::from_json(&target.doc.to_json()).is_ok());
}
#[test]
fn foreign_sketch_paste_preserves_world_position_in_a_placed_component() {
use solidcraft_geom::Vec3;
let mut source = dimensioned_sketch();
let arc = [Vec3::new(1., 0., 0.), Vec3::new(0., 0., 1.), Vec3::new(-1., 0., 0.)];
for space in [solidcraft_sketch::WireSpace::World, solidcraft_sketch::WireSpace::Component] {
source.doc_mut().sketch_mut(1).unwrap().add_drawn_arc_in(&arc, space).unwrap();
}
source.refresh();
run(&mut source, "timeline.copy", json!({"features": ["S"]}));
let mut target = Session::default();
let made = run(&mut target, "component.create", json!({"name": "Target", "activate": false}));
let component = made["component"].as_u64().unwrap();
let occurrence = made["occurrence"].as_u64().unwrap();
run(&mut target, "occurrence.ground", json!({"occurrence": occurrence, "grounded": false}));
run(&mut target, "occurrence.move", json!({"occurrence": occurrence, "translate": [100, 20, 30], "axis": [0, 0, 1], "angle": "90 deg"}));
target.foreign_copy = source.foreign_copy.clone();
let id = run(&mut target, "timeline.paste", json!({"from_design": true, "component": component, "component_path": [occurrence]}))["pasted"]
[0]["id"]
.as_u64()
.unwrap();
let original = source.world_state().sketch(1).unwrap().plane;
let pasted = target.world_state().sketch(id).unwrap().plane;
assert!(pasted.origin.dist(original.origin) < 1e-6, "{original:?} vs {pasted:?}");
assert!(pasted.x.dist(original.x) < 1e-6);
assert!(pasted.y.dist(original.y) < 1e-6);
assert!((sketch_area(&target, id) - 200.).abs() < 1e-6);
assert_eq!(target.doc.feature(id).unwrap().component, component);
for (original, pasted) in
source.world_state().sketch(1).unwrap().sketch.wires.iter().zip(&target.world_state().sketch(id).unwrap().sketch.wires)
{
for (a, b) in original.pts.iter().chain(&original.fit).zip(pasted.pts.iter().chain(&pasted.fit)) {
assert!(a.dist(*b) < 1e-6, "wire {:?}: {a:?} vs {b:?}", original.space);
}
let (a, b) = (original.arc.unwrap(), pasted.arc.unwrap());
assert!(a.center.dist(b.center) < 1e-6);
assert!(a.normal.dist(b.normal) < 1e-6);
assert!((a.radius - b.radius).abs() < 1e-6);
}
let moved = run(
&mut target,
"timeline.paste",
json!({"from_design": true, "component": component, "component_path": [occurrence], "translate": [2, 3, 4]}),
)["pasted"][0]["id"]
.as_u64()
.unwrap();
let frame = target.placed_document().path_transform(component, &[occurrence]).unwrap();
let delta = solidcraft_doc::apply_vector(&frame, Vec3::new(2., 3., 4.));
for (original, pasted) in
source.world_state().sketch(1).unwrap().sketch.wires.iter().zip(&target.world_state().sketch(moved).unwrap().sketch.wires)
{
for (a, b) in original.pts.iter().chain(&original.fit).zip(pasted.pts.iter().chain(&pasted.fit)) {
assert!((*a + delta).dist(*b) < 1e-6, "translated wire {:?}: {a:?} vs {b:?}", original.space);
}
}
}
#[test]
fn foreign_sketch_paste_refuses_external_references_and_bad_parameters_atomically() {
let mut source = dimensioned_sketch();
let mut target = dimensioned_sketch();
// The same numeric ID in the target must never become the sketch's missing plane.
if let solidcraft_doc::FeatureKind::Sketch { plane, .. } = &mut source.doc_mut().feature_mut(1).unwrap().kind {
*plane = solidcraft_doc::PlaneRef::Construction { feature: 1.into() };
}
run(&mut source, "timeline.copy", json!({"features": ["S"]}));
target.foreign_copy = source.foreign_copy.clone();
let before = target.doc.to_json();
let undo = target.undo.len();
let error = target.execute("timeline.paste", &json!({"from_design": true})).unwrap_err().to_string();
assert!(error.contains("fixed plane"), "{error}");
assert_eq!(target.doc.to_json(), before);
assert_eq!(target.undo.len(), undo);
for params in
[json!({"from_design":"yes"}), json!({"from_design":true,"translate":"bad"}), json!({"from_design":true,"component_path":["bad"]})]
{
assert!(target.execute("timeline.paste", &params).is_err());
assert_eq!(target.doc.to_json(), before);
}
}
#[test]
fn foreign_sketch_paste_remaps_links_and_rejects_missing_source_sketches() {
let mut source = dimensioned_sketch();
run(&mut source, "sketch.create", json!({"plane":"XY","offset":5,"name":"Projected"}));
run(&mut source, "sketch.project", json!({"refs":[{"sketch":1,"curve":"l1"}]}));
run(&mut source, "sketch.finish", json!({}));
let mut target = dimensioned_sketch();
run(&mut source, "timeline.copy", json!({"features":["Projected"]}));
target.foreign_copy = source.foreign_copy.clone();
let before = target.doc.to_json();
let err = target.execute("timeline.paste", &json!({"from_design":true})).unwrap_err().to_string();
assert!(err.contains("external projected geometry"), "{err}");
assert_eq!(before, target.doc.to_json());
run(&mut source, "timeline.copy", json!({"features":["S","Projected"]}));
target.foreign_copy = source.foreign_copy.clone();
let result = run(&mut target, "timeline.paste", json!({"from_design":true}));
let first = result["pasted"][0]["id"].as_u64().unwrap();
let second = result["pasted"][1]["id"].as_u64().unwrap();
let copied = target.doc.sketch(second).unwrap();
assert!(matches!(copied.links[0].source, solidcraft_sketch::LinkSource::SketchCurve { sketch, .. } if sketch == first));
assert!(target.model.result(second).unwrap().error.is_none());
}
#[test]
fn foreign_sketch_paste_keeps_plane_input_units_and_text_parameters() {
let mut source = Session::default();
run(&mut source, "document.units", json!({"units":"in"}));
run(&mut source, "parameters.add", json!({"name":"height","expression":"2","unit":""}));
run(&mut source, "parameters.add", json!({"name":"Label","expression":"ABC","unit":"text"}));
run(&mut source, "sketch.create", json!({"plane":"XY","offset":"height","name":"Text"}));
run(&mut source, "sketch.text", json!({"text_expression":"Label + '-X'","at":[0,0],"height":"5 mm"}));
run(&mut source, "sketch.finish", json!({}));
run(&mut source, "timeline.copy", json!({"features":["Text"]}));
let mut target = Session::default();
run(&mut target, "parameters.add", json!({"name":"Label","expression":"other","unit":"text"}));
run(&mut target, "parameters.add", json!({"name":"d1","expression":"reserved","unit":"text"}));
target.foreign_copy = source.foreign_copy.clone();
let id = run(&mut target, "timeline.paste", json!({"from_design":true}))["pasted"][0]["id"].as_u64().unwrap();
assert!((target.model.state().sketch(id).unwrap().plane.origin.z - 50.8).abs() < 1e-9);
assert_eq!(target.doc.text_param("Label").unwrap().text, "other");
assert_eq!(target.doc.text_param("Label_2").unwrap().text, "ABC");
assert_eq!(target.doc.text_param("d1").unwrap().text, "reserved");
assert!(target.doc.param("d1").is_none());
let state = target.model.state();
let text = &state.sketch(id).unwrap().sketch.links[0].source;
assert!(matches!(text, solidcraft_sketch::LinkSource::Text { text, .. } if text == "ABC-X"));
assert!(solidcraft_doc::Document::from_json(&target.doc.to_json()).is_ok());
}
#[test]
fn foreign_sketch_paste_copies_equation_parameters_but_not_the_local_variable() {
let mut source = Session::default();
run(&mut source, "parameters.add", json!({"name":"height","expression":"3 mm"}));
run(&mut source, "sketch.create", json!({"plane":"XY","name":"Curve"}));
run(&mut source, "sketch.equation_curve", json!({"x":"t","y":"height + t * t","start":-2,"end":2}));
run(&mut source, "sketch.finish", json!({}));
run(&mut source, "timeline.copy", json!({"features":["Curve"]}));
let mut target = Session::default();
run(&mut target, "parameters.add", json!({"name":"height","expression":"99 mm"}));
target.foreign_copy = source.foreign_copy.clone();
let id = run(&mut target, "timeline.paste", json!({"from_design":true}))["pasted"][0]["id"].as_u64().unwrap();
let state = target.model.state();
let sketch = &state.sketch(id).unwrap().sketch;
let equation = &sketch.equations[0];
assert_eq!(equation.x.as_deref(), Some("t"));
assert_eq!(equation.y, "height_2 + t * t");
let curve = sketch.curves.iter().find(|c| c.id == equation.curve).unwrap();
for point in curve.kind.point_ids() {
let p = sketch.points[point].pos;
assert!((p.y - 3. - p.x * p.x).abs() < 1e-8, "{p:?}");
}
assert!(target.doc.param("t").is_none());
}
/// Features pasted into a component placed elsewhere (offset and turned) are carried into its
/// frame: the pasted body sits where the original is in the world, in that component, and the
/// pasted sketch is named after the original.
+310
View File
@@ -0,0 +1,310 @@
//! Independent sketch features pasted from the immutable clipboard of another design.
use std::collections::{BTreeMap, BTreeSet};
use serde_json::{Value, json};
use solidcraft_doc::{Document, Feature, FeatureKind, Mat, PlaneRef};
use crate::params::{bad, vec3};
use crate::{Result, Sel, Session};
const CMD: &str = "timeline.paste";
/// References to geometry outside the copied sketches must never resolve against coincident
/// IDs or names in the destination. Fixed and expression-placed planes are self-contained.
fn independent_plane(plane: &PlaneRef, depth: usize) -> Result<()> {
if depth > 64 {
return Err(bad(CMD, "copied plane nesting exceeds 64"));
}
match plane {
PlaneRef::Origin { .. } | PlaneRef::Custom { .. } | PlaneRef::Placed { .. } => Ok(()),
PlaneRef::Offset { base, .. } | PlaneRef::Flipped { base, .. } | PlaneRef::AtAngle { base, line: None, .. } => {
independent_plane(base, depth + 1)
}
_ => Err(bad(CMD, "the copied sketch's plane depends on model geometry; convert it to a fixed plane before pasting into another design")),
}
}
fn independent_links(sketch: &solidcraft_sketch::Sketch, features: &BTreeSet<u64>, moved: bool) -> Result<()> {
use solidcraft_sketch::LinkSource as L;
for link in &sketch.links {
let supported = match &link.source {
L::Text { .. } | L::SketchAxis { .. } => true,
L::SketchCurve { sketch, .. } | L::SketchPoint { sketch, .. } => features.contains(sketch),
L::Origin | L::Axis { .. } => !moved,
L::Plane { name } => !moved && solidcraft_geom::Plane::named(name).is_some(),
_ => false,
};
if !supported {
return Err(bad(
CMD,
"the copied sketch has external projected geometry; unlink it or copy its source sketches before pasting into another design",
));
}
}
Ok(())
}
fn free_parameter_name(base: &str, taken: &mut BTreeSet<String>) -> Result<String> {
for index in 1..=solidcraft_doc::MAX_PARAMS + 1 {
let name = if index == 1 { base.to_string() } else { format!("{base}_{index}") };
if Document::param_name_problem(&name).is_none() && taken.insert(name.clone()) {
return Ok(name);
}
}
Err(bad(CMD, format!("no free name for copied parameter {base}")))
}
fn model_parameter_name(taken: &mut BTreeSet<String>) -> Result<String> {
for index in 1..=taken.len() + 1 {
let name = format!("d{index}");
if taken.insert(name.clone()) {
return Ok(name);
}
}
Err(bad(CMD, "no free model parameter name"))
}
/// Bring the complete expression dependency graph, including dimensions driven by another
/// dimension. Use the source definitions' units, never a destination parameter with the same name.
fn parameters(target: &mut Document, source: &Document, features: &[Feature], mapped: &mut BTreeMap<String, String>) -> Result<()> {
let definitions: BTreeMap<_, _> = source.param_defs().into_iter().map(|p| (p.name.clone(), p)).collect();
let mut pending: Vec<String> = features.iter().flat_map(|f| f.kind.expressions()).flat_map(solidcraft_doc::expr::references).collect();
let mut texts = BTreeSet::new();
for feature in features {
if let FeatureKind::Sketch { sketch, .. } = &feature.kind {
pending.extend(sketch.constraints.iter().filter_map(|c| c.param.clone()));
let text_and_points = sketch
.links
.iter()
.filter_map(|l| match &l.source {
solidcraft_sketch::LinkSource::Text { exprs, .. } => Some(exprs.list()),
_ => None,
})
.flatten()
.chain(sketch.points.iter().filter_map(|p| p.exprs.as_deref()).flat_map(solidcraft_sketch::PointExprs::list));
pending.extend(text_and_points.flat_map(|(_, e)| solidcraft_doc::expr::references(e)));
for equation in &sketch.equations {
pending
.extend(equation.list().into_iter().flat_map(|(_, e)| solidcraft_doc::expr::references(e)).filter(|n| n != equation.variable()));
}
texts.extend(sketch.text_word_exprs().into_iter().flat_map(|e| solidcraft_doc::text_params::references(e)));
}
}
let mut used = BTreeSet::new();
let mut work = 0;
while let Some(name) = pending.pop() {
work += 1;
if work > 100_000 {
return Err(bad(CMD, "copied parameter references exceed work limit"));
}
if used.insert(name.clone()) {
let p = definitions.get(&name).ok_or_else(|| bad(CMD, format!("copied sketch uses missing parameter {name}")))?;
pending.extend(solidcraft_doc::expr::references(&p.expr));
}
}
if target.params.len() + target.text_params.len() + used.len() + texts.len() > solidcraft_doc::MAX_PARAMS {
return Err(bad(CMD, "too many copied parameters"));
}
let mut taken: BTreeSet<_> = target.param_defs().into_iter().map(|p| p.name).chain(target.text_params.iter().map(|p| p.name.clone())).collect();
for name in &used {
if mapped.contains_key(name) {
continue;
}
let definition = definitions.get(name).ok_or_else(|| bad(CMD, "missing copied parameter definition"))?;
let model = source.param(name).is_none_or(|p| p.model);
let new = if model {
let new = model_parameter_name(&mut taken)?;
target.params.push(solidcraft_doc::Param {
name: new.clone(),
expr: definition.expr.clone(),
unit: definition.unit.clone(),
comment: String::new(),
model: true,
});
new
} else {
let new = free_parameter_name(name, &mut taken)?;
let mut p = source.param(name).cloned().ok_or_else(|| bad(CMD, "missing copied user parameter"))?;
p.name = new.clone();
target.params.push(p);
new
};
mapped.insert(name.clone(), new);
}
for name in texts {
let mut p = source.text_param(&name).cloned().ok_or_else(|| bad(CMD, format!("copied sketch uses missing text parameter {name}")))?;
p.name = free_parameter_name(&name, &mut taken)?;
mapped.insert(name, p.name.clone());
target.text_params.push(p);
}
for (old, new) in mapped.iter() {
if let Some(definition) = definitions.get(old)
&& let Some(p) = target.params.iter_mut().find(|p| p.name == *new)
{
p.expr = solidcraft_doc::clone_expression(&definition.expr, mapped);
p.comment = source.param(old).map(|p| p.comment.clone()).or_else(|| source.param_comments.get(old).cloned()).unwrap_or_default();
}
if let Some(comment) = source.param_comments.get(old) {
target.param_comments.insert(new.clone(), comment.clone());
}
}
Ok(())
}
fn text_expression(source: &str, mapped: &BTreeMap<String, String>) -> String {
let mut result = source.to_string();
let mut temporary = Vec::new();
for (i, (old, new)) in mapped.iter().enumerate() {
let mut token = format!("__paste_text_{i}");
while source.contains(&token) || mapped.keys().chain(mapped.values()).any(|name| name == &token) {
token.push('_');
}
result = solidcraft_doc::text_params::rename_reference(&result, old, &token);
temporary.push((token, new));
}
for (token, new) in temporary {
result = solidcraft_doc::text_params::rename_reference(&result, &token, new);
}
result
}
pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
let copy = s.foreign_copy.clone().ok_or_else(|| bad(CMD, "nothing was copied in another design"))?;
if copy.features.is_empty() || copy.features.len() > 1000 {
return Err(bad(CMD, "copy 1…1000 sketches before pasting into another design"));
}
let component = match p.get("component") {
None => s.active_component,
Some(v) => {
let key = match v {
Value::String(name) => name.clone(),
Value::Number(n) => n.to_string(),
_ => return Err(bad(CMD, "`component` must be a component id or name")),
};
s.doc.find_component(&key).ok_or_else(|| bad(CMD, format!("no component `{key}`")))?
}
};
let path = match p.get("component_path") {
Some(v) => v
.as_array()
.filter(|a| a.len() <= 64)
.and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())
.ok_or_else(|| bad(CMD, "`component_path` must list 0..64 occurrence ids"))?,
None if component == s.active_component => s.active_occurrence_path.clone().unwrap_or_else(|| s.doc.first_path(component)),
None => super::component::placing::placement_of(s, &s.placed_document(), component, None, "component_path", CMD)?.0,
};
let placed = s.placed_document();
let frame = placed.path_transform(component, &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"))?;
drop(placed);
let mut shift = solidcraft_doc::IDENTITY;
if let Some(t) = p.get("translate") {
let t = vec3(t).ok_or_else(|| bad(CMD, "`translate` must be [x, y, z]"))?;
shift[3] = [t.x, t.y, t.z, 1.];
}
let world_shift = solidcraft_doc::mat_mul(&frame, &solidcraft_doc::mat_mul(&shift, &into_target));
let mut placed_source = (*copy.doc).clone();
for occurrence in &mut placed_source.occurrences {
if let Some(m) = copy.pending_moves.get(&occurrence.id) {
occurrence.transform = *m;
}
}
let selected: BTreeSet<_> = copy.features.iter().map(|f| f.id).collect();
let mut transforms: BTreeMap<u64, Mat> = BTreeMap::new();
for feature in &copy.features {
let FeatureKind::Sketch { plane, sketch } = &feature.kind else {
return Err(bad(CMD, "only sketch features can be pasted between designs; copy a component to include other feature history"));
};
independent_plane(plane, 0)?;
let source_frame = placed_source
.path_transform(feature.component, &placed_source.first_path(feature.component))
.ok_or_else(|| bad(CMD, "the copied sketch's component placement is missing"))?;
let transform = solidcraft_doc::mat_mul(&shift, &solidcraft_doc::mat_mul(&into_target, &source_frame));
independent_links(sketch, &selected, !solidcraft_doc::is_identity(&transform))?;
transforms.insert(feature.id, transform);
}
let mut scratch = s.scratch();
let mut mapped = BTreeMap::new();
let mut ids = BTreeMap::new();
let mut names = BTreeMap::new();
let mut made = Vec::new();
for feature in &copy.features {
let taken = |name: &str| scratch.doc.features.iter().any(|f| f.name == name);
let name = if taken(&feature.name) { solidcraft_doc::copy_name(&feature.name, taken) } else { feature.name.clone() };
let id = scratch.doc_mut().add_feature(feature.kind.clone(), Some(&name))?;
let mut taken: BTreeSet<_> =
scratch.doc.param_defs().into_iter().map(|p| p.name).chain(scratch.doc.text_params.iter().map(|p| p.name.clone())).collect();
let text_names: BTreeSet<_> = scratch.doc.text_params.iter().map(|p| p.name.clone()).collect();
if let Some(added) = scratch.doc_mut().feature_mut(id) {
for name in &mut added.param_names {
if text_names.contains(name) {
*name = model_parameter_name(&mut taken)?;
}
}
}
if let Some(added) = scratch.doc.feature(id) {
mapped.extend(feature.param_names.iter().cloned().zip(added.param_names.iter().cloned()));
}
ids.insert(feature.id, id);
names.insert(feature.name.clone(), name.clone());
made.push(json!({"id": id, "name": name, "from": feature.name}));
}
parameters(scratch.doc_mut(), &copy.doc, &copy.features, &mut mapped)?;
let source_values = copy.doc.param_values().0;
for original in &copy.features {
let mut feature = original.clone();
let transform = transforms.get(&original.id).ok_or_else(|| bad(CMD, "missing copied sketch transform"))?;
// Nonliteral unitless length inputs are interpreted in their design's display units.
// Make that unit explicit before moving the expressions to a design with other units.
if copy.doc.units != s.doc.units {
for (_, e, kind) in feature.kind.inputs_mut() {
if kind == solidcraft_doc::expr::Kind::Length
&& !solidcraft_doc::expr::is_literal(e)
&& let Some((solidcraft_doc::expr::Kind::Length, scale)) = solidcraft_doc::expr::unit_info(copy.doc.units.trim())
&& solidcraft_doc::expr::eval_with(e, &|name| {
source_values.get(name).copied().ok_or_else(|| solidcraft_doc::DocError::Expr(format!("unknown parameter {name}")))
})?
.unitless()
{
*e = format!("({e}) * {scale} mm").into();
}
}
}
feature.remap_clone(&ids, &names, &BTreeMap::new(), &mapped)?;
if let FeatureKind::Sketch { plane, sketch } = &mut feature.kind {
// 3D wires carry their own coordinate space, independently of the sketch plane.
for wire in &mut sketch.wires {
let matrix = if wire.space == solidcraft_sketch::WireSpace::Component { transform } else { &world_shift };
solidcraft_doc::map_wire(wire, matrix);
}
// Patterns and text words have expressions outside FeatureKind's numeric inputs.
for pattern in &mut sketch.patterns {
for e in pattern.count_expression.iter_mut().chain(pattern.expressions.values_mut()) {
*e = solidcraft_doc::clone_expression(e, &mapped);
}
}
for e in sketch.text_word_exprs_mut() {
*e = text_expression(e, &mapped);
}
if !solidcraft_doc::is_identity(transform) {
super::clipboard::explicit_planes(plane);
}
}
feature.kind.transform_geometry(transform);
let id = *ids.get(&original.id).ok_or_else(|| bad(CMD, "missing copied sketch id"))?;
let added = scratch.doc_mut().feature_mut(id).ok_or_else(|| bad(CMD, "missing pasted sketch"))?;
added.kind = feature.kind;
added.component = component;
added.suppressed = original.suppressed;
}
scratch.refresh();
for id in ids.values() {
if let Some(error) = scratch.model.result(*id).and_then(|r| r.error.as_ref()) {
return Err(bad(CMD, format!("the pasted sketch did not rebuild: {error}")));
}
}
scratch.selection = ids.values().map(|id| Sel::Feature { id: *id }).collect();
s.accept_computed(scratch);
Ok(json!({"pasted": made, "errors": [], "notices": []}))
}
+1
View File
@@ -24,6 +24,7 @@ mod bom;
mod browser;
pub(crate) mod clearance;
mod clipboard;
mod clipboard_foreign;
mod compare;
mod component;
mod component_clone;
+21 -2
View File
@@ -185,13 +185,15 @@ 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,
/// Bodies, component placements or timeline features copied in one design, for pasting into another:
/// that design's 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,
/// Timeline features, in their original order (`timeline.paste` with `from_design`).
pub features: Vec<solidcraft_doc::Feature>,
/// Its placed model: what its Browser and view showed.
pub world: Arc<solidcraft_doc::ModelState>,
/// The bodies copied, as its Browser names them (a body seen in another placement under the
@@ -219,6 +221,7 @@ impl ForeignCopy {
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(),
features: Vec::new(),
world: session.world_state(),
bodies,
names,
@@ -229,6 +232,22 @@ impl ForeignCopy {
pending_moves: session.pending_moves.clone(),
}
}
/// Timeline Copy's snapshot. No placed body geometry is needed to paste sketches.
pub fn of_features(session: &Session) -> ForeignCopy {
ForeignCopy {
design: session.doc.name.clone(),
features: session.clipboard.clone(),
world: session.model.state(),
bodies: Vec::new(),
names: Vec::new(),
placements: Vec::new(),
placed: Vec::new(),
doc: session.doc.clone(),
model: session.model.clone(),
pending_moves: session.pending_moves.clone(),
}
}
}
/// One undo step.
+20 -3
View File
@@ -15,7 +15,8 @@
//!
//! 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,
//! where they were in the world (`component.paste_from_design`); completed sketches paste as
//! independent features with their parameters (`timeline.paste`); 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.
//!
@@ -154,7 +155,19 @@ pub fn pasting_components(app: &SolveApp) -> bool {
/// Whether copied features (sketches, …) are what Paste pastes now (a Sketches folder's menu
/// offers them).
pub fn pasting_features(app: &SolveApp) -> bool {
app.session.active_sketch.is_none() && app.linked_design_clipboard.is_none() && !app.session.clipboard.is_empty()
app.session.active_sketch.is_none()
&& app.linked_design_clipboard.is_none()
&& (!app.session.clipboard.is_empty() || foreign(app).is_some_and(|c| !c.features.is_empty()))
}
/// The same engine paste serves the keyboard and the Sketches folder/group menus.
fn paste_features(app: &mut SolveApp, component: u64, path: Vec<u64>) -> Result<Value, String> {
let copy = foreign(app).filter(|c| !c.features.is_empty()).cloned();
let from_design = copy.is_some();
if let Some(copy) = copy {
app.session.foreign_copy = Some(copy);
}
app.run("timeline.paste", json!({ "component": component, "component_path": path, "from_design": from_design }))
}
/// Whether copied or cut bodies are what Paste pastes now (a Bodies folder's menu offers them).
@@ -171,7 +184,7 @@ pub fn pasting_bodies(app: &SolveApp) -> bool {
pub fn paste_into_group(app: &mut SolveApp, at: Option<Pos2>, into: Option<(u64, Vec<u64>)>, group: Option<u64>, folder: &str) -> bool {
let (Some(group), Some((component, path))) = (group, into.clone()) else { return paste_into(app, at, false, into) };
if folder == "sketches" && pasting_features(app) {
let Ok(out) = app.run("timeline.paste", json!({ "component": component, "component_path": path })) else { return false };
let Ok(out) = paste_features(app, component, path) else { return false };
let items: Vec<String> = out
.get("pasted")
.and_then(Value::as_array)
@@ -314,6 +327,7 @@ pub fn copy(app: &mut SolveApp) -> bool {
}
let Ok(out) = app.run("timeline.copy", json!({ "features": features })) else { return copy_failed(app, None) };
replace_clipboard(app);
app.foreign_copy = app.session.foreign_copy.clone();
let names: Vec<&str> = out.get("copied").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
app.set_status(format!("Copied {}", names.join(", ")), false);
leave_text(app, format!("SolidCraft features: {}", names.join(", ")));
@@ -587,6 +601,9 @@ fn paste_placement(app: &SolveApp, at: Option<Pos2>) -> (Vec<u64>, [f64; 3]) {
/// 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<solidcraft_engine::ForeignCopy>, (component, path): (u64, Vec<u64>)) -> bool {
if !copy.features.is_empty() {
return paste_features(app, component, path).is_ok();
}
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 };
@@ -206,6 +206,47 @@ fn ctrl_c_ctrl_v_outside_a_sketch_copies_and_pastes_timeline_features() {
assert_eq!(h.app.session.doc.features.len(), 2, "{:?}", h.app.status);
}
#[test]
fn completed_sketch_copies_and_pastes_into_a_new_design() {
let (mut h, _) = rectangle();
h.app.run("sketch.finish", json!({})).unwrap();
let id = h.app.session.doc.features[0].id;
select(&mut h.app, json!({"type": "feature", "id": id}));
clipboard_event(&mut h, egui::Event::Copy, None);
crate::documents::new_tab(&mut h.app);
clipboard_event(&mut h, egui::Event::Paste("SolidCraft features".into()), None);
assert_eq!(h.app.session.doc.features.len(), 1, "{:?}", h.app.status);
let copied = &h.app.session.doc.features[0];
let sketch = h.app.session.doc.sketch(copied.id).unwrap();
assert_eq!(sketch.curves.len(), 4);
assert!(h.app.session.model.result(copied.id).unwrap().error.is_none());
}
#[test]
fn copied_sketch_survives_source_close_and_pastes_from_a_sketch_group_menu() {
use crate::context_menu::{Target, items, run_item};
let (mut h, _) = rectangle();
h.app.run("sketch.finish", json!({})).unwrap();
select(&mut h.app, json!({"type":"feature","id":1}));
assert!(super::copy(&mut h.app));
crate::documents::new_tab(&mut h.app);
crate::documents::close(&mut h.app, 0, true);
assert!(super::can_paste(&h.app) && super::pasting_features(&h.app));
assert!(!super::pasting_bodies(&h.app) && !super::pasting_components(&h.app));
let group = h.app.run("browser.group", json!({"folder":"sketches","name":"Copied"})).unwrap()["group"].as_u64().unwrap();
let item = items(&h.app, &Target::Group { id: group, scope: "c0".into() }).into_iter().find(|i| i.id == "ui.paste").unwrap();
assert!(item.enabled);
run_item(&mut h.app, &item, egui::Pos2::ZERO);
let id = h.app.session.doc.find_feature("Sketch1").unwrap().id;
assert_eq!(h.app.session.doc.sketch(id).unwrap().curves.len(), 4);
assert!(h.app.session.doc.browser_groups.iter().any(|g| g.id == group && g.items.contains(&id.to_string())));
// A later copy in this design replaces the cross-design snapshot everywhere.
select(&mut h.app, json!({"type":"feature","id":id}));
assert!(super::copy(&mut h.app));
assert!(super::paste(&mut h.app, None));
assert!(h.app.session.doc.find_feature("Sketch1 (2)").is_some());
}
#[test]
fn ctrl_x_cuts_the_sketch_selection_and_ctrl_v_brings_it_back() {
let (mut h, rect) = rectangle();