diff --git a/assets/locales/pending/sketches-to-parts.json b/assets/locales/pending/sketches-to-parts.json new file mode 100644 index 000000000..9b2d4c126 --- /dev/null +++ b/assets/locales/pending/sketches-to-parts.json @@ -0,0 +1,62 @@ +{ + "en": { + "browser.sketches_to_parts_already_in_part": "already in their part", + "browser.sketches_to_parts_design_body": "on a body of the design itself", + "browser.sketches_to_parts_moved": "Moved {moved} sketches to the part they're on", + "browser.sketches_to_parts_no_exact_attachment": "on a face without an exact attachment", + "browser.sketches_to_parts_not_on_face": "not on a part's face", + "browser.sketches_to_parts_part_missing": "their part is gone", + "browser.sketches_to_parts_result": "Moved {moved} sketches to the part they're on; {stayed} stayed: {why}", + "cmd.component_move_sketches_to_parts": "Move Sketches to Their Parts" + }, + "ar": { + "browser.sketches_to_parts_already_in_part": "موجودة بالفعل في جزئها", + "browser.sketches_to_parts_design_body": "على جسم من التصميم نفسه", + "browser.sketches_to_parts_moved": "نُقلت {moved} رسومات إلى الجزء الذي رُسمت عليه", + "browser.sketches_to_parts_no_exact_attachment": "على وجه بلا ارتباط دقيق", + "browser.sketches_to_parts_not_on_face": "ليست على وجه جزء", + "browser.sketches_to_parts_part_missing": "جزؤها لم يعد موجودًا", + "browser.sketches_to_parts_result": "نُقلت {moved} رسومات إلى الجزء الذي رُسمت عليه؛ وبقيت {stayed}: {why}", + "cmd.component_move_sketches_to_parts": "نقل الرسومات إلى أجزائها" + }, + "he": { + "browser.sketches_to_parts_already_in_part": "כבר בחלק שלהם", + "browser.sketches_to_parts_design_body": "על גוף של התכן עצמו", + "browser.sketches_to_parts_moved": "{moved} שרטוטים הועברו לחלק שעליו הם נמצאים", + "browser.sketches_to_parts_no_exact_attachment": "על פאה ללא הצמדה מדויקת", + "browser.sketches_to_parts_not_on_face": "לא על פאה של חלק", + "browser.sketches_to_parts_part_missing": "החלק שלהם כבר לא קיים", + "browser.sketches_to_parts_result": "{moved} שרטוטים הועברו לחלק שעליו הם נמצאים; {stayed} נשארו: {why}", + "cmd.component_move_sketches_to_parts": "העברת שרטוטים לחלקים שלהם" + }, + "ja": { + "browser.sketches_to_parts_already_in_part": "すでにその部品にある", + "browser.sketches_to_parts_design_body": "デザイン自体のボディ上にある", + "browser.sketches_to_parts_moved": "{moved} 個のスケッチを描かれている部品に移動しました", + "browser.sketches_to_parts_no_exact_attachment": "正確なアタッチメントのない面上にある", + "browser.sketches_to_parts_not_on_face": "部品の面上にない", + "browser.sketches_to_parts_part_missing": "部品がもうない", + "browser.sketches_to_parts_result": "{moved} 個のスケッチを描かれている部品に移動しました。{stayed} 個はそのまま:{why}", + "cmd.component_move_sketches_to_parts": "スケッチをそれぞれの部品に移動" + }, + "vi": { + "browser.sketches_to_parts_already_in_part": "đã ở trong chi tiết của chúng", + "browser.sketches_to_parts_design_body": "nằm trên một khối của chính thiết kế", + "browser.sketches_to_parts_moved": "Đã chuyển {moved} bản phác thảo vào chi tiết chứa chúng", + "browser.sketches_to_parts_no_exact_attachment": "nằm trên mặt không có liên kết chính xác", + "browser.sketches_to_parts_not_on_face": "không nằm trên mặt của một chi tiết", + "browser.sketches_to_parts_part_missing": "chi tiết của chúng không còn", + "browser.sketches_to_parts_result": "Đã chuyển {moved} bản phác thảo vào chi tiết chứa chúng; {stayed} giữ nguyên: {why}", + "cmd.component_move_sketches_to_parts": "Chuyển bản phác thảo vào chi tiết của chúng" + }, + "zh": { + "browser.sketches_to_parts_already_in_part": "已在其零件中", + "browser.sketches_to_parts_design_body": "位于设计本身的实体上", + "browser.sketches_to_parts_moved": "已将 {moved} 个草图移到其所在的零件", + "browser.sketches_to_parts_no_exact_attachment": "位于没有精确附着的面上", + "browser.sketches_to_parts_not_on_face": "不在零件的面上", + "browser.sketches_to_parts_part_missing": "其零件已不存在", + "browser.sketches_to_parts_result": "已将 {moved} 个草图移到其所在的零件;{stayed} 个保留原处:{why}", + "cmd.component_move_sketches_to_parts": "将草图移到各自的零件" + } +} diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index abe230dd8..4b965c17d 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -12,8 +12,8 @@ use solidcraft_geom::Vec3; use super::CommandSpec; use crate::params::{bad, bool_, str_, string_list, vec3}; use crate::schema::component::{ - EditInPlaceParams, EditInPlaceResult, FinishEditParams, FinishEditResult, MoveFeaturesParams, MoveFeaturesResult, OccurrenceAlignParams, - OccurrenceAlignResult, ReparentItemsParams, ReparentItemsResult, + EditInPlaceParams, EditInPlaceResult, FinishEditParams, FinishEditResult, MoveFeaturesParams, MoveFeaturesResult, MoveSketchesToPartsParams, + MoveSketchesToPartsResult, OccurrenceAlignParams, OccurrenceAlignResult, ReparentItemsParams, ReparentItemsResult, }; use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; @@ -21,6 +21,7 @@ use crate::{Result, Session}; const EDIT_IN_PLACE_CONTRACT: TypedContract = TypedContract::new(); const FINISH_EDIT_CONTRACT: TypedContract = TypedContract::new(); const MOVE_FEATURES_CONTRACT: TypedContract = TypedContract::new(); +const MOVE_SKETCHES_TO_PARTS_CONTRACT: TypedContract = TypedContract::new(); const REPARENT_ITEMS_CONTRACT: TypedContract = TypedContract::new(); #[path = "component_align.rs"] @@ -41,6 +42,8 @@ pub(super) mod properties; mod reparent; #[path = "component_reparent_items.rs"] mod reparent_items; +#[path = "component_sketches_to_parts.rs"] +mod sketches_to_parts; #[path = "component_transfer.rs"] mod transfer; @@ -122,7 +125,21 @@ pub static COMMANDS: &[CommandSpec] = &[ ), 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)"), + .params("sketches: [ids or names], component; the sketches keep their own coordinates (component.move_features keeps them where they are in the world), except that a sketch on an exactly attached face stays where it is on the face"), + CommandSpec::new( + "component.move_sketches.to_parts", + "Move Sketches to Their Parts", + crate::checked!("component.move_sketches.to_parts", sketches_to_parts::to_parts), + ) + .icon("move") + .contract(&MOVE_SKETCHES_TO_PARTS_CONTRACT) + .output(output_schema_for::) + .params( + "sketches?: [ids or names] (default: every sketch in the design) → moved, stayed, sketches [{sketch, name, component, part}], \ + kept [{sketch, name, code, reason}]. Each sketch whose plane is an exactly attached face of a part's body goes to that part, as \ + component.move_sketches moves it, and stays where it is on the face; the others (on an origin, construction or fixed \ + plane, on a body of the design itself, or already in their part) stay where they are. One undo step", + ), CommandSpec::new("component.move_features", "Move Features to Component", crate::checked!("component.move_features", move_features::move_features)) .icon("move") .contract(&MOVE_FEATURES_CONTRACT) @@ -520,6 +537,7 @@ fn move_sketches(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "`sketches` must list sketches")); } for id in &ids { + sketches_to_parts::reauthor(s, *id, to, cmd)?; if let Some(f) = s.doc_mut().feature_mut(*id) { f.component = to; } diff --git a/crates/engine/src/cmd/component_sketches_to_parts.rs b/crates/engine/src/cmd/component_sketches_to_parts.rs new file mode 100644 index 000000000..c36c752da --- /dev/null +++ b/crates/engine/src/cmd/component_sketches_to_parts.rs @@ -0,0 +1,139 @@ +//! Sketches and the component that owns them: a face-attached sketch moved to another component +//! keeps its place on the face, and `component.move_sketches.to_parts` (#10218) moves sketches +//! to the part whose face they are drawn on. +use serde_json::{Value, json}; +use solidcraft_doc::{EmbossFace, FeatureKind, PlaneRef, apply_point, apply_vector, mat_inverse, mat_mul}; +use solidcraft_geom::Plane; + +use crate::params::{bad, name_or_id_list}; +use crate::schema::component::{MoveSketchesToPartsResult, SketchKeptInPlace, SketchMovedToPart}; +use crate::{Result, Session}; + +/// The face a sketch's plane is built on, beneath an offset, flip or angle. +fn face_mut(mut plane: &mut PlaneRef) -> Option<&mut PlaneRef> { + for _ in 0..64 { + match plane { + PlaneRef::Offset { base, .. } | PlaneRef::Flipped { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::ThroughPoint { base, .. } => { + plane = base + } + PlaneRef::Face { .. } => return Some(plane), + _ => return None, + } + } + None +} + +/// Make the face-attached sketch `id`, about to belong to `to`, authored in a placement of `to`: +/// the placement its face is in when `to` owns the face, the design for the design, else `to`'s +/// first. The picked point, the repair plane and an angle's axis are carried into that placement, +/// so the sketch stays where it is on the face. Other sketches keep their own coordinates. +pub(super) fn reauthor(s: &mut Session, id: u64, to: u64, cmd: &str) -> Result<()> { + let Some(feature) = s.doc.feature(id) else { return Ok(()) }; + let from = feature.component; + let FeatureKind::Sketch { plane, .. } = &feature.kind else { return Ok(()) }; + let Some(anchor) = solidcraft_doc::face_anchor::plane_face_anchor(plane) else { return Ok(()) }; + if from == to { + return Ok(()); + } + let doc = s.placed_document(); + let path = if to == anchor.component { + anchor.path.clone() + } else if to == 0 { + Vec::new() + } else { + doc.first_path(to) + }; + let new_frame = EmbossFace::component_frame(&doc, to, &path)?; + let inverse = mat_inverse(&new_frame).ok_or_else(|| bad(cmd, "the component's placement can't be inverted"))?; + // A sketch whose old placement no longer resolves only gets the new one: its face anchor + // places it, and the picked point and repair plane are a guide. + let relative = anchor.author_frame(&doc, from).ok().map(|old| mat_mul(&inverse, &old)); + let Some(feature) = s.doc_mut().feature_mut(id) else { return Ok(()) }; + let FeatureKind::Sketch { plane, .. } = &mut feature.kind else { return Ok(()) }; + if let (Some(relative), PlaneRef::AtAngle { axis_origin, axis_dir, .. }) = (relative, &mut *plane) { + *axis_origin = apply_point(&relative, *axis_origin); + *axis_dir = apply_vector(&relative, *axis_dir); + } + let Some(PlaneRef::Face { plane: picked, at, anchor: Some(anchor), .. }) = face_mut(plane) else { return Ok(()) }; + anchor.author_path = path; + if let Some(relative) = relative { + *at = apply_point(&relative, *at); + if let Some(moved) = Plane::new(apply_point(&relative, picked.origin), apply_vector(&relative, picked.x), apply_vector(&relative, picked.y)) { + *picked = moved; + } + } + Ok(()) +} + +/// Why a sketch stays where it is (a code and its text), or the component whose face it is on. +fn part_of(s: &Session, owner: u64, plane: &PlaneRef) -> std::result::Result { + let mut base = plane; + for _ in 0..64 { + match base { + PlaneRef::Offset { base: inner, .. } + | PlaneRef::Flipped { base: inner, .. } + | PlaneRef::AtAngle { base: inner, .. } + | PlaneRef::ThroughPoint { base: inner, .. } => base = inner, + _ => break, + } + } + let PlaneRef::Face { anchor, .. } = base else { return Err(("not_on_face", "not on a face")) }; + let Some(anchor) = anchor else { + return Err(("no_exact_attachment", "its face has no exact attachment (a sheet metal panel, or picked before exact attachments)")); + }; + if anchor.component == 0 { + return Err(("design_body", "on a body of the design itself, not of a part")); + } + if s.doc.components.iter().all(|component| component.id != anchor.component) { + return Err(("part_missing", "its face's part is no longer in the design")); + } + if anchor.component == owner { + return Err(("already_in_part", "already in its part")); + } + Ok(anchor.component) +} + +/// `component.move_sketches.to_parts`: each sketch given (every sketch when none are) whose plane +/// is a face of a part's body goes to that part, as `component.move_sketches` moves it. One undo +/// step; the reply lists what moved and what stayed, and why. +pub(super) fn to_parts(s: &mut Session, p: &Value) -> Result { + let cmd = "component.move_sketches.to_parts"; + let ids: Vec = if p.get("sketches").is_some() { + let keys = name_or_id_list(cmd, p, "sketches")?; + let mut ids = Vec::with_capacity(keys.len().min(10_000)); + for key in &keys { + match s.doc.find_feature(key) { + Some(f) if matches!(f.kind, FeatureKind::Sketch { .. }) => { + if !ids.contains(&f.id) { + ids.push(f.id); + } + } + _ => return Err(bad(cmd, format!("no sketch `{key}`"))), + } + } + ids + } else { + s.doc.features.iter().filter(|f| matches!(f.kind, FeatureKind::Sketch { .. })).map(|f| f.id).collect() + }; + let mut result = MoveSketchesToPartsResult::default(); + let mut moves = Vec::new(); + for id in ids { + let Some(f) = s.doc.feature(id) else { continue }; + let FeatureKind::Sketch { plane, .. } = &f.kind else { continue }; + match part_of(s, f.component, plane) { + Ok(component) => { + let part = s.doc.components.iter().find(|c| c.id == component).map(|c| c.name.clone()).unwrap_or_default(); + result.sketches.push(SketchMovedToPart { sketch: id, name: f.name.clone(), component, part }); + moves.push((id, component)); + } + Err((code, reason)) => { + result.kept.push(SketchKeptInPlace { sketch: id, name: f.name.clone(), code: code.to_string(), reason: reason.to_string() }) + } + } + } + for (id, component) in moves { + super::move_sketches(s, &json!({"sketches": [id.to_string()], "component": component}))?; + } + (result.moved, result.stayed) = (result.sketches.len(), result.kept.len()); + serde_json::to_value(result).map_err(|e| bad(cmd, e.to_string())) +} diff --git a/crates/engine/src/schema/component.rs b/crates/engine/src/schema/component.rs index 53eace830..c84878fea 100644 --- a/crates/engine/src/schema/component.rs +++ b/crates/engine/src/schema/component.rs @@ -363,6 +363,54 @@ pub struct MoveFeaturesParams { pub component: Option, } +/// Move sketches to the part whose face they are drawn on (`component.move_sketches.to_parts`), +/// in one undo step. A sketch whose plane is an exactly attached face of a part's body goes to +/// that part, staying where it is on the face; the others stay where they are. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MoveSketchesToPartsParams { + /// The sketches to look at, by id or name. Default: every sketch in the design. + #[serde(default, deserialize_with = "present")] + #[schemars(with = "Vec")] + pub sketches: Option>, +} + +/// A sketch `component.move_sketches.to_parts` moved. +#[derive(Debug, Default, Serialize, JsonSchema)] +pub struct SketchMovedToPart { + pub sketch: u64, + pub name: String, + /// The part it went to: its component id and name. + pub component: u64, + pub part: String, +} + +/// A sketch `component.move_sketches.to_parts` left where it was, and why. +#[derive(Debug, Default, Serialize, JsonSchema)] +pub struct SketchKeptInPlace { + pub sketch: u64, + pub name: String, + /// Why, as a code: `not_on_face`, `no_exact_attachment`, `design_body`, `part_missing` or + /// `already_in_part`; and in words. + pub code: String, + pub reason: String, +} + +/// What `component.move_sketches.to_parts` returns. +#[derive(Debug, Default, Serialize, JsonSchema)] +pub struct MoveSketchesToPartsResult { + /// How many sketches moved, and how many stayed. + pub moved: usize, + pub stayed: usize, + /// The sketches that moved, each with the part it went to. + pub sketches: Vec, + /// The sketches that stayed, each with the reason. + pub kept: Vec, + /// 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, +} + /// What `component.move_features` returns. #[derive(Debug, Default, Serialize, JsonSchema)] pub struct MoveFeaturesResult { diff --git a/crates/engine/src/schema/component_tests.rs b/crates/engine/src/schema/component_tests.rs index 3acbf2fef..c486fe392 100644 --- a/crates/engine/src/schema/component_tests.rs +++ b/crates/engine/src/schema/component_tests.rs @@ -2,7 +2,10 @@ use std::sync::Arc; use serde_json::{Value, json}; -use super::{EditInPlaceParams, FinishEditParams, MoveFeaturesParams, OccurrenceAlignParams, OccurrenceAlignResult, ReparentItemsParams}; +use super::{ + EditInPlaceParams, FinishEditParams, MoveFeaturesParams, MoveSketchesToPartsParams, OccurrenceAlignParams, OccurrenceAlignResult, + ReparentItemsParams, +}; use crate::Session; use crate::schema::tests::{assert_keys, conforms}; use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; @@ -30,6 +33,7 @@ fn schemas_and_the_key_check_agree() { ], ); assert_keys(input_schema_for::(), &["component", "features"]); + assert_keys(input_schema_for::(), &["sketches"]); assert_keys(input_schema_for::(), &["bodies", "component", "component_path", "features", "occurrences"]); } @@ -79,3 +83,53 @@ fn replies_match_the_output_schema() { assert!(r2.get("param_warnings").is_some(), "{r2}"); assert!(conforms(schema, schema, &r2), "{r2} doesn't match {schema}"); } + +fn sketch_square(s: &mut Session) { + let run = |s: &mut Session, c: &str, p: Value| s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}")); + run(s, "sketch.rectangle.two_point", json!({"p0":[1,1],"p1":[3,3]})); + run(s, "sketch.finish", json!({})); +} + +/// `component.move_sketches.to_parts` (#10218): sketches drawn on a part's face while the design +/// was active go to that part and stay where they are on the face; the others stay and say why; +/// it is one undo step. +#[test] +fn sketches_move_to_the_part_whose_face_they_are_on() { + let mut s = Session::default(); + let run = |s: &mut Session, c: &str, p: Value| s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}")); + let part = run(&mut s, "component.create", json!({"name":"Part","parent":0,"grounded":false})); + let (component, occurrence) = (part["component"].as_u64().unwrap(), part["occurrence"].as_u64().unwrap()); + run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Base"})); + run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[30,0,0]})); + run(&mut s, "component.activate", json!({"component":0})); + let world = s.world_state(); + let base = world.body("Base").unwrap(); + let top = base.body.faces(0.01).unwrap().into_iter().max_by(|a, b| a.centroid.z.total_cmp(&b.centroid.z)).unwrap(); + let pick = json!({"body": base.name, "index": top.index, "face": [top.centroid.x, top.centroid.y, top.centroid.z], "path": [occurrence]}); + let on_face = run(&mut s, "sketch.create", json!({"name":"OnFace","plane":pick,"project_edges":false}))["sketch"].as_u64().unwrap(); + sketch_square(&mut s); + let on_xy = run(&mut s, "sketch.create", json!({"name":"OnXY","plane":"XY"}))["sketch"].as_u64().unwrap(); + sketch_square(&mut s); + let world_plane = |s: &Session| s.world_state().sketch(on_face).unwrap().plane; + let before = world_plane(&s); + assert_eq!(s.doc.feature(on_face).unwrap().component, 0); + let doc_before = s.doc.to_json(); + + let out = run(&mut s, "component.move_sketches.to_parts", json!({})); + assert_eq!((out["moved"].as_u64(), out["stayed"].as_u64()), (Some(1), Some(1)), "{out}"); + assert_eq!(out["sketches"][0]["part"], "Part"); + assert_eq!(out["kept"][0]["name"], "OnXY"); + assert_eq!(out["kept"][0]["reason"], "not on a face"); + assert_eq!(s.doc.feature(on_face).unwrap().component, component); + assert_eq!(s.doc.feature(on_xy).unwrap().component, 0); + let solidcraft_doc::FeatureKind::Sketch { plane, .. } = &s.doc.feature(on_face).unwrap().kind else { panic!("not sketch") }; + assert_eq!(solidcraft_doc::face_anchor::plane_face_anchor(plane).unwrap().author_path, vec![occurrence]); + assert!(s.model.result(on_face).unwrap().error.is_none()); + let after = world_plane(&s); + assert!((after.origin - before.origin).len() < 1e-6 && after.normal().dot(before.normal()) > 1. - 1e-9, "{before:?} {after:?}"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), doc_before, "one undo step"); + run(&mut s, "component.move_sketches.to_parts", json!({})); + let again = run(&mut s, "component.move_sketches.to_parts", json!({"sketches":["OnFace"]})); + assert_eq!((again["moved"].as_u64(), again["kept"][0]["reason"].as_str()), (Some(0), Some("already in its part"))); +} diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index cad32c7be..82300bc0a 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -376,6 +376,11 @@ pub fn group_items(app: &SolveApp, id: u64, scope: &str) -> Vec { v } +/// Move Sketches to Their Parts (`component.move_sketches.to_parts`) for `sketches` (ids). +pub(crate) fn sketches_to_parts_item(sketches: Vec) -> Item { + Item::action("component.move_sketches.to_parts", "Move Sketches to Their Parts", "move").with(json!({ "sketches": sketches })) +} + /// The menu of a folder row (Bodies, Sketches, Construction). pub fn folder_items(app: &SolveApp, component: u64, folder: &str, scope: &str) -> Vec { let sel: Vec = selected_keys(app, component, folder); @@ -388,6 +393,11 @@ pub fn folder_items(app: &SolveApp, component: u64, folder: &str, scope: &str) - } if folder == "sketches" { v.push(paste_item(app, component, scope, folder, None)); + // The folder's selected sketches, or all of them, go to the part whose face they are on (#10218). + if !app.session.doc.components.is_empty() && !all.is_empty() { + let sketches = if sel.is_empty() { all.iter().map(|e| e.key.clone()).collect() } else { sel.clone() }; + v.push(sketches_to_parts_item(sketches)); + } } v.push(Item::action("ui.newGroup", "New Group", "folder").with(json!({ "component": component, "folder": folder }))); if sel.len() > 1 { diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 3d770005b..872fbaa89 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -814,7 +814,23 @@ fn sketch_items(app: &SolveApp, id: u64) -> Vec { let dims = app.session.visibility.shown_dimensions.contains(&id); let editing = app.session.active_sketch == Some(id); let has_profiles = app.session.world_state().sketch(id).is_some_and(|s| !s.profiles.is_empty()); - vec![ + // This sketch, or every selected sketch when it is one of them, to the part it is on (#10218). + let selected: Vec = app + .session + .selection + .iter() + .filter_map(|sel| match sel { + solidcraft_engine::Sel::Feature { id } + if app.session.doc.feature(*id).is_some_and(|f| matches!(f.kind, solidcraft_engine::doc::FeatureKind::Sketch { .. })) => + { + Some(id.to_string()) + } + _ => None, + }) + .collect(); + let sketches = if selected.contains(&id.to_string()) { selected } else { vec![id.to_string()] }; + let parts = !app.session.doc.components.is_empty(); + let mut items = vec![ act("ui.extrudeSketch", "Extrude", "extrude").key("E").with(json!({ "sketch": id })).on(has_profiles && !editing), Item::sep(), act("ui.editSketch", "Edit Sketch", "sketch").with(json!({ "sketch": id })).on(!editing), @@ -826,6 +842,7 @@ fn sketch_items(app: &SolveApp, id: u64) -> Vec { 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 })), + crate::browser::sketches_to_parts_item(sketches).on(parts && !editing), Item::sep(), act("ui.lookAt", "Look At", "lookat").with(json!({ "sketch": id })), act("ui.sketchProfile", if profiles { "Hide Profile" } else { "Show Profile" }, "sketch").with(json!({ "sketch": id })), @@ -833,7 +850,9 @@ fn sketch_items(app: &SolveApp, id: u64) -> Vec { act(if visible { "ui.hideSketch" } else { "ui.showSketch" }, "Show/Hide", "eye").key("V").with(json!({ "sketch": id })), Item::sep(), act("ui.findTimeline", "Find in Timeline", "rollback").with(json!({ "feature": id })), - ] + ]; + items.retain(|item| parts || item.id != "component.move_sketches.to_parts"); + items } /// Construction geometry's row: edit, delete, rename, show or hide; sketch on planes. @@ -1790,6 +1809,7 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { } // They recompute the history from the changed feature on: off the frame, as the timeline does. "timeline.suppress" | "timeline.roll_to" if item.params.is_some() => drop(app.run_heavy(&item.id, p)), + "component.move_sketches.to_parts" => sketches_to_parts(app, p), id if item.params.is_some() => { let _ = app.run(id, p); } @@ -1797,6 +1817,30 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { } } +/// Move Sketches to the Part They're On, and say in the status bar how many moved and why the +/// others stayed (#10218). +fn sketches_to_parts(app: &mut SolveApp, p: Value) { + let out = match app.run("component.move_sketches.to_parts", p) { + Ok(out) => out, + Err(error) => return app.set_status(crate::friendly_error("component.move_sketches.to_parts", &error), true), + }; + let count = |key: &str| out.get(key).and_then(Value::as_u64).unwrap_or(0).to_string(); + let mut why: Vec = Vec::new(); + for kept in out.get("kept").and_then(Value::as_array).into_iter().flatten() { + let code = kept.get("code").and_then(Value::as_str).unwrap_or_default(); + let reason = crate::i18n::tr(&format!("browser.sketches_to_parts_{code}")).to_string(); + if !why.contains(&reason) { + why.push(reason); + } + } + let message = if why.is_empty() { + crate::i18n::format("browser.sketches_to_parts_moved", &[("moved", &count("moved"))]) + } else { + crate::i18n::format("browser.sketches_to_parts_result", &[("moved", &count("moved")), ("stayed", &count("stayed")), ("why", &why.join("; "))]) + }; + app.set_status(message, false); +} + /// Delete what is selected: sketch entities, features, and bodies (a Remove feature). pub fn delete(app: &mut SolveApp) { crate::delete::delete_selection(app); diff --git a/crates/ui-egui/src/occurrence_ui_tests.rs b/crates/ui-egui/src/occurrence_ui_tests.rs index 03abe02dd..638f95f40 100644 --- a/crates/ui-egui/src/occurrence_ui_tests.rs +++ b/crates/ui-egui/src/occurrence_ui_tests.rs @@ -561,3 +561,30 @@ fn dragging_an_occurrence_row_onto_the_top_of_a_sibling_reorders_them() { assert!(row(c).y < row(a).y && row(a).y < row(b).y, "the rows follow the saved order"); assert!(h.app.session.doc.occurrences.iter().all(|o| o.parent == 0), "none moved into another"); } + +/// #10218: the design's Sketches folder offers Move Sketches to the Part They're On for its +/// sketches; the one drawn on the part's face goes to the part, the one on XY stays, and the +/// status bar says so. +#[test] +fn sketches_folder_moves_its_sketches_to_the_part_they_are_on() { + let (mut h, component, occurrence) = crate::test_support::component_box(); + h.app.session.auto_project = false; + let world = h.app.session.world_state(); + let body = world.bodies.iter().find(|b| h.app.session.doc.model_body_component(b) == component).unwrap().name.clone(); + let face = world.body(&body).unwrap().body.faces(0.01).unwrap().into_iter().max_by(|a, b| a.centroid.z.total_cmp(&b.centroid.z)).unwrap(); + let pick = json!({"face":[face.centroid.x,face.centroid.y,face.centroid.z],"body":body,"index":face.index,"path":[occurrence]}); + let on_face = h.app.run("sketch.create", json!({"name":"OnFace","plane":pick})).unwrap()["sketch"].as_u64().unwrap(); + h.app.finish_sketch(); + let on_xy = h.app.run("sketch.create", json!({"name":"OnXY","plane":"XY"})).unwrap()["sketch"].as_u64().unwrap(); + h.app.finish_sketch(); + let target = Target::Folder { component: 0, folder: "sketches".into(), scope: "c0".into() }; + let items = context_menu::items(&h.app, &target); + let item = items.iter().find(|i| i.id == "component.move_sketches.to_parts").expect("on the Sketches folder's menu"); + assert_eq!(item.params.as_ref().unwrap()["sketches"], json!([on_face.to_string(), on_xy.to_string()])); + context_menu::run_item(&mut h.app, item, egui::Pos2::ZERO); + assert_eq!(h.app.session.doc.feature(on_face).unwrap().component, component); + assert_eq!(h.app.session.doc.feature(on_xy).unwrap().component, 0); + let (status, _, error) = h.app.status.clone().unwrap(); + assert!(!error && status.contains("Moved 1") && status.contains("1 stayed") && status.contains("not on a part's face"), "{status}"); + assert!(context_menu::items(&h.app, &Target::Sketch { id: on_xy }).iter().any(|i| i.id == "component.move_sketches.to_parts")); +} diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index 59a5a82f9..ad046e7d5 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -6,6 +6,16 @@ component has its own origin, bodies, sketches and timeline entries. The **activ (the radio button in the browser) receives new sketches and features; the others are drawn faded. +Sketches drawn on a part's face while the design was active belong to the design, so they +collect in its Sketches folder. **Move Sketches to Their Parts** +(`component.move_sketches.to_parts`), on a Sketches folder's menu and on a sketch's menu, moves +the folder's sketches (or the selected ones) to the part whose face each is drawn on, as dragging +it onto the part would. Each stays where it is on its face, and the whole move is one undo step. +A sketch with no single part to go to stays where it is: one on an origin, construction or fixed +plane, on a body of the design itself, on a face without an exact attachment, or already in its +part. The status bar says how many moved and why the others stayed; the command's reply lists +each sketch. With no `sketches` it looks at every sketch in the design. + A component is placed by its **occurrences**. Paste creates another instance of the same component, and **Paste New** creates an independent copy. Move an occurrence with the move triad, then **Capture Position** to keep it or **Revert** to put it back. SolidCraft asks before