SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Cut & paste features between components (#5798) (#5805)
Steven Waters57c0121cb369
diff --git a/assets/locales/pending/move-features-to-component.json b/assets/locales/pending/move-features-to-component.jsonnew file mode 100644index 0000000000..e98f8f31b2--- /dev/null+++ b/assets/locales/pending/move-features-to-component.json@@ -0,0 +1,34 @@+{+ "en": {+ "cmd.browser_reparent": "Move to Component",+ "cmd.component_move_features": "Move Features to Component"+ },+ "ja": {+ "cmd.browser_reparent": "コンポーネントへ移動",+ "cmd.component_move_features": "フィーチャーをコンポーネントに移動"+ },+ "zh": {+ "cmd.browser_reparent": "移动到组件",+ "cmd.component_move_features": "将特征移至组件"+ },+ "de": {+ "cmd.browser_reparent": "In andere Komponente verschieben",+ "cmd.component_move_features": "Merkmale in Komponente verschieben"+ },+ "ko": {+ "cmd.browser_reparent": "구성 요소로 이동",+ "cmd.component_move_features": "특성을 구성 요소로 이동"+ },+ "ar": {+ "cmd.browser_reparent": "نقل إلى مكوّن",+ "cmd.component_move_features": "نقل الميزات إلى مكوّن"+ },+ "he": {+ "cmd.browser_reparent": "העברה לרכיב",+ "cmd.component_move_features": "העברת פיצ'רים לרכיב"+ },+ "vi": {+ "cmd.browser_reparent": "Chuyển sang Cụm chi tiết",+ "cmd.component_move_features": "Di chuyển các tính năng vào cụm chi tiết"+ }+}diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rsindex 7d6b73e404..6042da3f52 100644--- a/crates/engine/src/cmd/clipboard.rs+++ b/crates/engine/src/cmd/clipboard.rs@@ -39,7 +39,7 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {}/// Origin planes become explicit planes so a translation can move them.-fn explicit_planes(p: &mut PlaneRef) {+pub(in crate::cmd) fn explicit_planes(p: &mut PlaneRef) {match p {PlaneRef::Origin { name } => {if let Some(plane) = solidcraft_geom::Plane::named(name) {diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rsindex 68d829968d..abe230dd85 100644--- a/crates/engine/src/cmd/component.rs+++ b/crates/engine/src/cmd/component.rs@@ -12,13 +12,16 @@ use solidcraft_geom::Vec3;use super::CommandSpec;use crate::params::{bad, bool_, str_, string_list, vec3};use crate::schema::component::{- EditInPlaceParams, EditInPlaceResult, FinishEditParams, FinishEditResult, OccurrenceAlignParams, OccurrenceAlignResult,+ EditInPlaceParams, EditInPlaceResult, FinishEditParams, FinishEditResult, MoveFeaturesParams, MoveFeaturesResult, OccurrenceAlignParams,+ OccurrenceAlignResult, ReparentItemsParams, ReparentItemsResult,};use crate::schema::{TypedContract, output_schema_for};use crate::{Result, Session};const EDIT_IN_PLACE_CONTRACT: TypedContract<EditInPlaceParams> = TypedContract::new();const FINISH_EDIT_CONTRACT: TypedContract<FinishEditParams> = TypedContract::new();+const MOVE_FEATURES_CONTRACT: TypedContract<MoveFeaturesParams> = TypedContract::new();+const REPARENT_ITEMS_CONTRACT: TypedContract<ReparentItemsParams> = TypedContract::new();#[path = "component_align.rs"]mod align;@@ -28,12 +31,16 @@ mod drag;mod foreign;#[path = "component_matrix.rs"]pub(super) mod matrix;+#[path = "component_move_features.rs"]+mod move_features;#[path = "component_placing.rs"]pub(super) mod placing;#[path = "component_properties.rs"]pub(super) mod properties;#[path = "component_reparent.rs"]mod reparent;+#[path = "component_reparent_items.rs"]+mod reparent_items;#[path = "component_transfer.rs"]mod transfer;@@ -113,7 +120,29 @@ pub static COMMANDS: &[CommandSpec] = &[A component that uses what isn't in it (another body, sketch or parameter) is refused, saying what. Returns \`bodies` and `feature`, or the pasted components' `paths`",),- CommandSpec::new("component.move_sketches", "Move Sketches to Component", move_sketches).icon("move").params("sketches: [ids or names], component"),+ CommandSpec::new("component.move_sketches", "Move Sketches to Component", move_sketches)+ .icon("move")+ .params("sketches: [ids or names], component; the sketches keep their own coordinates (component.move_features keeps them where they are in the world)"),+ CommandSpec::new("component.move_features", "Move Features to Component", crate::checked!("component.move_features", move_features::move_features))+ .icon("move")+ .contract(&MOVE_FEATURES_CONTRACT)+ .output(output_schema_for::<MoveFeaturesResult>)+ .params(+ "features: [ids or names] (sketches too); component?: where they go (default: the active one) → moved, component, bodies. \+ Ids, names and timeline order stay; the geometry stays where it is in the world; the bodies the features made move with \+ them. Refused while the timeline is rolled back, for a component placed more than once, and for a move that would break \+ a feature (nothing changes)",+ ),+ CommandSpec::new("browser.reparent", "Move to Component", crate::checked!("browser.reparent", reparent_items::reparent_items))+ .icon("move")+ .contract(&REPARENT_ITEMS_CONTRACT)+ .output(output_schema_for::<ReparentItemsResult>)+ .params(+ "Moves placements, features and bodies into a component. occurrences?: [ids or paths], features?: [ids or names], bodies?: [names], component?: where they go (default: the active \+ one), component_path?: its placement → component, occurrences, features, bodies (what moved). One undo step, all or \+ nothing: placements move first (taking what they hold), then features (taking the bodies they made), then the bodies \+ still elsewhere (a body transfer, which leaves its features behind)",+ ),CommandSpec::new("occurrence.copy", "Paste (Instance)", copy_occurrence).icon("copy").params("component (or occurrence): what to place again; path?: validates selected occurrence; parent?: component (default: the same parent); translate?: [x,y,z]; in_place?: bool (default false: the selected transform within the parent; true: where the selected placement is in the world, translate in world axes; a parent placed more than once is placed by parent_path?, else the active placement, and every instance gets the copy). Copies the selected effective transform, including pending moves"),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"),diff --git a/crates/engine/src/cmd/component_move_features.rs b/crates/engine/src/cmd/component_move_features.rsnew file mode 100644index 0000000000..50bf4ef34e--- /dev/null+++ b/crates/engine/src/cmd/component_move_features.rs@@ -0,0 +1,143 @@+//! Moving timeline features (sketches included) into another component.+//!+//! It is an organisational change: ids, names and timeline positions stay, nothing is copied, and+//! the geometry stays where it is in the world (a moved feature's picks, planes and directions are+//! re-expressed in the new component's frame). Bodies follow the feature that made them. The move+//! is made on a scratch copy and the whole timeline is evaluated; the result is adopted only when+//! no feature, moved or left behind, gained an error. Otherwise nothing changes.++use std::collections::{BTreeMap, BTreeSet};++use solidcraft_doc::{Feature, FeatureKind, is_identity, mat_inverse, mat_mul};++use super::super::clipboard::explicit_planes;+use super::*;+use crate::params::name_or_id_list;++pub(super) fn move_features(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "component.move_features";+ let dest = if p.get("component").is_some() { component(s, p, "component", cmd)? } else { s.active_component };+ let keys = name_or_id_list(cmd, p, "features")?;+ if keys.is_empty() || keys.len() > 1000 {+ return Err(bad(cmd, "`features` must list 1…1000 features"));+ }+ if s.doc.marker.is_some() {+ return Err(bad(cmd, "finish timeline rollback before moving features"));+ }+ if !s.pending_moves.is_empty() {+ return Err(bad(cmd, "finish the component move in progress first"));+ }+ let mut ids = BTreeSet::new();+ for k in &keys {+ ids.insert(s.doc.find_feature(k).map(|f| f.id).ok_or_else(|| bad(cmd, format!("no feature `{k}`")))?);+ }+ let moving: BTreeSet<u64> = ids.into_iter().filter(|id| s.doc.feature(*id).is_some_and(|f| f.component != dest)).collect();+ if moving.is_empty() {+ return Err(bad(cmd, "already in that component"));+ }+ let moved: Vec<Feature> = s.doc.features.iter().filter(|f| moving.contains(&f.id)).cloned().collect();+ // One placement each: a component placed twice has no single frame to keep the geometry in.+ let placements = |c: u64| s.doc.occurrences.iter().filter(|o| o.component == c).count();+ let sources: BTreeSet<u64> = moved.iter().map(|f| f.component).collect();+ if sources.iter().chain([&dest]).any(|c| *c != 0 && placements(*c) > 1) {+ return Err(bad(cmd, "a component placed more than once can't take part in this move"));+ }+ if moved.iter().any(|f| matches!(f.kind, FeatureKind::BodyTransfer { .. })) {+ return Err(bad(cmd, "a recorded body transfer can't be moved"));+ }+ // The bodies that move with the features: those they are the origin of.+ let moved_bodies: BTreeSet<String> = s.body_origins().into_iter().filter(|(_, f)| moving.contains(f)).map(|(body, _)| body).collect();+ if moved_bodies.iter().any(|b| s.doc.body_components.contains_key(b) || s.doc.body_offsets.contains_key(b)) {+ return Err(bad(cmd, "a body that was transferred between components can't be moved with its features"));+ }+ // A join or boolean whose inputs would end up in two components.+ for f in &s.doc.features {+ let mut inputs: BTreeSet<String> = f.kind.input_bodies().into_iter().collect();+ inputs.extend(f.participants.iter().cloned());+ let (inside, outside) =+ (inputs.iter().filter(|b| moved_bodies.contains(*b)).count(), inputs.iter().filter(|b| !moved_bodies.contains(*b)).count());+ if inside > 0 && outside > 0 && inputs.len() > 1 {+ return Err(bad(cmd, format!("{} works on bodies that would be split between components", f.name)));+ }+ }+ let to_dest = mat_inverse(&s.doc.component_transform(dest)).ok_or_else(|| bad(cmd, "the target component's frame is not invertible"))?;+ let dest_path = s.doc.first_path(dest);+ let before_errors: BTreeMap<u64, bool> = s.doc.features.iter().map(|f| (f.id, s.model.result(f.id).is_some_and(|r| r.error.is_some()))).collect();++ let mut scratch = s.scratch();+ let doc = scratch.doc_mut();+ for old in &moved {+ let delta = mat_mul(&to_dest, &s.doc.component_transform(old.component));+ let Some(f) = doc.feature_mut(old.id) else { continue };+ f.component = dest;+ if !is_identity(&delta) {+ if let FeatureKind::Sketch { plane, .. } | FeatureKind::ConstructionPlane { plane } = &mut f.kind {+ explicit_planes(plane);+ }+ f.kind.transform_geometry(&delta);+ }+ }+ // Attached sketches and embossed faces carry the placement of the body they sit on and of+ // the component they were authored in: those that moved are rewritten, nothing else changes.+ for f in &mut doc.features {+ let authored_here = moving.contains(&f.id);+ let rewrite = |body: &str, path: &mut Vec<u64>, author_path: &mut Vec<u64>| {+ if moved_bodies.contains(body) {+ *path = dest_path.clone();+ }+ if authored_here {+ *author_path = dest_path.clone();+ }+ };+ match &mut f.kind {+ FeatureKind::Sketch { plane, .. } => {+ if let Some(anchor) = crate::cmd::sketch::face::anchor_mut(plane) {+ let moved_body = moved_bodies.contains(&anchor.target.body);+ rewrite(&anchor.target.body, &mut anchor.path, &mut anchor.author_path);+ if moved_body {+ anchor.component = dest;+ }+ }+ }+ FeatureKind::Emboss { face: Some(face), .. } => {+ let body = face.body.as_ref().to_string();+ rewrite(&body, &mut face.path, &mut face.author_path);+ }+ _ => {}+ }+ }+ scratch.refresh();+ // Any feature that gains an error, moved or left behind, stops the move.+ let broken = scratch+ .doc+ .features+ .iter()+ .filter(|f| !before_errors.get(&f.id).copied().unwrap_or(false))+ .find_map(|f| scratch.model.result(f.id).and_then(|r| r.error.clone()).map(|e| (f.name.clone(), e)));+ if let Some((name, error)) = broken {+ return Err(bad(cmd, format!("moving would break {name}: {error}")));+ }+ s.accept_computed(scratch);+ let names: Vec<&str> = moved.iter().map(|f| f.name.as_str()).collect();+ Ok(json!({"moved": names, "component": dest, "bodies": moved_bodies}))+}++impl Session {+ /// The feature each body depends on first, by body name: the earliest feature whose own result+ /// holds a body of that name (a converted mesh keeps its import), else the creator the body+ /// carries (the pieces of a split). Moving that feature moves the body.+ pub fn body_origins(&self) -> BTreeMap<String, u64> {+ let mut origins = BTreeMap::new();+ for f in &self.doc.features {+ if let Some(r) = self.model.result(f.id) {+ for b in r.state.bodies.iter().filter(|b| b.feature == f.id) {+ origins.entry(b.name.clone()).or_insert(f.id);+ }+ }+ }+ for b in &self.model.state().bodies {+ origins.entry(b.name.clone()).or_insert(b.feature);+ }+ origins+ }+}diff --git a/crates/engine/src/cmd/component_reparent.rs b/crates/engine/src/cmd/component_reparent.rsindex 3e1e23525d..35edd2d0b6 100644--- a/crates/engine/src/cmd/component_reparent.rs+++ b/crates/engine/src/cmd/component_reparent.rs@@ -92,16 +92,22 @@ pub(super) fn reparent(s: &mut Session, p: &Value) -> Result<Value> {}}s.accept_computed(scratch);+ follow_visibility(s, &old_path, &new_path);+ Ok(json!({"occurrence": id, "parent": to, "path": new_path, "transform": transform}))+}++/// Hidden placements and folders under `old_path` follow it to `new_path`. `accept_computed` does+/// not carry them, so whoever accepts a computed move into a session does this after.+pub(super) fn follow_visibility(s: &mut Session, old_path: &[u64], new_path: &[u64]) {for hidden in &mut s.visibility.hidden_occurrences {- if let Some(moved) = rebased(hidden, &old_path, &new_path) {+ 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));+ 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}))}diff --git a/crates/engine/src/cmd/component_reparent_items.rs b/crates/engine/src/cmd/component_reparent_items.rsnew file mode 100644index 0000000000..184be1fb1b--- /dev/null+++ b/crates/engine/src/cmd/component_reparent_items.rs@@ -0,0 +1,151 @@+//! Moving placements, timeline features and bodies into a component in one undo step+//! (`browser.reparent`: the owner of each changes, whatever its kind).+//!+//! What Paste does after Cut. Each kind moves by its own command (`occurrence.reparent`,+//! `component.move_features`, `component.move_bodies`), in that order, on a scratch copy, so what+//! an earlier step carried along is left alone by a later one: a moved component takes its+//! features and bodies with it, moved features take the bodies they made. The result is adopted+//! only when every step succeeds, as one undo step; otherwise nothing changes.++use std::collections::BTreeSet;++use super::move_features::move_features;+use super::reparent::{follow_visibility, reparent};+use super::transfer;+use super::*;+use crate::params::{name_or_id_list, string_list};++/// Most items of each kind in one move.+const MAX_ITEMS: usize = 1000;++/// A placement named by its occurrence id, or by its path from the top of the design.+fn placements(s: &Session, p: &Value, cmd: &str) -> Result<Vec<(u64, Option<Vec<u64>>)>> {+ let list = match p.get("occurrences") {+ None | Some(Value::Null) => return Ok(Vec::new()),+ Some(Value::Array(a)) if a.len() <= MAX_ITEMS => a,+ Some(_) => return Err(bad(cmd, format!("`occurrences` must list at most {MAX_ITEMS} placements"))),+ };+ let mut out: Vec<(u64, Option<Vec<u64>>)> = Vec::new();+ for entry in list {+ let found = match entry {+ Value::Number(n) => n.as_u64().map(|id| (id, None)),+ Value::Array(a) if !a.is_empty() && a.len() <= 64 => {+ a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>().and_then(|path| path.last().copied().map(|id| (id, Some(path))))+ }+ _ => None,+ };+ let (id, path) = found.ok_or_else(|| bad(cmd, "`occurrences` must list occurrence ids or paths of 1..64 occurrence ids"))?;+ if !s.doc.occurrences.iter().any(|o| o.id == id) {+ return Err(bad(cmd, format!("no occurrence {id}")));+ }+ if !out.iter().any(|(seen, _)| *seen == id) {+ out.push((id, path));+ }+ }+ Ok(out)+}++pub(super) fn reparent_items(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "browser.reparent";+ let dest = if p.get("component").is_some() { component(s, p, "component", cmd)? } else { s.active_component };+ let dest_path = p.get("component_path").cloned();+ let occurrences = placements(s, p, cmd)?;+ let features = name_or_id_list(cmd, p, "features")?;+ let bodies = string_list(cmd, p, "bodies")?;+ if features.len() > MAX_ITEMS || bodies.len() > MAX_ITEMS {+ return Err(bad(cmd, format!("`features` and `bodies` must list at most {MAX_ITEMS} items each")));+ }+ if occurrences.is_empty() && features.is_empty() && bodies.is_empty() {+ return Err(bad(cmd, "give `occurrences`, `features` or `bodies` to move"));+ }+ if s.doc.marker.is_some() {+ return Err(bad(cmd, "finish timeline rollback before moving"));+ }+ let mut feature_ids = BTreeSet::new();+ for k in &features {+ feature_ids.insert(s.doc.find_feature(k).map(|f| f.id).ok_or_else(|| bad(cmd, format!("no feature `{k}`")))?);+ }+ {+ let state = s.model.state();+ if let Some(missing) = bodies.iter().find(|b| state.body(b).is_none()) {+ return Err(bad(cmd, format!("no body `{missing}`")));+ }+ }++ let mut sc = s.scratch();+ sc.active_component = s.active_component;+ sc.active_occurrence_path = s.active_occurrence_path.clone();++ // Components first: each takes everything it holds.+ let mut moved_placements = Vec::new();+ let mut moved_components = Vec::new();+ let mut followed: Vec<(Vec<u64>, Vec<u64>)> = Vec::new();+ for (id, path) in &occurrences {+ let Some(o) = sc.doc.occurrences.iter().find(|o| o.id == *id).cloned() else { continue };+ if o.parent == dest {+ continue;+ }+ let mut params = json!({"occurrence": id, "parent": dest});+ if let Some(path) = path {+ params["path"] = json!(path);+ }+ if let Some(parent_path) = &dest_path {+ params["parent_path"] = parent_path.clone();+ }+ let old_path = occurrence_path(&sc, ¶ms, *id, cmd)?;+ let out = reparent(&mut sc, ¶ms)?;+ let new_path = out.get("path").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect::<Vec<_>>());+ followed.extend(new_path.map(|new| (old_path, new)));+ moved_placements.push(*id);+ moved_components.push(o.component);+ }+ // What a moved component holds travels with it.+ let travels = |sc: &Session, component: u64| moved_components.iter().any(|c| sc.doc.inside_component(component, *c));++ // Then features, which take the bodies they made.+ let features_to_move: Vec<u64> =+ feature_ids.iter().copied().filter(|id| sc.doc.feature(*id).is_some_and(|f| f.component != dest && !travels(&sc, f.component))).collect();+ let mut moved_features = Vec::new();+ if !features_to_move.is_empty() {+ let mut params = json!({"features": features_to_move, "component": dest});+ if let Some(path) = &dest_path {+ params["component_path"] = path.clone();+ }+ let out = move_features(&mut sc, ¶ms)?;+ moved_features =+ out.get("moved").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();+ }++ // Last the bodies still elsewhere: one a moved component or feature carried is already there.+ let bodies_to_move: Vec<String> = {+ let state = sc.model.state();+ bodies+ .iter()+ .filter(|b| {+ state.body(b).is_some_and(|body| {+ let at = sc.doc.model_body_component(body);+ at != dest && !travels(&sc, at)+ })+ })+ .cloned()+ .collect()+ };+ if !bodies_to_move.is_empty() {+ let mut params = json!({"bodies": bodies_to_move, "component": dest});+ if let Some(path) = &dest_path {+ params["component_path"] = path.clone();+ }+ transfer::move_bodies(&mut sc, ¶ms)?;+ }++ if moved_placements.is_empty() && moved_features.is_empty() && bodies_to_move.is_empty() {+ return Err(bad(cmd, "already in that component"));+ }+ // The steps above are this command's one undo step.+ sc.undo.clear();+ s.accept_computed(sc);+ for (old, new) in &followed {+ follow_visibility(s, old, new);+ }+ Ok(json!({"component": dest, "occurrences": moved_placements, "features": moved_features, "bodies": bodies_to_move}))+}diff --git a/crates/engine/src/cmd/component_transfer_tests.rs b/crates/engine/src/cmd/component_transfer_tests.rsindex 921d661173..86df8a7b0c 100644--- a/crates/engine/src/cmd/component_transfer_tests.rs+++ b/crates/engine/src/cmd/component_transfer_tests.rs@@ -290,3 +290,205 @@ fn edited_transfer_destination_updates_history_owner_copy_and_reopen() {assert_eq!(reopened.model.state().body("Block").unwrap().component, b);assert_eq!(reopened.model.state().body("Block (2)").unwrap().component, copied);}++/// A 10 × 10 × 5 block (sketch `S`, extrude `Extrude1`, body `Block`) in the design with a sketch+/// `Top` on its top face, and a component `Part` placed 100 mm along X. The design is active.+fn block_and_part() -> (Session, u64) {+ 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"}));+ run(&mut s, "sketch.create", json!({"plane": {"face": [5, 5, 5]}, "name": "Top"}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [2, 2], "p1": [4, 4]}));+ run(&mut s, "sketch.finish", json!({}));+ let part = run(&mut s, "component.create", json!({"name": "Part"}))["component"].as_u64().unwrap();+ let first = s.doc.occurrence_of(part).map(|o| o.id).unwrap();+ run(&mut s, "occurrence.move", json!({"occurrence": first, "translate": [100, 0, 0], "capture": true, "move_grounded": true}));+ run(&mut s, "component.activate", json!({"component": 0}));+ (s, part)+}++/// The lowest corner of every body in the world, rounded.+fn world_corners(s: &Session) -> Vec<Vec<f64>> {+ s.world_state()+ .bodies+ .iter()+ .map(|b| {+ let min = b.mesh().bounds().min;+ vec![min.x.round(), min.y.round(), min.z.round()]+ })+ .collect()+}++#[test]+fn move_features_keeps_the_world_and_the_attachment_in_the_active_component() {+ let (mut s, part) = block_and_part();+ let ids: Vec<u64> = s.doc.features.iter().map(|f| f.id).collect();+ let names: Vec<String> = s.doc.features.iter().map(|f| f.name.clone()).collect();+ let corners = world_corners(&s);+ // No `component`: the features go to the active one.+ run(&mut s, "component.activate", json!({"component": part}));+ let r = run(&mut s, "component.move_features", json!({"features": ["S", "Extrude1"]}));+ assert_eq!(r["moved"], json!(["S", "Extrude1"]), "{r}");+ // Nothing was added or renamed.+ assert_eq!(s.doc.features.iter().map(|f| f.id).collect::<Vec<_>>(), ids);+ assert_eq!(s.doc.features.iter().map(|f| f.name.clone()).collect::<Vec<_>>(), names);+ for name in ["S", "Extrude1"] {+ assert_eq!(s.doc.find_feature(name).map(|f| f.component), Some(part));+ }+ assert_eq!(s.doc.find_feature("Top").map(|f| f.component), Some(0));+ assert_eq!(world_corners(&s), corners, "the block is where it was in the world");+ // The sketch left behind follows the body into its new component and still evaluates.+ let top = s.doc.find_feature("Top").unwrap();+ assert!(s.model.result(top.id).is_some_and(|r| r.error.is_none()));+ let anchor = match top.kind.clone() {+ FeatureKind::Sketch { mut plane, .. } => crate::cmd::sketch::face::anchor_mut(&mut plane).cloned(),+ _ => None,+ };+ assert_eq!(anchor.map(|a| (a.component, a.path)), Some((part, s.doc.first_path(part))));+}++/// Moved without its body, or with the body moved from under it, a feature would break: the move+/// is refused and nothing changes.+#[test]+fn move_features_refuses_a_move_that_would_break_a_feature() {+ for moves in [["S2", "Cut1"], ["S1", "Extrude1"]] {+ let mut s = Session::default();+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S1"}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 20]}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"sketch": "S1", "distance": 10, "body_name": "Block"}));+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S2"}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [10, 10]}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"sketch": "S2", "distance": 4, "operation": "cut", "name": "Cut1"}));+ let part = run(&mut s, "component.create", json!({"name": "Part", "activate": false}))["component"].as_u64().unwrap();+ let (before, steps) = (s.doc.to_json(), s.undo.len());+ let e = s.execute("component.move_features", &json!({"features": moves, "component": part})).unwrap_err().to_string();+ assert!(e.contains("moving would"), "{moves:?}: {e}");+ assert_eq!((s.doc.to_json(), s.undo.len()), (before, steps), "{moves:?}");+ }+}++#[test]+fn move_features_refusals_change_nothing() {+ let (mut s, part) = block_and_part();+ let refused = |s: &mut Session, params: Value, why: &str| {+ let (before, steps) = (s.doc.to_json(), s.undo.len());+ let e = s.execute("component.move_features", ¶ms).unwrap_err().to_string();+ assert!(e.contains(why), "{e}");+ assert_eq!((s.doc.to_json(), s.undo.len()), (before, steps));+ };+ refused(&mut s, json!({"features": ["S"], "component": 0}), "already in that component");+ refused(&mut s, json!({"features": ["Nope"], "component": part}), "no feature");+ refused(&mut s, json!({"features": [], "component": part}), "1…1000");+ refused(&mut s, json!({"features": ["S"], "component": "Nowhere"}), "no component");+ // A component placed twice.+ run(&mut s, "occurrence.copy", json!({"component": part}));+ refused(&mut s, json!({"features": ["S", "Extrude1"], "component": part}), "more than once");+ // Rolled back.+ run(&mut s, "timeline.roll_to", json!({"position": 1}));+ refused(&mut s, json!({"features": ["S"], "component": part}), "rollback");+}++#[test]+fn move_features_refuses_a_boolean_whose_inputs_would_be_split() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A", "name": "BoxA"}));+ run(+ &mut s,+ "solid.box",+ json!({"length": 10, "width": 10, "height": 10, "corner": [10, 0, 0], "operation": "new_body", "body_name": "B", "name": "BoxB"}),+ );+ run(&mut s, "solid.combine", json!({"target": "A", "tools": ["B"], "operation": "join", "name": "Joined"}));+ let part = run(&mut s, "component.create", json!({"name": "Part", "activate": false}))["component"].as_u64().unwrap();+ let before = s.doc.to_json();+ let e = s.execute("component.move_features", &json!({"features": ["BoxA"], "component": part})).unwrap_err().to_string();+ assert!(e.contains("split between components"), "{e}");+ assert_eq!(s.doc.to_json(), before);+}++/// Each kind moves by its own step, all or nothing, as one undo step: a block's features without+/// the cut that works on it break, so the first call changes nothing; with it, the second moves+/// the placement, the features and the body that is not made by them, and skips the block they carry.+#[test]+fn reparent_items_moves_each_kind_all_or_nothing() {+ let (mut s, part) = block_and_part();+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S2"}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [10, 10]}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"sketch": "S2", "distance": 4, "operation": "cut", "name": "Cut1"}));+ run(+ &mut s,+ "solid.box",+ json!({"length": 10, "width": 10, "height": 10, "corner": [50, 0, 0], "operation": "new_body", "body_name": "Plate", "name": "PlateBox"}),+ );+ let sub = run(&mut s, "component.create", json!({"name": "Sub", "activate": false}));+ let sub_occurrence = sub["occurrence"].as_u64().unwrap();+ let (before, steps, corners) = (s.doc.to_json(), s.undo.len(), world_corners(&s));+ let moves = |features: Value| json!({"occurrences": [sub_occurrence], "features": features, "bodies": ["Block", "Plate"], "component": part});+ // Cut1 would be left without its body: nothing moves, the placement included.+ let e = s.execute("browser.reparent", &moves(json!(["S", "Extrude1"]))).unwrap_err().to_string();+ assert!(e.contains("moving would"), "{e}");+ assert_eq!((s.doc.to_json(), s.undo.len()), (before, steps));+ let r = run(&mut s, "browser.reparent", moves(json!(["S", "Extrude1", "S2", "Cut1"])));+ assert_eq!(r["occurrences"], json!([sub_occurrence]), "{r}");+ assert_eq!(r["features"], json!(["S", "Extrude1", "S2", "Cut1"]), "{r}");+ assert_eq!(r["bodies"], json!(["Plate"]), "Block went with its features: {r}");+ assert_eq!(s.undo.len(), steps + 1, "one undo step");+ assert_eq!(s.doc.occurrences.iter().find(|o| o.id == sub_occurrence).map(|o| o.parent), Some(part));+ assert_eq!(world_corners(&s), corners, "everything is where it was in the world");+}++#[test]+fn reparent_items_leaves_the_contents_of_a_moved_component_alone() {+ let (mut s, part) = block_and_part();+ let dest = run(&mut s, "component.create", json!({"name": "Dest", "activate": false}))["component"].as_u64().unwrap();+ let occurrence = s.doc.occurrence_of(part).map(|o| o.id).unwrap();+ // A feature inside Part is named as well as Part: it travels with Part, not on its own.+ run(&mut s, "component.activate", json!({"component": part}));+ run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "body_name": "Inner", "name": "InnerBox"}));+ run(&mut s, "component.activate", json!({"component": 0}));+ let r = run(&mut s, "browser.reparent", json!({"occurrences": [occurrence], "features": ["InnerBox"], "bodies": ["Inner"], "component": dest}));+ assert_eq!(r["features"], json!([]), "{r}");+ assert_eq!(r["bodies"], json!([]), "{r}");+ assert_eq!(s.doc.find_feature("InnerBox").map(|f| f.component), Some(part));+}++#[test]+fn reparent_items_refusals_change_nothing() {+ let (mut s, part) = block_and_part();+ let refused = |s: &mut Session, params: Value, why: &str| {+ let (before, steps) = (s.doc.to_json(), s.undo.len());+ let e = s.execute("browser.reparent", ¶ms).unwrap_err().to_string();+ assert!(e.contains(why), "{e}");+ assert_eq!((s.doc.to_json(), s.undo.len()), (before, steps));+ };+ refused(&mut s, json!({"component": part}), "give `occurrences`");+ refused(&mut s, json!({"features": ["S"], "component": 0}), "already in that component");+ refused(&mut s, json!({"bodies": ["Nope"], "component": part}), "no body");+ refused(&mut s, json!({"occurrences": [9999], "component": part}), "no occurrence");+ refused(&mut s, json!({"occurrences": ["x"], "component": part}), "occurrence ids");+ let many: Vec<u64> = (0..1001).collect();+ refused(&mut s, json!({"occurrences": many, "component": part}), "at most 1000");+ run(&mut s, "timeline.roll_to", json!({"position": 1}));+ refused(&mut s, json!({"features": ["S"], "component": part}), "rollback");+}++/// Placements hidden inside a moved component are still hidden under their new path.+#[test]+fn reparent_items_keeps_hidden_placements_hidden() {+ let (mut s, part) = block_and_part();+ let made = run(&mut s, "component.create", json!({"name": "Dest", "activate": false}));+ let (dest, dest_occurrence) = (made["component"].as_u64().unwrap(), made["occurrence"].as_u64().unwrap());+ let outer = run(&mut s, "component.create", json!({"name": "Outer", "activate": false}));+ let (outer_component, outer_occurrence) = (outer["component"].as_u64().unwrap(), outer["occurrence"].as_u64().unwrap());+ let inner =+ run(&mut s, "component.create", json!({"name": "Inner", "parent": outer_component, "activate": false}))["occurrence"].as_u64().unwrap();+ s.visibility.hidden_occurrences.push(vec![outer_occurrence, inner]);+ run(&mut s, "browser.reparent", json!({"occurrences": [outer_occurrence], "component": dest}));+ assert_eq!(s.visibility.hidden_occurrences, vec![vec![dest_occurrence, outer_occurrence, inner]]);+ assert_eq!(s.doc.occurrences.iter().find(|o| o.id == outer_occurrence).map(|o| o.parent), Some(dest));+ let _ = part;+}diff --git a/crates/engine/src/schema/component.rs b/crates/engine/src/schema/component.rsindex ef918bb65e..53eace8304 100644--- a/crates/engine/src/schema/component.rs+++ b/crates/engine/src/schema/component.rs@@ -349,6 +349,82 @@ pub struct OccurrenceAlignResult {pub param_warnings: Vec<String>,}+/// Move timeline features (sketches too) into a component. Their ids, names and timeline order+/// stay, the geometry stays where it is in the world, and the bodies they made move with them.+/// Nothing changes when the move would break a feature, while the timeline is rolled back, or+/// for a component placed more than once.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct MoveFeaturesParams {+ /// The features to move, by id or name.+ pub features: Vec<IdOrName>,+ /// The component they go to, by id or name. Default: the active component.+ #[serde(default, deserialize_with = "present")]+ pub component: Option<IdOrName>,+}++/// What `component.move_features` returns.+#[derive(Debug, Default, Serialize, JsonSchema)]+pub struct MoveFeaturesResult {+ /// The names of the features that moved.+ pub moved: Vec<String>,+ /// The component they went to.+ pub component: u64,+ /// The bodies that moved with them.+ pub bodies: Vec<String>,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// A placement: an occurrence id, or its path of occurrence ids from the top of the design.+#[derive(Debug, Deserialize, JsonSchema)]+#[serde(untagged)]+pub enum PlacementRef {+ Id(u64),+ Path(Vec<u64>),+}++/// Move placements, timeline features and bodies into a component in one undo step, all or+/// nothing. Placements move first and take what they hold, then features, which take the bodies+/// they made, then the bodies still elsewhere (a body transfer, which leaves its features+/// behind). Anything already in the component is left alone.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ReparentItemsParams {+ /// The placements to move.+ #[serde(default, deserialize_with = "present")]+ pub occurrences: Option<Vec<PlacementRef>>,+ /// The features to move, by id or name.+ #[serde(default, deserialize_with = "present")]+ pub features: Option<Vec<IdOrName>>,+ /// The bodies to move, by name.+ #[serde(default, deserialize_with = "present")]+ pub bodies: Option<Vec<String>>,+ /// The component they go to, by id or name. Default: the active component.+ #[serde(default, deserialize_with = "present")]+ pub component: Option<IdOrName>,+ /// The placement of that component to place them by, as occurrence ids from the top.+ #[serde(default, deserialize_with = "present")]+ pub component_path: Option<Vec<u64>>,+}++/// What `browser.reparent` returns.+#[derive(Debug, Default, Serialize, JsonSchema)]+pub struct ReparentItemsResult {+ /// The component they went to.+ pub component: u64,+ /// The occurrence ids that moved.+ pub occurrences: Vec<u64>,+ /// The names of the features that moved.+ pub features: Vec<String>,+ /// The bodies that were transferred on their own.+ pub bodies: Vec<String>,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}+#[cfg(test)]#[path = "component_tests.rs"]mod tests;diff --git a/crates/engine/src/schema/component_tests.rs b/crates/engine/src/schema/component_tests.rsindex 0ef2d01713..3acbf2fef9 100644--- a/crates/engine/src/schema/component_tests.rs+++ b/crates/engine/src/schema/component_tests.rs@@ -2,7 +2,7 @@ use std::sync::Arc;use serde_json::{Value, json};-use super::{EditInPlaceParams, FinishEditParams, OccurrenceAlignParams, OccurrenceAlignResult};+use super::{EditInPlaceParams, FinishEditParams, MoveFeaturesParams, OccurrenceAlignParams, OccurrenceAlignResult, ReparentItemsParams};use crate::Session;use crate::schema::tests::{assert_keys, conforms};use crate::schema::{ParamCheck, input_schema_for, output_schema_for};@@ -29,6 +29,8 @@ fn schemas_and_the_key_check_agree() {"to_plane",],);+ assert_keys(input_schema_for::<MoveFeaturesParams>(), &["component", "features"]);+ assert_keys(input_schema_for::<ReparentItemsParams>(), &["bodies", "component", "component_path", "features", "occurrences"]);}#[test]diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rsindex 89cdc4491b..3fa35fe533 100644--- a/crates/ui-egui/src/browser.rs+++ b/crates/ui-egui/src/browser.rs@@ -1549,6 +1549,8 @@ fn occurrence_rows_inner(let own_visible = !on_screen || !app.session.occurrence_hidden(path);let selected = on_screen && app.session.selection.iter().any(|s| matches!(s, Sel::Occurrence { path: selected } if selected == path));let faded = app.session.active_occurrence_path.as_ref().is_some_and(|p| !path.starts_with(p) && !p.starts_with(path));+ // A cut component has a dashed outline until Paste moves it.+ let cut = app.cut.placements.iter().any(|p| p.as_slice() == path);let badges: &[&str] = if placement.grounded { &["pin"] } else { &[] };app.tree.remember(key);let appearance = if crate::render_workspace::active(app) {@@ -1571,8 +1573,8 @@ fn occurrence_rows_inner(count: &appearance.count,name: true,selected,- // A cut component is faded until Paste moves it.- dim: faded || !visible || app.cut_placements.iter().any(|p| p.as_slice() == path),+ dim: faded || !visible,+ cut,radio: Some(active),badges,mark: acts.lit.placement(&app.session.doc, path, placement.component),@@ -2647,6 +2649,10 @@ fn entry_row(Some(Sel::Body { name }) => app.session.visibility.locked_bodies.contains(name),_ => e.locked,};+ // What is cut (a body, a sketch, or a body made by a cut feature) has a dashed+ // outline until Paste moves it.+ let cut = (folder == "bodies" && crate::edit_clipboard::body_is_cut(app, &e.key))+ || matches!(&e.sel, Some(Sel::Feature { id }) if app.cut.features.contains(id));let badges: &[&str] = if locked { &["lock"] } else { &[] };// Cached with the evaluated model; the preference is read as the row is drawn.let sketch_state = e.sketch_state.filter(|_| app.preferences.sketch_state_icons);@@ -2663,8 +2669,8 @@ fn entry_row(label: &e.label,name: true,selected,- // A cut body is faded until Paste moves it.- dim: !e.visible || parent_hidden || (folder == "bodies" && app.cut_bodies.contains(&e.key)),+ dim: !e.visible || parent_hidden,+ cut,color: e.color,swatch: appearance.swatch,secondary: &appearance.name,diff --git a/crates/ui-egui/src/browser/features.rs b/crates/ui-egui/src/browser/features.rsindex ffe96f01c4..37c4f46903 100644--- a/crates/ui-egui/src/browser/features.rs+++ b/crates/ui-egui/src/browser/features.rs@@ -225,6 +225,8 @@ fn feature_row(let eye = (is_sketch || !bodies.is_empty()).then_some(visible);let status = crate::timeline::feature_status(app, id);let tip = status.and_then(|_| crate::timeline::feature_message(app, id));+ // A cut feature has a dashed outline until Paste moves it.+ let cut = app.cut.features.contains(&id);let r = draw_row(ui,ui.id().with(("browser_feature", id)),@@ -236,6 +238,7 @@ fn feature_row(label: &label,selected,dim: dim || (!is_sketch && eye == Some(false)),+ cut,action,mark,status,diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rsindex b602dc1c5a..84842b57d9 100644--- a/crates/ui-egui/src/context_menu.rs+++ b/crates/ui-egui/src/context_menu.rs@@ -565,6 +565,8 @@ fn feature_items(app: &SolveApp, id: u64) -> Vec<Item> {.with(json!({"feature":id, "suppressed": !suppressed})).on(exists),act("timeline.roll_to", "Roll Back Here", "rollback").with(json!({"feature":id})).on(exists),+ act("ui.cut", "Cut", "cut").key("Ctrl+X").on(exists && crate::edit_clipboard::can_cut(app)),+ act("ui.copy", "Copy", "copy").key("Ctrl+C").on(exists && crate::edit_clipboard::something_to_copy(app)),act("ui.delete", "Delete", "delete").key("Del").with(json!({"items": [{"type": "feature", "id": id}]})).on(exists),Item::sep(),act("ui.findTimeline", "Find in Timeline", "rollback").with(json!({"feature":id})).on(exists),@@ -767,6 +769,7 @@ 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.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": [{"type": "feature", "id": id}] })),diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rsindex cb41fdfd3f..60c4d7f13a 100644--- a/crates/ui-egui/src/documents.rs+++ b/crates/ui-egui/src/documents.rs@@ -41,13 +41,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+ /// Bodies, components and features copied or cut in this design: their names and paths mean nothing/// in another one (copied features stay with the session the same way). Another design/// pastes them from `SolveApp::foreign_copy`.copied_bodies: Vec<String>,copied_placements: Vec<Vec<u64>>,- cut_bodies: Vec<String>,- cut_placements: Vec<Vec<u64>>,+ cut: crate::edit_clipboard::CutSet,/// `SolveApp::own_clipboard_stamp`.own_clipboard_stamp: u64,}@@ -117,8 +116,7 @@ fn take_view(app: &mut SolveApp) -> 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),+ cut: std::mem::take(&mut app.cut),own_clipboard_stamp: app.own_clipboard_stamp,}}@@ -130,8 +128,7 @@ fn put_view(app: &mut SolveApp, v: DocView) {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;+ app.cut = v.cut;app.own_clipboard_stamp = v.own_clipboard_stamp;crate::edit_clipboard::drop_stale(app);}diff --git a/crates/ui-egui/src/edit_clipboard.rs b/crates/ui-egui/src/edit_clipboard.rsindex 73febe7e0a..114c14ccbd 100644--- a/crates/ui-egui/src/edit_clipboard.rs+++ b/crates/ui-egui/src/edit_clipboard.rs@@ -8,9 +8,10 @@//! 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.+//! whichever was copied last. Cut on components, bodies or timeline features only marks them (a+//! [`CutSet`]): Paste moves them into the component in one step (`browser.reparent`, where+//! they are), and a copy or Esc before that leaves them be. A component placed more than once (an+//! instance) isn't cut.//!//! Copied bodies paste into another design (tab) too, as imported bodies without their history,//! and copied components as independent copies with their history (Paste and Paste New alike),@@ -29,6 +30,26 @@ use solidcraft_engine::Sel;use crate::SolveApp;+/// What Cut marked: components (by placement path), timeline features (by id, sketches included)+/// and bodies (by name). They stay where they are, shown faded, until Paste moves them.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct CutSet {+ pub placements: Vec<Vec<u64>>,+ pub features: Vec<u64>,+ pub bodies: Vec<String>,+}++impl CutSet {+ pub fn is_empty(&self) -> bool {+ self.placements.is_empty() && self.features.is_empty() && self.bodies.is_empty()+ }+}++/// Whether Cut has marked the body: named itself, or moving with a feature that is marked.+pub fn body_is_cut(app: &SolveApp, name: &str) -> bool {+ app.cut.bodies.iter().any(|b| b == name)+}+/// 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);@@ -97,8 +118,7 @@ pub(crate) fn drop_stale(app: &mut SolveApp) {app.session.sketch_clipboard = None;app.copied_bodies.clear();app.copied_placements.clear();- app.cut_bodies.clear();- app.cut_placements.clear();+ app.cut = CutSet::default();}}@@ -112,8 +132,7 @@ pub fn can_paste(app: &SolveApp) -> bool {} else {foreign(app).is_some()|| !app.session.clipboard.is_empty()- || !app.cut_bodies.is_empty()- || !app.cut_placements.is_empty()+ || !app.cut.is_empty()|| !app.copied_bodies.is_empty()|| !app.copied_placements.is_empty()}@@ -143,7 +162,7 @@ pub fn pasting_bodies(app: &SolveApp) -> bool {app.session.active_sketch.is_none()&& app.session.clipboard.is_empty()&& app.linked_design_clipboard.is_none()- && (!app.copied_bodies.is_empty() || !app.cut_bodies.is_empty() || foreign_bodies(app))+ && (!app.copied_bodies.is_empty() || !app.cut.bodies.is_empty() || foreign_bodies(app))}/// [`paste_into`], then what was pasted into `group` of the component's `folder`: a group's menu@@ -183,8 +202,8 @@ pub fn paste_into_group(app: &mut SolveApp, at: Option<Pos2>, into: Option<(u64,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 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);};@@ -202,7 +221,7 @@ fn clear_clipboard(app: &mut SolveApp) {replace_clipboard(app);}-/// A new copy or cut replaces the copied bodies, components, cut bodies and design (copied+/// A new copy or cut replaces the copied bodies, components, the cut and design (copied/// features and sketch geometry are replaced by the commands that copy them), in this design and/// for the others: it is the last one.fn replace_clipboard(app: &mut SolveApp) {@@ -211,19 +230,17 @@ fn replace_clipboard(app: &mut SolveApp) {app.foreign_copy = None;app.copied_bodies.clear();app.copied_placements.clear();- app.cut_bodies.clear();- app.cut_placements.clear();+ app.cut = CutSet::default();app.linked_design_clipboard = None;}-/// Leave bodies that were cut where they are (Esc, or another copy): another design has nothing-/// of them to paste either.+/// Leave what was cut where it is (Esc, or another copy): another design has nothing of it to paste+/// either.pub fn drop_cut(app: &mut SolveApp) {- if !app.cut_bodies.is_empty() || !app.cut_placements.is_empty() {+ if !app.cut.is_empty() {app.foreign_copy = None;}- app.cut_bodies.clear();- app.cut_placements.clear();+ app.cut = CutSet::default();}/// A copy (or cut) that can't be done: it says why, and the clipboard is left empty.@@ -331,43 +348,96 @@ fn placement_cut_refused(app: &SolveApp, placements: &[Vec<u64>]) -> Option<StriNone}-/// Is there something Cut would cut: sketch geometry in a sketch, otherwise components or bodies-/// that may move.+/// What Cut marks for the selection, or why it can't. A selected component takes what it holds+/// with it, and a selected feature takes the body it is the origin of, so those are left out of the+/// set (and so are not marked, nor moved on their own): components, features and bodies chosen+/// together are one move.+fn cut_set(app: &SolveApp) -> Result<CutSet, String> {+ let mut set = CutSet { placements: placement_selection(app), features: crate::timeline::selected_feature_ids(app), bodies: body_selection(app) };+ if set.is_empty() {+ return Err("Select components, bodies, sketches or timeline features to cut".into());+ }+ if !set.placements.is_empty()+ && let Some(why) = placement_cut_refused(app, &set.placements)+ {+ return Err(why);+ }+ if !set.bodies.is_empty()+ && let Some(why) = body_cut_refused(app, &set.bodies)+ {+ return Err(why);+ }+ let doc = &app.session.doc;+ // A placement inside another selected one moves with it.+ let all = set.placements.clone();+ set.placements.retain(|p| !all.iter().any(|q| q.len() < p.len() && p.starts_with(q)));+ let held: Vec<u64> = set.placements.iter().filter_map(|p| app.session.occurrence_placement(p).ok()).map(|p| p.component).collect();+ let inside = |component: u64| held.iter().any(|c| doc.inside_component(component, *c));+ set.features.retain(|id| doc.feature(*id).is_some_and(|f| !inside(f.component)));+ let features = set.features.clone();+ // A body belongs to the feature it depends on first, and moves with it.+ let origins = app.session.body_origins();+ let state = app.session.model.state();+ set.bodies.retain(|b| {+ state.body(b).is_some_and(|body| {+ let origin = origins.get(&body.name).copied().unwrap_or(body.feature);+ !inside(doc.model_body_component(body)) && !features.contains(&origin)+ })+ });+ Ok(set)+}++/// What Cut says it marked, and how to leave it: "Cut 1 component, 3 features, 1 body (Esc to Cancel)".+fn cut_summary(set: &CutSet) -> String {+ let count = |n: usize, one: &str, many: &str| (n > 0).then(|| format!("{n} {}", if n == 1 { one } else { many }));+ let parts: Vec<String> = [+ count(set.placements.len(), "component", "components"),+ count(set.features.len(), "feature", "features"),+ count(set.bodies.len(), "body", "bodies"),+ ]+ .into_iter()+ .flatten()+ .collect();+ format!("Cut {} (Esc to Cancel)", parts.join(", "))+}++/// The names of what `set` marks, for the system clipboard text.+fn cut_names(app: &SolveApp, set: &CutSet) -> Vec<String> {+ let placements = set.placements.iter().filter_map(|p| app.session.occurrence_placement(p).ok()).map(|p| p.name);+ let features = set.features.iter().filter_map(|id| app.session.doc.feature(*id)).map(|f| f.name.clone());+ placements.chain(features).chain(set.bodies.iter().cloned()).collect()+}++/// Is there something Cut would cut: sketch geometry in a sketch, otherwise components, bodies or+/// timeline features 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_set(app).is_ok()}/// Cut: in a sketch, the selected sketch geometry (copied, then deleted: one undo step); otherwise-/// the selected bodies, which stay until Paste moves them.+/// the selected components, bodies and timeline features, which stay until Paste moves them.pub fn cut(app: &mut SolveApp) -> bool {if app.session.active_sketch.is_none() {- 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.foreign_copy = Some(std::sync::Arc::new(solidcraft_engine::ForeignCopy::of(&app.session, Vec::new(), placements.clone())));- 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));- }+ let set = match cut_set(app) {+ Ok(set) => set,+ Err(why) => 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(", ")));- // Another design pastes copies of them.- app.foreign_copy = Some(std::sync::Arc::new(solidcraft_engine::ForeignCopy::of(&app.session, bodies.clone(), Vec::new())));- app.cut_bodies = bodies;+ let names = cut_names(app, &set);+ app.set_status(cut_summary(&set), false);+ leave_text(app, format!("SolidCraft cut: {}", names.join(", ")));+ // Another design pastes copies of the bodies and components cut, but features never leave their+ // design: a cut that holds any feature leaves another design nothing to paste.+ if set.features.is_empty() {+ app.foreign_copy =+ Some(std::sync::Arc::new(solidcraft_engine::ForeignCopy::of(&app.session, set.bodies.clone(), set.placements.clone())));+ }+ app.cut = set;+ // What is cut is the faded set; the selection that chose it would only muddy which that is.+ let _ = app.run("select.clear", json!({}));return true;}let entities = sketch_selection(app);@@ -455,11 +525,8 @@ pub fn paste_into(app: &mut SolveApp, at: Option<Pos2>, new_copy: bool, into: Opreturn paste_from_design(app, copy, into);}// Features copied later replace bodies and components (copying those empties the features).- if app.session.clipboard.is_empty() && !app.cut_bodies.is_empty() {- return paste_cut_bodies(app, into);- }- if app.session.clipboard.is_empty() && !app.cut_placements.is_empty() {- return paste_cut_placements(app, into);+ if app.session.clipboard.is_empty() && !app.cut.is_empty() {+ return paste_cut(app, into);}if app.session.clipboard.is_empty() && !app.copied_placements.is_empty() {return paste_placements(app, new_copy, into);@@ -537,62 +604,59 @@ fn paste_from_design(app: &mut SolveApp, copy: std::sync::Arc<solidcraft_engine:true}-/// Move the cut bodies into `into` (a component, placed by its placement), where they are; they-/// are selected and the clipboard empties. Bodies already in it stay as they are. A move that-/// can't be done says why and keeps the cut, to paste somewhere else.-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);+/// Move what was cut into `into` (a component, placed by its placement), where it is, in one+/// step (`browser.reparent`); what moved is selected and the cut is spent. What is gone, or+/// already there, is skipped. A move that can't be done says why and keeps the cut, to paste+/// somewhere else.+fn paste_cut(app: &mut SolveApp, (component, path): (u64, Vec<u64>)) -> bool {+ let cut = std::mem::take(&mut app.cut);let foreign = app.foreign_copy.take();- if moving.is_empty() {+ let (placements, features, bodies) = {+ let doc = &app.session.doc;+ let state = app.session.model.state();+ let placements: Vec<Vec<u64>> = cut+ .placements+ .iter()+ .filter(|p| {+ app.session.occurrence_placement(p).is_ok()+ && p.last().is_some_and(|id| doc.occurrences.iter().any(|o| o.id == *id && o.parent != component))+ })+ .cloned()+ .collect();+ let features: Vec<u64> = cut.features.iter().copied().filter(|id| doc.feature(*id).is_some_and(|f| f.component != component)).collect();+ let bodies: Vec<String> =+ cut.bodies.iter().filter(|b| state.body(b).is_some_and(|body| doc.model_body_component(body) != component)).cloned().collect();+ (placements, features, bodies)+ };+ if placements.is_empty() && features.is_empty() && bodies.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;+ let params = json!({ "occurrences": placements, "features": features, "bodies": bodies, "component": component, "component_path": path });+ let Ok(out) = app.run("browser.reparent", params) else {+ app.cut = cut;app.foreign_copy = foreign;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 foreign = app.foreign_copy.take();- 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;- app.foreign_copy = foreign;- 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();+ };+ let ids = |key: &str| -> Vec<Value> { out.get(key).and_then(Value::as_array).cloned().unwrap_or_default() };+ let mut moved: Vec<Sel> = Vec::new();+ for id in ids("occurrences").iter().filter_map(Value::as_u64) {+ let to: Vec<u64> = path.iter().copied().chain([id]).collect();+ // Moved components arrive folded.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;+ for name in ids("features").iter().filter_map(Value::as_str) {+ if let Some(f) = app.session.doc.find_feature(name) {+ moved.push(Sel::Feature { id: f.id });+ }+ }+ for name in ids("bodies").iter().filter_map(Value::as_str) {+ moved.push(Sel::Body { name: name.to_string() });}+ let count = moved.len();let _ = app.run("select.set", json!({ "items": moved }));- app.set_status("Moved the cut components", false);+ app.set_status(format!("Moved {count} {}", if count == 1 { "item" } else { "items" }), false);true}diff --git a/crates/ui-egui/src/edit_clipboard_tests.rs b/crates/ui-egui/src/edit_clipboard_tests.rsindex dfefdaf924..ed12e6f919 100644--- a/crates/ui-egui/src/edit_clipboard_tests.rs+++ b/crates/ui-egui/src/edit_clipboard_tests.rs@@ -445,7 +445,7 @@ fn a_cut_body_moves_into_the_component_it_is_pasted_in() {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));+ assert!(app.cut.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");@@ -471,12 +471,82 @@ fn a_cut_component_moves_into_the_component_it_is_pasted_in() {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));+ assert!(app.cut.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");}+/// Features and the body they made, selected together, are cut together: the body is left out of+/// the cut set (it moves with the features, never on its own) and Paste moves the lot in one undo+/// step.+#[test]+fn cut_features_and_their_body_move_in_one_step() {+ 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();+ app.run("solid.extrude", json!({"sketch": "S", "distance": 5, "body_name": "Block"})).unwrap();+ let part = app.run("component.create", json!({"name": "Part", "activate": false})).unwrap()["component"].as_u64().unwrap();+ let ids: Vec<u64> = ["S", "Extrude1"].iter().map(|n| app.session.doc.find_feature(n).unwrap().id).collect();+ let items: Vec<Sel> = ids.iter().map(|id| Sel::Feature { id: *id }).chain([Sel::Body { name: "Block".into() }]).collect();+ app.run("select.set", json!({ "items": items })).unwrap();+ assert!(super::can_cut(&app) && super::cut(&mut app));+ assert!(app.session.selection.is_empty(), "the cut set is what is marked, not the selection that chose it");+ assert_eq!(app.cut.features, ids);+ assert!(app.cut.bodies.is_empty(), "the body moves with the features that made it, not on its own");+ assert!(!super::body_is_cut(&app, "Block"), "and is not marked as cut");+ app.run("component.activate", json!({"component": part})).unwrap();+ let steps = app.session.undo.len();+ assert!(super::paste(&mut app, None));+ assert!(ids.iter().all(|id| app.session.doc.feature(*id).is_some_and(|f| f.component == part)));+ assert_eq!(app.session.undo.len(), steps + 1);+ assert!(app.cut.is_empty() && !super::can_paste(&app));+}++/// A component takes what it holds: marking it leaves its features and bodies unmarked, so they+/// are not outlined and the user need not select them.+#[test]+fn a_cut_component_leaves_what_it_holds_unmarked() {+ let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());+ let made = app.run("component.create", json!({"name": "Part"})).unwrap();+ let (part, at) = (made["component"].as_u64().unwrap(), made["occurrence"].as_u64().unwrap());+ app.run("solid.box", json!({"length": 5, "width": 5, "height": 5, "body_name": "Inner", "name": "InnerBox"})).unwrap();+ app.run("component.activate", json!({"component": 0})).unwrap();+ app.run("component.create", json!({"name": "Holder", "activate": false})).unwrap();+ let inner = app.session.doc.find_feature("InnerBox").unwrap().id;+ app.run("select.set", json!({"items": [Sel::Occurrence { path: vec![at] }, Sel::Feature { id: inner }, Sel::Body { name: "Inner".into() }]}))+ .unwrap();+ assert!(super::cut(&mut app));+ assert_eq!(app.cut.placements, vec![vec![at]]);+ assert!(app.cut.features.is_empty() && app.cut.bodies.is_empty());+ assert!(!super::body_is_cut(&app, "Inner"));+ let _ = part;+}++/// A paste that can't be done says so and keeps the cut, to paste somewhere else.+#[test]+fn a_cut_that_cannot_move_stays_cut() {+ let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());+ app.run("sketch.create", json!({"plane": "XY", "name": "S1"})).unwrap();+ app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 20]})).unwrap();+ app.run("sketch.finish", json!({})).unwrap();+ app.run("solid.extrude", json!({"sketch": "S1", "distance": 10, "body_name": "Block"})).unwrap();+ app.run("sketch.create", json!({"plane": "XY", "name": "S2"})).unwrap();+ app.run("sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [10, 10]})).unwrap();+ app.run("sketch.finish", json!({})).unwrap();+ app.run("solid.extrude", json!({"sketch": "S2", "distance": 4, "operation": "cut", "name": "Cut1"})).unwrap();+ let part = app.run("component.create", json!({"name": "Part", "activate": false})).unwrap()["component"].as_u64().unwrap();+ let ids: Vec<u64> = ["S2", "Cut1"].iter().map(|n| app.session.doc.find_feature(n).unwrap().id).collect();+ app.run("select.set", json!({"items": ids.iter().map(|id| Sel::Feature { id: *id }).collect::<Vec<_>>()})).unwrap();+ assert!(super::cut(&mut app));+ app.run("component.activate", json!({"component": part})).unwrap();+ let before = app.session.doc.to_json();+ assert!(!super::paste(&mut app, None), "the cut would be left without its body");+ assert_eq!(app.session.doc.to_json(), before);+ assert_eq!(app.cut.features, ids, "the cut is kept");+}+/// 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]@@ -602,6 +672,22 @@ fn bodies_cut_in_another_design_paste_as_copies() {assert!(!super::can_paste(&app), "Esc left nothing to paste");}+/// Features never leave their design: a cut that holds one leaves another design nothing to paste,+/// while its own design still pastes it.+#[test]+fn a_cut_with_a_feature_leaves_another_design_nothing_to_paste() {+ let mut app = crate::SolveApp::new(design_with_cube("Bracket"), crate::Services::default());+ app.run("solid.box", json!({"length":1,"width":1,"height":1,"body_name":"Pin","operation":"new_body","translate":[10,0,0]})).unwrap();+ let first = app.session.doc.features[0].id;+ app.run("select.set", json!({"items": [Sel::Feature { id: first }, Sel::Body { name: "Pin".into() }]})).unwrap();+ assert!(super::cut(&mut app));+ assert_eq!((app.cut.features.clone(), app.cut.bodies.clone()), (vec![first], vec!["Pin".to_string()]));+ crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap();+ assert!(!super::can_paste(&app), "a feature stays in its design");+ crate::documents::switch(&mut app, 0);+ assert!(super::can_paste(&app), "its own design still pastes the cut");+}+/// Components copied in one design paste into another as independent copies with their history/// (Paste and Paste New alike), named as they were, folded and selected; the original stays.#[test]@@ -715,7 +801,7 @@ fn a_second_placements_body_copies_but_is_not_cut() {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.cut.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));diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex c5ec6c920e..776ab4cb37 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -560,8 +560,9 @@ pub struct SolveApp {/// 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>,+ /// Components, timeline features and bodies cut with Cut: they stay until Paste moves them+ /// into a component.+ pub cut: edit_clipboard::CutSet,/// Counts copies and cuts in every open design: the last one is what pastes.pub clipboard_stamp: u64,/// The copy or cut this design made last (`clipboard_stamp` then): when it isn't the last@@ -570,8 +571,6 @@ pub struct SolveApp {/// The bodies (or components) the last copy or cut took, with the design they were in, to/// paste into another design (`component.paste_from_design`).pub foreign_copy: Option<std::sync::Arc<solidcraft_engine::ForeignCopy>>,- /// 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.@@ -763,11 +762,10 @@ impl SolveApp {copied_bodies: Vec::new(),clipboard_text: None,copied_placements: Vec::new(),- cut_bodies: Vec::new(),+ cut: Default::default(),clipboard_stamp: 0,own_clipboard_stamp: 0,foreign_copy: None,- cut_placements: Vec::new(),esc_handled: false,last_escape: None,status: None,diff --git a/crates/ui-egui/src/ui_kit/tree.rs b/crates/ui-egui/src/ui_kit/tree.rsindex 10a0dbc8a4..731abd856a 100644--- a/crates/ui-egui/src/ui_kit/tree.rs+++ b/crates/ui-egui/src/ui_kit/tree.rs@@ -31,6 +31,8 @@ pub(crate) struct Row<'a> {pub(crate) name: bool,pub(crate) selected: bool,pub(crate) dim: bool,+ /// What Cut has marked, until Paste moves it: the row has a dashed outline.+ pub(crate) cut: bool,pub(crate) color: Option<Color32>,/// Draw the icon in this one colour instead of its artwork (a sketch's solve state, #7245).pub(crate) icon_ink: Option<Color32>,@@ -308,6 +310,11 @@ pub(crate) fn tree_row(ui: &mut egui::Ui, id: egui::Id, row: &Row) -> RowResp {let elided = galley.elided;crate::scenario::publish_rect(&format!("row_label:{}", row.label), Rect::from_min_size(pos2(x, cy - galley.size().y / 2.0), galley.size()));ui.painter().with_clip_rect(ui.painter().clip_rect().intersect(r)).galley(pos2(x, cy - galley.size().y / 2.0), galley, col);+ if row.cut {+ let inside = r.shrink2(vec2(t.space_2, t.space_2));+ let corners = [inside.left_top(), inside.right_top(), inside.right_bottom(), inside.left_bottom(), inside.left_top()];+ ui.painter().add(egui::Shape::dashed_line(&corners, Stroke::new(1.2, t.text_dim), 4.0, 3.0));+ }let mut bx = (x + lw + 6.0 + name_action_width).min(r.right() - 16.0);for b in row.badges {let br = Rect::from_center_size(pos2(bx + 6.0, cy), vec2(t.space_12, t.space_12));