Squashed for the rebase onto main. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"en": {
|
||||
"cmd.component_copy_bodies": "Paste Bodies",
|
||||
"cmd.occurrence_reparent": "Move to Component"
|
||||
},
|
||||
"ja": {
|
||||
"cmd.component_copy_bodies": "ボディを貼り付け",
|
||||
"cmd.occurrence_reparent": "コンポーネントへ移動"
|
||||
},
|
||||
"zh": {
|
||||
"cmd.component_copy_bodies": "粘贴实体",
|
||||
"cmd.occurrence_reparent": "移动到组件"
|
||||
}
|
||||
}
|
||||
@@ -272,6 +272,12 @@ impl Document {
|
||||
Some((c, m))
|
||||
}
|
||||
|
||||
/// World transform of one placement of `component`: the occurrence `path` from the root
|
||||
/// (empty for the root itself). `None` when the path no longer leads to that component.
|
||||
pub fn path_transform(&self, component: u64, path: &[u64]) -> Option<Mat> {
|
||||
self.path_placement(path).and_then(|(c, m)| (c == component).then_some(m))
|
||||
}
|
||||
|
||||
/// Every placement of each component: (component, occurrence path ids, world transform).
|
||||
/// A branch stops past [`MAX_PLACEMENT_DEPTH`] levels, the walk past [`MAX_PLACEMENTS`] placements.
|
||||
pub fn placements(&self) -> Vec<(u64, Vec<u64>, Mat)> {
|
||||
@@ -389,12 +395,36 @@ impl Document {
|
||||
false
|
||||
}
|
||||
|
||||
/// Would putting a placement of `component` into `parent` put it inside itself: is `parent`
|
||||
/// the component, or inside it, created in it or placed in it at any depth? Placements can sit
|
||||
/// apart from where their component was created ([`Self::component_within`] follows only
|
||||
/// that), so both are followed.
|
||||
pub fn inside_component(&self, parent: u64, component: u64) -> bool {
|
||||
if self.component_within(parent, component) {
|
||||
return true;
|
||||
}
|
||||
let mut stack = vec![component];
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
while let Some(c) = stack.pop() {
|
||||
if !seen.insert(c) || seen.len() > MAX_PLACEMENTS {
|
||||
continue;
|
||||
}
|
||||
for o in self.occurrences.iter().filter(|o| o.parent == c) {
|
||||
if o.component == parent {
|
||||
return true;
|
||||
}
|
||||
stack.push(o.component);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Add an occurrence of an existing component into `parent`.
|
||||
pub fn add_occurrence(&mut self, component: u64, parent: u64, transform: Mat) -> Result<u64> {
|
||||
if component == 0 || !self.components.iter().any(|c| c.id == component) {
|
||||
return Err(DocError::Unknown(format!("component {component}")));
|
||||
}
|
||||
if self.component_within(parent, component) {
|
||||
if self.inside_component(parent, component) {
|
||||
return Err(DocError::Invalid("a component can't contain itself".into()));
|
||||
}
|
||||
if self.occurrences.len() >= 100_000 {
|
||||
|
||||
@@ -82,7 +82,7 @@ pub use eval::{
|
||||
world_state_reusing,
|
||||
};
|
||||
pub use expr::Expr;
|
||||
pub use names::{BodyName, FeatureId, FeatureName, SketchId};
|
||||
pub use names::{BodyName, FeatureId, FeatureName, SketchId, copy_name};
|
||||
pub use params::{ParamRow, ParamUser, cycles};
|
||||
pub use points::{Dir, FacePick, Position, plain};
|
||||
pub use solidcraft_kernel as kernel;
|
||||
|
||||
@@ -193,3 +193,28 @@ impl std::fmt::Display for SketchId {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of a copy of `name` (a pasted body, feature or component): the name and the next
|
||||
/// number in brackets that `taken` doesn't hold — `Cube` → `Cube (2)`, another copy of `Cube` →
|
||||
/// `Cube (3)`. A name that already ends in brackets takes the number right after them: a copy of
|
||||
/// `Cube (2)` → `Cube (2)(2)`.
|
||||
pub fn copy_name(name: &str, taken: impl Fn(&str) -> bool) -> String {
|
||||
let name = name.trim();
|
||||
let gap = if name.ends_with(')') { "" } else { " " };
|
||||
(2..100_002u64).map(|i| format!("{name}{gap}({i})")).find(|c| !taken(c)).unwrap_or_else(|| format!("{name}{gap}(2)"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod copy_name_tests {
|
||||
use super::copy_name;
|
||||
|
||||
#[test]
|
||||
fn a_copy_takes_the_next_free_number() {
|
||||
let taken = |names: &'static [&'static str]| move |n: &str| names.contains(&n);
|
||||
assert_eq!(copy_name("Cube", taken(&["Cube"])), "Cube (2)");
|
||||
assert_eq!(copy_name("Cube", taken(&["Cube", "Cube (2)"])), "Cube (3)");
|
||||
assert_eq!(copy_name("Cube (2)", taken(&["Cube", "Cube (2)", "Cube (3)"])), "Cube (2)(2)");
|
||||
assert_eq!(copy_name("Cube (2)", taken(&["Cube (2)", "Cube (2)(2)"])), "Cube (2)(3)");
|
||||
assert_eq!(copy_name("Sketch1", taken(&["Sketch1"])), "Sketch1 (2)");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,9 +13,11 @@ use crate::{Result, Session};
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("timeline.copy", "Copy Features", copy).icon("copy").noundo().params("features: [ids or names] (in timeline order on paste)"),
|
||||
CommandSpec::new("timeline.paste", "Paste Features", paste)
|
||||
.icon("paste")
|
||||
.params("translate?: [x,y,z] (moves the copies' geometry); the copies go at the marker"),
|
||||
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)",
|
||||
),
|
||||
];
|
||||
|
||||
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -63,26 +65,79 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => None,
|
||||
};
|
||||
let feats = s.clipboard.clone();
|
||||
let comp = s.active_component;
|
||||
let comp = match p.get("component") {
|
||||
None => s.active_component,
|
||||
Some(v) => {
|
||||
let key = match v {
|
||||
Value::Number(n) => n.to_string(),
|
||||
Value::String(name) => name.clone(),
|
||||
_ => 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 given_path = 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::<Option<Vec<_>>>())
|
||||
.ok_or_else(|| bad(cmd, "`component_path` must list 0..64 occurrence ids"))?,
|
||||
),
|
||||
};
|
||||
let mut sketches: BTreeMap<u64, u64> = BTreeMap::new();
|
||||
let mut bodies: BTreeMap<String, String> = BTreeMap::new();
|
||||
let mut used: std::collections::BTreeSet<String> = s.model.state().bodies.iter().map(|body| body.name.clone()).collect();
|
||||
let mut notices = Vec::new();
|
||||
let author_path = s.active_occurrence_path.clone().unwrap_or_else(|| s.doc.first_path(comp));
|
||||
// The placement the copies are authored in: the one named, the active one (into the active
|
||||
// component, as before), else the target's only (or active) placement.
|
||||
let author_path = match given_path {
|
||||
Some(path) => path,
|
||||
None if comp == s.active_component => s.active_occurrence_path.clone().unwrap_or_else(|| s.doc.first_path(comp)),
|
||||
None => super::component::placing::placement_of(s, &s.placed_document(), comp, None, "component_path", cmd)?.0,
|
||||
};
|
||||
solidcraft_doc::EmbossFace::component_frame(&s.placed_document(), comp, &author_path)?;
|
||||
// A copy from another component goes where its original is in the world: its geometry moves
|
||||
// from its component's frame (its first placement, where its bodies have their own names)
|
||||
// into the target's.
|
||||
let placed = s.placed_document();
|
||||
let target_frame = placed.path_transform(comp, &author_path).ok_or_else(|| bad(cmd, "that path is not a placement of the target"))?;
|
||||
let to_target = solidcraft_doc::mat_inverse(&target_frame).ok_or_else(|| bad(cmd, "the target's frame is not invertible"))?;
|
||||
let frame_change: BTreeMap<u64, solidcraft_doc::Mat> = feats
|
||||
.iter()
|
||||
.map(|f| f.component)
|
||||
.filter(|from| *from != comp)
|
||||
.map(|from| {
|
||||
let source = placed.path_transform(from, &placed.first_path(from)).unwrap_or(solidcraft_doc::IDENTITY);
|
||||
(from, solidcraft_doc::mat_mul(&to_target, &source))
|
||||
})
|
||||
.collect();
|
||||
drop(placed);
|
||||
let mut shift = solidcraft_doc::IDENTITY;
|
||||
if let Some(t) = translate {
|
||||
shift[3][0] = t.x;
|
||||
shift[3][1] = t.y;
|
||||
shift[3][2] = t.z;
|
||||
}
|
||||
let mut names: BTreeMap<String, String> = BTreeMap::new();
|
||||
let mut made = Vec::new();
|
||||
for f in feats {
|
||||
let mut kind = f.kind.clone();
|
||||
kind.remap_refs(&sketches, &names);
|
||||
let m = solidcraft_doc::mat_mul(&shift, frame_change.get(&f.component).unwrap_or(&solidcraft_doc::IDENTITY));
|
||||
let moved = m.iter().enumerate().any(|(i, row)| row.iter().enumerate().any(|(j, v)| (v - if i == j { 1.0 } else { 0.0 }).abs() > 1e-12));
|
||||
// A body made by an earlier copy is the one this copy acts on (#613).
|
||||
kind.remap_bodies(&bodies);
|
||||
if let FeatureKind::Sketch { plane, .. } = &mut kind
|
||||
&& let Some(anchor) = super::sketch::face::anchor_mut(plane)
|
||||
{
|
||||
let internal = bodies.contains_key(&anchor.target.body);
|
||||
if !internal && translate.is_some_and(|translate| translate.len() > 1e-12) {
|
||||
return Err(bad(cmd, "translated paste retains an external exact face attachment; explicitly convert it to a fixed plane first"));
|
||||
if !internal && moved {
|
||||
return Err(bad(
|
||||
cmd,
|
||||
"a moved paste (translated, or into a component placed elsewhere) retains an external exact face attachment; \
|
||||
explicitly convert it to a fixed plane first",
|
||||
));
|
||||
}
|
||||
if !internal {
|
||||
notices.push(format!("pasted sketch retains external exact face attachment to {}", anchor.target.body));
|
||||
@@ -118,17 +173,12 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// `X (2)`, `X (3)`, and a second import of a file shows `Aa (2)` for the stored `Aa`. The
|
||||
// copies are found by the shown names; the stored ones only name the copies.
|
||||
let shown = if built.len() == outputs.len() { built } else { outputs.clone() };
|
||||
let copied_names: Vec<_> = outputs
|
||||
// Each copy is named after the body as shown, numbered: `Aa` → `Aa (2)`, `Aa (2)` → `Aa (2)(2)`.
|
||||
let copied_names: Vec<_> = shown
|
||||
.iter()
|
||||
.zip(&shown)
|
||||
.map(|(original, shown)| {
|
||||
let base = format!("{original} (copy)");
|
||||
let mut name = base.clone();
|
||||
let mut suffix = 2usize;
|
||||
while !used.insert(name.clone()) {
|
||||
name = format!("{base} {suffix}");
|
||||
suffix += 1;
|
||||
}
|
||||
.map(|shown| {
|
||||
let name = solidcraft_doc::copy_name(shown, |n| used.contains(n));
|
||||
used.insert(name.clone());
|
||||
bodies.insert(shown.clone(), name.clone());
|
||||
name
|
||||
})
|
||||
@@ -143,14 +193,10 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(t) = translate {
|
||||
if moved {
|
||||
if let FeatureKind::Sketch { plane, .. } | FeatureKind::ConstructionPlane { plane } = &mut kind {
|
||||
explicit_planes(plane);
|
||||
}
|
||||
let mut m = solidcraft_doc::IDENTITY;
|
||||
m[3][0] = t.x;
|
||||
m[3][1] = t.y;
|
||||
m[3][2] = t.z;
|
||||
kind.transform_geometry(&m);
|
||||
}
|
||||
// A cylinder Emboss finds its face only by the persistent name recorded when it was made
|
||||
@@ -160,7 +206,9 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let id = doc.add_feature(kind, None)?;
|
||||
// A copy keeps its original's name, numbered: `Sketch1` → `Sketch1 (2)`.
|
||||
let name = solidcraft_doc::copy_name(&f.name, |n| doc.features.iter().any(|x| x.name == n));
|
||||
let id = doc.add_feature(kind, Some(&name))?;
|
||||
if let Some(nf) = doc.feature_mut(id) {
|
||||
nf.component = comp;
|
||||
nf.body_names = copied_names;
|
||||
@@ -197,6 +245,50 @@ mod tests {
|
||||
run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[test]
|
||||
fn features_pasted_into_a_component_placed_elsewhere_stay_where_they_were() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": 5, "body_name": "Block"}));
|
||||
let made = run(&mut s, "component.create", json!({"name": "A", "activate": false}));
|
||||
let (a, at) = (made["component"].as_u64().unwrap(), made["occurrence"].as_u64().unwrap());
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": at, "grounded": false}));
|
||||
run(&mut s, "occurrence.move", json!({"occurrence": at, "translate": [100, 0, 0], "axis": [0, 0, 1], "angle": "90 deg"}));
|
||||
run(&mut s, "timeline.copy", json!({"features": ["S", "Extrude1"]}));
|
||||
let r = run(&mut s, "timeline.paste", json!({"component": a, "component_path": [at]}));
|
||||
assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}");
|
||||
assert_eq!(r["pasted"][0]["name"], "S (2)");
|
||||
let world = s.world_state();
|
||||
let (original, copy) = (world.body("Block").unwrap().mesh().bounds(), world.body("Block (2)").unwrap().mesh().bounds());
|
||||
assert!(copy.min.dist(original.min) < 1e-6 && copy.max.dist(original.max) < 1e-6, "{original:?} vs {copy:?}");
|
||||
let state = s.model.state();
|
||||
assert_eq!(s.doc.model_body_component(state.body("Block (2)").unwrap()), a);
|
||||
}
|
||||
|
||||
/// A sketch attached to a face of a body that isn't copied with it can't be carried into a
|
||||
/// component placed elsewhere: the paste is refused, saying to make its plane fixed first.
|
||||
#[test]
|
||||
fn a_face_attached_sketch_is_not_moved_into_a_component_placed_elsewhere() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20, "body_name": "Block"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": {"face": [10, 10, 20]}, "name": "OnTop"}));
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [2, 2], "p1": [6, 6]}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
let made = run(&mut s, "component.create", json!({"name": "A", "activate": false}));
|
||||
let (a, at) = (made["component"].as_u64().unwrap(), made["occurrence"].as_u64().unwrap());
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": at, "grounded": false}));
|
||||
run(&mut s, "occurrence.move", json!({"occurrence": at, "translate": [100, 0, 0]}));
|
||||
run(&mut s, "timeline.copy", json!({"features": ["OnTop"]}));
|
||||
let err = s.execute("timeline.paste", &json!({"component": a, "component_path": [at]})).unwrap_err().to_string();
|
||||
assert!(err.contains("fixed plane"), "{err}");
|
||||
assert!(s.doc.find_feature("OnTop (2)").is_none(), "nothing was pasted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_paste_sketch_and_extrude() {
|
||||
let mut s = Session::default();
|
||||
@@ -327,7 +419,7 @@ mod tests {
|
||||
let import = run(&mut s, "file.insert_step", json!({"path": path.to_string_lossy()}))["feature"].clone();
|
||||
assert_eq!(body_names(&s), ["Aa", "Bb", "Cc"]);
|
||||
paste_import_with_two_lifts(&mut s, &import, ["Aa", "Bb", "Cc"]);
|
||||
assert_eq!(body_names(&s), ["Aa", "Bb", "Cc", "Aa (copy)", "Bb (copy)", "Cc (copy)"]);
|
||||
assert_eq!(body_names(&s), ["Aa", "Bb", "Cc", "Aa (2)", "Bb (2)", "Cc (2)"]);
|
||||
let at: Vec<Vec<f64>> = LIFTED.iter().chain(&LIFTED).map(|c| c.to_vec()).collect();
|
||||
assert_eq!(corners(&mut s), at);
|
||||
}
|
||||
@@ -384,7 +476,7 @@ mod tests {
|
||||
assert_eq!(corners(&mut s), at, "{:?}", body_names(&s));
|
||||
let m = run(&mut s, "inspect.measure", json!({}));
|
||||
let names: Vec<&str> = m["bodies"].as_array().unwrap().iter().filter_map(|b| b["name"].as_str()).collect();
|
||||
assert_eq!(names, ["Aa (copy)", "Bb (copy)", "Cc (copy)", "Aa", "Bb", "Cc", "Aa (2)", "Bb (2)", "Cc (2)"]);
|
||||
assert_eq!(names, ["Aa (2)(2)", "Bb (2)(2)", "Cc (2)(2)", "Aa", "Bb", "Cc", "Aa (2)", "Bb (2)", "Cc (2)"]);
|
||||
}
|
||||
|
||||
/// A cylinder Emboss finds its face by the persistent name it recorded when it was made. The
|
||||
@@ -411,7 +503,7 @@ mod tests {
|
||||
assert!(mark.face_names.first().is_some_and(|n| n.starts_with(&format!("F{tube}:"))), "{:?}", mark.face_names);
|
||||
assert!((volume(&mut s) - 2.0 * one).abs() < 1e-6, "{translate:?}: both cylinders carry a badge");
|
||||
if translate.is_some() {
|
||||
let m = run(&mut s, "inspect.measure", json!({"bodies": ["Sleeve (copy)"]}));
|
||||
let m = run(&mut s, "inspect.measure", json!({"bodies": ["Sleeve (2)"]}));
|
||||
let body = &m["bodies"][0];
|
||||
let x = body["center_of_mass"][0].as_f64().unwrap_or(f64::NAN);
|
||||
let y = body["bbox"]["max"][1].as_f64().unwrap_or(f64::NAN);
|
||||
@@ -435,7 +527,7 @@ mod tests {
|
||||
assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}");
|
||||
let round = r["pasted"][2]["name"].as_str().unwrap_or_default().to_string();
|
||||
let def = run(&mut s, "timeline.inspect", json!({"feature": round}));
|
||||
assert_eq!(def["definition"]["body"], "Block (copy)", "{def}");
|
||||
assert_eq!(def["definition"]["body"], "Block (2)", "{def}");
|
||||
let m = run(&mut s, "inspect.measure", json!({}));
|
||||
assert_eq!(m["body_count"], 2, "{m}");
|
||||
assert!((volume(&mut s) - 2.0 * one).abs() < 1e-6, "both blocks are rounded: {m}");
|
||||
@@ -468,10 +560,10 @@ mod tests {
|
||||
run(&mut s, "timeline.copy", json!({"features": ["Roof", "Shelf", "S", "Up", "T", "On"]}));
|
||||
let r = run(&mut s, "timeline.paste", json!({"translate": [100, 0, 10]}));
|
||||
assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}");
|
||||
let up = measures(&mut s, "Up (copy)");
|
||||
let up = measures(&mut s, "Up (2)");
|
||||
assert!((up["bbox"]["min"][2].as_f64().unwrap_or(0.0) - 10.0).abs() < 1e-6, "{up}");
|
||||
assert!((up["bbox"]["max"][2].as_f64().unwrap_or(0.0) - 30.0).abs() < 1e-6, "it ends on the pasted roof: {up}");
|
||||
let on = measures(&mut s, "On (copy)");
|
||||
let on = measures(&mut s, "On (2)");
|
||||
assert!((on["bbox"]["min"][2].as_f64().unwrap_or(0.0) - 22.0).abs() < 1e-6, "it starts on the pasted shelf: {on}");
|
||||
assert!((on["bbox"]["max"][2].as_f64().unwrap_or(0.0) - 27.0).abs() < 1e-6, "{on}");
|
||||
}
|
||||
@@ -486,7 +578,7 @@ mod tests {
|
||||
run(&mut s, "timeline.copy", json!({"features": ["Block", "Drill"]}));
|
||||
let r = run(&mut s, "timeline.paste", json!({"translate": [60, 0, -6]}));
|
||||
assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}");
|
||||
let (block, copy) = (measures(&mut s, "Block"), measures(&mut s, "Block (copy)"));
|
||||
let (block, copy) = (measures(&mut s, "Block"), measures(&mut s, "Block (2)"));
|
||||
let v = |m: &serde_json::Value| m["volume_mm3"].as_f64().unwrap_or(f64::NAN);
|
||||
assert!((v(&block) - (16000.0 - std::f64::consts::PI * 25.0 * 10.0)).abs() < 1.0, "a through hole: {block}");
|
||||
assert!((v(©) - v(&block)).abs() < 1e-6, "the pasted hole goes through too: {copy}");
|
||||
@@ -504,7 +596,7 @@ mod tests {
|
||||
run(&mut s, "timeline.copy", json!({"features": ["S", "Turn"]}));
|
||||
let r = run(&mut s, "timeline.paste", json!({"translate": [50, 0, 0]}));
|
||||
assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}");
|
||||
let (arc, copy) = (measures(&mut s, "Arc"), measures(&mut s, "Arc (copy)"));
|
||||
let (arc, copy) = (measures(&mut s, "Arc"), measures(&mut s, "Arc (2)"));
|
||||
let v = |m: &serde_json::Value| m["volume_mm3"].as_f64().unwrap_or(f64::NAN);
|
||||
// A quarter turn of a 5 × 5 section whose centre is 12.5 from the axis.
|
||||
let quarter = 25.0 * std::f64::consts::FRAC_PI_2 * 12.5;
|
||||
@@ -527,12 +619,12 @@ mod tests {
|
||||
assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}");
|
||||
let spring = r["pasted"][1]["name"].as_str().unwrap_or_default().to_string();
|
||||
let def = run(&mut s, "timeline.inspect", json!({"feature": spring}));
|
||||
assert_eq!(def["definition"]["targets"], json!(["Plate (copy)"]), "{def}");
|
||||
assert_eq!(def["definition"]["targets"], json!(["Plate (2)"]), "{def}");
|
||||
let st = s.world_state();
|
||||
let v = |name: &str| solidcraft_kernel::measure(&st.body(name).unwrap().body).unwrap().volume;
|
||||
// A spring on the wrong plate is hundreds of mm³ off. The two plates are measured apart
|
||||
// (one moved 50 mm), which the boolean and the measure each round in their own way:
|
||||
// a few 1e-6 mm³ on 5000.
|
||||
assert!((v("Plate") - v("Plate (copy)")).abs() < 1e-8 * v("Plate"), "each plate carries one spring: {} vs {}", v("Plate"), v("Plate (copy)"));
|
||||
assert!((v("Plate") - v("Plate (2)")).abs() < 1e-8 * v("Plate"), "each plate carries one spring: {} vs {}", v("Plate"), v("Plate (2)"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,8 +17,12 @@ use crate::{Result, Session};
|
||||
mod drag;
|
||||
#[path = "component_matrix.rs"]
|
||||
pub(super) mod matrix;
|
||||
#[path = "component_placing.rs"]
|
||||
pub(super) mod placing;
|
||||
#[path = "component_properties.rs"]
|
||||
pub(super) mod properties;
|
||||
#[path = "component_reparent.rs"]
|
||||
mod reparent;
|
||||
#[path = "component_transfer.rs"]
|
||||
mod transfer;
|
||||
|
||||
@@ -55,11 +59,21 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
"component: removes the rigid joints that hold its contents together (an imported assembly's rigid group), so its parts \
|
||||
move and take joints one by one → joints (the ids removed)",
|
||||
),
|
||||
CommandSpec::new("component.move_bodies", "Move Bodies to Component", move_bodies).icon("move").params("bodies: [names], component"),
|
||||
CommandSpec::new("component.move_bodies", "Move Bodies to Component", move_bodies).icon("move").params(
|
||||
"bodies: [names], component; component_path?: its placement to place them by (default: its only one, else the active \
|
||||
one; a component placed more than once gets them in every instance); from_path?: the placement of their component they \
|
||||
move from (default: its only one, else its first, where its bodies have their own names)",
|
||||
),
|
||||
CommandSpec::new("component.copy_bodies", "Paste Bodies", copy_bodies).icon("paste").params(
|
||||
"bodies: [names, as the Browser shows them: a body seen in another placement of its component (`Cube (B:2)`) is copied \
|
||||
from there]; component?: where the copies go (default: the active one); component_path?: its placement to place them \
|
||||
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.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]. Copies the selected effective transform, including pending moves"),
|
||||
CommandSpec::new("component.paste_new", "Paste New", paste_new).icon("paste").params("component: independently copy its nested definition graph and history, materials and styles; occurrence?, path?: selected source placement; translate?: [x,y,z]. Reassigned external bodies become base geometry; retained external links and omitted boundary joints are reported"),
|
||||
.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"),
|
||||
CommandSpec::new("component.paste_new", "Paste New", paste_new).icon("paste").params("component: independently copy its nested definition graph and history, materials and styles; occurrence?, path?: selected source placement; parent?: component the copy goes in (default: the source placement's; not the component or one inside it); in_place?, parent_path?: as occurrence.copy; translate?: [x,y,z]. Reassigned external bodies become base geometry; retained external links and omitted boundary joints are reported"),
|
||||
CommandSpec::new("occurrence.move", "Move Occurrence", move_occurrence).icon("move")
|
||||
.params("occurrence; path?: exact placement; space?: local|world (default local); translate?: [x,y,z]; axis?: [x,y,z], angle?: radians or \"30 deg\", origin?: [x,y,z]; matrix?: [12 or 16 numbers] (instead of translate/axis/angle/origin: a rigid move as a row-major 3x4 rotation-and-translation or 4x4 matrix, flat or as rows; one that is a rotation only up to rounding is orthonormalised, a scale, shear or mirror is refused); tolerance?: largest accepted |RᵀR − I| (default 1e-9, at most 1e-3); capture?: bool (default true; false keeps it pending until Capture Position); move_grounded?: bool (default false: a grounded occurrence refuses; true moves it and it stays grounded). Nested occurrence definitions remain shared"),
|
||||
CommandSpec::new("occurrence.drag", "Drag Occurrence", drag::drag).icon("move").params(
|
||||
@@ -68,6 +82,11 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
moves stay pending. Shared definitions move in all placements. Grounded parts and parts joints hold to something fixed are refused (joint.reach moves those)",
|
||||
),
|
||||
CommandSpec::new("occurrence.ground", "Ground", ground).icon("ground").params("occurrence; grounded?: bool (default toggles)"),
|
||||
CommandSpec::new("occurrence.reparent", "Move to Component", reparent::reparent).icon("move").params(
|
||||
"occurrence; path?: exact placement; parent: component id or name (0 or \"root\" for the design); parent_path?: the parent's \
|
||||
placement to place it by (default: its only one, else the active one; every instance of the parent gets it). The placement \
|
||||
keeps its world position; a move that would break a feature is refused",
|
||||
),
|
||||
CommandSpec::new("component.capture_position", "Capture Position", capture).at("SOLID", "POSITION").icon("capture").params("keeps pending occurrence moves"),
|
||||
CommandSpec::new("component.revert_position", "Revert Position", revert).at("SOLID", "POSITION").icon("revert").noundo().params("occurrences?: [ids] (default all); drops selected pending occurrence moves"),
|
||||
];
|
||||
@@ -303,6 +322,74 @@ fn move_bodies(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
transfer::move_bodies(s, p)
|
||||
}
|
||||
|
||||
/// Copies of bodies in a component (Ctrl+C, Ctrl+V on bodies): each body is copied in place in
|
||||
/// its own component, then the copies move to the target keeping their place in the world, as
|
||||
/// `component.move_bodies` keeps it. One step to undo.
|
||||
fn copy_bodies(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "component.copy_bodies";
|
||||
let to = if p.get("component").is_some() { component(s, p, "component", cmd)? } else { s.active_component };
|
||||
let names = string_list(p, "bodies");
|
||||
if names.is_empty() || names.len() > 1000 {
|
||||
return Err(bad(cmd, "`bodies` must list 1…1000 bodies"));
|
||||
}
|
||||
let state = s.model.state();
|
||||
// Bodies by their component, and the placement they are copied as: a body is named as its
|
||||
// component's first placement shows it, and one seen in another placement (`Cube (B:2)`) is
|
||||
// that body, copied from where that placement shows it.
|
||||
let mut groups: std::collections::BTreeMap<(u64, Option<Vec<u64>>), Vec<String>> = std::collections::BTreeMap::new();
|
||||
let mut placed_bodies = None;
|
||||
for name in &names {
|
||||
if let Some(body) = state.body(name) {
|
||||
groups.entry((s.doc.model_body_component(body), None)).or_default().push(name.clone());
|
||||
continue;
|
||||
}
|
||||
let placed = placed_bodies.get_or_insert_with(|| s.doc.body_frames_with_source(&state));
|
||||
let (_, source, component, path, _) = placed.iter().find(|(shown, ..)| shown == name).ok_or_else(|| bad(cmd, format!("no body `{name}`")))?;
|
||||
groups.entry((*component, Some(path.clone()))).or_default().push(source.clone());
|
||||
}
|
||||
drop(state);
|
||||
let mut scratch = s.scratch();
|
||||
let mut copies = Vec::new();
|
||||
for ((from, from_path), bodies) in groups {
|
||||
// The copy is made where its body is, so it starts out in the same place.
|
||||
scratch.active_component = from;
|
||||
scratch.active_occurrence_path = None;
|
||||
let mut made = string_list(&scratch.execute("solid.move", &json!({"bodies": bodies, "copy": true}))?, "created_bodies");
|
||||
// Each copy is its body's name numbered as all copies are (`Cube (2)`, `Cube (2)(2)`): the
|
||||
// move names a copy of `Cube (2)` `Cube (2) (2)`.
|
||||
if made.len() == bodies.len() {
|
||||
for (copy, original) in made.iter_mut().zip(&bodies) {
|
||||
let state = scratch.model.state();
|
||||
let name = solidcraft_doc::copy_name(original, |n| n != copy.as_str() && state.body(n).is_some());
|
||||
drop(state);
|
||||
if name != *copy {
|
||||
scratch.execute("body.rename", &json!({"body": copy, "name": name}))?;
|
||||
*copy = name;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The active placement again: a target placed more than once is placed by it.
|
||||
scratch.active_component = s.active_component;
|
||||
scratch.active_occurrence_path = s.active_occurrence_path.clone();
|
||||
if from != to && !made.is_empty() {
|
||||
let mut moved = json!({"bodies": made, "component": to});
|
||||
if let Some(path) = p.get("component_path") {
|
||||
moved["component_path"] = path.clone();
|
||||
}
|
||||
if let Some(path) = from_path {
|
||||
moved["from_path"] = json!(path);
|
||||
}
|
||||
transfer::move_bodies(&mut scratch, &moved)?;
|
||||
}
|
||||
copies.extend(made);
|
||||
}
|
||||
// The steps above are this command's one undo step.
|
||||
scratch.undo.clear();
|
||||
scratch.selection = copies.iter().map(|name| crate::Sel::Body { name: name.clone() }).collect();
|
||||
s.accept_computed(scratch);
|
||||
Ok(json!({"bodies": copies, "component": to}))
|
||||
}
|
||||
|
||||
pub(crate) fn transfer_constructor_result(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
transfer::move_result(s, p)
|
||||
}
|
||||
@@ -350,8 +437,12 @@ pub(super) fn copy_occurrence(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let parent = if p.get("parent").is_some() { component(s, p, "parent", cmd)? } else { src.parent };
|
||||
let t = move_vector(p, "translate", Vec3::ZERO, true, cmd)?;
|
||||
let base = s.pending_moves.get(&src.id).unwrap_or(&src.transform);
|
||||
let m = solidcraft_doc::mat_mul(&translation(t), base);
|
||||
let m = if bool_(p, "in_place") == Some(true) {
|
||||
placing::in_place(s, &occurrence_path(s, p, src.id, cmd)?, parent, placing::parent_path(p, cmd)?.as_deref(), t, cmd)?
|
||||
} else {
|
||||
let base = s.pending_moves.get(&src.id).unwrap_or(&src.transform);
|
||||
solidcraft_doc::mat_mul(&translation(t), base)
|
||||
};
|
||||
if !valid_position(&m) {
|
||||
return Err(bad(cmd, "copy transform exceeds supported numeric range"));
|
||||
}
|
||||
@@ -380,12 +471,21 @@ fn paste_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.doc.occurrence_of(comp).cloned()
|
||||
};
|
||||
let t = move_vector(p, "translate", Vec3::ZERO, true, cmd)?;
|
||||
let base = occ.as_ref().map(|o| s.pending_moves.get(&o.id).copied().unwrap_or(o.transform)).unwrap_or(solidcraft_doc::IDENTITY);
|
||||
let transform = solidcraft_doc::mat_mul(&translation(t), &base);
|
||||
let parent = if p.get("parent").is_some() { component(s, p, "parent", cmd)? } else { occ.as_ref().map(|o| o.parent).unwrap_or(src.parent) };
|
||||
// A copy of a component holds what the component holds: not a place for it to go.
|
||||
if s.doc.inside_component(parent, comp) {
|
||||
return Err(bad(cmd, format!("can't paste a copy of {} inside itself", src.name)));
|
||||
}
|
||||
let transform = match occ.as_ref().filter(|_| bool_(p, "in_place") == Some(true)) {
|
||||
Some(o) => placing::in_place(s, &occurrence_path(s, p, o.id, cmd)?, parent, placing::parent_path(p, cmd)?.as_deref(), t, cmd)?,
|
||||
None => {
|
||||
let base = occ.as_ref().map(|o| s.pending_moves.get(&o.id).copied().unwrap_or(o.transform)).unwrap_or(solidcraft_doc::IDENTITY);
|
||||
solidcraft_doc::mat_mul(&translation(t), &base)
|
||||
}
|
||||
};
|
||||
if !valid_position(&transform) {
|
||||
return Err(bad(cmd, "copy transform exceeds supported numeric range"));
|
||||
}
|
||||
let parent = occ.as_ref().map(|o| o.parent).unwrap_or(src.parent);
|
||||
super::component_clone::paste(s, comp, occ, transform, parent, p)
|
||||
}
|
||||
|
||||
|
||||
@@ -84,13 +84,7 @@ fn cloned_path(source: &Document, path: &[u64], root: u64, destination: &[u64],
|
||||
}
|
||||
|
||||
fn unique(base: &str, used: &mut BTreeSet<String>) -> String {
|
||||
let stem = format!("{base} (copy)");
|
||||
let mut name = stem.clone();
|
||||
let mut n = 2;
|
||||
while used.contains(&name) {
|
||||
name = format!("{stem} {n}");
|
||||
n += 1;
|
||||
}
|
||||
let name = solidcraft_doc::copy_name(base, |n| used.contains(n));
|
||||
used.insert(name.clone());
|
||||
name
|
||||
}
|
||||
@@ -234,13 +228,11 @@ pub(super) fn paste(
|
||||
let mut names = BTreeMap::new();
|
||||
let mut bodies = BTreeMap::new();
|
||||
let mut parameters = BTreeMap::new();
|
||||
let mut used: BTreeSet<String> = source
|
||||
.features
|
||||
.iter()
|
||||
.map(|f| f.name.clone())
|
||||
.chain(source.components.iter().map(|c| c.name.clone()))
|
||||
.chain(state.bodies.iter().map(|b| b.name.clone()))
|
||||
.collect();
|
||||
// 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<String> = source.components.iter().map(|c| c.name.clone()).collect();
|
||||
let mut used_features: BTreeSet<String> = source.features.iter().map(|f| f.name.clone()).collect();
|
||||
let mut used_bodies: BTreeSet<String> = 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.
|
||||
@@ -251,7 +243,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);
|
||||
let name = unique(&c.name, &mut used_components);
|
||||
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) {
|
||||
@@ -303,7 +295,7 @@ pub(super) fn paste(
|
||||
if let Some(result) = s.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.entry(name.clone()).or_insert_with(|| unique(name, &mut used_bodies));
|
||||
}
|
||||
if named_by(&f.body_names, &created) {
|
||||
shown.insert(f.id, created.clone());
|
||||
@@ -315,7 +307,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.entry(name.clone()).or_insert_with(|| unique(name, &mut used_bodies));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -350,9 +342,9 @@ pub(super) fn paste(
|
||||
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);
|
||||
let new_name = unique(&body.name, &mut used_bodies);
|
||||
bodies.insert(body.name.clone(), new_name.clone());
|
||||
let feature_name = unique(&format!("{} Base", body.name), &mut used);
|
||||
let feature_name = unique(&format!("{} Base", body.name), &mut used_features);
|
||||
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),
|
||||
@@ -366,7 +358,7 @@ pub(super) fn paste(
|
||||
}
|
||||
// Allocate all history IDs before rewriting any forward reference.
|
||||
for f in &feats {
|
||||
let name = unique(&f.name, &mut used);
|
||||
let name = unique(&f.name, &mut used_features);
|
||||
let id = scratch.doc_mut().add_feature(f.kind.clone(), Some(&name))?;
|
||||
if let Some(new) = scratch.doc.feature(id) {
|
||||
for (old, pn) in f.param_names.iter().zip(&new.param_names) {
|
||||
@@ -490,7 +482,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);
|
||||
let name = unique("Assigned-out bodies", &mut used_features);
|
||||
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;
|
||||
|
||||
@@ -143,16 +143,12 @@ fn unique_name(base: &str, used: &mut BTreeSet<String>) -> Result<String> {
|
||||
used.insert(base.to_string());
|
||||
return Ok(base.to_string());
|
||||
}
|
||||
for index in 1..=MAX_RECORDS {
|
||||
let name = if index == 1 { format!("{base} (copy)") } else { format!("{base} (copy {index})") };
|
||||
if name.len() > MAX_NAME {
|
||||
return Err(invalid("copied assembly name is too long"));
|
||||
}
|
||||
if used.insert(name.clone()) {
|
||||
return Ok(name);
|
||||
}
|
||||
let name = solidcraft_doc::copy_name(base, |n| used.contains(n));
|
||||
if name.len() > MAX_NAME {
|
||||
return Err(invalid("copied assembly name is too long"));
|
||||
}
|
||||
Err(invalid("could not allocate a unique assembly name"))
|
||||
used.insert(name.clone());
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
fn next_id(id: &mut u64) -> Result<u64> {
|
||||
|
||||
@@ -86,7 +86,7 @@ fn internal_relationships_receive_independent_ids_and_remapped_typed_references(
|
||||
assert_eq!((a.joints[4].a.occurrence, a.joints[4].b.occurrence), (101, 102));
|
||||
assert_eq!(a.joints[4].values, source.assembly.joints[0].values);
|
||||
assert_eq!(a.joints[4].limits, source.assembly.joints[0].limits);
|
||||
assert_eq!(a.joints[4].name, "Joint1 (copy)");
|
||||
assert_eq!(a.joints[4].name, "Joint1 (2)");
|
||||
assert_eq!(a.origins.len(), 4);
|
||||
// Its x reference's face is the copy's too.
|
||||
assert!(matches!(&a.origins[3].origin.snap, Snap::FaceCenter { face: Some(face), x: Some(XRef::Face { face: x, .. }), .. }
|
||||
@@ -191,7 +191,7 @@ fn second_copy_has_unique_names_and_keeps_global_contact_switches_unchanged() {
|
||||
clone_assembly(&mut destination, &source, &BTreeMap::from([(1, 101), (2, 102)]), &features, &BTreeMap::new()).unwrap();
|
||||
destination.occurrences.extend([201, 202].map(occurrence));
|
||||
clone_assembly(&mut destination, &source, &BTreeMap::from([(1, 201), (2, 202)]), &features, &BTreeMap::new()).unwrap();
|
||||
assert_eq!(destination.assembly.joints[6].name, "Joint1 (copy 2)");
|
||||
assert_eq!(destination.assembly.joints[6].name, "Joint1 (3)");
|
||||
assert!(destination.assembly.contact_enabled && destination.assembly.contact_all);
|
||||
let names: BTreeSet<&str> = destination.assembly.origins.iter().map(|x| x.name.as_str()).collect();
|
||||
assert_eq!(names.len(), destination.assembly.origins.len());
|
||||
@@ -228,16 +228,16 @@ fn paste_new_internal_motion_study_drives_only_the_copied_assembly_and_reopens()
|
||||
assert_eq!(s.doc.assembly.origins.len(), 2);
|
||||
assert_eq!(s.doc.assembly.contact_sets.len(), 2);
|
||||
assert_eq!(s.doc.assembly.exploded.len(), 2);
|
||||
let copied_joint = s.doc.assembly.joints.iter().find(|j| j.name == "Rail (copy)").unwrap().id;
|
||||
let copied_joint = s.doc.assembly.joints.iter().find(|j| j.name == "Rail (2)").unwrap().id;
|
||||
let copied_moving = s.doc.assembly.joints.iter().find(|j| j.id == copied_joint).unwrap().b.occurrence;
|
||||
assert_ne!(copied_moving, moving);
|
||||
run(&mut s, "motion.play", json!({"study":"Travel (copy)","step":10}));
|
||||
run(&mut s, "motion.play", json!({"study":"Travel (2)","step":10}));
|
||||
assert_eq!(s.doc.assembly.joints.iter().find(|j| j.id == source_joint).unwrap().values, vec![0.0]);
|
||||
assert_eq!(s.doc.assembly.joints.iter().find(|j| j.id == copied_joint).unwrap().values, vec![6.0]);
|
||||
assert_eq!(s.doc.occurrences.iter().find(|o| o.id == moving).unwrap().transform, original);
|
||||
let reopened = Document::from_json(&s.doc.to_json()).unwrap();
|
||||
assert_eq!(reopened.assembly, s.doc.assembly);
|
||||
assert!(reopened.assembly.studies.iter().any(|m| m.name == "Travel (copy)" && m.keys[0].joint == copied_joint));
|
||||
assert!(reopened.assembly.studies.iter().any(|m| m.name == "Travel (2)" && m.keys[0].joint == copied_joint));
|
||||
}
|
||||
|
||||
/// An edge origin's edge, face and corner edge are the copy's too.
|
||||
|
||||
@@ -241,7 +241,7 @@ fn renamed_pattern_outputs_and_later_body_operands_follow_clone() {
|
||||
let new = copied["component"].as_u64().unwrap();
|
||||
near(volume(&mut s, new), 24.0);
|
||||
let state = s.model.state();
|
||||
let target = state.bodies.iter().find(|b| b.name == "Custom Output (copy)").unwrap();
|
||||
let target = state.bodies.iter().find(|b| b.name == "Custom Output (2)").unwrap();
|
||||
near(solidcraft_kernel::measure(&target.body).unwrap().centroid.y, 6.0);
|
||||
assert_eq!(s.doc.features.iter().filter(|f| f.component == new && matches!(f.kind, solidcraft_doc::FeatureKind::Move { .. })).count(), 1);
|
||||
}
|
||||
@@ -331,7 +331,7 @@ fn selected_second_occurrence_emboss_copy_remaps_target_and_author_paths_and_reo
|
||||
let placement = copied["occurrence"].as_u64().unwrap();
|
||||
let emboss = s.doc.features.iter().find(|f| f.component == new && matches!(f.kind, solidcraft_doc::FeatureKind::Emboss { .. })).unwrap();
|
||||
let solidcraft_doc::FeatureKind::Emboss { face: Some(face), .. } = &emboss.kind else { panic!("missing selected face") };
|
||||
assert_eq!(face.body, "Sleeve (copy)");
|
||||
assert_eq!(face.body, "Sleeve (2)");
|
||||
assert_eq!(face.path, vec![placement]);
|
||||
assert_eq!(face.author_path, vec![placement]);
|
||||
near(volume(&mut s, new), original_volume);
|
||||
@@ -432,14 +432,14 @@ fn external_transfer_entry_and_internal_rotated_transfer_clone_once() {
|
||||
let copied = copy(&mut s, parent);
|
||||
assert_eq!(copied["frozen_bodies"], json!(["Foreign"]));
|
||||
let state = s.model.state();
|
||||
let body = state.body("Foreign (copy)").unwrap();
|
||||
let body = state.body("Foreign (2)").unwrap();
|
||||
let after = body.mesh().bounds();
|
||||
assert!(before.min.dist(after.min) < 1e-6);
|
||||
assert!(before.max.dist(after.max) < 1e-6);
|
||||
assert!(body.transferred);
|
||||
let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() };
|
||||
reopened.refresh();
|
||||
assert!(reopened.model.state().body("Foreign (copy)").unwrap().mesh().bounds().min.dist(before.min) < 1e-6);
|
||||
assert!(reopened.model.state().body("Foreign (2)").unwrap().mesh().bounds().min.dist(before.min) < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -461,7 +461,7 @@ fn suppressed_external_entry_does_not_supply_clone_baseline() {
|
||||
run(&mut s, "component.move_bodies", json!({"component":part,"bodies":["Foreign"]}));
|
||||
let before = s.model.state().body("Foreign").unwrap().mesh().bounds();
|
||||
copy(&mut s, part);
|
||||
let after = s.model.state().body("Foreign (copy)").unwrap().mesh().bounds();
|
||||
let after = s.model.state().body("Foreign (2)").unwrap().mesh().bounds();
|
||||
assert!(before.min.dist(after.min) < 1e-6);
|
||||
assert!(before.max.dist(after.max) < 1e-6);
|
||||
}
|
||||
@@ -481,7 +481,7 @@ fn transferred_frozen_face_paint_ignores_consumed_legacy_offset() {
|
||||
let original = s.doc.appearances.faces.iter().find(|face| face.body == "Foreign").unwrap();
|
||||
let expected = solidcraft_doc::naming::point_on_face(&s.model.state(), original.name.as_ref().unwrap(), original.point).unwrap().0;
|
||||
copy(&mut s, part);
|
||||
let paint = s.doc.appearances.faces.iter().find(|face| face.body == "Foreign (copy)").unwrap();
|
||||
let paint = s.doc.appearances.faces.iter().find(|face| face.body == "Foreign (2)").unwrap();
|
||||
assert!(paint.point.dist(expected) < 1e-6, "{:?} versus {expected:?}", paint.point);
|
||||
}
|
||||
|
||||
@@ -696,8 +696,8 @@ fn paste_new_of_a_design_linked_twice_moves_the_copy_of_each_body() {
|
||||
assert_eq!(corners(&s, copied), lifted(), "{:?}", body_names(&s));
|
||||
// The material of a body goes to its copy, and no material is kept for a body that does not exist.
|
||||
let names = body_names(&s);
|
||||
assert!(s.doc.materials.contains_key("Aa (2) (copy)"));
|
||||
assert_eq!(s.doc.materials.get("Aa (2) (copy)"), s.doc.materials.get("Aa (2)"));
|
||||
assert!(s.doc.materials.contains_key("Aa (2)(2)"));
|
||||
assert_eq!(s.doc.materials.get("Aa (2)(2)"), s.doc.materials.get("Aa (2)"));
|
||||
assert!(s.doc.materials.keys().all(|body| names.contains(body)), "{:?} for {names:?}", s.doc.materials.keys().collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Where something pasted or moved into a component goes: placed by one placement of that
|
||||
//! component, so it sits where its original is in the world. A component placed more than once is
|
||||
//! one definition: what goes in it goes in every instance, placed by the one named (`parent_path`,
|
||||
//! `component_path`), else its only placement, else the active one, and in the same place in the
|
||||
//! others.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The `parent_path` parameter: the placement of the parent to place by (`[]`: the design).
|
||||
pub(super) fn parent_path(p: &Value, cmd: &str) -> Result<Option<Vec<u64>>> {
|
||||
let Some(value) = p.get("parent_path") else { return Ok(None) };
|
||||
value
|
||||
.as_array()
|
||||
.filter(|a| a.len() <= 64)
|
||||
.and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())
|
||||
.map(Some)
|
||||
.ok_or_else(|| bad(cmd, "`parent_path` must list 0..64 occurrence ids"))
|
||||
}
|
||||
|
||||
/// The transform a copy of the placement at `path` takes in `parent` to sit where the placement
|
||||
/// is in the world, then moved by `translate` (in the world). The parent is placed by
|
||||
/// [`placement_of`]: in its other instances the copy sits in the same place within them.
|
||||
pub(super) fn in_place(s: &Session, path: &[u64], parent: u64, parent_path: Option<&[u64]>, translate: Vec3, cmd: &str) -> Result<Mat> {
|
||||
let doc = s.placed_document();
|
||||
let component =
|
||||
path.last().and_then(|id| doc.occurrences.iter().find(|o| o.id == *id)).map(|o| o.component).ok_or_else(|| bad(cmd, "no placement"))?;
|
||||
let world = doc.path_transform(component, path).ok_or_else(|| bad(cmd, "that placement is gone"))?;
|
||||
let (_, frame) = placement_of(s, &doc, parent, parent_path, "parent_path", cmd)?;
|
||||
let inverse = solidcraft_doc::mat_inverse(&frame).ok_or_else(|| bad(cmd, "the parent's frame is not invertible"))?;
|
||||
Ok(solidcraft_doc::mat_mul(&inverse, &solidcraft_doc::mat_mul(&translation(translate), &world)))
|
||||
}
|
||||
|
||||
/// The placement of `component` a move or paste is placed by (the design is the empty path): its
|
||||
/// path and world frame. `path` when given (it must lead to `component`), else its only
|
||||
/// placement, else the active placement when that is one of it. `key` names the parameter that
|
||||
/// gives `path`, for the error when none of them settles it.
|
||||
pub(in crate::cmd) fn placement_of(
|
||||
s: &Session,
|
||||
doc: &solidcraft_doc::Document,
|
||||
component: u64,
|
||||
path: Option<&[u64]>,
|
||||
key: &str,
|
||||
cmd: &str,
|
||||
) -> Result<(Vec<u64>, Mat)> {
|
||||
let name = || doc.components.iter().find(|c| c.id == component).map(|c| c.name.clone()).unwrap_or_else(|| "that component".into());
|
||||
if let Some(path) = path {
|
||||
let frame = doc.path_transform(component, path).ok_or_else(|| bad(cmd, format!("that path is not a placement of {}", name())))?;
|
||||
return Ok((path.to_vec(), frame));
|
||||
}
|
||||
let all: Vec<(u64, Vec<u64>, Mat)> = doc.placements().into_iter().filter(|(c, _, _)| *c == component).collect();
|
||||
match all.as_slice() {
|
||||
[(_, path, frame)] => Ok((path.clone(), *frame)),
|
||||
[] => Err(bad(cmd, "that component is not placed in the design")),
|
||||
_ => all
|
||||
.iter()
|
||||
.find(|(_, path, _)| s.active_occurrence_path.as_deref() == Some(path.as_slice()))
|
||||
.map(|(_, path, frame)| (path.clone(), *frame))
|
||||
.ok_or_else(|| bad(cmd, format!("{} is placed more than once: activate the placement to work in, or give it as `{key}`", name()))),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Moving a placement into another component, or out to the design, where it stays in the world.
|
||||
//! Its local transform is worked out again in the new parent's frame. A parent placed more than
|
||||
//! once is one definition: what goes in it goes in every instance, placed by the one instance
|
||||
//! named (`parent_path`, else the active placement) and in the same place in the others. Paths
|
||||
//! through the placement change: the session's paths (selection, active and hidden placements,
|
||||
//! hidden folders) follow it, and a move that would leave a feature failing that worked before
|
||||
//! (a face attachment found through the old path) is refused.
|
||||
|
||||
use super::placing::{parent_path, placement_of};
|
||||
use super::*;
|
||||
use crate::Sel;
|
||||
|
||||
/// `path` with its leading `from` replaced by `to`, when it starts with `from`.
|
||||
fn rebased(path: &[u64], from: &[u64], to: &[u64]) -> Option<Vec<u64>> {
|
||||
path.strip_prefix(from).map(|rest| to.iter().chain(rest).copied().collect())
|
||||
}
|
||||
|
||||
pub(super) fn reparent(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "occurrence.reparent";
|
||||
let id = occurrence(s, p, cmd)?;
|
||||
let to = component(s, p, "parent", cmd)?;
|
||||
let o = s.doc.occurrences.iter().find(|o| o.id == id).cloned().ok_or_else(|| bad(cmd, "no occurrence"))?;
|
||||
if o.parent == to {
|
||||
return Ok(json!({"occurrence": id, "parent": to, "path": occurrence_path(s, p, id, cmd)?}));
|
||||
}
|
||||
if s.doc.inside_component(to, o.component) {
|
||||
return Err(bad(cmd, format!("{} can't go inside itself or a component within it", o.name)));
|
||||
}
|
||||
if s.doc.marker.is_some() {
|
||||
return Err(bad(cmd, "finish timeline rollback before moving placements"));
|
||||
}
|
||||
if s.held_by_rigid_group(id).is_some() {
|
||||
return Err(bad(cmd, format!("{} is held by a rigid group: Unlock Contents (component.unlock) first", o.name)));
|
||||
}
|
||||
// From the placement named (`path`), into the parent's placement named (`parent_path`).
|
||||
let moved = occurrence_path(s, p, id, cmd)?;
|
||||
let to_given = parent_path(p, cmd)?;
|
||||
let doc = s.placed_document();
|
||||
let (from_path, from_frame) = placement_of(s, &doc, o.parent, moved.split_last().map(|(_, up)| up), "path", cmd)?;
|
||||
let (to_path, to_frame) = placement_of(s, &doc, to, to_given.as_deref(), "parent_path", cmd)?;
|
||||
let local = doc.occurrences.iter().find(|x| x.id == id).map(|x| x.transform).unwrap_or(o.transform);
|
||||
let world = solidcraft_doc::mat_mul(&from_frame, &local);
|
||||
let inverse = solidcraft_doc::mat_inverse(&to_frame).ok_or_else(|| bad(cmd, "the new parent's frame is not invertible"))?;
|
||||
let transform = solidcraft_doc::mat_mul(&inverse, &world);
|
||||
if !solidcraft_doc::valid_transfer_matrix(&transform) {
|
||||
return Err(bad(cmd, "the move exceeds the supported rigid coordinate range"));
|
||||
}
|
||||
drop(doc);
|
||||
let old_path: Vec<u64> = from_path.iter().copied().chain([id]).collect();
|
||||
let new_path: Vec<u64> = to_path.iter().copied().chain([id]).collect();
|
||||
|
||||
let mut scratch = s.scratch();
|
||||
// Pending moves along both parents and of the placement itself are kept: its new transform
|
||||
// was worked out from them.
|
||||
for ancestor in from_path.iter().chain(&to_path) {
|
||||
if let Some(pending) = scratch.pending_moves.remove(ancestor)
|
||||
&& let Some(x) = scratch.doc_mut().occurrences.iter_mut().find(|x| x.id == *ancestor)
|
||||
{
|
||||
x.transform = pending;
|
||||
}
|
||||
}
|
||||
scratch.pending_moves.remove(&id);
|
||||
if let Some(x) = scratch.doc_mut().occurrences.iter_mut().find(|x| x.id == id) {
|
||||
x.parent = to;
|
||||
x.transform = transform;
|
||||
}
|
||||
// Once all its placements sit in the new parent, the component belongs there too, so what
|
||||
// follows the component tree (the parent's eye, its bodies) takes it along.
|
||||
if scratch.doc.occurrences.iter().filter(|x| x.component == o.component).all(|x| x.parent == to)
|
||||
&& let Some(c) = scratch.doc_mut().components.iter_mut().find(|c| c.id == o.component)
|
||||
{
|
||||
c.parent = to;
|
||||
}
|
||||
// The paths through it follow it before the model is worked out again: that drops a selected
|
||||
// or active placement whose path no longer leads anywhere.
|
||||
for sel in &mut scratch.selection {
|
||||
if let Sel::Occurrence { path } = sel
|
||||
&& let Some(moved) = rebased(path, &old_path, &new_path)
|
||||
{
|
||||
*path = moved;
|
||||
}
|
||||
}
|
||||
if let Some(active) = scratch.active_occurrence_path.as_deref().and_then(|path| rebased(path, &old_path, &new_path)) {
|
||||
scratch.active_occurrence_path = Some(active);
|
||||
}
|
||||
scratch.refresh();
|
||||
for f in &scratch.doc.features {
|
||||
let broke = scratch.model.result(f.id).and_then(|r| r.error.as_ref());
|
||||
let was_fine = s.model.result(f.id).is_none_or(|r| r.error.is_none());
|
||||
if let Some(error) = broke.filter(|_| was_fine) {
|
||||
return Err(bad(cmd, format!("moving {} would break {}: {error}", o.name, f.name)));
|
||||
}
|
||||
}
|
||||
s.accept_computed(scratch);
|
||||
for hidden in &mut s.visibility.hidden_occurrences {
|
||||
if let Some(moved) = rebased(hidden, &old_path, &new_path) {
|
||||
*hidden = moved;
|
||||
}
|
||||
}
|
||||
let (old_scope, new_scope) = (Session::folder_scope(&old_path), Session::folder_scope(&new_path));
|
||||
for key in &mut s.visibility.hidden_folders {
|
||||
if let Some(rest) = key.strip_prefix(&old_scope).filter(|rest| rest.starts_with('/')) {
|
||||
*key = format!("{new_scope}{rest}");
|
||||
}
|
||||
}
|
||||
Ok(json!({"occurrence": id, "parent": to, "path": new_path, "transform": transform}))
|
||||
}
|
||||
@@ -60,7 +60,15 @@ fn transfer(s: &mut Session, name: &str, to: u64, frames: &UniqueFrames, cmd: &s
|
||||
bad(cmd, "body transfer requires one source and destination placement; shared instances cannot preserve a unique world pose")
|
||||
})
|
||||
};
|
||||
let source = unique(from)?;
|
||||
// A body of a component placed more than once goes by its name at the first placement,
|
||||
// where the name is its own: it moves from there.
|
||||
let first =
|
||||
frames.get(&from).is_some_and(Option::is_none).then(|| doc.first_path(from)).and_then(|path| Some((doc.path_transform(from, &path)?, path)));
|
||||
let first = first.map(|(frame, path)| (path, frame));
|
||||
let source = match &first {
|
||||
Some(placed) => placed,
|
||||
None => unique(from)?,
|
||||
};
|
||||
let destination = unique(to)?;
|
||||
let old = doc.model_body_offset(body).map(|offset| solidcraft_doc::mat_mul(&source.1, offset)).unwrap_or(source.1);
|
||||
let inv = solidcraft_doc::mat_inverse(&destination.1).ok_or_else(|| bad(cmd, "destination frame is not invertible"))?;
|
||||
@@ -124,6 +132,18 @@ pub(super) fn from_bodies(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"components":made}))
|
||||
}
|
||||
|
||||
/// A placement path parameter (`component_path`: the target's placement to place by,
|
||||
/// `from_path`: the source's placement to move from).
|
||||
fn path_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Vec<u64>>> {
|
||||
let Some(value) = p.get(key) else { return Ok(None) };
|
||||
value
|
||||
.as_array()
|
||||
.filter(|a| a.len() <= 64)
|
||||
.and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())
|
||||
.map(Some)
|
||||
.ok_or_else(|| bad(cmd, format!("`{key}` must list 0..64 occurrence ids")))
|
||||
}
|
||||
|
||||
pub(super) fn move_bodies(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
move_at_boundary(s, p, false)
|
||||
}
|
||||
@@ -139,7 +159,27 @@ fn move_at_boundary(s: &mut Session, p: &Value, allow_boundary: bool) -> Result<
|
||||
let to = super::component(s, p, "component", cmd)?;
|
||||
let bodies = body_names(s, p, cmd, allow_boundary)?;
|
||||
let mut scratch = s.scratch();
|
||||
let frames = unique_frames(&scratch, cmd)?;
|
||||
let mut frames = unique_frames(&scratch, cmd)?;
|
||||
// The target is placed by `component_path`, else its only placement, else the active one: a
|
||||
// component placed more than once gets the bodies in every instance, placed by that one.
|
||||
let given = path_param(p, "component_path", cmd)?;
|
||||
if given.is_some() || frames.get(&to).is_some_and(Option::is_none) {
|
||||
let placed = super::placing::placement_of(&scratch, &scratch.placed_document(), to, given.as_deref(), "component_path", cmd)?;
|
||||
frames.insert(to, Some(placed));
|
||||
}
|
||||
// The bodies move from the placement named (`from_path`: one of several where their component
|
||||
// is placed), as that placement shows them.
|
||||
if let Some(path) = path_param(p, "from_path", cmd)? {
|
||||
let placed = scratch.placed_document();
|
||||
let component = path
|
||||
.last()
|
||||
.and_then(|id| placed.occurrences.iter().find(|o| o.id == *id))
|
||||
.map(|o| o.component)
|
||||
.ok_or_else(|| bad(cmd, "`from_path` is no placement"))?;
|
||||
let frame = placed.path_transform(component, &path).ok_or_else(|| bad(cmd, "`from_path` is no placement"))?;
|
||||
drop(placed);
|
||||
frames.insert(component, Some((path, frame)));
|
||||
}
|
||||
let mut features = Vec::new();
|
||||
for name in &bodies {
|
||||
features.push(transfer(&mut scratch, name, to, &frames, cmd)?);
|
||||
|
||||
@@ -60,6 +60,8 @@ fn shared_destination_refuses_without_mutating_document_or_session() {
|
||||
run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Block"}));
|
||||
let c = run(&mut s, "component.create", json!({"name":"Shared"}))["component"].as_u64().unwrap();
|
||||
run(&mut s, "occurrence.copy", json!({"component":c,"translate":[20,0,0]}));
|
||||
// No placement of the shared target is named or active to place the body by.
|
||||
run(&mut s, "component.activate", json!({"component":0}));
|
||||
let document = s.doc.to_json();
|
||||
let active = s.active_component;
|
||||
assert!(s.execute("component.move_bodies", &json!({"component":c,"bodies":["Block"]})).is_err());
|
||||
@@ -282,9 +284,9 @@ fn edited_transfer_destination_updates_history_owner_copy_and_reopen() {
|
||||
assert_eq!(s.doc.to_json(), saved);
|
||||
assert_eq!(s.pending_moves, pending);
|
||||
let copied = run(&mut s, "component.paste_new", json!({"component":b}))["component"].as_u64().unwrap();
|
||||
assert_eq!(s.model.state().body("Block (copy)").unwrap().component, copied);
|
||||
assert_eq!(s.model.state().body("Block (2)").unwrap().component, copied);
|
||||
let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() };
|
||||
reopened.refresh();
|
||||
assert_eq!(reopened.model.state().body("Block").unwrap().component, b);
|
||||
assert_eq!(reopened.model.state().body("Block (copy)").unwrap().component, copied);
|
||||
assert_eq!(reopened.model.state().body("Block (2)").unwrap().component, copied);
|
||||
}
|
||||
|
||||
@@ -59,12 +59,12 @@ fn certified_annulus_side_rows_follow_radius_edits_and_clone() {
|
||||
run(&mut s, "component.paste_new", json!({"component":part,"translate":[30,0,0]}));
|
||||
assert_eq!(s.doc.configs.columns.len(), 2);
|
||||
run(&mut s, "config.activate", json!({"row":"Painted"}));
|
||||
assert_eq!(painted_radius(&s, "Ring (copy)", 12.), 2);
|
||||
assert_eq!(painted_radius(&s, "Ring (2)", 12.), 2);
|
||||
let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
|
||||
let mut reopened = Session::new(reopened);
|
||||
run(&mut reopened, "config.activate", json!({"row":"Painted"}));
|
||||
assert_eq!(painted_radius(&reopened, "Ring", 12.), 2);
|
||||
assert_eq!(painted_radius(&reopened, "Ring (copy)", 12.), 2);
|
||||
assert_eq!(painted_radius(&reopened, "Ring (2)", 12.), 2);
|
||||
run(&mut reopened, "config.activate", json!({"row":"Default"}));
|
||||
assert!(reopened.doc.appearances.faces.is_empty());
|
||||
}
|
||||
@@ -259,7 +259,7 @@ fn certified_import_payload_binding_roundtrip_clone_and_replacement_refusal() {
|
||||
);
|
||||
run(&mut s, "component.paste_new", json!({"component":part,"translate":[30,0,0]}));
|
||||
run(&mut s, "config.activate", json!({"row":"Painted"}));
|
||||
assert_eq!(painted_radius(&s, "Imported (copy)", 10.), pieces);
|
||||
assert_eq!(painted_radius(&s, "Imported (2)", 10.), pieces);
|
||||
let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
|
||||
let mut s = Session::new(reopened);
|
||||
run(&mut s, "config.activate", json!({"row":"Painted"}));
|
||||
@@ -270,7 +270,7 @@ fn certified_import_payload_binding_roundtrip_clone_and_replacement_refusal() {
|
||||
assert_ne!(&**payload, step.as_str());
|
||||
s.refresh();
|
||||
assert!(s.doc.face_colors(s.model.state().body("Imported").unwrap()).is_empty());
|
||||
assert_eq!(painted_radius(&s, "Imported (copy)", 10.), pieces);
|
||||
assert_eq!(painted_radius(&s, "Imported (2)", 10.), pieces);
|
||||
let before = s.doc.clone();
|
||||
let history = s.undo.len();
|
||||
assert!(s.execute("config.preview", &json!({"row":"Painted"})).is_err());
|
||||
|
||||
@@ -1082,3 +1082,237 @@ fn a_hole_at_a_point_on_a_nested_step_parts_face_drills_it() {
|
||||
run(&mut s, "solid.hole", json!({"sketch": sketch, "diameter": 4, "depth": 5}));
|
||||
assert_block_changed_by(&mut s, -std::f64::consts::PI * 4.0 * 5.0);
|
||||
}
|
||||
|
||||
/// Pasting a body into a component placed elsewhere puts the copy in that component, where the
|
||||
/// body is in the world, as one step to undo.
|
||||
#[test]
|
||||
fn pasted_bodies_go_into_the_component_where_the_body_is() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20, "body_name": "Cube"}));
|
||||
let (component, occurrence) = created(&mut s, "A");
|
||||
run(&mut s, "occurrence.move", json!({"occurrence": occurrence, "translate": [100,0,0]}));
|
||||
let undo = s.undo.len();
|
||||
let out = run(&mut s, "component.copy_bodies", json!({"bodies": ["Cube"]}));
|
||||
let copy = out["bodies"][0].as_str().unwrap().to_string();
|
||||
assert_eq!(s.undo.len(), undo + 1, "one step to undo");
|
||||
let state = s.model.state();
|
||||
assert_eq!(s.doc.model_body_component(state.body(©).unwrap()), component);
|
||||
let placed = run(&mut s, "occurrence.properties", json!({"occurrence": occurrence, "path": [occurrence]}));
|
||||
for i in 0..3 {
|
||||
near(&placed["total"]["center_of_mass"][i], 10.0);
|
||||
}
|
||||
assert_eq!(s.selection, vec![crate::Sel::Body { name: copy.clone() }]);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(s.model.state().body(©).is_none());
|
||||
}
|
||||
|
||||
/// A component pasted into another component, as an instance or as a new copy, sits where the
|
||||
/// copied placement is in the world; a new copy can't go inside the component itself.
|
||||
#[test]
|
||||
fn components_paste_in_place_into_another_component() {
|
||||
let mut s = Session::default();
|
||||
let (part, part_occurrence) = created(&mut s, "Part");
|
||||
run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2}));
|
||||
run(&mut s, "occurrence.move", json!({"occurrence": part_occurrence, "translate": [50,0,0]}));
|
||||
run(&mut s, "component.activate", json!({"component": 0}));
|
||||
let (holder, holder_occurrence) = created(&mut s, "Holder");
|
||||
run(&mut s, "occurrence.move", json!({"occurrence": holder_occurrence, "translate": [0,100,0]}));
|
||||
let source = json!({"component": part, "occurrence": part_occurrence, "parent": holder, "in_place": true});
|
||||
let instance = run(&mut s, "occurrence.copy", source.clone())["occurrence"].as_u64().unwrap();
|
||||
let copy = run(&mut s, "component.paste_new", source)["occurrence"].as_u64().unwrap();
|
||||
for placed in [instance, copy] {
|
||||
let result = run(&mut s, "occurrence.properties", json!({"occurrence": placed, "path": [holder_occurrence, placed]}));
|
||||
for (i, expected) in [51.0, 1.0, 1.0].into_iter().enumerate() {
|
||||
near(&result["total"]["center_of_mass"][i], expected);
|
||||
}
|
||||
}
|
||||
let into_itself = json!({"component": holder, "occurrence": holder_occurrence, "parent": holder, "in_place": true});
|
||||
assert!(s.execute("component.paste_new", &into_itself).is_err());
|
||||
}
|
||||
|
||||
/// Pasted into a component placed more than once, a component goes into every instance: placed
|
||||
/// by the active instance where the copied one is, and in the same place in the other.
|
||||
#[test]
|
||||
fn a_component_pasted_into_an_instanced_component_goes_into_every_instance() {
|
||||
let mut s = Session::default();
|
||||
let (_, part_occurrence) = created(&mut s, "Part");
|
||||
run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2}));
|
||||
run(&mut s, "component.activate", json!({"component": 0}));
|
||||
let (plate, first) = created(&mut s, "Plate");
|
||||
let second = run(&mut s, "occurrence.copy", json!({"component": plate, "translate": [0,100,0]}))["occurrence"].as_u64().unwrap();
|
||||
run(&mut s, "component.activate", json!({"component": 0}));
|
||||
let source = json!({"occurrence": part_occurrence, "parent": plate, "in_place": true});
|
||||
assert!(s.execute("occurrence.copy", &source).is_err(), "no instance of Plate to place it by");
|
||||
run(&mut s, "component.activate", json!({"component": plate, "occurrence": second, "path": [second]}));
|
||||
let pasted = run(&mut s, "occurrence.copy", source)["occurrence"].as_u64().unwrap();
|
||||
for (instance, y) in [(second, 1.0), (first, -99.0)] {
|
||||
let result = run(&mut s, "occurrence.properties", json!({"occurrence": pasted, "path": [instance, pasted]}));
|
||||
near(&result["total"]["center_of_mass"][1], y);
|
||||
}
|
||||
}
|
||||
|
||||
/// A body pasted into a component placed more than once goes into every instance: placed by the
|
||||
/// active instance where the body is, and in the same place in the other.
|
||||
#[test]
|
||||
fn a_body_pasted_into_an_instanced_component_goes_into_every_instance() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"}));
|
||||
let (plate, first) = created(&mut s, "Plate");
|
||||
let second = run(&mut s, "occurrence.copy", json!({"component": plate, "translate": [0,100,0]}))["occurrence"].as_u64().unwrap();
|
||||
run(&mut s, "component.activate", json!({"component": plate, "occurrence": second, "path": [second]}));
|
||||
run(&mut s, "component.copy_bodies", json!({"bodies": ["Cube"]}));
|
||||
for (instance, y) in [(second, 1.0), (first, -99.0)] {
|
||||
let result = run(&mut s, "occurrence.properties", json!({"occurrence": instance, "path": [instance]}));
|
||||
near(&result["total"]["center_of_mass"][1], y);
|
||||
}
|
||||
}
|
||||
|
||||
/// A nested placement moves out to the design and back in, staying where it is in the world, and
|
||||
/// the session's paths to it (selection, hidden placements) follow it.
|
||||
#[test]
|
||||
fn reparent_keeps_the_world_position_and_follows_paths() {
|
||||
let mut s = Session::default();
|
||||
let (parent_component, parent) = created(&mut s, "Parent");
|
||||
run(&mut s, "occurrence.move", json!({"occurrence": parent, "translate": [100,0,0], "axis": [0,0,1], "angle": "90 deg"}));
|
||||
let (_, child) = created(&mut s, "Child");
|
||||
run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2}));
|
||||
let centre =
|
||||
|s: &mut Session, path: Value| run(s, "occurrence.properties", json!({"occurrence": child, "path": path}))["total"]["center_of_mass"].clone();
|
||||
let before = centre(&mut s, json!([parent, child]));
|
||||
run(&mut s, "select.set", json!({"items": [{"type": "occurrence", "path": [parent, child]}]}));
|
||||
s.visibility.hidden_occurrences.push(vec![parent, child]);
|
||||
|
||||
let out = run(&mut s, "occurrence.reparent", json!({"occurrence": child, "parent": "root"}));
|
||||
assert_eq!(out["path"], json!([child]));
|
||||
assert_eq!(s.doc.occurrences.iter().find(|o| o.id == child).unwrap().parent, 0);
|
||||
let after = centre(&mut s, json!([child]));
|
||||
for i in 0..3 {
|
||||
near(&after[i], before[i].as_f64().unwrap());
|
||||
}
|
||||
assert_eq!(s.selection, vec![crate::Sel::Occurrence { path: vec![child] }]);
|
||||
assert_eq!(s.visibility.hidden_occurrences, vec![vec![child]]);
|
||||
|
||||
run(&mut s, "occurrence.reparent", json!({"occurrence": child, "parent": parent_component}));
|
||||
let back = centre(&mut s, json!([parent, child]));
|
||||
for i in 0..3 {
|
||||
near(&back[i], before[i].as_f64().unwrap());
|
||||
}
|
||||
// Undo puts it where it was.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc.occurrences.iter().find(|o| o.id == child).unwrap().parent, 0);
|
||||
}
|
||||
|
||||
/// A component can't go inside itself or what it holds. Out of a parent placed more than once it
|
||||
/// moves from the placement named, keeping that one's place in the world.
|
||||
#[test]
|
||||
fn reparent_refuses_cycles_and_moves_out_of_a_named_instance() {
|
||||
let mut s = Session::default();
|
||||
let (parent_component, parent) = created(&mut s, "Parent");
|
||||
let (child_component, child) = created(&mut s, "Child");
|
||||
run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2}));
|
||||
for into in [parent_component, child_component] {
|
||||
assert!(s.execute("occurrence.reparent", &json!({"occurrence": parent, "parent": into})).is_err(), "into {into}");
|
||||
}
|
||||
let second = run(&mut s, "occurrence.copy", json!({"component": parent_component, "translate": [50,0,0]}))["occurrence"].as_u64().unwrap();
|
||||
let err = s.execute("occurrence.reparent", &json!({"occurrence": child, "parent": 0})).unwrap_err().to_string();
|
||||
assert!(err.contains("path"), "which placement is ambiguous: {err}");
|
||||
run(&mut s, "occurrence.reparent", json!({"occurrence": child, "path": [second, child], "parent": 0}));
|
||||
let result = run(&mut s, "occurrence.properties", json!({"occurrence": child, "path": [child]}));
|
||||
near(&result["total"]["center_of_mass"][0], 51.0);
|
||||
}
|
||||
|
||||
/// A component placed somewhere other than where it was made still can't take a placement of
|
||||
/// what holds it: A placed in B means B can't then be placed in A, by copy or by a move.
|
||||
#[test]
|
||||
fn a_component_placed_in_another_cannot_then_hold_it() {
|
||||
let mut s = Session::default();
|
||||
let a = run(&mut s, "component.create", json!({"name": "A", "activate": false}))["component"].as_u64().unwrap();
|
||||
let b = run(&mut s, "component.create", json!({"name": "B", "activate": false}));
|
||||
let (b, b_occurrence) = (b["component"].as_u64().unwrap(), b["occurrence"].as_u64().unwrap());
|
||||
run(&mut s, "occurrence.copy", json!({"component": a, "parent": b}));
|
||||
assert!(s.execute("occurrence.copy", &json!({"component": b, "parent": a})).is_err(), "B inside A inside B");
|
||||
assert!(s.execute("occurrence.reparent", &json!({"occurrence": b_occurrence, "parent": a})).is_err(), "moved, too");
|
||||
}
|
||||
|
||||
/// A component named after its body: each Paste New numbers the component and its body alike,
|
||||
/// one after the other, with no number skipped (they are numbered among their own kind).
|
||||
#[test]
|
||||
fn paste_new_numbers_a_component_and_its_body_alike() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Plate"}));
|
||||
let plate = run(&mut s, "component.from_bodies", json!({"bodies": ["Plate"]}))["components"][0]["component"].as_u64().unwrap();
|
||||
for _ in 0..2 {
|
||||
run(&mut s, "component.paste_new", json!({"component": plate}));
|
||||
}
|
||||
let components: Vec<&str> = s.doc.components.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(components, ["Plate", "Plate (2)", "Plate (3)"]);
|
||||
let state = s.model.state();
|
||||
let mut bodies: Vec<&str> = state.bodies.iter().map(|b| b.name.as_str()).collect();
|
||||
bodies.sort_unstable();
|
||||
assert_eq!(bodies, ["Plate", "Plate (2)", "Plate (3)"]);
|
||||
}
|
||||
|
||||
/// A Paste New copy has features of its own: editing the copy leaves the original as it was.
|
||||
#[test]
|
||||
fn a_paste_new_copy_is_independent_of_its_original() {
|
||||
let mut s = Session::default();
|
||||
let (part, _) = created(&mut s, "Part");
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": 5, "body_name": "Block"}));
|
||||
run(&mut s, "component.activate", json!({"component": 0}));
|
||||
run(&mut s, "component.paste_new", json!({"component": part}));
|
||||
run(&mut s, "timeline.edit", json!({"feature": "Extrude1 (2)", "set": {"extent": {"distance": "30"}}}));
|
||||
let state = s.model.state();
|
||||
let volume = |name: &str| solidcraft_kernel::measure(&state.body(name).unwrap().body).unwrap().volume;
|
||||
assert!((volume("Block") - 500.0).abs() < 1e-6, "the original is as it was");
|
||||
assert!((volume("Block (2)") - 3000.0).abs() < 1e-6, "the copy changed");
|
||||
}
|
||||
|
||||
/// What was pasted and moved keeps its place, name and component when the design is saved and
|
||||
/// opened again.
|
||||
#[test]
|
||||
fn pasted_and_moved_things_survive_reopening() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"}));
|
||||
let (a, a_at) = created(&mut s, "A");
|
||||
run(&mut s, "occurrence.move", json!({"occurrence": a_at, "translate": [100,0,0]}));
|
||||
run(&mut s, "component.copy_bodies", json!({"bodies": ["Cube"]}));
|
||||
run(&mut s, "component.activate", json!({"component": 0}));
|
||||
let (_, b_at) = created(&mut s, "B");
|
||||
run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "corner": [50, 0, 0], "body_name": "Pin"}));
|
||||
run(&mut s, "component.activate", json!({"component": 0}));
|
||||
run(&mut s, "occurrence.reparent", json!({"occurrence": b_at, "parent": a}));
|
||||
let before = s.world_state();
|
||||
let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() };
|
||||
reopened.refresh();
|
||||
let after = reopened.world_state();
|
||||
for name in ["Cube", "Cube (2)", "Pin"] {
|
||||
let (was, is) = (before.body(name).unwrap().mesh().bounds(), after.body(name).unwrap().mesh().bounds());
|
||||
assert!(was.min.dist(is.min) < 1e-6 && was.max.dist(is.max) < 1e-6, "{name}: {was:?} → {is:?}");
|
||||
}
|
||||
let state = reopened.model.state();
|
||||
assert_eq!(reopened.doc.model_body_component(state.body("Cube (2)").unwrap()), a);
|
||||
assert_eq!(reopened.doc.occurrences.iter().find(|o| o.id == b_at).unwrap().parent, a);
|
||||
}
|
||||
|
||||
/// A body seen in another placement of its component (`Cube (B:2)`) copies from there: the copy
|
||||
/// is of that body, named after it, and sits where that placement shows it.
|
||||
#[test]
|
||||
fn a_body_seen_in_another_placement_copies_from_there() {
|
||||
let mut s = Session::default();
|
||||
let (b, _) = created(&mut s, "B");
|
||||
run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"}));
|
||||
run(&mut s, "component.activate", json!({"component": 0}));
|
||||
let second = run(&mut s, "occurrence.copy", json!({"component": b, "translate": [0,100,0]}))["occurrence"].as_u64().unwrap();
|
||||
let shown = s.occurrence_placement(&[second]).unwrap().bodies[0].world.clone();
|
||||
assert_ne!(shown, "Cube");
|
||||
let out = run(&mut s, "component.copy_bodies", json!({"bodies": [shown.clone()], "component": 0}));
|
||||
assert_eq!(out["bodies"], json!(["Cube (2)"]));
|
||||
let world = s.world_state();
|
||||
let (seen, copy) = (world.body(&shown).unwrap().mesh().bounds(), world.body("Cube (2)").unwrap().mesh().bounds());
|
||||
assert!(seen.min.dist(copy.min) < 1e-6 && seen.max.dist(copy.max) < 1e-6, "{seen:?} vs {copy:?}");
|
||||
let state = s.model.state();
|
||||
assert_eq!(s.doc.model_body_component(state.body("Cube (2)").unwrap()), 0);
|
||||
}
|
||||
|
||||
@@ -1955,13 +1955,20 @@ fn components_occurrences_and_world_placement() {
|
||||
run(&mut s, "component.capture_position", json!({}));
|
||||
assert!(s.pending_moves.is_empty());
|
||||
assert!((bbox(&mut s, "ArmBody")["min"][2].as_f64().unwrap() - 5.0).abs() < 1e-9);
|
||||
// A definition placed twice cannot receive one world body without duplicating it.
|
||||
// A component placed twice gets a body in both instances, placed by the placement named or
|
||||
// active: with neither, the move is refused and names the parameter that would settle it.
|
||||
let document = s.doc.to_json();
|
||||
let pending = s.pending_moves.clone();
|
||||
let error = s.execute("component.move_bodies", &json!({"bodies": ["Base"], "component": "Arm"})).unwrap_err();
|
||||
assert!(error.to_string().contains("one source and destination placement"), "{error}");
|
||||
assert!(error.to_string().contains("placed more than once") && error.to_string().contains("`component_path`"), "{error}");
|
||||
assert_eq!(s.doc.to_json(), document);
|
||||
assert_eq!(s.pending_moves, pending);
|
||||
// Placed by the first placement, the body stays where it is in the world there.
|
||||
run(&mut s, "component.move_bodies", json!({"bodies": ["Base"], "component": "Arm", "component_path": [occ]}));
|
||||
assert_eq!(s.world_state().body("Base").unwrap().component, cid);
|
||||
assert_eq!(bbox(&mut s, "Base")["min"], json!([0.0, 0.0, 0.0]));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc.to_json(), document);
|
||||
// The independent Paste New result has one placement and can receive it.
|
||||
let copied = pn["component"].as_u64().unwrap();
|
||||
run(&mut s, "component.move_bodies", json!({"bodies": ["Base"], "component": copied}));
|
||||
|
||||
@@ -230,16 +230,36 @@ pub fn group_name(app: &SolveApp, id: u64) -> Option<String> {
|
||||
find_group(app, id).map(|g| g.name.clone())
|
||||
}
|
||||
|
||||
/// The placement a folder's scope key names: `c0` the design, `o:<ids>` a placement's path.
|
||||
fn scope_path(scope: &str) -> Vec<u64> {
|
||||
scope.strip_prefix("o:").map(|ids| ids.split('/').filter_map(|id| id.parse().ok()).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Paste on a Bodies or Sketches folder or group: copied (or cut) bodies, or copied sketches and
|
||||
/// features, go into its component (that placement), and into the group.
|
||||
fn paste_item(app: &SolveApp, component: u64, scope: &str, folder: &str, group: Option<u64>) -> Item {
|
||||
let mut item = Item::action("ui.paste", "Paste", "paste")
|
||||
.key("Ctrl+V")
|
||||
.with(json!({ "component": component, "path": scope_path(scope), "group": group, "folder": folder }));
|
||||
item.enabled = if folder == "sketches" { crate::edit_clipboard::pasting_features(app) } else { crate::edit_clipboard::pasting_bodies(app) };
|
||||
item
|
||||
}
|
||||
|
||||
/// The menu of a group row.
|
||||
pub fn group_items(app: &SolveApp, id: u64, scope: &str) -> Vec<Item> {
|
||||
let Some(g) = find_group(app, id) else { return Vec::new() };
|
||||
let mut v = vec![
|
||||
let mut v = Vec::new();
|
||||
// Paste beside Rename, as the clipboard sits beside Delete and Rename in every menu.
|
||||
if g.folder == "bodies" || g.folder == "sketches" {
|
||||
v.push(paste_item(app, g.component, scope, &g.folder, Some(id)));
|
||||
}
|
||||
v.extend([
|
||||
Item::action("ui.rename", "Rename", "rename").with(json!({ "group": id })),
|
||||
Item::action("ui.ungroup", "Ungroup", "folder").with(json!({ "group": id })),
|
||||
Item::sep(),
|
||||
// The group itself: its items keep their own state.
|
||||
Item::action("ui.folderVisible", "Show/Hide", "eye").key("V").with(json!({ "key": format!("{scope}/g{id}") })),
|
||||
];
|
||||
]);
|
||||
if g.folder == "bodies" {
|
||||
v.push(Item::action("ui.isolate", "Isolate", "body").with(json!({ "bodies": group_bodies(app, id) })));
|
||||
}
|
||||
@@ -253,8 +273,12 @@ pub fn folder_items(app: &SolveApp, component: u64, folder: &str, scope: &str) -
|
||||
let mut v = Vec::new();
|
||||
if folder == "bodies" {
|
||||
let bodies: Vec<String> = all.iter().map(|e| e.key.clone()).collect();
|
||||
v.push(paste_item(app, component, scope, folder, None));
|
||||
v.push(Item::action("component.from_bodies", "Create Components from Bodies", "component").with(json!({ "bodies": bodies })));
|
||||
}
|
||||
if folder == "sketches" {
|
||||
v.push(paste_item(app, component, scope, folder, None));
|
||||
}
|
||||
v.push(
|
||||
Item::action("ui.newGroup", if folder == "sketches" { "New Sketch Group" } else { "New Group" }, "folder")
|
||||
.with(json!({ "component": component, "folder": folder })),
|
||||
@@ -1273,6 +1297,12 @@ fn occurrence_key(path: &[u64]) -> String {
|
||||
key
|
||||
}
|
||||
|
||||
/// Show a placement's row closed: a pasted (or moved) component arrives folded, whatever a row
|
||||
/// at that path showed before.
|
||||
pub(crate) fn close_placement(app: &mut SolveApp, path: &[u64]) {
|
||||
app.tree.collapsed.insert(occurrence_key(path));
|
||||
}
|
||||
|
||||
/// A placement, rather than a component definition: repeated child IDs remain distinct
|
||||
/// because their complete paths are the selection and row identity.
|
||||
fn occurrence_rows(app: &mut SolveApp, ui: &mut egui::Ui, path: &[u64], depth: usize, acts: &mut Actions, cache: &mut cache::Cache) {
|
||||
@@ -1316,7 +1346,8 @@ fn occurrence_rows_inner(
|
||||
label: &placement.label,
|
||||
name: true,
|
||||
selected,
|
||||
dim: faded || !visible,
|
||||
// A cut component is faded until Paste moves it.
|
||||
dim: faded || !visible || app.cut_placements.iter().any(|p| p.as_slice() == path),
|
||||
radio: Some(active),
|
||||
badges,
|
||||
mark: acts.lit.placement(&app.session.doc, path, placement.component),
|
||||
@@ -2248,7 +2279,8 @@ fn entry_row(
|
||||
label: &e.label,
|
||||
name: true,
|
||||
selected,
|
||||
dim: !visible || parent_hidden,
|
||||
// A cut body is faded until Paste moves it.
|
||||
dim: !e.visible || parent_hidden || (folder == "bodies" && app.cut_bodies.contains(&e.key)),
|
||||
color: e.color,
|
||||
badges,
|
||||
mark,
|
||||
|
||||
@@ -646,6 +646,10 @@ fn body_items(app: &SolveApp, bodies: &[String], browser: bool) -> Vec<Item> {
|
||||
act("ui.sendToSlicer", "Send to Slicer", "export").with(json!({ "bodies": names })).on(crate::dialogs_save_mesh::available(app)),
|
||||
act("ui.export", "Export…", "export").with(json!({ "bodies": names })),
|
||||
Item::sep(),
|
||||
// The clipboard beside Delete, Remove and Rename, as in every menu.
|
||||
act("ui.cut", "Cut", "cut").key("Ctrl+X").on(crate::edit_clipboard::can_cut(app)),
|
||||
act("ui.copy", "Copy", "copy").key("Ctrl+C").on(crate::edit_clipboard::something_to_copy(app)),
|
||||
act("ui.paste", "Paste", "paste").key("Ctrl+V").on(crate::edit_clipboard::can_paste(app)),
|
||||
act("ui.delete", "Delete", "delete").key("Del").with(json!({ "items": items })).on(!locked),
|
||||
cmd(app, "solid.remove", "Remove").with(json!({ "bodies": names })).on(!locked),
|
||||
act("ui.rename", "Rename", "rename").with(json!({ "body": bodies.first() })).on(one),
|
||||
@@ -681,6 +685,8 @@ fn sketch_items(app: &SolveApp, id: u64) -> Vec<Item> {
|
||||
act("ui.redefineSketch", "Redefine Sketch Plane", "plane").with(json!({ "sketch": id })),
|
||||
act("ui.exportDxf", "Export DXF…", "export").with(json!({ "sketch": id })),
|
||||
Item::sep(),
|
||||
act("ui.copy", "Copy", "copy").key("Ctrl+C").on(crate::edit_clipboard::something_to_copy(app)),
|
||||
act("ui.paste", "Paste", "paste").key("Ctrl+V").on(crate::edit_clipboard::can_paste(app)),
|
||||
act("ui.delete", "Delete", "delete").key("Del").with(json!({ "items": [{"type": "feature", "id": id}] })),
|
||||
act("ui.rename", "Rename", "rename").with(json!({ "feature": id })),
|
||||
Item::sep(),
|
||||
@@ -781,11 +787,8 @@ fn occurrence_items(app: &SolveApp, path: &[u64]) -> Vec<Item> {
|
||||
}
|
||||
}
|
||||
"occurrence.copy" => item.params = Some(json!({"occurrence": placement.occurrence, "translate": [10,10,0]})),
|
||||
"ui.paste" | "ui.pasteNew" => item.params = Some(json!({"component": placement.component, "path": path})),
|
||||
"component.create" => item.params = Some(json!({"parent": placement.component, "parent_path": path})),
|
||||
"component.paste_new" => {
|
||||
item.label = "Paste New (Own Features)".into();
|
||||
item.params = Some(json!({"component":placement.component,"occurrence":placement.occurrence,"path":path,"translate":[10,10,0]}));
|
||||
}
|
||||
"ui.rename" => item.label = "Rename Component".into(),
|
||||
"ui.appearance" => item.label = "Component Appearance".into(),
|
||||
"ui.material" => item.label = "Component Physical Material".into(),
|
||||
@@ -827,6 +830,11 @@ fn component_items(app: &SolveApp, id: u64) -> Vec<Item> {
|
||||
let bodies = component_bodies(app, id);
|
||||
let hidden = !bodies.is_empty() && bodies.iter().all(|b| app.session.visibility.hidden_bodies.contains(b));
|
||||
let names = json!(bodies);
|
||||
// The clipboard: Copy takes the selection (the row right-clicked); Paste puts what was copied
|
||||
// inside this component (never a component inside itself or what it holds); Paste New pastes
|
||||
// copied components as independent copies.
|
||||
let into = json!({ "component": id, "path": app.session.doc.first_path(id) });
|
||||
let pastes_here = crate::edit_clipboard::can_paste_into(app, id);
|
||||
let mut v = Vec::new();
|
||||
if doc.parts.contains_key(&id) {
|
||||
v.push(cmd(app, "parts.resize", "Edit").with(json!({"component":id})));
|
||||
@@ -858,8 +866,6 @@ fn component_items(app: &SolveApp, id: u64) -> Vec<Item> {
|
||||
}
|
||||
v.push(cmd(app, "component.create", "New Component").with(json!({ "parent": id })));
|
||||
if id == 0 {
|
||||
v.push(act("ui.copyDesign", "Copy", "copy").key("Ctrl+C"));
|
||||
v.push(act("ui.paste", "Paste", "paste").key("Ctrl+V").on(crate::edit_clipboard::can_paste(app)));
|
||||
v.push(cmd(app, "component.from_bodies", "Create Components from Bodies").with(json!({ "bodies": names })).on(!bodies.is_empty()));
|
||||
}
|
||||
v.push(Item::sep());
|
||||
@@ -891,9 +897,22 @@ fn component_items(app: &SolveApp, id: u64) -> Vec<Item> {
|
||||
.on(!bodies.is_empty() && crate::dialogs_save_mesh::available(app)),
|
||||
);
|
||||
v.push(Item::sep());
|
||||
// The clipboard, then Delete and Rename, in the same place for the design and its components
|
||||
// (the design is copied as a saved design to link, and is neither cut nor deleted).
|
||||
if id == 0 {
|
||||
v.push(act("ui.copyDesign", "Copy", "copy").key("Ctrl+C"));
|
||||
} else {
|
||||
v.push(act("ui.cut", "Cut", "cut").key("Ctrl+X").on(crate::edit_clipboard::can_cut(app)));
|
||||
v.push(act("ui.copy", "Copy", "copy").key("Ctrl+C").on(crate::edit_clipboard::something_to_copy(app)));
|
||||
}
|
||||
v.push(act("ui.paste", "Paste", "paste").key("Ctrl+V").with(into.clone()).on(pastes_here));
|
||||
v.push(
|
||||
act("ui.pasteNew", "Paste New", "paste")
|
||||
.key("Ctrl+Shift+V")
|
||||
.with(into.clone())
|
||||
.on(pastes_here && crate::edit_clipboard::pasting_components(app)),
|
||||
);
|
||||
if id != 0 {
|
||||
v.push(cmd(app, "occurrence.copy", "Paste (Instance)").with(json!({ "component": id, "translate": [10, 10, 0] })));
|
||||
v.push(cmd(app, "component.paste_new", "Paste New").with(json!({ "component": id, "translate": [10, 10, 0] })));
|
||||
v.push(act("ui.delete", "Delete", "delete").key("Del").with(json!({ "occurrences": [occ.map(|o| o.id)] })).on(occ.is_some()));
|
||||
}
|
||||
v.push(act("ui.rename", "Rename", "rename").with(json!({ "component": id })));
|
||||
@@ -1003,9 +1022,6 @@ fn sketch_entity_items(app: &SolveApp) -> Vec<Item> {
|
||||
v.extend(explode_text(app));
|
||||
}
|
||||
v.push(cmd(app, "sketch.move", "Move/Copy").key("M"));
|
||||
v.push(act("ui.cut", "Cut", "cut").key("Ctrl+X"));
|
||||
v.push(act("ui.copy", "Copy", "copy").key("Ctrl+C"));
|
||||
v.push(act("ui.paste", "Paste", "paste").key("Ctrl+V").on(app.session.sketch_clipboard.is_some()));
|
||||
if !curves.is_empty() {
|
||||
v.push(cmd(app, "sketch.construction", "Normal / Construction").with(json!({ "curves": curves })));
|
||||
}
|
||||
@@ -1027,6 +1043,10 @@ fn sketch_entity_items(app: &SolveApp) -> Vec<Item> {
|
||||
v.push(cmd(app, "sketch.offset.break", "Break Offset Association").with(json!({"curve":curves[0]})));
|
||||
}
|
||||
v.push(act("ui.fix", "Fix/Unfix", "c_fix").with(json!({ "entities": ents })));
|
||||
// The clipboard beside Delete, as in every menu.
|
||||
v.push(act("ui.cut", "Cut", "cut").key("Ctrl+X"));
|
||||
v.push(act("ui.copy", "Copy", "copy").key("Ctrl+C"));
|
||||
v.push(act("ui.paste", "Paste", "paste").key("Ctrl+V").on(app.session.sketch_clipboard.is_some()));
|
||||
v.push(act("ui.delete", "Delete", "delete").key("Del"));
|
||||
v.push(cmd(app, "sketch.dimension", "Sketch Dimension").with(json!({ "entities": ents })).on(ents.len() <= 2));
|
||||
let mut c = Vec::new();
|
||||
@@ -1148,7 +1168,21 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) {
|
||||
"ui.copy" => drop(crate::edit_clipboard::copy(app)),
|
||||
"ui.copyDesign" => drop(crate::edit_clipboard::copy_design(app)),
|
||||
"ui.cut" => drop(crate::edit_clipboard::cut(app)),
|
||||
"ui.paste" => drop(crate::edit_clipboard::paste(app, Some(at))),
|
||||
"ui.paste" | "ui.pasteNew" => {
|
||||
// A component's menu pastes into it (that placement); the others into the active one.
|
||||
let into = id_of(&p, "component").map(|c| {
|
||||
let path = p.get("path").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect());
|
||||
(c, path.unwrap_or_else(|| app.session.doc.first_path(c)))
|
||||
});
|
||||
match id_of(&p, "group") {
|
||||
// A Bodies group's menu: into the group too.
|
||||
Some(group) => {
|
||||
let folder = p.get("folder").and_then(Value::as_str).unwrap_or("bodies");
|
||||
let _ = crate::edit_clipboard::paste_into_group(app, Some(at), into, Some(group), folder);
|
||||
}
|
||||
None => drop(crate::edit_clipboard::paste_into(app, Some(at), item.id == "ui.pasteNew", into)),
|
||||
}
|
||||
}
|
||||
"ui.editSketchPattern" => {
|
||||
if let Some(id) = p.get("pattern").and_then(Value::as_str) {
|
||||
crate::sketch_modify_ui::edit_pattern(app, id);
|
||||
|
||||
@@ -37,6 +37,12 @@ pub struct DocSlot {
|
||||
#[derive(Clone, Debug, Default)]
|
||||
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).
|
||||
copied_bodies: Vec<String>,
|
||||
copied_placements: Vec<Vec<u64>>,
|
||||
cut_bodies: Vec<String>,
|
||||
cut_placements: Vec<Vec<u64>>,
|
||||
}
|
||||
|
||||
impl DocSlot {
|
||||
@@ -92,7 +98,13 @@ impl Documents {
|
||||
}
|
||||
|
||||
fn take_view(app: &mut SolveApp) -> DocView {
|
||||
DocView { render: std::mem::take(&mut app.render_workspace.view) }
|
||||
DocView {
|
||||
render: std::mem::take(&mut app.render_workspace.view),
|
||||
copied_bodies: std::mem::take(&mut app.copied_bodies),
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
fn put_view(app: &mut SolveApp, v: DocView) {
|
||||
@@ -100,6 +112,10 @@ fn put_view(app: &mut SolveApp, v: DocView) {
|
||||
crate::render_workspace::invalidate_images(app);
|
||||
crate::render_workspace::invalidate_scene(app);
|
||||
crate::render_workspace::sync_backend(app);
|
||||
app.copied_bodies = v.copied_bodies;
|
||||
app.copied_placements = v.copied_placements;
|
||||
app.cut_bodies = v.cut_bodies;
|
||||
app.cut_placements = v.cut_placements;
|
||||
}
|
||||
|
||||
/// Put `slot` into the app and return what was there.
|
||||
|
||||
@@ -4,28 +4,28 @@
|
||||
//! In a sketch they copy the selected sketch geometry (`sketch.copy`) and paste it at the cursor
|
||||
//! (`sketch.paste` with `at`); Cut copies the sketch geometry and deletes it (`sketch.cut`), or offset from the original when the cursor is not over the
|
||||
//! viewport. Outside a sketch they copy the selected timeline features and paste them at the
|
||||
//! history marker (`timeline.copy` / `timeline.paste`).
|
||||
//! history marker (`timeline.copy` / `timeline.paste`), the selected bodies and paste copies of
|
||||
//! them into the active component, where the bodies are (`component.copy_bodies`), or the
|
||||
//! selected components and paste new instances of them there (`occurrence.copy`), or with
|
||||
//! Ctrl+Shift+V new independent copies (`component.paste_new`), where they are too. Paste pastes
|
||||
//! whichever was copied last. Cut on bodies or components only marks them: Paste moves them into
|
||||
//! 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.
|
||||
//!
|
||||
//! 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
|
||||
//! context to write it).
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
use egui::Pos2;
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_engine::Sel;
|
||||
|
||||
use crate::SolveApp;
|
||||
|
||||
/// Text for the system clipboard, written on the next frame.
|
||||
static PENDING_TEXT: Mutex<Option<String>> = Mutex::new(None);
|
||||
|
||||
fn leave_text(text: String) {
|
||||
if let Ok(mut pending) = PENDING_TEXT.lock() {
|
||||
*pending = Some(text);
|
||||
}
|
||||
/// Leave text for the system clipboard: this app's next frame writes it ([`flush`]).
|
||||
fn leave_text(app: &mut SolveApp, text: String) {
|
||||
app.clipboard_text = Some(text);
|
||||
}
|
||||
|
||||
/// The selected sketch geometry of the active sketch.
|
||||
@@ -40,23 +40,160 @@ fn sketch_selection(app: &SolveApp) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The selected component placements (by path).
|
||||
fn placement_selection(app: &SolveApp) -> Vec<Vec<u64>> {
|
||||
app.session.selection.iter().filter_map(|s| if let Sel::Occurrence { path } = s { Some(path.clone()) } else { None }).collect()
|
||||
}
|
||||
|
||||
/// The selected bodies.
|
||||
fn body_selection(app: &SolveApp) -> Vec<String> {
|
||||
app.session.selection.iter().filter_map(|s| if let Sel::Body { name } = s { Some(name.clone()) } else { None }).collect()
|
||||
}
|
||||
|
||||
/// 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]
|
||||
|| !crate::timeline::selected_feature_ids(app).is_empty()
|
||||
|| !body_selection(app).is_empty()
|
||||
|| !placement_selection(app).is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Is there something Paste would paste here?
|
||||
pub fn can_paste(app: &SolveApp) -> bool {
|
||||
if app.session.active_sketch.is_some() {
|
||||
app.session.sketch_clipboard.is_some()
|
||||
} else if app.linked_design_clipboard.is_some() {
|
||||
// A copied design is what pastes, and never into itself.
|
||||
!design_copied_here(app)
|
||||
} else {
|
||||
app.linked_design_clipboard.is_some() || !app.session.clipboard.is_empty()
|
||||
!app.session.clipboard.is_empty()
|
||||
|| !app.cut_bodies.is_empty()
|
||||
|| !app.cut_placements.is_empty()
|
||||
|| !app.copied_bodies.is_empty()
|
||||
|| !app.copied_placements.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// The design copied (to paste as a linked component) is the one open: it can't go into itself.
|
||||
fn design_copied_here(app: &SolveApp) -> bool {
|
||||
app.linked_design_clipboard.is_some() && app.linked_design_clipboard == app.session.path
|
||||
}
|
||||
|
||||
/// Whether copied components are what Paste pastes now (not features, nor a design to link).
|
||||
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()
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
|
||||
/// Whether copied or cut bodies are what Paste pastes now (a Bodies folder's menu offers them).
|
||||
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())
|
||||
}
|
||||
|
||||
/// [`paste_into`], then what was pasted into `group` of the component's `folder`: a group's menu
|
||||
/// pastes into the group (the pasted bodies, which a body paste leaves selected, or the pasted
|
||||
/// sketches).
|
||||
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 items: Vec<String> = out
|
||||
.get("pasted")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|m| m.get("id").and_then(Value::as_u64))
|
||||
.filter(|id| app.session.doc.feature(*id).is_some_and(|f| matches!(f.kind, solidcraft_engine::doc::FeatureKind::Sketch { .. })))
|
||||
.map(|id| id.to_string())
|
||||
.collect();
|
||||
if !items.is_empty() {
|
||||
let _ = app.run("browser.move", json!({ "component": component, "folder": "sketches", "items": items, "group": group }));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if !paste_into(app, at, false, into) {
|
||||
return false;
|
||||
}
|
||||
let items: Vec<String> =
|
||||
app.session.selection.iter().filter_map(|s| if let Sel::Body { name } = s { Some(name.clone()) } else { None }).collect();
|
||||
if !items.is_empty() {
|
||||
let _ = app.run("browser.move", json!({ "component": component, "folder": "bodies", "items": items, "group": group }));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Is there something Paste would paste into `component` (a component's menu)? Copied components
|
||||
/// never go inside themselves or what they hold.
|
||||
pub fn can_paste_into(app: &SolveApp, component: u64) -> bool {
|
||||
let placements = if pasting_components(app) {
|
||||
&app.copied_placements
|
||||
} else if app.session.clipboard.is_empty() && app.linked_design_clipboard.is_none() && !app.cut_placements.is_empty() {
|
||||
&app.cut_placements
|
||||
} else {
|
||||
return can_paste(app);
|
||||
};
|
||||
placements
|
||||
.iter()
|
||||
.filter_map(|path| app.session.occurrence_placement(path).ok())
|
||||
.all(|p| !app.session.doc.inside_component(component, p.component))
|
||||
}
|
||||
|
||||
/// Empty every clipboard (features, sketch geometry, bodies, components, a design): a copy that
|
||||
/// fails leaves nothing behind it, so Paste never pastes what was copied before.
|
||||
fn clear_clipboard(app: &mut SolveApp) {
|
||||
app.session.clipboard.clear();
|
||||
app.session.sketch_clipboard = None;
|
||||
replace_clipboard(app);
|
||||
}
|
||||
|
||||
/// 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).
|
||||
fn replace_clipboard(app: &mut SolveApp) {
|
||||
app.copied_bodies.clear();
|
||||
app.copied_placements.clear();
|
||||
app.cut_bodies.clear();
|
||||
app.cut_placements.clear();
|
||||
app.linked_design_clipboard = None;
|
||||
}
|
||||
|
||||
/// Leave bodies that were cut where they are (Esc, or another copy).
|
||||
pub fn drop_cut(app: &mut SolveApp) {
|
||||
app.cut_bodies.clear();
|
||||
app.cut_placements.clear();
|
||||
}
|
||||
|
||||
/// A copy (or cut) that can't be done: it says why, and the clipboard is left empty.
|
||||
fn copy_failed(app: &mut SolveApp, why: Option<&str>) -> bool {
|
||||
clear_clipboard(app);
|
||||
if let Some(why) = why {
|
||||
app.set_status(why, true);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Copy the saved root design. The path stays in this app, outside per-document sessions.
|
||||
pub fn copy_design(app: &mut SolveApp) -> bool {
|
||||
let Some(path) = app.session.path.clone().filter(|_| !app.session.is_dirty()) else {
|
||||
app.set_status("Save this design before copying it as a linked component", true);
|
||||
return false;
|
||||
return copy_failed(app, Some("Save this design before copying it as a linked component"));
|
||||
};
|
||||
replace_clipboard(app);
|
||||
app.linked_design_clipboard = Some(path);
|
||||
leave_text(format!("SolidCraft linked design: {}", app.session.doc.name));
|
||||
leave_text(app, format!("SolidCraft linked design: {}", app.session.doc.name));
|
||||
app.set_status("Copied design: switch to the assembly and paste to insert a linked component", false);
|
||||
true
|
||||
}
|
||||
@@ -69,47 +206,125 @@ pub fn copy(app: &mut SolveApp) -> bool {
|
||||
if app.session.active_sketch.is_some() {
|
||||
let entities = sketch_selection(app);
|
||||
if entities.is_empty() {
|
||||
app.set_status("Select sketch geometry to copy", true);
|
||||
return false;
|
||||
return copy_failed(app, Some("Select sketch geometry to copy"));
|
||||
}
|
||||
let Ok(out) = app.run("sketch.copy", json!({ "entities": entities })) else { return false };
|
||||
app.linked_design_clipboard = None;
|
||||
// The command says why when it fails.
|
||||
let Ok(out) = app.run("sketch.copy", json!({ "entities": entities })) else { return copy_failed(app, None) };
|
||||
replace_clipboard(app);
|
||||
let n = out.get("curves").and_then(Value::as_u64).unwrap_or(0) + out.get("points").and_then(Value::as_u64).unwrap_or(0);
|
||||
let k = out.get("constraints").and_then(Value::as_u64).unwrap_or(0);
|
||||
let text = format!("SolidCraft sketch geometry: {n} entities, {k} constraints and dimensions");
|
||||
app.set_status(format!("Copied {n} sketch entities with {k} constraints and dimensions"), false);
|
||||
leave_text(text);
|
||||
leave_text(app, text);
|
||||
return true;
|
||||
}
|
||||
let features = crate::timeline::selected_feature_ids(app);
|
||||
if features.is_empty() {
|
||||
app.set_status("Select sketch geometry or timeline features to copy", true);
|
||||
return false;
|
||||
let bodies = body_selection(app);
|
||||
let placements = placement_selection(app);
|
||||
// Components picked (in the browser): instances or copies of them paste.
|
||||
if features.is_empty() && !placements.is_empty() {
|
||||
// The last copy is what Paste pastes: what was copied before gives way.
|
||||
app.session.clipboard.clear();
|
||||
replace_clipboard(app);
|
||||
let names: Vec<String> = 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.copied_placements = placements;
|
||||
return true;
|
||||
}
|
||||
let Ok(out) = app.run("timeline.copy", json!({ "features": features })) else { return false };
|
||||
app.linked_design_clipboard = None;
|
||||
// Bodies picked (in the browser or the view) with no features: copies of them paste.
|
||||
if features.is_empty() && !bodies.is_empty() {
|
||||
app.session.clipboard.clear();
|
||||
replace_clipboard(app);
|
||||
app.set_status(format!("Copied {}", bodies.join(", ")), false);
|
||||
leave_text(app, format!("SolidCraft bodies: {}", bodies.join(", ")));
|
||||
app.copied_bodies = bodies;
|
||||
return true;
|
||||
}
|
||||
if features.is_empty() {
|
||||
return copy_failed(app, Some("Select sketch geometry, bodies or timeline features to copy"));
|
||||
}
|
||||
let Ok(out) = app.run("timeline.copy", json!({ "features": features })) else { return copy_failed(app, None) };
|
||||
replace_clipboard(app);
|
||||
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(format!("SolidCraft features: {}", names.join(", ")));
|
||||
leave_text(app, format!("SolidCraft features: {}", names.join(", ")));
|
||||
true
|
||||
}
|
||||
|
||||
/// Cut the selected sketch geometry: copy it, then delete it (one undo step).
|
||||
/// Why the selected bodies can't be cut (`None`: they can): none selected, a locked one, or one
|
||||
/// that is a placed copy's (it is moved through its component).
|
||||
fn body_cut_refused(app: &SolveApp, bodies: &[String]) -> Option<String> {
|
||||
if bodies.is_empty() {
|
||||
return Some("Select bodies (or, in a sketch, sketch geometry) to cut".into());
|
||||
}
|
||||
let state = app.session.model.state();
|
||||
if let Some(b) = bodies.iter().find(|b| state.body(b).is_none()) {
|
||||
return Some(format!("{b} is a placed copy's body: cut it from its component's first placement"));
|
||||
}
|
||||
bodies.iter().find(|b| app.session.visibility.locked_bodies.contains(b)).map(|b| format!("{b} is locked"))
|
||||
}
|
||||
|
||||
/// Why the selected components can't be cut (`None`: they can): one placed more than once (an
|
||||
/// instance: cutting it would take every instance along), or held by a rigid group.
|
||||
fn placement_cut_refused(app: &SolveApp, placements: &[Vec<u64>]) -> Option<String> {
|
||||
for path in placements {
|
||||
let Ok(p) = app.session.occurrence_placement(path) else { return Some("that component is gone".into()) };
|
||||
if app.session.doc.occurrences.iter().filter(|o| o.component == p.component).count() > 1 {
|
||||
return Some(format!("{} is placed more than once: an instance can't be cut (copy it instead)", p.name));
|
||||
}
|
||||
if app.session.held_by_rigid_group(p.occurrence).is_some() {
|
||||
return Some(format!("{} is held by a rigid group: Unlock Contents first", p.name));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Is there something Cut would cut: sketch geometry in a sketch, otherwise components or bodies
|
||||
/// that may move.
|
||||
pub fn can_cut(app: &SolveApp) -> bool {
|
||||
if app.session.active_sketch.is_some() {
|
||||
return !sketch_selection(app).is_empty();
|
||||
}
|
||||
let placements = placement_selection(app);
|
||||
if placements.is_empty() { body_cut_refused(app, &body_selection(app)).is_none() } else { placement_cut_refused(app, &placements).is_none() }
|
||||
}
|
||||
|
||||
/// Cut: in a sketch, the selected sketch geometry (copied, then deleted: one undo step); otherwise
|
||||
/// the selected bodies, which stay until Paste moves them.
|
||||
pub fn cut(app: &mut SolveApp) -> bool {
|
||||
if app.session.active_sketch.is_none() {
|
||||
app.set_status("Cut works on sketch geometry: edit a sketch and select some", true);
|
||||
return false;
|
||||
let placements = placement_selection(app);
|
||||
if !placements.is_empty() {
|
||||
if let Some(why) = placement_cut_refused(app, &placements) {
|
||||
return copy_failed(app, Some(&why));
|
||||
}
|
||||
clear_clipboard(app);
|
||||
let names: Vec<String> = 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.cut_placements = placements;
|
||||
return true;
|
||||
}
|
||||
let bodies = body_selection(app);
|
||||
if let Some(why) = body_cut_refused(app, &bodies) {
|
||||
return copy_failed(app, Some(&why));
|
||||
}
|
||||
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(", ")));
|
||||
app.cut_bodies = bodies;
|
||||
return true;
|
||||
}
|
||||
let entities = sketch_selection(app);
|
||||
if entities.is_empty() {
|
||||
app.set_status("Select sketch geometry to cut", true);
|
||||
return false;
|
||||
return copy_failed(app, Some("Select sketch geometry to cut"));
|
||||
}
|
||||
let Ok(out) = app.run("sketch.cut", json!({ "entities": entities })) else { return false };
|
||||
app.linked_design_clipboard = None;
|
||||
let Ok(out) = app.run("sketch.cut", json!({ "entities": entities })) else { return copy_failed(app, None) };
|
||||
replace_clipboard(app);
|
||||
let n = out.get("curves").and_then(Value::as_u64).unwrap_or(0) + out.get("points").and_then(Value::as_u64).unwrap_or(0);
|
||||
app.set_status(format!("Cut {n} sketch entities"), false);
|
||||
leave_text(format!("SolidCraft sketch geometry: {n} entities"));
|
||||
leave_text(app, format!("SolidCraft sketch geometry: {n} entities"));
|
||||
true
|
||||
}
|
||||
|
||||
@@ -127,8 +342,25 @@ fn sketch_point(app: &SolveApp, at: Option<Pos2>) -> Option<[f64; 2]> {
|
||||
}
|
||||
|
||||
/// Paste: in a sketch, the copied sketch geometry centred at `at` (or offset from the original
|
||||
/// when `at` is not over the sketch); otherwise the copied features at the history marker.
|
||||
/// when `at` is not over the sketch); otherwise the copied features at the history marker, or
|
||||
/// the copied bodies or components into the active component (components as new instances, or
|
||||
/// with `new_copy` as independent copies).
|
||||
pub fn paste(app: &mut SolveApp, at: Option<Pos2>) -> bool {
|
||||
paste_as(app, at, false)
|
||||
}
|
||||
|
||||
/// [`paste`]; `new_copy`: copied components paste as independent copies (Ctrl+Shift+V).
|
||||
pub fn paste_as(app: &mut SolveApp, at: Option<Pos2>, new_copy: bool) -> bool {
|
||||
paste_into(app, at, new_copy, None)
|
||||
}
|
||||
|
||||
/// [`paste_as`], copied bodies and components going into `into` (a component and the placement
|
||||
/// of it to place them by: a component's menu) instead of the active component.
|
||||
pub fn paste_into(app: &mut SolveApp, at: Option<Pos2>, new_copy: bool, into: Option<(u64, Vec<u64>)>) -> bool {
|
||||
let into = into.unwrap_or_else(|| {
|
||||
let active = app.session.active_component;
|
||||
(active, app.session.active_occurrence_path.clone().unwrap_or_else(|| app.session.doc.first_path(active)))
|
||||
});
|
||||
if app.session.active_sketch.is_some() {
|
||||
if app.session.sketch_clipboard.is_none() {
|
||||
app.set_status("Nothing to paste: copy sketch geometry first", true);
|
||||
@@ -143,6 +375,10 @@ pub fn paste(app: &mut SolveApp, at: Option<Pos2>) -> bool {
|
||||
app.set_status(format!("Pasted {n} sketch entities (selected: drag them, or press M to move them)"), false);
|
||||
return true;
|
||||
}
|
||||
if design_copied_here(app) {
|
||||
app.set_status("A design can't be pasted into itself: paste it as a linked component in another design", true);
|
||||
return false;
|
||||
}
|
||||
if let Some(path) = app.linked_design_clipboard.clone() {
|
||||
let (parent_path, translate) = paste_placement(app, at);
|
||||
// The copied design is one the user opened: its server is the user's choice.
|
||||
@@ -161,11 +397,34 @@ pub fn paste(app: &mut SolveApp, at: Option<Pos2>) -> bool {
|
||||
app.set_status("Pasted linked component: use Move/Copy to position it", false);
|
||||
return true;
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
if app.session.clipboard.is_empty() && !app.cut_placements.is_empty() {
|
||||
return paste_cut_placements(app, into);
|
||||
}
|
||||
if app.session.clipboard.is_empty() && !app.copied_placements.is_empty() {
|
||||
return paste_placements(app, new_copy, into);
|
||||
}
|
||||
if app.session.clipboard.is_empty() && !app.copied_bodies.is_empty() {
|
||||
let bodies = app.copied_bodies.clone();
|
||||
// Placed by that placement: a component placed more than once gets them in each.
|
||||
let (component, path) = into;
|
||||
let Ok(out) = app.run("component.copy_bodies", json!({ "bodies": bodies, "component": component, "component_path": path })) else {
|
||||
return false;
|
||||
};
|
||||
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 {}", made.join(", ")), false);
|
||||
return true;
|
||||
}
|
||||
if app.session.clipboard.is_empty() {
|
||||
app.set_status("Nothing to paste: copy timeline features first", true);
|
||||
app.set_status("Nothing to paste: copy bodies or timeline features first", true);
|
||||
return false;
|
||||
}
|
||||
app.run("timeline.paste", json!({})).is_ok()
|
||||
// Into that component (that placement), each where its original is in the world.
|
||||
let (component, path) = into;
|
||||
app.run("timeline.paste", json!({ "component": component, "component_path": path })).is_ok()
|
||||
}
|
||||
|
||||
/// Place the copied design's origin on the pointed solid surface, otherwise its parent's
|
||||
@@ -200,11 +459,103 @@ fn paste_placement(app: &SolveApp, at: Option<Pos2>) -> (Vec<u64>, [f64; 3]) {
|
||||
(path, [local.x, local.y, local.z])
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn paste_cut_bodies(app: &mut SolveApp, (component, path): (u64, Vec<u64>)) -> bool {
|
||||
let state = app.session.model.state();
|
||||
let moving: Vec<String> = app
|
||||
.cut_bodies
|
||||
.iter()
|
||||
.filter(|b| state.body(b).is_some_and(|body| app.session.doc.model_body_component(body) != component))
|
||||
.cloned()
|
||||
.collect();
|
||||
drop(state);
|
||||
let cut = std::mem::take(&mut app.cut_bodies);
|
||||
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;
|
||||
return false;
|
||||
}
|
||||
let _ = app.run("select.set", json!({ "items": moving.iter().map(|b| json!({"type": "body", "name": b})).collect::<Vec<_>>() }));
|
||||
app.set_status(format!("Moved {}", moving.join(", ")), false);
|
||||
true
|
||||
}
|
||||
|
||||
/// Move the cut components into `into` (a component, placed by its placement), where they are
|
||||
/// (`occurrence.reparent`); they are selected and the clipboard empties. Ones already in it stay
|
||||
/// 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<u64>)) -> bool {
|
||||
let cut = std::mem::take(&mut app.cut_placements);
|
||||
let mut moved = Vec::new();
|
||||
for from in &cut {
|
||||
let Some(&occurrence) = from.last() else { continue };
|
||||
if app.session.doc.occurrences.iter().any(|o| o.id == occurrence && o.parent == component) {
|
||||
continue;
|
||||
}
|
||||
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;
|
||||
return false;
|
||||
};
|
||||
let to: Vec<u64> = out.get("path").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default();
|
||||
crate::browser::close_placement(app, &to);
|
||||
moved.push(Sel::Occurrence { path: to });
|
||||
}
|
||||
if moved.is_empty() {
|
||||
app.set_status("Already in that component: nothing to move", false);
|
||||
return true;
|
||||
}
|
||||
let _ = app.run("select.set", json!({ "items": moved }));
|
||||
app.set_status("Moved the cut components", false);
|
||||
true
|
||||
}
|
||||
|
||||
/// New instances (or with `new_copy`, independent copies) of the copied components in `into` (a
|
||||
/// component, placed by its placement), where the components are; they are selected. A component
|
||||
/// never goes inside itself or what it holds: that is refused and says so.
|
||||
fn paste_placements(app: &mut SolveApp, new_copy: bool, (active, base): (u64, Vec<u64>)) -> bool {
|
||||
let mut made = Vec::new();
|
||||
let mut names = Vec::new();
|
||||
for path in app.copied_placements.clone() {
|
||||
let Some(placement) = app.session.occurrence_placement(&path).ok() else { continue };
|
||||
// Placed by that placement: a component placed more than once gets it in each.
|
||||
let source = json!({ "occurrence": placement.occurrence, "path": path, "parent": active, "parent_path": base, "in_place": true });
|
||||
let out = if new_copy {
|
||||
let mut p = source;
|
||||
p["component"] = json!(placement.component);
|
||||
app.run("component.paste_new", p)
|
||||
} else {
|
||||
app.run("occurrence.copy", source)
|
||||
};
|
||||
// A paste that can't be done (into itself) has said why.
|
||||
let Ok(out) = out else { return false };
|
||||
if let Some(id) = out.get("occurrence").and_then(Value::as_u64) {
|
||||
let path: Vec<u64> = base.iter().copied().chain([id]).collect();
|
||||
// Pasted components arrive folded.
|
||||
crate::browser::close_placement(app, &path);
|
||||
made.push(Sel::Occurrence { path });
|
||||
}
|
||||
names.push(placement.name);
|
||||
}
|
||||
if made.is_empty() {
|
||||
app.set_status("Nothing to paste: the copied components are gone", true);
|
||||
return false;
|
||||
}
|
||||
let _ = app.run("select.set", json!({ "items": made }));
|
||||
let how = if new_copy { "a new copy" } else { "a new instance" };
|
||||
app.set_status(format!("Pasted {how} of {}", names.join(", ")), false);
|
||||
true
|
||||
}
|
||||
|
||||
/// The frame's Copy, Cut and Paste events (and Ctrl+C / Ctrl+X / Ctrl+V sent as key presses), plus any
|
||||
/// clipboard text a menu's Copy left. Called by the global shortcuts when no text field has the
|
||||
/// keyboard.
|
||||
pub fn handle(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
let (copies, cuts, pastes, pointer) = ctx.input(|i| {
|
||||
let (copies, cuts, pastes, shift, pointer) = ctx.input(|i| {
|
||||
let mut copies = 0;
|
||||
let mut cuts = 0;
|
||||
let mut pastes = 0;
|
||||
@@ -224,13 +575,12 @@ pub fn handle(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
egui::Event::Key { key: egui::Key::X, pressed: true, modifiers, .. } if modifiers.command && !modifiers.shift && !modifiers.alt => {
|
||||
cuts += 1
|
||||
}
|
||||
egui::Event::Key { key: egui::Key::V, pressed: true, modifiers, .. } if modifiers.command && !modifiers.shift && !modifiers.alt => {
|
||||
pastes += 1
|
||||
}
|
||||
egui::Event::Key { key: egui::Key::V, pressed: true, modifiers, .. } if modifiers.command && !modifiers.alt => pastes += 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(copies, cuts, pastes, i.pointer.latest_pos())
|
||||
// The window system's paste event carries no keys: Shift held makes it Ctrl+Shift+V.
|
||||
(copies, cuts, pastes, i.modifiers.shift, i.pointer.latest_pos())
|
||||
});
|
||||
if copies > 0 {
|
||||
copy(app);
|
||||
@@ -239,14 +589,14 @@ pub fn handle(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
cut(app);
|
||||
}
|
||||
if pastes > 0 {
|
||||
paste(app, pointer);
|
||||
paste_as(app, pointer, shift);
|
||||
}
|
||||
flush(ctx);
|
||||
flush(app, ctx);
|
||||
}
|
||||
|
||||
/// Write clipboard text a copy left.
|
||||
pub fn flush(ctx: &egui::Context) {
|
||||
if let Some(text) = PENDING_TEXT.lock().ok().and_then(|mut p| p.take()) {
|
||||
pub fn flush(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
if let Some(text) = app.clipboard_text.take() {
|
||||
ctx.copy_text(text);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -366,6 +366,7 @@ fn contribution_linked_clipboard_refuses_unsaved_dirty_self_and_missing_sources(
|
||||
assert!(!super::copy_design(&mut app));
|
||||
app = contribution_saved_part(&file);
|
||||
assert!(super::copy_design(&mut app));
|
||||
assert!(!super::can_paste(&app), "Paste is off in the design copied: it can't go into itself");
|
||||
let doc = app.session.doc.clone();
|
||||
assert!(!super::paste(&mut app, None));
|
||||
assert_eq!(app.session.doc, doc);
|
||||
@@ -403,3 +404,244 @@ fn contribution_native_copy_paste_events_insert_the_saved_design_in_another_tab(
|
||||
assert_eq!(h.app.session.doc.links.len(), 1, "{:?}", h.app.status);
|
||||
assert_eq!(h.app.session.undo.len(), 1);
|
||||
}
|
||||
|
||||
/// A copy that fails (here, with nothing selected) leaves the clipboard empty: Paste is off, and
|
||||
/// what was copied before is not pasted.
|
||||
#[test]
|
||||
fn a_failed_copy_empties_the_clipboard() {
|
||||
let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());
|
||||
app.run("solid.box", json!({"length":2,"width":2,"height":2,"body_name":"Cube"})).unwrap();
|
||||
app.run("select.set", json!({"items": [{"type": "body", "name": "Cube"}]})).unwrap();
|
||||
assert!(super::copy(&mut app));
|
||||
assert!(super::can_paste(&app));
|
||||
app.run("select.clear", json!({})).unwrap();
|
||||
assert!(!super::copy(&mut app));
|
||||
assert!(app.copied_bodies.is_empty());
|
||||
assert!(!super::can_paste(&app), "nothing is left to paste");
|
||||
assert!(!super::paste(&mut app, None));
|
||||
assert_eq!(app.session.model.state().bodies.len(), 1);
|
||||
}
|
||||
|
||||
/// Cut on a body only marks it; Paste moves it into the active component (where it is), and the
|
||||
/// clipboard empties. Esc before that leaves it where it was; a locked body is not cut.
|
||||
#[test]
|
||||
fn a_cut_body_moves_into_the_component_it_is_pasted_in() {
|
||||
let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());
|
||||
app.run("solid.box", json!({"length":2,"width":2,"height":2,"body_name":"Cube"})).unwrap();
|
||||
let part = app.run("component.create", json!({"name":"Part","activate":false})).unwrap()["component"].as_u64().unwrap();
|
||||
let owner = |app: &crate::SolveApp| {
|
||||
let state = app.session.model.state();
|
||||
app.session.doc.model_body_component(state.body("Cube").unwrap())
|
||||
};
|
||||
app.run("select.set", json!({"items": [{"type": "body", "name": "Cube"}]})).unwrap();
|
||||
assert!(super::can_cut(&app));
|
||||
assert!(super::cut(&mut app));
|
||||
assert_eq!(owner(&app), 0, "a cut body stays until it is pasted");
|
||||
super::drop_cut(&mut app);
|
||||
assert!(!super::can_paste(&app), "Esc left it where it was");
|
||||
app.run("select.set", json!({"items": [{"type": "body", "name": "Cube"}]})).unwrap();
|
||||
assert!(super::cut(&mut app));
|
||||
app.run("component.activate", json!({"component": part})).unwrap();
|
||||
assert!(super::paste(&mut app, None));
|
||||
assert_eq!(owner(&app), part);
|
||||
assert_eq!(app.session.model.state().bodies.len(), 1, "moved, not copied");
|
||||
assert!(app.cut_bodies.is_empty() && !super::can_paste(&app));
|
||||
app.session.visibility.locked_bodies.push("Cube".into());
|
||||
app.run("select.set", json!({"items": [{"type": "body", "name": "Cube"}]})).unwrap();
|
||||
assert!(!super::can_cut(&app) && !super::cut(&mut app), "a locked body stays");
|
||||
}
|
||||
|
||||
/// A component placed once cuts and pastes into another component, where it is; it never pastes
|
||||
/// into itself, and an instance (a component placed more than once) isn't cut.
|
||||
#[test]
|
||||
fn a_cut_component_moves_into_the_component_it_is_pasted_in() {
|
||||
let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());
|
||||
let made = |app: &mut crate::SolveApp, name: &str| {
|
||||
let out = app.run("component.create", json!({"name": name, "activate": false})).unwrap();
|
||||
(out["component"].as_u64().unwrap(), out["occurrence"].as_u64().unwrap())
|
||||
};
|
||||
let (part, part_at) = made(&mut app, "Part");
|
||||
let (holder, holder_at) = made(&mut app, "Holder");
|
||||
app.run("select.set", json!({"items": [{"type": "occurrence", "path": [part_at]}]})).unwrap();
|
||||
assert!(super::can_cut(&app));
|
||||
assert!(super::cut(&mut app));
|
||||
assert!(!super::can_paste_into(&app, part), "not into itself");
|
||||
assert!(super::can_paste_into(&app, holder));
|
||||
assert!(super::paste_into(&mut app, None, false, Some((holder, vec![holder_at]))));
|
||||
assert_eq!(app.session.doc.occurrences.iter().find(|o| o.id == part_at).unwrap().parent, holder);
|
||||
assert_eq!(app.session.selection, vec![solidcraft_engine::Sel::Occurrence { path: vec![holder_at, part_at] }]);
|
||||
assert!(!crate::browser::is_open(&app, &format!("o:{holder_at}/{part_at}"), true), "it arrives folded");
|
||||
assert!(app.cut_placements.is_empty() && !super::can_paste(&app));
|
||||
app.run("occurrence.copy", json!({"component": holder})).unwrap();
|
||||
app.run("select.set", json!({"items": [{"type": "occurrence", "path": [holder_at]}]})).unwrap();
|
||||
assert!(!super::can_cut(&app) && !super::cut(&mut app), "an instance isn't cut");
|
||||
}
|
||||
|
||||
/// A copied body pastes into a component's Bodies folder from the folder's menu: the copy goes
|
||||
/// into that component. With nothing copied, the folder's Paste is off.
|
||||
#[test]
|
||||
fn a_copied_body_pastes_into_a_bodies_folder() {
|
||||
use crate::context_menu::{Target, items, run_item};
|
||||
let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());
|
||||
app.run("solid.box", json!({"length":2,"width":2,"height":2,"body_name":"Cube"})).unwrap();
|
||||
let out = app.run("component.create", json!({"name":"Part","activate":false})).unwrap();
|
||||
let (part, at) = (out["component"].as_u64().unwrap(), out["occurrence"].as_u64().unwrap());
|
||||
let folder = Target::Folder { component: part, folder: "bodies".into(), scope: format!("o:{at}") };
|
||||
let paste = |app: &crate::SolveApp| items(app, &folder).into_iter().find(|i| i.id == "ui.paste").unwrap();
|
||||
assert!(!paste(&app).enabled, "nothing copied yet");
|
||||
app.run("select.set", json!({"items": [{"type": "body", "name": "Cube"}]})).unwrap();
|
||||
assert!(super::copy(&mut app));
|
||||
let item = paste(&app);
|
||||
assert!(item.enabled);
|
||||
run_item(&mut app, &item, egui::Pos2::ZERO);
|
||||
let state = app.session.model.state();
|
||||
let copy = state.body("Cube (2)").expect("the copy");
|
||||
assert_eq!(app.session.doc.model_body_component(copy), part);
|
||||
}
|
||||
|
||||
/// A copied sketch pastes into a component's Sketches folder from the folder's menu: the copy,
|
||||
/// named after it, goes into that component.
|
||||
#[test]
|
||||
fn a_copied_sketch_pastes_into_a_sketches_folder() {
|
||||
use crate::context_menu::{Target, items, run_item};
|
||||
let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());
|
||||
app.run("sketch.create", json!({"plane": "XY", "name": "S"})).unwrap();
|
||||
app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})).unwrap();
|
||||
app.run("sketch.finish", json!({})).unwrap();
|
||||
let out = app.run("component.create", json!({"name":"Part","activate":false})).unwrap();
|
||||
let (part, at) = (out["component"].as_u64().unwrap(), out["occurrence"].as_u64().unwrap());
|
||||
let folder = Target::Folder { component: part, folder: "sketches".into(), scope: format!("o:{at}") };
|
||||
let paste = |app: &crate::SolveApp| items(app, &folder).into_iter().find(|i| i.id == "ui.paste").unwrap();
|
||||
let id = app.session.doc.find_feature("S").unwrap().id;
|
||||
app.run("select.set", json!({"items": [{"type": "feature", "id": id}]})).unwrap();
|
||||
assert!(super::copy(&mut app));
|
||||
let item = paste(&app);
|
||||
assert!(item.enabled);
|
||||
run_item(&mut app, &item, egui::Pos2::ZERO);
|
||||
let copy = app.session.doc.find_feature("S (2)").expect("the copy");
|
||||
assert_eq!(copy.component, part);
|
||||
}
|
||||
|
||||
fn plain_app() -> crate::SolveApp {
|
||||
crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default())
|
||||
}
|
||||
|
||||
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.
|
||||
#[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();
|
||||
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));
|
||||
assert!(super::paste(&mut app, None));
|
||||
assert!(app.session.model.state().body("Cube (2)").is_some());
|
||||
}
|
||||
|
||||
/// 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]
|
||||
fn the_last_copy_is_what_pastes() {
|
||||
let mut app = plain_app();
|
||||
app.run("solid.box", json!({"length":2,"width":2,"height":2,"body_name":"Cube"})).unwrap();
|
||||
let at = app.run("component.create", json!({"name":"Part","activate":false})).unwrap()["occurrence"].as_u64().unwrap();
|
||||
select(&mut app, json!({"type": "body", "name": "Cube"}));
|
||||
assert!(super::copy(&mut app));
|
||||
select(&mut app, json!({"type": "occurrence", "path": [at]}));
|
||||
assert!(super::copy(&mut app));
|
||||
assert!(app.copied_bodies.is_empty() && app.copied_placements == vec![vec![at]]);
|
||||
let placements = app.session.doc.occurrences.len();
|
||||
assert!(super::paste(&mut app, None));
|
||||
assert_eq!(app.session.doc.occurrences.len(), placements + 1, "the component pasted");
|
||||
assert!(app.session.model.state().body("Cube (2)").is_none(), "not the body");
|
||||
select(&mut app, json!({"type": "body", "name": "Cube"}));
|
||||
assert!(super::copy(&mut app));
|
||||
assert!(app.copied_placements.is_empty());
|
||||
assert!(super::paste(&mut app, None));
|
||||
assert!(app.session.model.state().body("Cube (2)").is_some(), "now the body");
|
||||
assert_eq!(app.session.doc.occurrences.len(), placements + 1);
|
||||
}
|
||||
|
||||
/// Paste on a group puts what was pasted in that group: a body in a Bodies group, a sketch in a
|
||||
/// Sketches group.
|
||||
#[test]
|
||||
fn pasting_on_a_group_puts_the_copy_in_it() {
|
||||
use crate::context_menu::{Target, items, run_item};
|
||||
let mut app = plain_app();
|
||||
app.run("solid.box", json!({"length":2,"width":2,"height":2,"body_name":"Cube"})).unwrap();
|
||||
app.run("sketch.create", json!({"plane": "XY", "name": "S"})).unwrap();
|
||||
app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})).unwrap();
|
||||
app.run("sketch.finish", json!({})).unwrap();
|
||||
let bodies = app.run("browser.group", json!({"folder": "bodies", "name": "Kept"})).unwrap()["group"].as_u64().unwrap();
|
||||
let sketches = app.run("browser.group", json!({"folder": "sketches", "name": "Drawn"})).unwrap()["group"].as_u64().unwrap();
|
||||
let paste_on = |app: &mut crate::SolveApp, group: u64| {
|
||||
let item = items(app, &Target::Group { id: group, scope: "c0".into() }).into_iter().find(|i| i.id == "ui.paste").unwrap();
|
||||
assert!(item.enabled);
|
||||
run_item(app, &item, egui::Pos2::ZERO);
|
||||
};
|
||||
let holds = |app: &crate::SolveApp, group: u64, key: &str| {
|
||||
app.session.doc.browser_groups.iter().any(|g| g.id == group && g.items.iter().any(|k| k == key))
|
||||
};
|
||||
select(&mut app, json!({"type": "body", "name": "Cube"}));
|
||||
assert!(super::copy(&mut app));
|
||||
paste_on(&mut app, bodies);
|
||||
assert!(holds(&app, bodies, "Cube (2)"));
|
||||
let id = app.session.doc.find_feature("S").unwrap().id;
|
||||
select(&mut app, json!({"type": "feature", "id": id}));
|
||||
assert!(super::copy(&mut app));
|
||||
paste_on(&mut app, sketches);
|
||||
let copy = app.session.doc.find_feature("S (2)").unwrap().id;
|
||||
assert!(holds(&app, sketches, ©.to_string()));
|
||||
}
|
||||
|
||||
/// While a component is cut, Paste moves it and Paste New (an independent copy) is off.
|
||||
#[test]
|
||||
fn paste_new_is_off_while_a_component_is_cut() {
|
||||
use crate::context_menu::{Target, items};
|
||||
let mut app = plain_app();
|
||||
let at = app.run("component.create", json!({"name":"Part","activate":false})).unwrap()["occurrence"].as_u64().unwrap();
|
||||
let holder = app.run("component.create", json!({"name":"Holder","activate":false})).unwrap()["component"].as_u64().unwrap();
|
||||
select(&mut app, json!({"type": "occurrence", "path": [at]}));
|
||||
assert!(super::cut(&mut app));
|
||||
let menu = items(&app, &Target::Component { id: holder });
|
||||
let find = |id: &str| menu.iter().find(|i| i.id == id).unwrap();
|
||||
assert!(find("ui.paste").enabled);
|
||||
assert!(!find("ui.pasteNew").enabled);
|
||||
}
|
||||
|
||||
/// A body of a component's second placement is that component's body seen there: it isn't cut on
|
||||
/// its own (that would take it out of every placement), but it copies, and pastes where that
|
||||
/// placement shows it.
|
||||
#[test]
|
||||
fn a_second_placements_body_copies_but_is_not_cut() {
|
||||
let mut app = plain_app();
|
||||
let made = app.run("component.create", json!({"name":"B"})).unwrap();
|
||||
let b = made["component"].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();
|
||||
let second = app.run("occurrence.copy", json!({"component": b, "translate": [30, 0, 0]})).unwrap()["occurrence"].as_u64().unwrap();
|
||||
let placed = app.session.occurrence_placement(&[second]).unwrap();
|
||||
let seen = placed.bodies.first().unwrap().world.clone();
|
||||
assert_ne!(seen, "Cube", "the second placement shows it under a name of its own");
|
||||
select(&mut app, json!({"type": "body", "name": seen}));
|
||||
assert!(!super::can_cut(&app));
|
||||
assert!(!super::cut(&mut app));
|
||||
assert!(app.cut_bodies.is_empty() && !super::can_paste(&app));
|
||||
assert!(app.status.as_ref().is_some_and(|(text, _, error)| *error && text.contains("placed copy")), "{:?}", app.status);
|
||||
select(&mut app, json!({"type": "body", "name": seen}));
|
||||
assert!(super::copy(&mut app));
|
||||
assert!(super::paste(&mut app, None), "{:?}", app.status);
|
||||
let world = app.session.world_state();
|
||||
let (there, copy) = (world.body(&seen).unwrap().mesh().bounds(), world.body("Cube (2)").expect("the copy").mesh().bounds());
|
||||
assert!(there.min.dist(copy.min) < 1e-6 && there.max.dist(copy.max) < 1e-6, "{there:?} vs {copy:?}");
|
||||
}
|
||||
|
||||
@@ -505,6 +505,18 @@ pub struct SolveApp {
|
||||
pub(crate) apply_gate: Option<std::sync::Arc<std::sync::Mutex<std::sync::mpsc::Receiver<()>>>>,
|
||||
/// The last command started interactively (id, label), for Repeat.
|
||||
pub last_command: Option<(String, String)>,
|
||||
/// Bodies copied with Copy (by name), pasted into the active component by Paste.
|
||||
pub copied_bodies: Vec<String>,
|
||||
/// Text a copy left for the system clipboard, written on the next frame (so a paste event
|
||||
/// follows: the window system sends one only while the clipboard holds text).
|
||||
pub(crate) clipboard_text: Option<String>,
|
||||
/// Component placements copied with Copy (by path): Paste places new instances of them in
|
||||
/// the active component, Paste New (Ctrl+Shift+V) independent copies.
|
||||
pub copied_placements: Vec<Vec<u64>>,
|
||||
/// Bodies cut with Cut (by name): they stay until Paste moves them into a component.
|
||||
pub cut_bodies: Vec<String>,
|
||||
/// Component placements cut with Cut (by path): they stay until Paste moves them.
|
||||
pub cut_placements: Vec<Vec<u64>>,
|
||||
/// Esc was already acted on this frame (by the shortcuts), so later handlers skip it.
|
||||
pub esc_handled: bool,
|
||||
/// When Esc was last pressed (input time): a second press soon after finishes the sketch.
|
||||
@@ -679,6 +691,11 @@ impl SolveApp {
|
||||
#[cfg(test)]
|
||||
apply_gate: None,
|
||||
last_command: None,
|
||||
copied_bodies: Vec::new(),
|
||||
clipboard_text: None,
|
||||
copied_placements: Vec::new(),
|
||||
cut_bodies: Vec::new(),
|
||||
cut_placements: Vec::new(),
|
||||
esc_handled: false,
|
||||
last_escape: None,
|
||||
status: None,
|
||||
|
||||
@@ -364,7 +364,15 @@ fn component_menu_activates_grounds_and_pastes() {
|
||||
act(&mut app, &t, "Ground");
|
||||
assert!(app.session.doc.occurrence_of(c).unwrap().grounded);
|
||||
assert!(!find(&context_menu::items(&app, &t), "Move/Copy").enabled, "grounded");
|
||||
act(&mut app, &t, "Paste New");
|
||||
// Paste New pastes an independent copy of the copied component into another one (here the
|
||||
// design): it is off until a component is copied, and never into itself.
|
||||
let placement = Target::Occurrence { path: app.session.doc.first_path(c) };
|
||||
app.session.selection = vec![solidcraft_engine::Sel::Occurrence { path: app.session.doc.first_path(c) }];
|
||||
act(&mut app, &placement, "Copy");
|
||||
assert_eq!(app.copied_placements.len(), 1, "{:?}", app.status);
|
||||
let design = Target::Component { id: 0 };
|
||||
assert!(find(&context_menu::items(&app, &design), "Paste New").enabled);
|
||||
act(&mut app, &design, "Paste New");
|
||||
assert_eq!(app.session.doc.components.len(), 2);
|
||||
}
|
||||
|
||||
|
||||
@@ -99,10 +99,18 @@ fn occurrence_second_row_selects_exact_path_and_menu_actions() {
|
||||
assert!((bounds.center().x - 55.0).abs() < 1e-8);
|
||||
let target = Target::Occurrence { path: vec![second] };
|
||||
let items = context_menu::items(&h.app, &target);
|
||||
let independent = items.iter().find(|i| i.id == "component.paste_new").unwrap();
|
||||
assert_eq!(independent.label, "Paste New (Own Features)");
|
||||
assert_eq!(independent.params.as_ref().unwrap()["occurrence"], second);
|
||||
assert_eq!(independent.params.as_ref().unwrap()["path"], json!([second]));
|
||||
// Copy takes this placement (the row right-clicked). Paste New pastes an independent copy of
|
||||
// it into the design, never into itself: off on its own row, on on the design's.
|
||||
let copy = items.iter().find(|i| i.id == "ui.copy").unwrap();
|
||||
assert!(copy.enabled);
|
||||
context_menu::run_item(&mut h.app, copy, egui::Pos2::ZERO);
|
||||
assert_eq!(h.app.copied_placements, vec![vec![second]]);
|
||||
let own = context_menu::items(&h.app, &target);
|
||||
assert!(!own.iter().find(|i| i.id == "ui.pasteNew").unwrap().enabled, "not into itself");
|
||||
let design = context_menu::items(&h.app, &Target::Component { id: 0 });
|
||||
let independent = design.iter().find(|i| i.id == "ui.pasteNew").unwrap();
|
||||
assert!(independent.enabled);
|
||||
assert_eq!(independent.params.as_ref().unwrap()["component"], 0);
|
||||
let properties = items.iter().find(|i| i.id == "ui.properties").unwrap();
|
||||
assert_eq!(properties.params.as_ref().unwrap()["occurrence"], second);
|
||||
context_menu::run_item(&mut h.app, properties, egui::Pos2::ZERO);
|
||||
@@ -301,3 +309,29 @@ fn a_body_dropped_on_a_bodies_folder_moves_into_that_component() {
|
||||
h.frames(3);
|
||||
assert_eq!(owner(&h, "Pin"), 0, "Pin moved back into the root component");
|
||||
}
|
||||
|
||||
/// Paste on a component's row pastes inside it: never a component inside itself, so that Paste
|
||||
/// is off on its own row, and a copy of it pastes into its parent (here the design) from there.
|
||||
#[test]
|
||||
fn a_copied_component_pastes_into_its_parent_not_into_itself() {
|
||||
let (mut h, component, _, second) = fixture();
|
||||
click(&mut h, &[second], "row");
|
||||
let own = Target::Occurrence { path: vec![second] };
|
||||
let design = Target::Component { id: 0 };
|
||||
let find = |h: &Harness, target: &Target, id: &str| context_menu::items(&h.app, target).into_iter().find(|i| i.id == id).unwrap();
|
||||
assert!(!find(&h, &own, "ui.pasteNew").enabled, "nothing copied yet");
|
||||
let copy = find(&h, &own, "ui.copy");
|
||||
context_menu::run_item(&mut h.app, ©, egui::Pos2::ZERO);
|
||||
assert!(!find(&h, &own, "ui.paste").enabled, "not inside itself");
|
||||
assert!(!find(&h, &own, "ui.pasteNew").enabled);
|
||||
let paste = find(&h, &design, "ui.paste");
|
||||
assert!(paste.enabled);
|
||||
let before = h.app.session.doc.occurrences.len();
|
||||
context_menu::run_item(&mut h.app, &paste, egui::Pos2::ZERO);
|
||||
assert_eq!(h.app.session.doc.occurrences.len(), before + 1);
|
||||
let pasted = h.app.session.doc.occurrences.last().unwrap().clone();
|
||||
assert_eq!((pasted.component, pasted.parent), (component, 0), "an instance of Block, in the design");
|
||||
assert_eq!(h.app.session.selection, vec![Sel::Occurrence { path: vec![pasted.id] }]);
|
||||
assert!((pasted.transform[3][0] - 50.0).abs() < 1e-9, "where the copied instance is");
|
||||
assert!(!crate::browser::is_open(&h.app, &format!("o:{}", pasted.id), true), "it arrives folded");
|
||||
}
|
||||
|
||||
@@ -999,7 +999,7 @@ mod tests {
|
||||
h.step(&json!({"widget": "Paste"})).unwrap();
|
||||
assert_eq!(h.app.session.doc.features.len(), 4, "left: {left}");
|
||||
let bodies: Vec<String> = h.app.session.model.state().bodies.iter().map(|b| b.name.clone()).collect();
|
||||
assert_eq!(bodies, ["One", "Two", "One (copy)", "Two (copy)"], "left: {left}");
|
||||
assert_eq!(bodies, ["One", "Two", "One (2)", "Two (2)"], "left: {left}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2026,7 +2026,7 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
if shown {
|
||||
crate::edit_clipboard::handle(app, ctx);
|
||||
} else {
|
||||
crate::edit_clipboard::flush(ctx);
|
||||
crate::edit_clipboard::flush(app, ctx);
|
||||
}
|
||||
for (k, repeat) in keys {
|
||||
use egui::Key;
|
||||
@@ -2055,8 +2055,9 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
Key::Y => drop(app.run("edit.redo", json!({}))),
|
||||
// Copy, Cut and Paste (`edit_clipboard::handle`).
|
||||
Key::C | Key::X | Key::V if !mods.shift && !mods.alt => {}
|
||||
// Copy, Cut and Paste, and Paste New with Shift (`edit_clipboard::handle`).
|
||||
Key::C | Key::X if !mods.shift && !mods.alt => {}
|
||||
Key::V if !mods.alt => {}
|
||||
// Ctrl+Shift+S is Save As; Ctrl+S keeps saving over the current file (#6558).
|
||||
Key::S if mods.shift && !mods.alt => save_as(app),
|
||||
Key::S => save(app),
|
||||
@@ -2109,6 +2110,7 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
} else if app.dialog.is_some() || app.pending_feature_edit.is_some() {
|
||||
crate::dialogs::cancel(app);
|
||||
} else if !app.session.selection.is_empty() || app.session.active_sketch.is_none() {
|
||||
crate::edit_clipboard::drop_cut(app);
|
||||
app.tree.picked_joints.clear();
|
||||
let _ = app.run("select.clear", json!({}));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user