SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Sketch: replace a sketch's contents with another sketch, from this design or another file (#11125) (#12712)
PaddleStroke91a06a546e6c
diff --git a/assets/locales/pending/sketch-replace.json b/assets/locales/pending/sketch-replace.jsonnew file mode 100644index 0000000000..235ebaed47--- /dev/null+++ b/assets/locales/pending/sketch-replace.json@@ -0,0 +1,47 @@+{+ "en": {+ "cmd.sketch.replace": "Replace Sketch",+ "ui.replace_sketch.from_file": "From a Design File…",+ "ui.replace_sketch.no_sketches": "That design has no sketch to take"+ },+ "ar": {+ "cmd.sketch.replace": "استبدال الرسم",+ "ui.replace_sketch.from_file": "من ملف تصميم…",+ "ui.replace_sketch.no_sketches": "لا يحتوي هذا التصميم على رسم يمكن أخذه"+ },+ "de": {+ "cmd.sketch.replace": "Skizze ersetzen",+ "ui.replace_sketch.from_file": "Aus einer Konstruktionsdatei…",+ "ui.replace_sketch.no_sketches": "Diese Konstruktion enthält keine Skizze"+ },+ "fr": {+ "cmd.sketch.replace": "Remplacer l’esquisse",+ "ui.replace_sketch.from_file": "Depuis un fichier de conception…",+ "ui.replace_sketch.no_sketches": "Cette conception ne contient aucune esquisse"+ },+ "he": {+ "cmd.sketch.replace": "החלפת סקיצה",+ "ui.replace_sketch.from_file": "מקובץ תכנון…",+ "ui.replace_sketch.no_sketches": "בתכנון הזה אין סקיצה לקחת"+ },+ "ja": {+ "cmd.sketch.replace": "スケッチを置き換え",+ "ui.replace_sketch.from_file": "デザインファイルから…",+ "ui.replace_sketch.no_sketches": "そのデザインには取り込めるスケッチがありません"+ },+ "ko": {+ "cmd.sketch.replace": "스케치 바꾸기",+ "ui.replace_sketch.from_file": "디자인 파일에서…",+ "ui.replace_sketch.no_sketches": "그 디자인에는 가져올 스케치가 없습니다"+ },+ "vi": {+ "cmd.sketch.replace": "Thay thế phác thảo",+ "ui.replace_sketch.from_file": "Từ một tệp thiết kế…",+ "ui.replace_sketch.no_sketches": "Thiết kế đó không có phác thảo nào để lấy"+ },+ "zh": {+ "cmd.sketch.replace": "替换草图",+ "ui.replace_sketch.from_file": "从设计文件…",+ "ui.replace_sketch.no_sketches": "该设计中没有可用的草图"+ }+}diff --git a/crates/engine/src/cmd/sketch_clipboard.rs b/crates/engine/src/cmd/sketch_clipboard.rsindex 1752c2d4dc..f975a5c6fd 100644--- a/crates/engine/src/cmd/sketch_clipboard.rs+++ b/crates/engine/src/cmd/sketch_clipboard.rs@@ -9,6 +9,7 @@ use std::collections::BTreeMap;use serde_json::{Value, json};use solidcore_record::Vec2;+use solidcraft_doc::Document;use solidcraft_geom::Aabb2;use solidcraft_sketch::{ConstraintKind, CurveKind, LinkKind, LinkSource, Sketch};@@ -16,13 +17,14 @@ use super::sketch::edit;use super::sketch_store;use super::{CommandSpec, in_sketch};use crate::params::{bad, string_list, vec2};-use crate::schema::sketch_clipboard::{Copied, CopyParams, CutParams, PasteParams, Pasted};+use crate::schema::sketch_clipboard::{Copied, CopyParams, CutParams, PasteParams, Pasted, ReplaceParams, Replaced};use crate::schema::{TypedContract, output_schema_for};use crate::{Result, Sel, Session};const COPY_CONTRACT: TypedContract<CopyParams> = TypedContract::new();const CUT_CONTRACT: TypedContract<CutParams> = TypedContract::new();const PASTE_CONTRACT: TypedContract<PasteParams> = TypedContract::new();+const REPLACE_CONTRACT: TypedContract<ReplaceParams> = TypedContract::new();pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("sketch.copy", "Copy Sketch Entities", crate::checked!("sketch.copy", copy)).icon("copy")@@ -44,6 +46,13 @@ pub static COMMANDS: &[CommandSpec] = &[.params("at?: [x, y] (sketch point the copy's centre goes to) | translate?: [x, y]; without either, offset from the original in its own sketch and at the same coordinates in another; sketch?: target (default: the active sketch)",),+ CommandSpec::new("sketch.replace", "Replace Sketch", crate::checked!("sketch.replace", replace))+ .icon("sketch")+ .contract(&REPLACE_CONTRACT)+ .output(output_schema_for::<Replaced>)+ .params(+ "sketch?: the sketch to replace (default: the active sketch); from: the sketch whose contents take its place (id or name); file?: a design file `from` is in (default: this design). The sketch keeps its plane, place in the timeline and the features built on it; its curves, points, constraints, dimensions and texts become a copy of `from`'s, at the same sketch coordinates (one undo step)",+ ),];/// A curve of the clipboard; its points are indices into [`SketchClip::points`].@@ -85,8 +94,14 @@ pub struct SketchClip {pub extent: f64,/// Pastes made without a position since the copy (each lands one offset further on).pub pastes: u32,+ /// The clipboard point that stands for the sketch origin (in a whole-sketch copy): a paste+ /// ties it to the origin of the sketch it goes to rather than adding a point.+ pub origin: Option<usize>,}+/// The id of a sketch's origin point.+const ORIGIN: &str = "origin";+impl SketchClip {/// This clipboard as another design pastes it (#9258): at the same sketch coordinates (its/// sketch ids mean nothing there), and with nothing that names the copied design's@@ -146,8 +161,17 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {return Err(bad(cmd, "select the sketch curves or points to copy"));}let sk = sketch_store::read(&s.doc, id)?;+ let (clip, out) = clip_of(&s.doc, sk, id, &ids, false, cmd)?;+ s.sketch_clipboard = Some(clip);+ reply(cmd, out)+}++/// The clipboard copy of the entities `ids` of sketch `id` (`sk`, in `doc`), and what it holds.+/// `whole` is a copy of the whole sketch for [`replace`]: its fixes come along, its constraints to+/// the origin stay tied to the origin of the sketch it goes to, and an empty sketch is a copy too.+fn clip_of(doc: &Document, sk: &Sketch, id: u64, ids: &[String], whole: bool, cmd: &str) -> Result<(SketchClip, Copied)> {let (mut cs, mut ps, mut texts): (Vec<usize>, Vec<usize>, Vec<String>) = (Vec::new(), Vec::new(), Vec::new());- for e in &ids {+ for e in ids {if let Some(c) = sk.curve_index(e) {match text_of(sk, c) {Some(t) if !texts.iter().any(|x| x == t) => texts.push(t.to_string()),@@ -169,6 +193,11 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {let mut clip = SketchClip { sketch: id, ..Default::default() };// Points: those of the copied curves, then the lone ones, each once.let mut pmap: BTreeMap<usize, usize> = BTreeMap::new();+ if whole && let Some(o) = sk.points.iter().position(|q| q.id == ORIGIN) {+ clip.points.push(Vec2::ZERO);+ clip.origin = Some(0);+ pmap.insert(o, 0);+ }let take = |q: usize, clip: &mut SketchClip, pmap: &mut BTreeMap<usize, usize>| -> usize {*pmap.entry(q).or_insert_with(|| {clip.points.push(sk.point(q).unwrap_or_default());@@ -193,21 +222,17 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {}}for c in &sk.constraints {- // Fixes and pattern or offset relations stay with the original.- if matches!(- c.kind,- ConstraintKind::Fix { .. }- | ConstraintKind::PatternPoint { .. }- | ConstraintKind::PatternRadius { .. }- | ConstraintKind::OffsetDistance { .. }- ) {+ // Pattern or offset relations stay with the original, and so do the fixes of a part copy.+ if matches!(c.kind, ConstraintKind::PatternPoint { .. } | ConstraintKind::PatternRadius { .. } | ConstraintKind::OffsetDistance { .. })+ || (!whole && matches!(c.kind, ConstraintKind::Fix { .. }))+ {continue;}let mut kind = c.kind.clone();if !kind.remap(&|q| pmap.get(&q).copied(), &|k| cmap.get(&k).copied()) {continue;}- let param = c.param.as_ref().map(|name| match s.doc.param(name) {+ let param = c.param.as_ref().map(|name| match doc.param(name) {Some(x) => (x.expr.clone(), x.unit.clone()),None => (format!("{}", kind.value().unwrap_or_default()), if kind.is_angle() { "rad".into() } else { "mm".into() }),});@@ -238,12 +263,13 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {add(*q);}}- if bounds.is_empty() {+ if !bounds.is_empty() {+ clip.center = bounds.center();+ let size = bounds.size();+ clip.extent = size.x.max(size.y);+ } else if !whole {return Err(bad(cmd, "nothing to copy"));}- clip.center = bounds.center();- let size = bounds.size();- clip.extent = size.x.max(size.y);let out = Copied {curves: clip.curves.len() + texts.iter().map(|t| sk.link_curves(t).len()).sum::<usize>(),points: clip.lone.len(),@@ -252,8 +278,7 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {center: [clip.center.x, clip.center.y],param_warnings: Vec::new(),};- s.sketch_clipboard = Some(clip);- reply(cmd, out)+ Ok((clip, out))}fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {@@ -315,58 +340,7 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {}let mut p = p.clone();p["sketch"] = json!(target);- let ((curves, lone, constraints), info) = edit(s, &p, cmd, false, |sk, doc| {- if sk.curves.len().saturating_add(clip.curves.len()) > solidcraft_sketch::MAX_CURVES {- return Err(solidcraft_sketch::SketchError::TooLarge.into());- }- let mut pts = Vec::with_capacity(clip.points.len());- for q in &clip.points {- pts.push(sk.add_point(*q + t, None)?);- }- let mut made = Vec::with_capacity(clip.curves.len());- for c in &clip.curves {- let mut kind = c.kind.clone();- kind.map_points(&|q| pts.get(q).copied().unwrap_or(usize::MAX));- let i = sk.add_curve(kind, None)?;- if let Some(cu) = sk.curves.get_mut(i) {- cu.construction = c.construction;- cu.centerline = c.centerline;- cu.reversed = c.reversed;- cu.infinite = c.infinite;- }- made.push(i);- }- let mut cons = Vec::new();- for c in &clip.constraints {- let mut kind = c.kind.clone();- if !kind.remap(&|q| pts.get(q).copied(), &|k| made.get(k).copied()) {- continue;- }- // Each pasted dimension gets its own parameter, with the same expression.- let param = c.param.as_ref().map(|(e, u)| doc.new_model_param(e, u));- let id = sk.add_constraint(kind, param)?;- if let Some(nc) = sk.constraints.last_mut() {- nc.driven = c.driven;- nc.text = c.text;- }- cons.push(id);- }- let mut curve_ids: Vec<String> = made.iter().filter_map(|i| sk.curves.get(*i).map(|c| c.id.clone())).collect();- for (src, path) in &clip.texts {- let mut src = src.clone();- let LinkSource::Text { at, style, exprs, .. } = &mut src else { continue };- style.path = path.and_then(|k| made.get(k)).and_then(|i| sk.curves.get(*i)).map(|c| c.id.clone());- *at += t;- // The copy sits where it was pasted: its place no longer follows the original's expressions.- exprs.x = None;- exprs.y = None;- let geom = sk.text_source_geometry(&src)?;- let link = sk.add_link(LinkKind::Text, src, &geom)?;- curve_ids.extend(sk.link_curves(&link).into_iter().filter_map(|i| sk.curves.get(i).map(|c| c.id.clone())));- }- let lone: Vec<String> = clip.lone.iter().filter_map(|n| pts.get(*n)).filter_map(|i| sk.points.get(*i).map(|q| q.id.clone())).collect();- Ok((curve_ids, lone, cons))- })?;+ let ((curves, lone, constraints), info) = edit(s, &p, cmd, false, |sk, doc| paste_clip(sk, doc, &clip, t))?;if !positioned&& target == clip.sketch&& let Some(c) = s.sketch_clipboard.as_mut()@@ -384,6 +358,160 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {reply(cmd, Pasted { curves, points: lone, constraints, translate: [t.x, t.y], sketch: info, param_warnings: Vec::new() })}+/// The feature id of the sketch `key` (an id or a name, as [`sketch_store::target`] reads them)+/// in `doc`.+fn sketch_in(doc: &Document, key: &Value, cmd: &str) -> Result<u64> {+ let (name, found) = match key {+ Value::Number(n) => {+ let id = n.as_u64().ok_or_else(|| bad(cmd, "`from` must be a sketch id or name"))?;+ (id.to_string(), doc.feature(id))+ }+ Value::String(x) => (x.clone(), doc.find_feature(x)),+ _ => return Err(bad(cmd, "`from` must be a sketch id or name")),+ };+ let f = found.ok_or_else(|| bad(cmd, format!("no sketch `{name}`")))?;+ if !matches!(f.kind, solidcraft_doc::FeatureKind::Sketch { .. }) {+ return Err(bad(cmd, format!("`{name}` is not a sketch")));+ }+ Ok(f.id)+}++/// A copy of every curve, point, constraint, dimension and text of sketch `id` in `doc`.+fn whole_clip(doc: &Document, id: u64, cmd: &str) -> Result<SketchClip> {+ let sk = sketch_store::read(doc, id)?;+ let ids: Vec<String> = sk.curves.iter().map(|c| c.id.clone()).chain(sk.points.iter().filter(|q| q.id != ORIGIN).map(|q| q.id.clone())).collect();+ Ok(clip_of(doc, sk, id, &ids, true, cmd)?.0)+}++/// `sketch.replace` (#11125): the sketch keeps its feature (plane, place in the timeline, name,+/// display options and what is built on it) and takes a copy of another sketch's contents, as a+/// whole-sketch copy and paste would. Projected geometry comes as ordinary geometry; patterns,+/// offsets and formula curves come as the geometry they made. The dimension parameters the old+/// contents had, when nothing else uses them, go with them.+fn replace(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "sketch.replace";+ if !(p.is_object() || p.is_null()) {+ return Err(bad(cmd, "params must be an object"));+ }+ let target = sketch_store::target(s, p, cmd)?;+ let from = p.get("from").filter(|v| !v.is_null()).ok_or_else(|| bad(cmd, "`from`: the sketch to take the contents of"))?;+ let file = match p.get("file").filter(|v| !v.is_null()) {+ None => None,+ Some(Value::String(f)) if !f.trim().is_empty() => Some(f.clone()),+ Some(_) => return Err(bad(cmd, "`file` must be the path of a design file")),+ };+ let clip = match &file {+ Some(path) => {+ let (other, _) =+ solidcraft_io::read_design_file(path, None::<fn(solidcraft_io::DesignPreview)>).map_err(|e| bad(cmd, format!("{path}: {e}")))?;+ let source = sketch_in(&other, from, cmd)?;+ whole_clip(&other, source, cmd)?.for_another_design()+ }+ None => {+ let source = sketch_in(&s.doc, from, cmd)?;+ if source == target {+ return Err(bad(cmd, "a sketch can't be replaced by itself"));+ }+ whole_clip(&s.doc, source, cmd)?+ }+ };+ let ((curves, points, constraints), info) = edit(s, &json!({ "sketch": target }), cmd, false, |sk, doc| {+ let old: Vec<String> = sk.constraints.iter().filter_map(|c| c.param.clone()).collect();+ // Emptied, but its id counters kept: the new contents' ids carry on from the old ones, so+ // a reference to an old curve or point (a sweep path, a profile picked by its curves)+ // finds nothing and says so, rather than taking a new, unrelated curve that happens to get+ // the same id.+ let mut fresh = sk.clone();+ fresh.points.retain(|q| q.id == ORIGIN);+ fresh.curves.clear();+ fresh.constraints.clear();+ fresh.patterns.clear();+ fresh.links.clear();+ fresh.offsets.clear();+ fresh.freeform_offsets.clear();+ fresh.wires.clear();+ fresh.equations.clear();+ // The old contents' own dimension parameters go with them; one something else uses stays.+ sketch_store::write(doc, target, fresh.clone())?;+ for name in &old {+ if doc.param(name).is_some_and(|x| x.model) {+ let _ = doc.remove_param(name);+ }+ }+ *sk = fresh;+ paste_clip(sk, doc, &clip, Vec2::ZERO)+ })?;+ if s.active_sketch == Some(target) {+ s.selection.clear();+ }+ let source = match from {+ Value::String(x) => x.clone(),+ other => other.to_string(),+ };+ reply(cmd, Replaced { sketch_id: target, from: source, file, curves, points, constraints, sketch: info, param_warnings: Vec::new() })+}++/// The ids of what a paste added: curves (those of texts included), lone points, constraints.+type PastedIds = (Vec<String>, Vec<String>, Vec<String>);++/// Add a copy of `clip`, moved by `t`, to `sk`.+fn paste_clip(sk: &mut Sketch, doc: &mut Document, clip: &SketchClip, t: Vec2) -> Result<PastedIds> {+ if sk.curves.len().saturating_add(clip.curves.len()) > solidcraft_sketch::MAX_CURVES {+ return Err(solidcraft_sketch::SketchError::TooLarge.into());+ }+ let mut pts = Vec::with_capacity(clip.points.len());+ let origin = sk.points.iter().position(|q| q.id == ORIGIN);+ for (i, q) in clip.points.iter().enumerate() {+ match origin.filter(|_| clip.origin == Some(i)) {+ Some(o) => pts.push(o),+ None => pts.push(sk.add_point(*q + t, None)?),+ }+ }+ let mut made = Vec::with_capacity(clip.curves.len());+ for c in &clip.curves {+ let mut kind = c.kind.clone();+ kind.map_points(&|q| pts.get(q).copied().unwrap_or(usize::MAX));+ let i = sk.add_curve(kind, None)?;+ if let Some(cu) = sk.curves.get_mut(i) {+ cu.construction = c.construction;+ cu.centerline = c.centerline;+ cu.reversed = c.reversed;+ cu.infinite = c.infinite;+ }+ made.push(i);+ }+ let mut cons = Vec::new();+ for c in &clip.constraints {+ let mut kind = c.kind.clone();+ if !kind.remap(&|q| pts.get(q).copied(), &|k| made.get(k).copied()) {+ continue;+ }+ // Each pasted dimension gets its own parameter, with the same expression.+ let param = c.param.as_ref().map(|(e, u)| doc.new_model_param(e, u));+ let id = sk.add_constraint(kind, param)?;+ if let Some(nc) = sk.constraints.last_mut() {+ nc.driven = c.driven;+ nc.text = c.text;+ }+ cons.push(id);+ }+ let mut curve_ids: Vec<String> = made.iter().filter_map(|i| sk.curves.get(*i).map(|c| c.id.clone())).collect();+ for (src, path) in &clip.texts {+ let mut src = src.clone();+ let LinkSource::Text { at, style, exprs, .. } = &mut src else { continue };+ style.path = path.and_then(|k| made.get(k)).and_then(|i| sk.curves.get(*i)).map(|c| c.id.clone());+ *at += t;+ // The copy sits where it was pasted: its place no longer follows the original's expressions.+ exprs.x = None;+ exprs.y = None;+ let geom = sk.text_source_geometry(&src)?;+ let link = sk.add_link(LinkKind::Text, src, &geom)?;+ curve_ids.extend(sk.link_curves(&link).into_iter().filter_map(|i| sk.curves.get(i).map(|c| c.id.clone())));+ }+ let lone: Vec<String> = clip.lone.iter().filter_map(|n| pts.get(*n)).filter_map(|i| sk.points.get(*i).map(|q| q.id.clone())).collect();+ Ok((curve_ids, lone, cons))+}+#[cfg(test)]#[path = "sketch_clipboard_tests.rs"]mod tests;diff --git a/crates/engine/src/cmd/sketch_clipboard_tests.rs b/crates/engine/src/cmd/sketch_clipboard_tests.rsindex 8809c6a2c3..0ee63eeb63 100644--- a/crates/engine/src/cmd/sketch_clipboard_tests.rs+++ b/crates/engine/src/cmd/sketch_clipboard_tests.rs@@ -294,3 +294,166 @@ fn sketch_geometry_pastes_into_another_design_with_values_not_foreign_parameterslet at = pos(sketch(&b, sb), &again[0]);assert!(at.iter().zip(&corner).all(|(p, q)| p.dist(*q) < 1e-6), "{at:?}");}++fn volume(s: &Session) -> f64 {+ s.model.state().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).sum()+}++/// A design with sketch `Small` (a 10 x 10 square from the origin) extruded 5 mm, then sketch+/// `Big` (a dimensioned 30 x 20 rectangle tied to the origin) on the same plane.+fn two_sketches() -> Session {+ let mut s = Session::default();+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Small"}));+ 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": "Small", "distance": 5.0, "operation": "new_body"}));+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Big"}));+ let rect = strs(&run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [30, 20]}))["curves"]);+ run(&mut s, "sketch.constraint.coincident", json!({"a": format!("{}.start", rect[0]), "b": "origin"}));+ run(&mut s, "sketch.dimension", json!({"entities": [rect[0]], "value": 30}));+ run(&mut s, "sketch.dimension", json!({"entities": [rect[1]], "value": 20}));+ run(&mut s, "sketch.finish", json!({}));+ s+}++/// Replace Sketch (#11125): the sketch keeps its feature, and the extrude built on it now makes+/// the other sketch's shape (10 x 10 x 5 = 500 mm³ becomes 30 x 20 x 5 = 3000 mm³). The copy's+/// constraints come along, the one to the origin tied to this sketch's origin, its dimensions+/// with their own parameters; the source is untouched; one undo step puts it all back.+#[test]+fn replace_sketch_gives_a_sketch_another_sketchs_contents_and_keeps_its_features() {+ let mut s = two_sketches();+ assert!((volume(&s) - 500.0).abs() < 1e-6, "{}", volume(&s));+ let small = s.doc.find_feature("Small").unwrap().id;+ let big = s.doc.find_feature("Big").unwrap().id;+ let features = s.doc.features.len();+ let params = s.doc.params.len();+ let source = s.doc.sketch(big).unwrap().clone();+ let before = s.doc.to_json();++ let out = run(&mut s, "sketch.replace", json!({"sketch": "Small", "from": "Big"}));+ assert_eq!(out["sketch_id"], json!(small));+ assert_eq!(strs(&out["curves"]).len(), 4);+ assert_eq!(s.doc.features.len(), features, "no feature added or removed");+ assert_eq!(s.doc.find_feature("Small").map(|f| f.id), Some(small), "the sketch keeps its id and name");+ assert!((volume(&s) - 3000.0).abs() < 1e-6, "the extrude follows: {}", volume(&s));+ let sk = sketch(&s, small);+ assert_eq!(sk.constraints.len(), source.constraints.len(), "every constraint comes along");+ assert_eq!(sk.points.iter().filter(|q| q.id == "origin").count(), 1, "one origin");+ let origin = sk.points.iter().position(|q| q.id == "origin").unwrap();+ assert!(+ sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Coincident { p, q } if p == origin || q == origin)),+ "the corner stays tied to the origin: {:?}",+ sk.constraints+ );+ let names: Vec<String> = sk.constraints.iter().filter_map(|c| c.param.clone()).collect();+ let theirs: Vec<String> = source.constraints.iter().filter_map(|c| c.param.clone()).collect();+ assert_eq!(names.len(), 2);+ assert!(names.iter().all(|n| !theirs.contains(n)), "its own parameters: {names:?} vs {theirs:?}");+ assert_eq!(s.doc.params.len(), params + 2);+ assert_eq!(serde_json::to_value(s.doc.sketch(big).unwrap()).unwrap(), serde_json::to_value(&source).unwrap(), "the source is untouched");+ // Its dimensions drive it: a new width changes this sketch only.+ run(&mut s, "parameters.change", json!({"name": names[0], "expression": "40"}));+ assert!((volume(&s) - 4000.0).abs() < 1e-6, "{}", volume(&s));+ run(&mut s, "edit.undo", json!({}));+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(s.doc.to_json(), before, "one undo step");+}++/// The old contents' dimension parameters go with them, unless something else uses them; a+/// parameter the user made stays.+#[test]+fn replace_sketch_drops_the_old_dimension_parameters_nothing_else_uses() {+ let mut s = two_sketches();+ run(&mut s, "parameters.change", json!({"name": "w", "expression": "12"}));+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Third"}));+ let rect = strs(&run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [12, 8]}))["curves"]);+ run(&mut s, "sketch.dimension", json!({"entities": [rect[0]], "value": "w"}));+ run(&mut s, "sketch.dimension", json!({"entities": [rect[1]], "value": 8}));+ run(&mut s, "sketch.finish", json!({}));+ let third = s.doc.find_feature("Third").unwrap().id;+ let params: Vec<String> = sketch(&s, third).constraints.iter().filter_map(|c| c.param.clone()).collect();+ assert_eq!(params.len(), 2, "{params:?}");+ run(&mut s, "sketch.replace", json!({"sketch": third, "from": "Small"}));+ for name in ¶ms {+ let kept = s.doc.param(name);+ assert!(kept.is_none_or(|p| !p.model), "`{name}` went with the old dimension: {kept:?}");+ }+ assert!(s.doc.param("w").is_some(), "the user's parameter stays");+}++/// A feature that names the old contents' curves (here a profile picked by its curve ids) never+/// takes the new contents' curves that happen to get the same ids: the new ids carry on from the+/// old ones, so the reference finds nothing and the feature says so, instead of quietly building+/// from unrelated geometry (30 x 20 x 5 = 3000 mm³ here).+#[test]+fn replace_sketch_never_rebinds_a_reference_to_an_old_curve_onto_a_new_one() {+ let mut s = Session::default();+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Small"}));+ let square = strs(&run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]}))["curves"]);+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"sketch": "Small", "distance": 5.0, "operation": "new_body", "profiles": [{"curves": square}]}));+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Big"}));+ let rect = strs(&run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [30, 20]}))["curves"]);+ run(&mut s, "sketch.finish", json!({}));+ assert_eq!(square, rect, "both sketches numbered their curves alike: {square:?} {rect:?}");+ assert!((volume(&s) - 500.0).abs() < 1e-6, "{}", volume(&s));+ let before = s.doc.to_json();+ match s.execute("sketch.replace", &json!({"sketch": "Small", "from": "Big"})) {+ Ok(out) => {+ let new = strs(&out["curves"]);+ assert!(new.iter().all(|id| !square.contains(id)), "new ids, not the old ones again: {new:?} vs {square:?}");+ assert!(s.model.results.iter().any(|r| r.error.is_some()), "the extrude says its curves are gone");+ }+ Err(_) => assert_eq!(s.doc.to_json(), before, "a refused replace changes nothing"),+ }+ assert!((volume(&s) - 3000.0).abs() > 1.0, "never built from the unrelated new curves: {}", volume(&s));+}++/// Sketch contents come from a sketch in another design file, at the same sketch coordinates; a+/// dimension that named that design's parameter keeps its value, without the parameter.+#[test]+fn replace_sketch_takes_a_sketch_from_another_design_file() {+ let dir = std::env::temp_dir().join(format!("solidcraft-replace-sketch-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("Other.sc");+ let mut other = Session::default();+ run(&mut other, "parameters.change", json!({"name": "w", "expression": "1 in"}));+ run(&mut other, "sketch.create", json!({"plane": "XZ", "name": "Plate"}));+ let rect = strs(&run(&mut other, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [25.4, 10]}))["curves"]);+ run(&mut other, "sketch.dimension", json!({"entities": [rect[0]], "value": "w"}));+ run(&mut other, "sketch.finish", json!({}));+ run(&mut other, "file.save_as", json!({"path": path.to_string_lossy()}));++ let mut s = two_sketches();+ let file = path.to_string_lossy().to_string();+ let out = run(&mut s, "sketch.replace", json!({"sketch": "Small", "from": "Plate", "file": file}));+ assert_eq!(out["file"], json!(file));+ assert!((volume(&s) - 25.4 * 10.0 * 5.0).abs() < 1e-6, "{}", volume(&s));+ assert!(s.doc.param("w").is_none(), "the other design's parameter is not brought in");+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn replace_sketch_refuses_bad_requests_and_leaves_the_design_as_it_was() {+ let mut s = two_sketches();+ let before = s.doc.to_json();+ let extrude = s.doc.features.iter().find(|f| !matches!(f.kind, solidcraft_doc::FeatureKind::Sketch { .. })).unwrap().id;+ for bad in [+ json!({"sketch": "Small"}),+ json!({"sketch": "Small", "from": "Small"}),+ json!({"sketch": "Small", "from": "Nope"}),+ json!({"sketch": "Small", "from": 1.5}),+ json!({"sketch": "Small", "from": [1]}),+ json!({"sketch": "Small", "from": extrude}),+ json!({"sketch": "Nope", "from": "Big"}),+ json!({"from": "Big"}),+ json!({"sketch": "Small", "from": "Big", "file": 3}),+ json!({"sketch": "Small", "from": "Big", "file": "Z:/no/such/file.solidcraft"}),+ json!([1, 2]),+ json!("text"),+ ] {+ assert!(s.execute("sketch.replace", &bad).is_err(), "{bad}");+ assert_eq!(s.doc.to_json(), before, "{bad}");+ }+}diff --git a/crates/engine/src/schema/sketch_clipboard.rs b/crates/engine/src/schema/sketch_clipboard.rsindex 8f481c188e..7a94b59786 100644--- a/crates/engine/src/schema/sketch_clipboard.rs+++ b/crates/engine/src/schema/sketch_clipboard.rs@@ -114,6 +114,44 @@ pub struct Pasted {pub param_warnings: Vec<String>,}+/// Replace the contents of a sketch with a copy of another sketch's, in one undo step. The sketch+/// keeps its plane, its place in the timeline and the features built on it.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ReplaceParams {+ /// The sketch to replace (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchRef>,+ /// The sketch whose curves, points, constraints, dimensions and texts take its place.+ pub from: SketchRef,+ /// A design file `from` is in (default: this design).+ #[serde(default)]+ pub file: Option<String>,+}++/// What `sketch.replace` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct Replaced {+ /// The replaced sketch's feature id.+ pub sketch_id: u64,+ /// The sketch the contents came from.+ pub from: String,+ /// The design file it is in, when not this design.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub file: Option<String>,+ /// The sketch's new curves' ids.+ pub curves: Vec<String>,+ /// Its new lone points' ids.+ pub points: Vec<String>,+ /// Its new constraints' and dimensions' ids.+ pub constraints: Vec<String>,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: Value,+ /// 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 = "sketch_clipboard_tests.rs"]mod tests;diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rsindex 461da7cc05..d552a95f41 100644--- a/crates/ui-egui/src/context_menu.rs+++ b/crates/ui-egui/src/context_menu.rs@@ -68,6 +68,13 @@ pub enum Target {InsertDesign,/// Model › Edit Sketch: choose an existing sketch when none is uniquely selected.EditSketch,+ /// Replace Sketch from a design file (#11125): the file's sketches, one of which takes the+ /// place of sketch `sketch`'s contents.+ ReplaceSketchFile {+ sketch: u64,+ path: String,+ sketches: Vec<(u64, String)>,+ },/// View › Visual style: the four styles, the current one marked (#8868).VisualStyle,/// View › Navigation tool: Orbit, Pan, Zoom; the latched one marked (#8868).@@ -466,6 +473,10 @@ pub fn items(app: &SolveApp, target: &Target) -> Vec<Item> {.collect(),Target::NamedView { name } => crate::browser::view_items(app, name),Target::InsertDesign => insert_design_items(app),+ Target::ReplaceSketchFile { sketch, path, sketches } => sketches+ .iter()+ .map(|(from, name)| cmd(app, "sketch.replace", name).with(json!({ "sketch": sketch, "from": from, "file": path })))+ .collect(),Target::EditSketch => {let items: Vec<Item> = app.session@@ -878,6 +889,7 @@ fn sketch_items(app: &SolveApp, id: u64) -> Vec<Item> {Item::sep(),act("ui.editSketch", "Edit Sketch", "sketch").with(json!({ "sketch": id })).on(!editing),act("ui.redefineSketch", "Redefine Sketch Plane", "plane").with(json!({ "sketch": id })),+ replace_sketch_item(app, id).on(!editing),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)),@@ -898,6 +910,41 @@ fn sketch_items(app: &SolveApp, id: u64) -> Vec<Item> {items}+/// Replace Sketch (#11125): each other sketch of the design, whose contents can take the place+/// of this one's, then a design file to take a sketch from.+fn replace_sketch_item(app: &SolveApp, id: u64) -> Item {+ let mut item = act("ui.replaceSketch", "Replace Sketch", "sketch");+ let others = app.session.doc.features.iter().filter(|f| f.id != id && matches!(f.kind, FeatureKind::Sketch { .. }));+ for f in others {+ item.children.push(cmd(app, "sketch.replace", &f.name).with(json!({ "sketch": id, "from": f.id })));+ }+ if !item.children.is_empty() {+ item.children.push(Item::sep());+ }+ item.children.push(act("ui.replaceSketchFromFile", app.tr("ui.replace_sketch.from_file"), "open").with(json!({ "sketch": id })));+ item+}++/// Replace Sketch from a file: the design file's sketches to choose from, in a menu at `at`;+/// a file with one sketch replaces at once.+fn replace_sketch_from_file(app: &mut SolveApp, sketch: u64, at: Pos2) {+ app.pick_open_for(&solidcraft_engine::io::DESIGN_EXTS, move |app, path| {+ let Some(path) = path else { return };+ let sketches: Vec<(u64, String)> = match solidcraft_engine::io::read_design_file(&path, None::<fn(solidcraft_engine::io::DesignPreview)>) {+ Ok((doc, _)) => doc.features.iter().filter(|f| matches!(f.kind, FeatureKind::Sketch { .. })).map(|f| (f.id, f.name.clone())).collect(),+ Err(e) => {+ app.set_status(format!("{path}: {e}"), true);+ return;+ }+ };+ match sketches.as_slice() {+ [] => app.set_status(app.tr("ui.replace_sketch.no_sketches").to_string(), true),+ [(from, _)] => drop(app.run("sketch.replace", json!({ "sketch": sketch, "from": from, "file": path }))),+ _ => open_for(app, at, Target::ReplaceSketchFile { sketch, path, sketches }),+ }+ });+}+/// Construction geometry's row: edit, delete, rename, show or hide; sketch on planes.fn plane_items(app: &SolveApp, id: u64) -> Vec<Item> {let Some(f) = app.session.doc.feature(id) else { return Vec::new() };@@ -1731,6 +1778,13 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) {crate::browser::redefine_sketch(app, id);}}+ // Its entries are in its submenu.+ "ui.replaceSketch" => {}+ "ui.replaceSketchFromFile" => {+ if let Some(id) = id_of(&p, "sketch") {+ replace_sketch_from_file(app, id, at);+ }+ }"ui.hideSketch" | "ui.showSketch" => {if let Some(id) = id_of(&p, "sketch") {crate::browser::set_sketch_visible(app, id, item.id == "ui.showSketch");@@ -2324,7 +2378,9 @@ pub fn check_target(app: &SolveApp, target: &Target) -> Result<(), String> {| Target::NamedViews| Target::ViewGizmo => true,Target::Body { name } => crate::open_meshing::session_world(&app.session).body(name).is_some(),- Target::Sketch { id } => doc.feature(*id).is_some_and(|f| matches!(f.kind, FeatureKind::Sketch { .. })),+ Target::Sketch { id } | Target::ReplaceSketchFile { sketch: id, .. } => {+ doc.feature(*id).is_some_and(|f| matches!(f.kind, FeatureKind::Sketch { .. }))+ }// Construction geometry, as the browser's Construction folder lists it.Target::Plane { id } => doc.feature(*id).is_some_and(|f| {matches!(f.kind, FeatureKind::ConstructionPlane { .. } | FeatureKind::ConstructionAxis { .. } | FeatureKind::ConstructionPoint { .. })diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex d4cd346e7c..cdc76b99d1 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1392,6 +1392,15 @@ impl SolveApp {if let Ok(v) = &r {match id {"sketch.finish" | "sketch.cancel" => self.sketch_closed(v.get("sketch").and_then(Value::as_u64)),+ // The sketch being edited has all new contents: a tool's picks named the old ones.+ "sketch.replace" if v.get("sketch_id").and_then(Value::as_u64).is_some_and(|id| self.session.active_sketch == Some(id)) => {+ if let Some(tool) = self.tool.as_mut() {+ tool.pts.clear();+ tool.hover = None;+ tool.picks.clear();+ tool.point_picks.clear();+ }+ }"view.fit" | "view.home" => self.frame_view(id == "view.home"),"view.tool" => {self.viewport.nav = match v.get("tool").and_then(Value::as_str) {diff --git a/crates/ui-egui/src/menu_tests.rs b/crates/ui-egui/src/menu_tests.rsindex 12f9553de5..3a7ae0aec9 100644--- a/crates/ui-egui/src/menu_tests.rs+++ b/crates/ui-egui/src/menu_tests.rs@@ -327,6 +327,77 @@ fn sketch_menu_hides_and_moves_to_another_plane() {assert_eq!(app.tree.redefine, Some(id));}+/// Replace Sketch (#11125): a sketch row's flyout lists the design's other sketches, one of which+/// gives this sketch its contents, then a design file to take one from; that file's sketches are+/// listed the same way.+#[test]+fn sketch_menu_replaces_a_sketch_with_another_sketchs_contents() {+ let mut app = SolveApp::new(Session::default(), Services::default());+ app.run("sketch.create", json!({"plane": "XY", "name": "Small"})).unwrap();+ app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})).unwrap();+ app.finish_sketch();+ app.run("sketch.create", json!({"plane": "XY", "name": "Round"})).unwrap();+ app.run("sketch.circle.center", json!({"center": [0, 0], "diameter": 6})).unwrap();+ app.finish_sketch();+ let small = app.session.doc.find_feature("Small").unwrap().id;+ let t = Target::Sketch { id: small };+ let replace = find(&context_menu::items(&app, &t), "Replace Sketch");+ assert!(replace.enabled);+ let labels: Vec<&str> = replace.children.iter().map(|i| i.label.as_str()).collect();+ assert_eq!(labels, ["Round", "", "From a Design File…"]);+ act(&mut app, &t, "Round");+ assert_eq!(app.session.doc.sketch(small).unwrap().curves.len(), 1, "the circle took the square's place");+ assert_eq!(app.session.doc.find_feature("Small").map(|f| f.id), Some(small));++ let dir = std::env::temp_dir().join(format!("solidcraft-menu-replace-sketch-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("Other.sc").to_string_lossy().to_string();+ let mut other = Session::default();+ other.execute("sketch.create", &json!({"plane": "XY", "name": "Lines"})).unwrap();+ other.execute("sketch.line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();+ other.execute("sketch.finish", &json!({})).unwrap();+ other.execute("sketch.create", &json!({"plane": "XY", "name": "Slot"})).unwrap();+ other.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [4, 2]})).unwrap();+ other.execute("sketch.finish", &json!({})).unwrap();+ other.execute("file.save_as", &json!({"path": path})).unwrap();+ let sketches: Vec<(u64, String)> = other.doc.features.iter().map(|f| (f.id, f.name.clone())).collect();+ let file = Target::ReplaceSketchFile { sketch: small, path: path.clone(), sketches };+ assert!(context_menu::check_target(&app, &file).is_ok());+ act(&mut app, &file, "Slot");+ assert_eq!(app.session.doc.sketch(small).unwrap().curves.len(), 4, "the file's rectangle took the circle's place");+ let _ = std::fs::remove_dir_all(&dir);+}++/// A script or the control channel may replace the sketch being edited: a constraint tool's+/// first pick named the old contents, so it is dropped, and the next click starts afresh rather+/// than constraining whichever new curve took that id.+#[test]+fn replacing_the_sketch_being_edited_drops_the_tools_picks() {+ let mut app = SolveApp::new(Session::default(), Services::default());+ app.run("sketch.create", json!({"plane": "XY", "name": "Round"})).unwrap();+ app.run("sketch.circle.center", json!({"center": [0, 0], "diameter": 6})).unwrap();+ app.finish_sketch();+ app.run("sketch.create", json!({"plane": "XY", "name": "Small"})).unwrap();+ let square: Vec<String> = app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})).unwrap()["curves"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|c| c.as_str().map(str::to_string))+ .collect();+ let small = app.session.active_sketch.unwrap();+ let mut tool = crate::tools::Tool::for_command("sketch.constraint.parallel").unwrap();+ tool.picks.push(square[0].clone());+ app.tool = Some(tool);+ app.run("sketch.replace", json!({"sketch": small, "from": "Round"})).unwrap();+ let tool = app.tool.as_ref().expect("the tool stays");+ assert!(tool.picks.is_empty(), "{:?}", tool.picks);+ // Another sketch's replacement leaves the tool alone.+ app.tool.as_mut().unwrap().picks.push("x".into());+ let round = app.session.doc.find_feature("Round").unwrap().id;+ app.run("sketch.replace", json!({"sketch": round, "from": "Small"})).unwrap();+ assert_eq!(app.tool.as_ref().unwrap().picks, vec!["x".to_string()]);+}+#[test]fn a_selected_arc_offers_an_arc_length_dimension() {// #6039: the arc length dimension existed as a command, but nothing in the UI led to it.diff --git a/tests/kernel-cases/EXEMPT b/tests/kernel-cases/EXEMPTindex 6097e71292..2ed26b6372 100644--- a/tests/kernel-cases/EXEMPT+++ b/tests/kernel-cases/EXEMPT@@ -298,6 +298,7 @@ sketch.point3d 2D sketch only (the sketch solver and engine tsketch.polygon.edge 2D sketch only (the sketch solver and engine tests); no kernel operationsketch.rectangle.three_point 2D sketch only (the sketch solver and engine tests); no kernel operationsketch.redefine 2D sketch only (the sketch solver and engine tests); no kernel operation+sketch.replace 2D sketch only (the sketch solver and engine tests); no kernel operationsketch.scale 2D sketch only (the sketch solver and engine tests); no kernel operationsketch.slot.arc_center 2D sketch only (the sketch solver and engine tests); no kernel operationsketch.slot.arc_three_point 2D sketch only (the sketch solver and engine tests); no kernel operation