From 0b787f8eae4244cd40f07dddccd2e1b27e4cf9f8 Mon Sep 17 00:00:00 2001 From: amolinari-autotex Date: Mon, 19 Oct 2026 23:07:01 +0200 Subject: [PATCH] Show and edit standard part configurations (#2680) (#2681) Thanks @amolinari-autotex. --- assets/locales/en.json | 1 + assets/locales/it.json | 1 + assets/locales/ja.json | 1 + assets/locales/zh.json | 1 + crates/engine/src/cmd/parts.rs | 104 ++++- crates/engine/src/frames.rs | 14 + crates/ui-egui/src/browser.rs | 17 +- crates/ui-egui/src/context_menu.rs | 18 + crates/ui-egui/src/dialogs.rs | 7 +- crates/ui-egui/src/dialogs_part_size.rs | 534 ++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 1 + docs/occurrence-workflows.md | 31 ++ 12 files changed, 721 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/src/dialogs_part_size.rs diff --git a/assets/locales/en.json b/assets/locales/en.json index 1baf03392..7557c6b44 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1398,6 +1398,7 @@ "ui.pan_zoom_orbit": "Pan, zoom, orbit", "ui.parallel": "Parallel", "ui.parameters": "Parameters", + "ui.part_size_shared": "Rebuilds the part, replacing any added features. All occurrences of this component update.", "ui.paste": "Paste", "ui.path": "Path", "ui.pattern_on_path": "Pattern on Path", diff --git a/assets/locales/it.json b/assets/locales/it.json index 05720236e..64e3bc8f9 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -1317,6 +1317,7 @@ "ui.pan_zoom_orbit": "Panoramica, zoom, orbita", "ui.parallel": "Parallelo", "ui.parameters": "Parametri", + "ui.part_size_shared": "Ricostruisce la parte, sostituendo le eventuali lavorazioni aggiunte. Si aggiornano tutte le occorrenze del componente.", "ui.paste": "Incolla", "ui.path": "Percorso", "ui.pattern_on_path": "Ripetizione su percorso", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 3bce6c952..ba6fbfe04 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1398,6 +1398,7 @@ "ui.pan_zoom_orbit": "パン、ズーム、オービット", "ui.parallel": "平行", "ui.parameters": "パラメータ", + "ui.part_size_shared": "パーツを再構築し、追加したフィーチャを置き換えます。このコンポーネントのすべての配置が更新されます。", "ui.paste": "貼り付け", "ui.path": "パス", "ui.pattern_on_path": "パス上のパターン", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 0c43a6905..8bfb7be4e 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1398,6 +1398,7 @@ "ui.pan_zoom_orbit": "平移、缩放、环绕", "ui.parallel": "平行", "ui.parameters": "参数", + "ui.part_size_shared": "重新生成零件并替换额外添加的特征。此零部件的所有实例都会更新。", "ui.paste": "粘贴", "ui.path": "路径", "ui.pattern_on_path": "路径阵列", diff --git a/crates/engine/src/cmd/parts.rs b/crates/engine/src/cmd/parts.rs index 36ffcd4fc..f2e29caad 100644 --- a/crates/engine/src/cmd/parts.rs +++ b/crates/engine/src/cmd/parts.rs @@ -26,7 +26,7 @@ pub static COMMANDS: &[CommandSpec] = &[ length? (mm; screws, bolts, set screws, pins; default a standard length near 2.5 d); \ at?: [x,y,z] on a hole's rim or wall (the part seats on the hole's face with a rigid joint) | point?: [x,y,z] with direction?: [x,y,z] (no joint); name?", ), - CommandSpec::new("parts.resize", "Change Part Size", resize).icon("scale") + CommandSpec::new("parts.resize", "Change Part Size", resize_atomic).icon("scale") .params("component: id|name of an inserted part; size?; length? — rebuilds it (joints keep it seated)"), ]; @@ -215,16 +215,20 @@ fn run(s: &mut Session, id: &str, p: Value) -> Result { /// A hex prism (across flats `af`) from z0 to z1, joined or cut. fn hex(s: &mut Session, af: f64, z0: f64, z1: f64, op: &str) -> Result<()> { - run(s, "sketch.create", json!({"plane": "XY", "offset": z0}))?; + run(s, "sketch.create", json!({"plane": "XY", "offset": format!("{z0} mm")}))?; run(s, "sketch.polygon.circumscribed", json!({"center": [0, 0], "radius": af / 2.0, "sides": 6}))?; run(s, "sketch.finish", json!({}))?; let (dist, dir) = if z1 >= z0 { (z1 - z0, "positive") } else { (z0 - z1, "negative") }; - run(s, "solid.extrude", json!({"distance": dist, "direction": dir, "operation": op}))?; + run(s, "solid.extrude", json!({"distance": format!("{dist} mm"), "direction": dir, "operation": op}))?; Ok(()) } fn cyl(s: &mut Session, d: f64, z0: f64, z1: f64, op: &str) -> Result<()> { - run(s, "solid.cylinder", json!({"diameter": d, "height": z1 - z0, "base": [0, 0, z0], "axis": [0, 0, 1], "operation": op}))?; + run( + s, + "solid.cylinder", + json!({"diameter": format!("{d} mm"), "height": format!("{} mm", z1 - z0), "base": [0, 0, z0], "axis": [0, 0, 1], "operation": op}), + )?; Ok(()) } @@ -245,6 +249,7 @@ fn thread(s: &mut Session, d: f64, pitch: f64, at: Vec3) { /// Build a part in the active component. fn build(s: &mut Session, sh: &Shape) -> Result<()> { + let _frame = crate::frames::local_geometry(); match *sh { Shape::Screw { d, pitch, len, head, socket } => { let k = match head { @@ -454,6 +459,19 @@ fn shape_len(sh: &Shape) -> Option { } } +/// Building the replacement runs several feature commands. Keep their intermediate history +/// and any failed build on a scratch session; the outer command records one complete undo. +fn resize_atomic(s: &mut Session, p: &Value) -> Result { + let mut computed = s.scratch(); + let result = resize(&mut computed, p)?; + computed.undo.clear(); + computed.active_component = s.active_component; + computed.active_occurrence_path = s.active_occurrence_path.clone(); + computed.active_sketch = s.active_sketch.filter(|id| computed.doc.feature(*id).is_some()); + s.accept_computed(computed); + Ok(result) +} + fn resize(s: &mut Session, p: &Value) -> Result { let cmd = "parts.resize"; let key = match p.get("component") { @@ -556,5 +574,83 @@ mod tests { run(&mut s, "parts.resize", json!({"component": comp, "size": "M8", "length": 25})); let (lo, hi) = bbox(&s, "SHCS M8x25"); assert!((hi.z - 18.0).abs() < 1e-6 && (lo.z + 15.0).abs() < 1e-6, "{lo:?} {hi:?}"); + assert!(s.model.state().threads.iter().any(|t| t.designation == "M8" && (t.pitch - 1.25).abs() < 1e-9)); + } + + #[test] + fn resizing_placed_parts_uses_local_geometry_and_millimetres_in_every_design_unit() { + for (family, initial, resized, prefix) in [ + ("socket_head_cap_screw", "M6", "M8", "SHCS"), + ("hex_bolt", "M6", "M8", "Hex Bolt"), + ("hex_nut", "M6", "M8", "Hex Nut"), + ("washer", "M6", "M8", "Washer"), + ("set_screw", "M6", "M8", "Set Screw"), + ("dowel_pin", "6", "8", "Dowel Pin"), + ("bearing", "608", "6200", "Bearing"), + ] { + let mut bounds = Vec::new(); + for units in ["mm", "in"] { + let mut s = Session::default(); + run(&mut s, "document.units", json!({"units":units})); + let part = run(&mut s, "parts.insert", json!({"family":family,"size":initial,"length":20,"point":[40,50,60],"direction":[1,0,0]})); + run(&mut s, "parts.resize", json!({"component":part["component"],"size":resized,"length":30})); + assert!(s.model.results.iter().all(|r| r.error.is_none()), "{family} {units}"); + let b = bbox(&s, prefix); + assert!(b.0.x < b.1.x && b.0.y < b.1.y && b.0.z < b.1.z, "{family} {units}: {b:?}"); + if matches!(family, "socket_head_cap_screw" | "hex_bolt" | "hex_nut" | "set_screw") { + assert!(s.model.state().threads.iter().any(|t| t.designation == "M8" && (t.pitch - 1.25).abs() < 1e-9), "{family} {units}"); + } + if family == "dowel_pin" { + assert!(b.0.dist(solidcraft_geom::Vec3::new(10., 46., 56.)) < 1e-6, "{b:?}"); + assert!(b.1.dist(solidcraft_geom::Vec3::new(40., 54., 64.)) < 1e-6, "{b:?}"); + } + bounds.push(b); + } + assert!(bounds[0].0.dist(bounds[1].0) < 1e-6 && bounds[0].1.dist(bounds[1].1) < 1e-6, "{family}: {bounds:?}"); + } + } + + #[test] + fn resizing_a_part_is_one_undo_and_keeps_the_active_occurrence() { + let mut s = Session::default(); + let part = run(&mut s, "parts.insert", json!({"family":"socket_head_cap_screw","size":"M6","length":20})); + let id = part["component"].as_u64().unwrap_or(0); + let copied = run(&mut s, "occurrence.copy", json!({"component":id,"translate":[40,0,0]})); + let path = vec![copied["occurrence"].as_u64().unwrap_or(0)]; + run(&mut s, "component.activate", json!({"component":id,"occurrence":copied["occurrence"],"path":path})); + let before = s.doc.clone(); + let undo = s.undo.len(); + run(&mut s, "parts.resize", json!({"component":id,"size":"M8","length":25})); + assert_eq!(s.undo.len(), undo + 1); + assert_eq!(s.active_component, id); + assert_eq!(s.active_occurrence_path, Some(path.clone())); + let after = s.doc.clone(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, before); + let redo = s.redo.len(); + assert!(s.execute("parts.resize", &json!({"component":id,"length":0})).is_err()); + assert_eq!(s.doc, before); + assert_eq!(s.redo.len(), redo); + assert_eq!(s.active_occurrence_path, Some(path)); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc, after); + } + + #[test] + fn resizing_a_part_at_the_history_limit_drops_only_one_old_step() { + let mut s = Session::default(); + let part = run(&mut s, "parts.insert", json!({"family":"washer","size":"M6"})); + let Some(snapshot) = s.undo.last().cloned() else { panic!("insert did not record history") }; + s.undo = (0..crate::MAX_UNDO) + .map(|index| { + let mut old = snapshot.clone(); + old.label = format!("Earlier step {index}"); + old + }) + .collect(); + run(&mut s, "parts.resize", json!({"component":part["component"],"size":"M8"})); + assert_eq!(s.undo.len(), crate::MAX_UNDO); + assert_eq!(s.undo.first().map(|step| step.label.as_str()), Some("Earlier step 1")); + assert_eq!(s.undo.last().map(|step| step.label.as_str()), Some("Change Part Size")); } } diff --git a/crates/engine/src/frames.rs b/crates/engine/src/frames.rs index 9d83ff9fb..ec9274e98 100644 --- a/crates/engine/src/frames.rs +++ b/crates/engine/src/frames.rs @@ -310,6 +310,20 @@ pub fn mapped() -> bool { MAPPED.with(std::cell::Cell::get) } +/// Author generated geometry directly in the active component's local frame. +/// Restores the enclosing command's mapping state, including on an error. +pub(crate) fn local_geometry() -> LocalGeometry { + LocalGeometry(MAPPED.with(|m| m.replace(true))) +} + +pub(crate) struct LocalGeometry(bool); + +impl Drop for LocalGeometry { + fn drop(&mut self) { + MAPPED.with(|m| m.set(self.0)); + } +} + /// A command running inside another (its parameters are already in component frames). pub struct Nested; diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 013734fc2..37d1c1f28 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -709,7 +709,8 @@ fn component_name(app: &SolveApp, id: u64) -> String { let doc = &app.session.doc; let name = doc.components.iter().find(|c| c.id == id).map(|c| c.name.clone()).unwrap_or_default(); let n = doc.occurrences.iter().filter(|o| o.component == id).count(); - if n > 1 { format!("{name} ({n} instances)") } else { format!("{name}:1") } + let name = if n > 1 { format!("{name} ({n} instances)") } else { format!("{name}:1") }; + crate::dialogs_part_size::browser_label(app, id, &name) } fn component_rows(app: &mut SolveApp, ui: &mut egui::Ui, id: u64, depth: usize, acts: &mut Actions) { @@ -766,7 +767,11 @@ fn component_rows(app: &mut SolveApp, ui: &mut egui::Ui, id: u64, depth: usize, } } if r.double { - let _ = app.run("component.activate", json!({ "component": id })); + if app.session.doc.parts.contains_key(&id) { + crate::dialogs_part_size::open(app, id); + } else { + let _ = app.run("component.activate", json!({ "component": id })); + } } if r.hovered { acts.hover_bodies = bodies.clone(); @@ -823,6 +828,7 @@ fn occurrence_rows(app: &mut SolveApp, ui: &mut egui::Ui, path: Vec, depth: let selected = app.session.selection.contains(&Sel::Occurrence { path: path.clone() }); let faded = app.session.active_occurrence_path.as_ref().is_some_and(|p| !path.starts_with(p) && !p.starts_with(&path)); let badges: &[&str] = if placement.grounded { &["pin"] } else { &[] }; + let label = crate::dialogs_part_size::browser_label(app, placement.component, &placement.name); app.tree.order.push(key.clone()); let r = draw_row( ui, @@ -832,7 +838,7 @@ fn occurrence_rows(app: &mut SolveApp, ui: &mut egui::Ui, path: Vec, depth: fold: Some(open), eye: Some(own_visible), icon: "component", - label: &placement.name, + label: &label, name: true, selected, dim: faded || !visible, @@ -869,9 +875,12 @@ fn occurrence_rows(app: &mut SolveApp, ui: &mut egui::Ui, path: Vec, depth: if r.eye { let _ = app.run("browser.visibility", json!({"visible": app.session.occurrence_hidden(&path), "paths": [path]})); } - if r.radio || r.double { + if r.radio || (r.double && !app.session.doc.parts.contains_key(&placement.component)) { let _ = app.run("component.activate", json!({"component": placement.component, "occurrence": placement.occurrence, "path": path})); } + if r.double && app.session.doc.parts.contains_key(&placement.component) { + crate::dialogs_part_size::open(app, placement.component); + } if r.clicked { click_select(app, ui, key.clone(), Some(Sel::Occurrence { path: path.clone() })); } diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index ec50701d7..e02217e2b 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -492,6 +492,11 @@ fn viewport_items(app: &SolveApp) -> Vec { return v; } if !sel.is_empty() { + if !v.iter().any(|item| item.id == "parts.resize") + && let Some(component) = crate::dialogs_part_size::selected_component(app) + { + v.push(cmd(app, "parts.resize", "Change Part Size").with(json!({"component":component}))); + } v.push(Item::sep()); v.push(act("ui.clear", "Clear Selection", "").key("Esc")); } @@ -525,6 +530,9 @@ fn body_items(app: &SolveApp, bodies: &[String], browser: bool) -> Vec { ]; if one { let b = bodies.first().cloned().unwrap_or_default(); + if let Some(component) = crate::dialogs_part_size::component_for_bodies(app, bodies) { + v.push(cmd(app, "parts.resize", "Change Part Size").with(json!({"component":component}))); + } v.push(Item::sep()); if !browser { v.push(act("ui.findBrowser", "Find in Browser", "").with(json!({ "body": b }))); @@ -669,6 +677,9 @@ fn component_items(app: &SolveApp, id: u64) -> Vec { let hidden = !bodies.is_empty() && bodies.iter().all(|b| app.session.visibility.hidden_bodies.contains(b)); let names = json!(bodies); let mut v = Vec::new(); + if doc.parts.contains_key(&id) { + v.push(cmd(app, "parts.resize", "Edit").with(json!({"component":id}))); + } if id != 0 { let grounded = occ.is_some_and(|o| o.grounded); let oid = occ.map(|o| o.id).unwrap_or(0); @@ -880,6 +891,13 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { let p = item.params.clone().unwrap_or(Value::Null); let bodies = strs(&p, "bodies"); match item.id.as_str() { + "parts.resize" => { + if let Some(component) = id_of(&p, "component") { + crate::dialogs_part_size::open(app, component); + } else { + app.start("parts.resize"); + } + } "ui.repeat" => { if let Some((id, _)) = app.last_command.clone() { app.start(&id); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 8965fdeab..531694cbc 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -348,6 +348,7 @@ pub enum Kind { Motion(crate::dialogs_motion::Mo), /// Insert Part from the standard parts library (`dialogs_parts`). Part(crate::dialogs_parts::Pt), + PartSize(crate::dialogs_part_size::Resize), /// Edit Text: a sketch text's content and placement (`sketch_text`). Text(Box), TextMove(crate::sketch_text_move::TextMove), @@ -716,6 +717,7 @@ impl Dialog { .or_else(|| crate::dialogs_appearance::start(app, id)) .or_else(|| crate::dialogs_motion::start(app, id)) .or_else(|| crate::dialogs_parts::start(app, id)) + .or_else(|| crate::dialogs_part_size::start(app, id)) .or_else(|| crate::sketch_text::start(app, id)) .or_else(|| crate::sketch_text_move::start(app, id)) .or_else(|| crate::sketch_modify_ui::start(app, id))?; @@ -854,7 +856,7 @@ impl Dialog { Kind::Surface(_) => return true, Kind::SketchModify(k) => return k.previews(), Kind::Plastic(k) => return k.previews(), - Kind::Part(_) => return true, + Kind::Part(_) | Kind::PartSize(_) => return true, _ => {} } matches!( @@ -1535,6 +1537,7 @@ fn title(k: &Kind) -> &'static str { Kind::Appearance(_) => "APPEARANCE", Kind::Motion(k) => k.title(), Kind::Part(_) => "INSERT PART", + Kind::PartSize(_) => "Change Part Size", Kind::Text(_) => "EDIT TEXT", Kind::TextMove(_) => "MOVE/COPY TEXT", Kind::SketchModify(k) => k.title(), @@ -3139,6 +3142,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { Kind::Appearance(k) => enter |= crate::dialogs_appearance::rows(app, ui, k, &mut d.inputs), Kind::Motion(k) => enter |= crate::dialogs_motion::rows(app, ui, k, &mut d.inputs), Kind::Part(k) => enter |= crate::dialogs_parts::rows(app, ui, k, &d.inputs), + Kind::PartSize(k) => enter |= crate::dialogs_part_size::rows(app, ui, k), Kind::Text(k) => enter |= crate::sketch_text::rows(ui, k, &mut d.inputs, &mut d.active), Kind::TextMove(k) => enter |= crate::sketch_text_move::rows(ui, k), Kind::ConfirmDelete { with, fail, .. } => { @@ -4474,6 +4478,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S Kind::Appearance(k) => return Ok(crate::dialogs_appearance::commands(k, &d.inputs)), Kind::Motion(k) => return crate::dialogs_motion::commands(app, k, &d.inputs), Kind::Part(k) => return crate::dialogs_parts::commands(app, k, &d.inputs), + Kind::PartSize(k) => return crate::dialogs_part_size::commands(app, k), Kind::Text(k) => return crate::sketch_text::commands(app, k), Kind::TextMove(k) => return crate::sketch_text_move::commands(app, k), }; diff --git a/crates/ui-egui/src/dialogs_part_size.rs b/crates/ui-egui/src/dialogs_part_size.rs new file mode 100644 index 000000000..9261ad128 --- /dev/null +++ b/crates/ui-egui/src/dialogs_part_size.rs @@ -0,0 +1,534 @@ +//! Change a placed standard part through the existing, undoable `parts.resize` command. + +use std::sync::Arc; + +use egui::RichText; +use serde_json::{Value, json}; +use solidcraft_engine::{Sel, doc::Document}; + +use crate::SolveApp; +use crate::dialogs::{Kind, combo, row_label}; +use crate::dialogs_parts::Family; +use crate::selection::SelInput; + +/// The active catalogue configuration belongs to the shared part, not its placements. +pub(crate) fn configuration(app: &SolveApp, component: u64) -> Option { + let part = app.session.doc.parts.get(&component)?; + let size = part.size.trim(); + if size.is_empty() { + return None; + } + Some(configuration_name(size, part.length)) +} + +fn configuration_name(size: &str, length: Option) -> String { + match length.filter(|length| length.is_finite() && *length > 0.0) { + Some(length) => format!("{size}×{length}"), + None => size.to_owned(), + } +} + +pub(crate) fn browser_label(app: &SolveApp, component: u64, name: &str) -> String { + match configuration(app, component) { + Some(configuration) => format!("{name} [{configuration}]"), + None => name.to_owned(), + } +} + +#[derive(Clone)] +pub struct Resize { + pub component: u64, + pub size: usize, + pub length: Option, + original_size: usize, + family: Family, + source: Arc, +} + +impl std::fmt::Debug for Resize { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Resize") + .field("component", &self.component) + .field("family", &self.family.id) + .field("size", &self.size) + .field("length", &self.length) + .finish_non_exhaustive() + } +} + +/// Resolve a whole definition, including bodies displayed through an occurrence path. +pub fn component_for_bodies(app: &SolveApp, bodies: &[String]) -> Option { + let state = app.session.world_state(); + let mut component = None; + for name in bodies { + let body = state.bodies.iter().find(|b| b.name == *name)?; + let id = app.session.doc.model_body_component(body); + if !app.session.doc.parts.contains_key(&id) || component.is_some_and(|c| c != id) { + return None; + } + component = Some(id); + } + component +} + +pub fn selected_component(app: &SolveApp) -> Option { + if app.session.selection.is_empty() { + let [id] = app.tree.picked_components.as_slice() else { return None }; + return app.session.doc.parts.contains_key(id).then_some(*id); + } + let mut bodies = Vec::new(); + let mut component = None; + for sel in &app.session.selection { + match sel { + Sel::Body { name } => bodies.push(name.clone()), + Sel::Face { body, .. } | Sel::Edge { body, .. } | Sel::Vertex { body, .. } => bodies.push(body.clone()), + Sel::Occurrence { path } => { + let id = app.session.occurrence_placement(path).ok()?.component; + if !app.session.doc.parts.contains_key(&id) || component.is_some_and(|c| c != id) { + return None; + } + component = Some(id); + } + _ => return None, + } + } + if !bodies.is_empty() { + let id = component_for_bodies(app, &bodies)?; + if component.is_some_and(|c| c != id) { + return None; + } + component = Some(id); + } + component +} + +impl Resize { + fn new(app: &SolveApp, component: u64) -> Option { + let part = app.session.doc.parts.get(&component)?; + let response = app.session.scratch().execute("parts.library", &json!({})).ok()?; + let mut family = crate::dialogs_parts::families(&response).into_iter().find(|f| f.id == part.family)?; + for (label, row) in &mut family.sizes { + if let Some(diameter) = row.get("size").and_then(Value::as_f64) { + *label = diameter.to_string(); + } + } + let size = family.sizes.iter().position(|(s, row)| match family.id.as_str() { + "dowel_pin" => part + .size + .trim_start_matches(['d', 'D', 'Ø']) + .trim() + .parse::() + .ok() + .is_some_and(|d| row.get("d").and_then(Value::as_f64) == Some(d)), + "bearing" => s == part.size.trim(), + _ => s.eq_ignore_ascii_case(&part.size), + })?; + Some(Self { component, size, original_size: size, length: part.length, family, source: app.session.doc.clone() }) + } + + fn current(&self, app: &SolveApp) -> Result<(), String> { + if !Arc::ptr_eq(&self.source, &app.session.doc) || !app.session.doc.parts.contains_key(&self.component) { + return Err("The design changed. Reopen Change Part Size for the component.".into()); + } + Ok(()) + } + + fn lengths(&self) -> Option> { + // A future library family may give each size its own lengths. + let row = &self.family.sizes.get(self.size)?.1; + let mut lengths: Vec = match row.get("lengths").and_then(Value::as_array) { + Some(values) => values.iter().filter_map(|v| v.as_f64().or_else(|| v.get("length").and_then(Value::as_f64))).collect(), + None => self.family.lengths.clone()?, + }; + if let Some(current) = self.length { + lengths.push(current); + } + lengths.retain(|l| l.is_finite() && *l > 0.0 && *l <= 2000.0); + lengths.sort_by(f64::total_cmp); + lengths.dedup(); + Some(lengths) + } +} + +pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { + if id != "parts.resize" { + return None; + } + Some((Kind::PartSize(Resize::new(app, selected_component(app)?)?), vec![])) +} + +/// Select the context menu's exact target before using the normal command-start lifecycle. +pub fn open(app: &mut SolveApp, component: u64) { + if Resize::new(app, component).is_none() { + app.set_status("Select an inserted standard part to change its size", true); + return; + } + app.session.selection.clear(); + app.tree.picked_components = vec![component]; + app.start("parts.resize"); +} + +pub fn rows(app: &SolveApp, ui: &mut egui::Ui, k: &mut Resize) -> bool { + row_label(ui, "Type"); + ui.add(egui::Label::new(format!("{} ({})", k.family.name, k.family.standard)).wrap()); + ui.end_row(); + row_label(ui, "Size"); + let sizes: Vec<&str> = k.family.sizes.iter().map(|s| s.0.as_str()).collect(); + combo(ui, "part_resize_size", &sizes, &mut k.size); + ui.end_row(); + if let Some(lengths) = k.lengths() { + let mut index = k.length.and_then(|l| lengths.iter().position(|x| *x == l)).unwrap_or(0); + let labels: Vec = lengths.iter().map(|l| crate::prefs::show_mm(app, *l, 1)).collect(); + let labels: Vec<&str> = labels.iter().map(String::as_str).collect(); + row_label(ui, "Length"); + combo(ui, "part_resize_length", &labels, &mut index); + ui.end_row(); + k.length = lengths.get(index).copied(); + } + if let Some((size, _)) = k.family.sizes.get(k.size) { + row_label(ui, "Configuration"); + ui.label(configuration_name(size, k.length)); + ui.end_row(); + } + row_label(ui, ""); + ui.add(egui::Label::new(RichText::new(crate::i18n::tr("ui.part_size_shared")).color(crate::theme::Tokens::get().text_dim)).wrap()); + ui.end_row(); + false +} + +pub fn commands(app: &SolveApp, k: &Resize) -> Result, String> { + k.current(app)?; + let (size, _) = k.family.sizes.get(k.size).ok_or("Pick a part size")?; + let mut params = json!({"component":k.component,"size":size}); + if let Some(length) = k.length { + if !length.is_finite() || length <= 0.0 || length > 2000.0 { + return Err("Part length must be greater than zero and at most 2000 mm".into()); + } + params["length"] = json!(length); + } + if k.size == k.original_size && k.source.parts.get(&k.component).is_some_and(|part| part.length == k.length) { + return Ok(Vec::new()); + } + Ok(vec![("parts.resize".into(), params)]) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use crate::context_menu::{self, Target}; + use solidcraft_engine::{Session, geom::Vec3}; + + fn part(family: &str, size: &str, length: Option) -> (SolveApp, u64) { + let mut app = SolveApp::new(Session::default(), crate::Services::default()); + let mut p = json!({"family":family,"size":size,"point":[10,20,30]}); + if let Some(length) = length { + p["length"] = json!(length); + } + let id = app.run("parts.insert", p).unwrap()["component"].as_u64().unwrap(); + (app, id) + } + + fn menu(app: &mut SolveApp, target: Target) { + let items = context_menu::items(app, &target); + let item = items.iter().find(|i| i.id == "parts.resize").expect("Change Part Size in context menu"); + context_menu::run_item(app, item, egui::Pos2::ZERO); + } + + fn editor(app: &SolveApp) -> &Resize { + let Kind::PartSize(k) = &app.dialog.as_ref().unwrap().kind else { panic!("not a part-size dialog") }; + k + } + + fn change(app: &mut SolveApp, size: &str, length: Option) { + let Kind::PartSize(k) = &mut app.dialog.as_mut().unwrap().kind else { panic!("not a part-size dialog") }; + k.size = k.family.sizes.iter().position(|(s, _)| s == size).unwrap(); + k.length = length; + } + + fn apply(app: &mut SolveApp) { + let commands = crate::dialogs::apply_commands(app, app.dialog.as_ref().unwrap()).unwrap(); + for (id, params) in commands { + app.run(&id, params).unwrap(); + } + crate::dialogs::cancel(app); + } + + #[test] + fn part_size_browser_configuration_edits_the_same_part_and_follows_history_and_reopen() { + let (mut app, component) = part("socket_head_cap_screw", "M6", Some(20.0)); + let first = app.session.doc.occurrence_of(component).unwrap().id; + let second = app.run("occurrence.copy", json!({"occurrence":first,"translate":[40,0,0]})).unwrap()["occurrence"].as_u64().unwrap(); + app.run("joint.create", json!({"name":"Seat","type":"rigid","a":{"occurrence":0,"point":[0,0,0]},"b":{"occurrence":first,"point":[0,0,0]}})) + .unwrap(); + let occurrences = app.session.doc.occurrences.clone(); + let joints = app.session.doc.assembly.joints.clone(); + let before = app.session.doc.clone(); + let undo = app.session.undo.len(); + let mut h = crate::scenario::Harness::new(); + h.app = app; + h.app.home.open = false; + for id in [first, second] { + h.app.tree.collapsed.insert(format!("o:{id}")); + } + h.frames(3); + assert_eq!(crate::browser::drawn_rows().iter().filter(|(label, _, _, _)| label.ends_with("[M6×20]")).count(), 2); + let at = h.call("ui.at", json!({"handle":format!("row:occurrence:{second}")})); + let at = at["result"].as_array().unwrap(); + h.call("ui.click", json!({"x":at[0],"y":at[1],"double":true})); + assert_eq!(editor(&h.app).component, component); + assert_eq!(h.app.session.doc, before, "opening configuration is not a model edit"); + assert_eq!(h.app.session.undo.len(), undo); + crate::dialogs::cancel(&mut h.app); + h.frames(2); + let at = h.call("ui.at", json!({"handle":format!("activate:occurrence:{second}")})); + let at = at["result"].as_array().unwrap(); + h.call("ui.click", json!({"x":at[0],"y":at[1]})); + assert!(h.app.dialog.is_none()); + assert_eq!(h.app.session.active_occurrence_path, Some(vec![second])); + let items = context_menu::items(&h.app, &Target::Occurrence { path: vec![second] }); + let edit = items.iter().find(|item| item.id == "parts.resize").unwrap(); + assert_eq!(edit.label, "Edit"); + context_menu::run_item(&mut h.app, edit, egui::Pos2::ZERO); + change(&mut h.app, "M8", Some(25.0)); + apply(&mut h.app); + h.frames(3); + assert_eq!(crate::browser::drawn_rows().iter().filter(|(label, _, _, _)| label.ends_with("[M8×25]")).count(), 2); + assert_eq!(h.app.session.doc.occurrences, occurrences); + assert_eq!(h.app.session.doc.assembly.joints, joints); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.active_occurrence_path, Some(vec![second])); + h.app.run("edit.undo", json!({})).unwrap(); + h.frames(3); + assert_eq!(crate::browser::drawn_rows().iter().filter(|(label, _, _, _)| label.ends_with("[M6×20]")).count(), 2); + h.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(configuration(&h.app, component).as_deref(), Some("M8×25")); + let file = std::env::temp_dir().join(format!("solidcraft-part-configuration-{}.solidcraft", std::process::id())); + h.app.run("file.save", json!({"path":file})).unwrap(); + let mut reopened = Session::default(); + reopened.execute("doc.open", &json!({"path":file})).unwrap(); + let reopened = SolveApp::new(reopened, Default::default()); + assert_eq!(configuration(&reopened, component).as_deref(), Some("M8×25")); + assert_eq!(reopened.session.doc.occurrences, occurrences); + let _ = std::fs::remove_file(&file); + let _ = std::fs::remove_file(file.with_extension("solidcraft.bak")); + } + + #[test] + fn part_size_configuration_names_use_catalogue_dimensions_and_keep_ordinary_labels() { + for (family, size, length, expected) in + [("socket_head_cap_screw", "M6", Some(20.5), "M6×20.5"), ("hex_nut", "M8", None, "M8"), ("bearing", "608", None, "608")] + { + let (mut app, component) = part(family, size, length); + app.run("document.units", json!({"units":"in"})).unwrap(); + assert_eq!(configuration(&app, component).as_deref(), Some(expected)); + assert_eq!(browser_label(&app, component, "Named placement"), format!("Named placement [{expected}]")); + assert_eq!(browser_label(&app, 0, "Assembly"), "Assembly"); + } + } + + #[test] + fn part_size_prefills_actual_values_and_resizes_shared_occurrences_in_one_undo() { + let (mut app, id) = part("socket_head_cap_screw", "M5", Some(20.5)); + app.run("occurrence.copy", json!({"component":id,"translate":[40,0,0]})).unwrap(); + let before = app.session.doc.clone(); + let undo = app.session.undo.len(); + let occurrences = before.occurrences.clone(); + menu(&mut app, Target::Component { id }); + let k = editor(&app); + assert_eq!(k.family.sizes[k.size].0, "M5"); + assert_eq!(k.length, Some(20.5)); + assert!(k.lengths().unwrap().contains(&20.5), "keep non-catalogue lengths on opening"); + assert_eq!(app.session.undo.len(), undo); + change(&mut app, "M6", Some(30.0)); + apply(&mut app); + assert_eq!(app.session.doc.occurrences, occurrences); + assert_eq!(app.session.doc.parts[&id].size, "M6"); + assert_eq!(app.session.doc.parts[&id].length, Some(30.0)); + assert_eq!(app.session.undo.len(), undo + 1); + let after = app.session.doc.clone(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc, before); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(app.session.doc, after); + } + + #[test] + fn part_size_keeps_the_joint_and_placement_of_a_seated_screw() { + let mut app = SolveApp::new(Session::default(), crate::Services::default()); + app.run("solid.box", json!({"length":40,"width":30,"height":10,"body_name":"Plate"})).unwrap(); + app.run("solid.hole", json!({"position":[20,15,10],"diameter":6.4})).unwrap(); + let out = app.run("parts.insert", json!({"family":"socket_head_cap_screw","size":"M6","length":20,"at":[23.2,15,10]})).unwrap(); + assert!(out["joint"].is_number()); + let id = out["component"].as_u64().unwrap(); + let joints = app.session.doc.assembly.joints.clone(); + let occurrences = app.session.doc.occurrences.clone(); + menu(&mut app, Target::Component { id }); + change(&mut app, "M8", Some(25.0)); + apply(&mut app); + assert_eq!(app.session.doc.assembly.joints, joints); + assert_eq!(app.session.doc.occurrences, occurrences); + let state = app.session.world_state(); + let body = state.bodies.iter().find(|b| app.session.doc.model_body_component(b) == id).unwrap(); + let bounds = body.mesh().bounds(); + assert!((bounds.max.z - 18.0).abs() < 1e-6 && (bounds.min.z + 15.0).abs() < 1e-6); + } + + #[test] + fn part_size_resolves_body_face_and_occurrence_contexts_and_rejects_mixed_targets() { + let (mut app, id) = part("hex_nut", "M5", None); + let body = app.session.world_state().bodies.iter().find(|b| app.session.doc.model_body_component(b) == id).unwrap().name.clone(); + menu(&mut app, Target::Body { name: body.clone() }); + assert_eq!(editor(&app).component, id); + crate::dialogs::cancel(&mut app); + app.session.selection = vec![Sel::Face { body: body.clone(), index: 0, point: Vec3::ZERO }]; + menu(&mut app, Target::Viewport); + assert_eq!(editor(&app).component, id); + crate::dialogs::cancel(&mut app); + let occurrence = app.session.doc.occurrence_of(id).unwrap().id; + menu(&mut app, Target::Occurrence { path: vec![occurrence] }); + assert_eq!(editor(&app).component, id); + assert!(component_for_bodies(&app, &["missing".into()]).is_none()); + app.session.selection = vec![Sel::Body { name: body }, Sel::Plane { name: "XY".into() }]; + assert!(selected_component(&app).is_none()); + assert!(!context_menu::items(&app, &Target::Component { id: 0 }).iter().any(|i| i.id == "parts.resize")); + } + + #[test] + fn part_size_cancel_and_preview_do_not_change_the_design_or_history() { + let (mut app, id) = part("hex_bolt", "M6", Some(20.0)); + let before = app.session.doc.clone(); + let undo = app.session.undo.len(); + menu(&mut app, Target::Component { id }); + change(&mut app, "M8", Some(30.0)); + let commands = crate::dialogs::apply_commands(&app, app.dialog.as_ref().unwrap()).unwrap(); + let mut scratch = app.session.scratch(); + scratch.execute(&commands[0].0, &commands[0].1).unwrap(); + assert_eq!(scratch.doc.parts[&id].size, "M8"); + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.doc, before); + assert_eq!(app.session.undo.len(), undo); + } + + #[test] + fn part_size_refuses_stale_documents_and_invalid_values() { + let (mut app, id) = part("socket_head_cap_screw", "M5", Some(20.0)); + let mut k = Resize::new(&app, id).unwrap(); + for bad in [0.0, -1.0, f64::NAN, f64::INFINITY, 2001.0] { + k.length = Some(bad); + assert!(commands(&app, &k).is_err()); + } + k.length = Some(20.0); + k.size = usize::MAX; + assert!(commands(&app, &k).is_err()); + let k = Resize::new(&app, id).unwrap(); + let (other, other_id) = part("hex_bolt", "M6", Some(20.0)); + assert_eq!(id, other_id, "same numeric id in another document"); + assert!(commands(&other, &k).is_err()); + app.run("document.units", json!({"units":"in"})).unwrap(); + assert!(commands(&app, &k).is_err()); + } + + #[test] + fn part_size_round_trips_all_builtin_families_without_adding_a_length_to_rings() { + for (family, size, length) in [ + ("socket_head_cap_screw", "M5", Some(20.0)), + ("hex_bolt", "M5", Some(20.0)), + ("hex_nut", "M5", None), + ("washer", "M5", None), + ("set_screw", "M5", Some(10.0)), + ("dowel_pin", "6", Some(20.0)), + ("bearing", "608", None), + ] { + let (app, id) = part(family, size, length); + let k = Resize::new(&app, id).unwrap(); + assert_eq!(k.component, id); + assert_eq!(k.family.sizes[k.size].0, size); + assert_eq!(k.length, length); + assert!(commands(&app, &k).unwrap().is_empty(), "confirming unchanged values does not rebuild"); + } + } + + #[test] + fn part_size_unchanged_ok_keeps_added_features_and_has_no_undo_step() { + let (mut app, id) = part("hex_bolt", "M6", Some(20.0)); + app.run("component.activate", json!({"component":id})).unwrap(); + app.run("solid.box", json!({"length":2,"width":3,"height":4,"body_name":"Added lug"})).unwrap(); + let before = app.session.doc.clone(); + let undo = app.session.undo.len(); + menu(&mut app, Target::Component { id }); + apply(&mut app); + assert_eq!(app.session.doc, before); + assert_eq!(app.session.undo.len(), undo); + } + + #[test] + fn part_size_opens_accepted_size_aliases_without_rebuilding_unchanged_parts() { + for (family, size, canonical, length) in [ + ("dowel_pin", "D6", "6", Some(20.0)), + ("dowel_pin", "Ø6", "6", Some(20.0)), + ("dowel_pin", "6.0", "6", Some(20.0)), + ("bearing", " 608 ", "608", None), + ] { + let (mut app, id) = part(family, size, length); + let before = app.session.doc.clone(); + let undo = app.session.undo.len(); + menu(&mut app, Target::Component { id }); + let k = editor(&app); + assert_eq!(k.family.sizes[k.size].0, canonical); + assert!(commands(&app, k).unwrap().is_empty()); + apply(&mut app); + assert_eq!(app.session.doc, before); + assert_eq!(app.session.undo.len(), undo); + assert_eq!(app.session.doc.parts[&id].size, size); + } + } + + #[test] + fn part_size_length_labels_use_design_units_without_rescaling_the_command() { + let (mut app, id) = part("socket_head_cap_screw", "M5", Some(20.5)); + app.run("document.units", json!({"units":"in"})).unwrap(); + let mut h = crate::scenario::Harness::new(); + h.app = app; + h.app.home.open = false; + menu(&mut h.app, Target::Component { id }); + h.frames(3); + let label = crate::prefs::show_mm(&h.app, 20.5, 1); + assert!(label.contains("in"), "a length in inches: {label}"); + assert!(h.widget_near(&label, "Length").is_some()); + change(&mut h.app, "M6", Some(20.5)); + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["length"], 20.5); + } + + #[test] + fn part_size_real_widgets_change_size_length_and_confirm_once() { + let (app, id) = part("socket_head_cap_screw", "M5", Some(20.5)); + let mut h = crate::scenario::Harness::new(); + h.app = app; + h.app.home.open = false; + h.frames(3); + let undo = h.app.session.undo.len(); + menu(&mut h.app, Target::Component { id }); + h.frames(3); + h.step(&json!({"widget":"M5","near":"Size"})).unwrap(); + h.step(&json!({"widget":"M6"})).unwrap(); + let current = crate::prefs::show_mm(&h.app, 20.5, 1); + let shorter = crate::prefs::show_mm(&h.app, 10.0, 1); + h.step(&json!({"widget":current,"near":"Length"})).unwrap(); + h.step(&json!({"widget":shorter})).unwrap(); + assert_eq!(editor(&h.app).length, Some(10.0)); + h.step(&json!({"widget":"OK"})).unwrap(); + for _ in 0..200 { + h.frames(1); + if h.app.dialog.is_none() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(h.app.dialog.is_none(), "the operation completed: {:?}", h.app.status); + assert_eq!(h.app.session.doc.parts[&id].size, "M6"); + assert_eq!(h.app.session.doc.parts[&id].length, Some(10.0)); + assert_eq!(h.app.session.undo.len(), undo + 1); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 89483780d..37a7b1d6e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -31,6 +31,7 @@ pub mod dialogs_coupling; pub mod dialogs_library; pub mod dialogs_motion; pub mod dialogs_move; +pub mod dialogs_part_size; pub mod dialogs_parts; pub mod dialogs_plastic; pub mod dialogs_save_mesh; diff --git a/docs/occurrence-workflows.md b/docs/occurrence-workflows.md index dff1ad317..846911ab5 100644 --- a/docs/occurrence-workflows.md +++ b/docs/occurrence-workflows.md @@ -59,3 +59,34 @@ New face-attached sketches capture the selected body's producer, certified face Use `sketch.redefine` with the sketch ID and a new plane to repair or convert an attachment. Its preview is disposable; Apply records one undo step. An optional `author_path` explicitly repairs a missing author placement. Rebinding a repeated owner from another active component requires that path. Changing the target or converting to a fixed plane detaches only the old automatic face borders, retaining their currently evaluated geometry and entity IDs; unrelated projection links remain live. Pending positions on the involved target and author paths are captured with the edit, while unrelated pending positions remain pending. Paste New remaps internal certified targets and authoring paths to the copied definitions. Timeline paste reports retained external face targets and refuses translating such attachments until an explicit fixed-plane conversion establishes independent geometry. Rename preserves certified body identity; another producer using the same body name cannot repair a lost attachment. + +## Change the size of a standard component + +An inserted standard part is one component with an active catalogue configuration. +Its Browser entry shows that configuration alongside its placement name, for example +`Screw:1 [M6×20]`. Double-click the entry or choose **Edit** to open its configuration +dialog. The activation radio still activates the component; double-clicking ordinary +components keeps its existing activation behavior. The viewport also offers +**Change Part Size** for a picked standard screw, bolt, nut, washer, pin or bearing. +The dialog starts with the +component's current family, size and actual length, including a non-catalogue +length. Choose a size and, for parts with a length, a length, then confirm with OK. +Cancel leaves the design unchanged. + +Resizing regenerates the standard part, replacing any extra features added inside +that component. The dialog warns about this before applying the change. + +This edits the component definition: every occurrence of that component receives +the new size. Its occurrences and their placements and joints are retained. Undo +reverts the size change in one step. Insert another standard part when a separate +component with a different size is needed. + +The dialog uses the same `parts.library` catalogue and `parts.resize` command as +scripts. It is offered only for inserted standard parts. Other component types +retain their usual feature-editing tools. + +The configuration is read from the existing standard-part family, size and length +metadata, so it survives save/reopen and follows undo/redo without renaming any +occurrence. Lengths in the compact configuration name are catalogue millimetres; +the dialog displays lengths in the design's units. General parameter-driven +configurations are outside this change.