From 50313d147f8bc28e8e0e63b408e17ade4d212712 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Wed, 21 Oct 2026 18:56:36 +0000 Subject: [PATCH 01/25] solid.mirror: copies join their source's component; follow the saved placement (#1938) * solid.mirror: copies join their source's component; follow the saved placement Three follow-ups to mirroring bodies of placed components: - A copy joins the component of the body it mirrors (or, when that component is placed more than once and a copy there would show at every placement, the innermost component around it placed once), so checks that group bodies by component see it beside its source. - The saved placement path, not the body's name, says which component a mirrored body is in: inserting the same file again reuses the body names, and the copies of the first insert vanished. - The mirror is evaluated again only when its own placements or its component's frame change, not on every occurrence move: each later command paid for one more mirror evaluation. Co-Authored-By: Claude Opus 5.5 (1M context) * solid.mirror: a saved placement must still lead to the body's component A stale or edited placement path that leads to another component's occurrence mirrored the body silently where that other component is placed. The mirror now reports that the placement no longer exists. The body's component comes from the evaluated body where a transfer recorded it, else from the component its name is recorded in or its feature's. When a later insert of the same file has taken over the name (the recorded component lies outside the components the body's own feature made), the placement has to lie inside those components instead, so mirrors of the first insert keep working. Co-Authored-By: Claude Opus 5.5 (1M context) * solid.mirror: the copies' component change is a pending format change v26 shipped in 0.15.0, so its mirror-placements note stays as released; the change of where a Mirror with placements puts its copies is noted in a new pending file instead. Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) --- crates/doc/src/assembly.rs | 8 +- crates/doc/src/document.rs | 6 +- crates/doc/src/eval.rs | 122 +++++++++++++---- .../pending/mirror-copies-join-component.rs | 7 + crates/engine/src/cmd/features.rs | 22 +-- crates/engine/src/tests/mirror_placed.rs | 126 ++++++++++++++++++ 6 files changed, 253 insertions(+), 38 deletions(-) create mode 100644 crates/doc/src/format/pending/mirror-copies-join-component.rs diff --git a/crates/doc/src/assembly.rs b/crates/doc/src/assembly.rs index c09a77258..93a557ca5 100644 --- a/crates/doc/src/assembly.rs +++ b/crates/doc/src/assembly.rs @@ -244,9 +244,9 @@ impl Document { m } - /// World transform of one placement of `component`: the occurrence `path` from the root - /// (empty for the root itself). `None` when the path no longer leads to that component. - pub fn path_transform(&self, component: u64, path: &[u64]) -> Option { + /// One placement: the component the occurrence `path` from the root leads to (the root for + /// an empty path) and its world transform. `None` when the path no longer exists. + pub fn path_placement(&self, path: &[u64]) -> Option<(u64, Mat)> { if path.len() > MAX_PLACEMENT_DEPTH + 1 { return None; } @@ -256,7 +256,7 @@ impl Document { m = mat_mul(&m, &o.transform); c = o.component; } - (c == component).then_some(m) + Some((c, m)) } /// Every placement of each component: (component, occurrence path ids, world transform). diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 742b0bf6f..ef77f1f52 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -685,8 +685,10 @@ pub enum FeatureKind { #[serde(default, skip_serializing_if = "std::ops::Not::not")] combine: bool, /// Where each of `bodies` is mirrored from: the occurrence path of the placement it was - /// picked at. The body is mirrored where that placement shows it, as the feature's own - /// component sees it. Empty in older designs, which mirror the bodies' own geometry. + /// picked at. The body is mirrored where that placement shows it, in the plane of the + /// feature's own component, and its copy joins the body's component (or, when that is + /// placed more than once, the innermost component around it placed once). Empty in older + /// designs, which mirror the bodies' own geometry. #[serde(default, skip_serializing_if = "Vec::is_empty")] placements: Vec>, }, diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index f673c785f..4927c5520 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1284,14 +1284,31 @@ fn placement_digest(doc: &Document, f: &Feature) -> u64 { FeatureKind::Revolve { to, .. } => to.is_some(), _ => false, }; - // A mirror of placed bodies follows where they are placed. - let placed_mirror = matches!(&f.kind, FeatureKind::Mirror { placements, .. } if !placements.is_empty()); + // A mirror of placed bodies follows the placements it was picked at and its own component's + // frame, not every occurrence: moving an unrelated one leaves it (and its cache) alone. + if let FeatureKind::Mirror { placements, bodies, .. } = &f.kind + && !placements.is_empty() + { + let mut h = std::collections::hash_map::DefaultHasher::new(); + doc.component_transform(f.component).iter().flatten().for_each(|x| x.to_bits().hash(&mut h)); + for placed in placements.iter().map(|path| mirror_copy_frame(doc, path)) { + placed.is_some().hash(&mut h); + if let Some((component, frame, picked)) = placed { + component.hash(&mut h); + frame.iter().chain(&picked).flatten().for_each(|x| x.to_bits().hash(&mut h)); + } + } + for b in bodies { + serde_json::to_string(&doc.body_offsets.get(&b.0)).unwrap_or_default().hash(&mut h); + } + return h.finish(); + } // A combine moves tools placed differently from its target into the target's frame (#3383). let combine = matches!(&f.kind, FeatureKind::Combine { .. }); if !to_object && !combine && drawn_tools_change_bodies(&f.kind) { return drawn_tools_digest(doc, f); } - if to_object || placed_mirror || combine { + if to_object || combine { return if doc.occurrences.is_empty() && doc.body_offsets.is_empty() { 0 } else { placements_hash(doc) }; } let FeatureKind::Sketch { plane, sketch } = &f.kind else { return 0 }; @@ -4745,18 +4762,69 @@ fn mirror_matrix(pl: &Plane) -> Mat { const MAX_INSTANCES: usize = 1000; -/// Where a mirrored body is, in the frame of the mirror's component: through the placement it -/// was picked at and the feature's component frame. `None` when that is the body's own frame -/// (and in older designs, which saved no placement). -fn mirrored_placement(doc: &Document, f: &Feature, mb: &ModelBody, path: Option<&[u64]>) -> Result> { +/// Where a mirrored body was picked and where its copy goes: the component the copy joins and +/// that component's world frame, and the frame the body's own geometry is in where it was picked +/// (its placement `path`, with its offset). `None` in older designs, which saved no placement and +/// mirror the body's own geometry. +fn mirrored_placement(doc: &Document, mb: &ModelBody, path: Option<&[u64]>) -> Result> { let Some(path) = path else { return Ok(None) }; - let owner = doc.model_body_component(mb); let lost = || DocError::Invalid(format!("the placement `{}` was mirrored at no longer exists", mb.name)); - let world = doc.path_transform(owner, path).ok_or_else(lost)?; - let world = doc.model_body_offset(mb).map(|offset| crate::mat_mul(&world, offset)).unwrap_or(world); - let inverse = crate::mat_inverse(&doc.component_transform(f.component)).ok_or_else(lost)?; - let rel = crate::mat_mul(&inverse, &world); - Ok((!crate::is_identity(&rel)).then_some(rel)) + // A stale or edited path that leads to another component no longer shows the body. + let (at, _) = doc.path_placement(path).ok_or_else(lost)?; + if !placement_shows(doc, mb, at) { + return Err(lost()); + } + let (component, frame, picked) = mirror_copy_frame(doc, path).ok_or_else(lost)?; + let source = doc.model_body_offset(mb).map(|offset| crate::mat_mul(&picked, offset)).unwrap_or(picked); + Ok(Some((component, frame, source))) +} + +/// Whether a placement of component `at` shows body `mb`: `at` is the body's component. That is +/// the evaluated body's own where a transfer recorded it, else the component its name is recorded +/// in (an import's bodies) or its feature's. Inserting the same file again reuses the body names +/// and points them at the new insert's components: when the recorded component lies outside the +/// components the body's own feature made, the name is another body's, and the placement only has +/// to lie inside the components the body's feature made. +fn placement_shows(doc: &Document, mb: &ModelBody, at: u64) -> bool { + let owner = doc.model_body_component(mb); + if owner == at { + return true; + } + if mb.transferred || mb.source_name.is_some() { + return false; + } + let made_in = doc.feature(mb.feature).map(|f| f.component).unwrap_or(0); + !component_within(doc, owner, made_in) && component_within(doc, at, made_in) +} + +/// Whether component `c` is `ancestor` or lies inside it (every component lies in the root). +fn component_within(doc: &Document, mut c: u64, ancestor: u64) -> bool { + for _ in 0..=doc.components.len() { + if c == ancestor || ancestor == 0 { + return true; + } + match doc.components.iter().find(|x| x.id == c) { + Some(x) if c != 0 => c = x.parent, + _ => return false, + } + } + false +} + +/// For a body mirrored at placement `path` (which, not the body's name, says where it is: a later +/// insert can reuse the name): the component its copy joins, that component's world frame, and +/// the placement's world frame. The copy joins the body's component, or, when that component is +/// placed more than once (a copy there would show at every placement), the innermost component +/// around it that is placed once. +fn mirror_copy_frame(doc: &Document, path: &[u64]) -> Option<(u64, Mat, Mat)> { + let (_, picked) = doc.path_placement(path)?; + let placed_once = |id: &u64| { + let component = doc.occurrences.iter().find(|o| o.id == *id).map(|o| o.component); + doc.occurrences.iter().filter(|o| Some(o.component) == component).count() == 1 + }; + let once = path.iter().take_while(|id| placed_once(id)).count(); + let (component, frame) = doc.path_placement(path.get(..once)?)?; + Some((component, frame, picked)) } /// The placements (column-major matrices) of a pattern's copies, the original excluded. @@ -5790,16 +5858,18 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: for (k, n) in bodies.iter().enumerate() { let i = st.bodies.iter().position(|b| &b.name == n).ok_or_else(|| DocError::Unknown(format!("body `{n}`")))?; let Some(mb) = st.bodies.get(i).cloned() else { continue }; - // A body of a component placed elsewhere is mirrored where it is shown: the copy - // (in this feature's component) from its placement, a joined body in its own frame. - let placed = mirrored_placement(doc, f, &mb, placements.get(k).map(Vec::as_slice))?; - let (copy, own) = match placed { - Some(rel) => { - let inverse = crate::mat_inverse(&rel).ok_or_else(|| DocError::Invalid(format!("the placement of `{n}` is singular")))?; - let copy = crate::mat_mul(&m, &rel); - (copy, crate::mat_mul(&inverse, ©)) + // A body picked where a placement shows it is mirrored there: the copy goes beside + // it into the component that placement shows, a joined body stays in its own frame. + let (component, copy, own) = match mirrored_placement(doc, &mb, placements.get(k).map(Vec::as_slice))? { + Some((component, frame, source)) => { + let singular = || DocError::Invalid(format!("the placement `{n}` was mirrored at is singular")); + let inverse = |m: &Mat| crate::mat_inverse(m).ok_or_else(singular); + // The plane is in this feature's component: the body mirrored in the world. + let here = doc.component_transform(f.component); + let world = crate::mat_mul(&crate::mat_mul(&here, &m), &crate::mat_mul(&inverse(&here)?, &source)); + (Some(component), crate::mat_mul(&inverse(&frame)?, &world), crate::mat_mul(&inverse(&source)?, &world)) } - None => (m, m), + None => (None, m, m), }; let mirrored = moved_copy(&mb, kernel::transform_matrix(&mb.body, if *combine { own } else { copy })?, 1); if *combine { @@ -5822,7 +5892,13 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } else { let name = copy_body_name(st, f, output, &mb.name); copy_sheet(st, &mb.name, &name, ©); - st.bodies.push(ModelBody::traced_new(name, mirrored, f.id)); + let mut body = ModelBody::traced_new(name, mirrored, f.id); + if let Some(c) = component.filter(|c| *c != f.component) { + // Kept in that component as a moved body is (and through later features). + body.component = c; + body.transferred = true; + } + st.bodies.push(body); output += 1; } } diff --git a/crates/doc/src/format/pending/mirror-copies-join-component.rs b/crates/doc/src/format/pending/mirror-copies-join-component.rs new file mode 100644 index 000000000..76c092535 --- /dev/null +++ b/crates/doc/src/format/pending/mirror-copies-join-component.rs @@ -0,0 +1,7 @@ +//! A Mirror of bodies with `placements` puts each copy in the component of the body it mirrors +//! (or, when that component is placed more than once, the innermost component around it placed +//! once) instead of the Mirror's own component; the copy is mirrored at the same placement as +//! before. Nothing new is saved and older designs need no transformation: a Mirror without +//! `placements` mirrors the bodies' own geometry into its own component as before, and one saved +//! with `placements` by 0.15 puts its copies beside their bodies when it is opened. The last +//! release asks for an update instead of opening a design in this format. diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 6664de789..d441131b6 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -1481,22 +1481,26 @@ fn mirror(s: &mut Session, p: &Value) -> Result { /// Bodies picked where the viewport shows them: each world name ("Body1", or "Body1 (Occ:2)" /// for a further instance) becomes its component's body name, with the occurrence path of the -/// placement it was picked at. Names stay as they are (and no placement is kept) while every -/// component is in place, or when one of them is not a body. +/// placement it was picked at (where the copy goes). Names stay as they are, and no placement is +/// kept, while every body is in the active component and every component in place, or when one +/// of them is not a body. fn placed_bodies(s: &Session, names: Vec, cmd: &str) -> Result<(Vec, Vec>)> { - if names.is_empty() || !crate::frames::placed(s) { + if names.is_empty() || s.doc.occurrences.is_empty() { return Ok((names, Vec::new())); } let frames = s.doc.body_frames_with_source(&s.model.state()); let mut picked = Vec::with_capacity(names.len()); for name in &names { - let Some((_, own, _, path, _)) = frames.iter().find(|(world, ..)| world == name) else { return Ok((names, Vec::new())) }; - if path.iter().any(|id| s.pending_moves.contains_key(id)) { - return Err(bad(cmd, format!("`{name}` has a position that is not captured yet: Capture Position (component.capture_position) first"))); - } - picked.push((own.clone(), path.clone())); + let Some((_, own, component, path, _)) = frames.iter().find(|(world, ..)| world == name) else { return Ok((names, Vec::new())) }; + picked.push((own.clone(), *component, path.clone())); } - Ok(picked.into_iter().unzip()) + if !crate::frames::placed(s) && picked.iter().all(|(_, component, _)| *component == s.active_component) { + return Ok((names, Vec::new())); + } + if let Some((name, ..)) = picked.iter().find(|(_, _, path)| path.iter().any(|id| s.pending_moves.contains_key(id))) { + return Err(bad(cmd, format!("`{name}` has a position that is not captured yet: Capture Position (component.capture_position) first"))); + } + Ok(picked.into_iter().map(|(own, _, path)| (own, path)).unzip()) } /// The other name of an origin plane (`Top` for `XY`, `XY` for `Top`...), if `name` is one. diff --git a/crates/engine/src/tests/mirror_placed.rs b/crates/engine/src/tests/mirror_placed.rs index 781fca352..17bcebc5a 100644 --- a/crates/engine/src/tests/mirror_placed.rs +++ b/crates/engine/src/tests/mirror_placed.rs @@ -63,6 +63,12 @@ fn a_further_instance_is_mirrored_at_its_own_placement() { assert_eq!(copies.len(), 2, "{r}"); assert_box(world_box(&s, &copies[0]), mirrored_yz(&s, "ArmBody")); assert_box(world_box(&s, &copies[1]), mirrored_yz(&s, &instance)); + // A component placed twice would show a copy at both placements: the copies join the + // innermost component around it that is placed once, here the design itself. + let st = s.model.state(); + for copy in &copies { + assert_eq!(s.doc.model_body_component(st.body(copy).unwrap()), 0, "{copy}"); + } } #[test] @@ -103,3 +109,123 @@ fn a_position_not_captured_yet_is_refused() { let e = s.execute("solid.mirror", &json!({"bodies": ["ArmBody"], "plane": "YZ"})).unwrap_err().to_string(); assert!(e.contains("Capture Position"), "{e}"); } + +#[test] +fn a_copy_goes_beside_its_source_in_that_component() { + // Moved or in place, a component's mirrored body is a body of that component. + for moved in [true, false] { + let mut s = Session::default(); + let (component, occurrence) = moved_arm(&mut s); + if !moved { + run(&mut s, "occurrence.move", json!({"occurrence": occurrence, "base_transform": solidcraft_doc::IDENTITY})); + } + let copy = created(&run(&mut s, "solid.mirror", json!({"bodies": ["ArmBody"], "plane": "YZ"}))); + let st = s.model.state(); + assert_eq!(s.doc.model_body_component(st.body(©).unwrap()), component, "moved: {moved}"); + assert_box(world_box(&s, ©), mirrored_yz(&s, "ArmBody")); + // It stays there through a later feature on it. + run(&mut s, "solid.move", json!({"bodies": [copy.clone()], "translate": [0, 0, 5]})); + assert_eq!(s.doc.model_body_component(s.model.state().body(©).unwrap()), component, "moved: {moved}"); + } +} + +/// Inserting the same file again reuses its body names; a mirror of the first insert's bodies +/// keeps mirroring them (their copies vanished: the names led to the second insert's components). +#[test] +fn inserting_the_same_file_again_keeps_the_mirrored_copies() { + let dir = std::env::temp_dir().join(format!("solidcraft-mirror-placed-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("nested.step").to_string_lossy().replace('\\', "/"); + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name": "Outer"})); + run(&mut s, "solid.box", json!({"length": 30, "width": 30, "height": 5, "body_name": "Plate"})); + let inner = run(&mut s, "component.create", json!({"name": "Inner"}))["occurrence"].as_u64().unwrap(); + run(&mut s, "solid.box", json!({"length": 40, "width": 20, "height": 10, "body_name": "Block"})); + run(&mut s, "component.activate", json!({"component": 0})); + run(&mut s, "occurrence.move", json!({"occurrence": inner, "axis": [0, 0, 1], "angle": "90 deg", "translate": [100, 0, 0]})); + run(&mut s, "file.export", json!({"path": file})); + + let mut s = Session::default(); + run(&mut s, "file.insert_step", json!({"path": file, "name": "A"})); + let wanted: Vec<(Vec3, Vec3)> = ["Plate", "Block"].iter().map(|b| mirrored_yz(&s, b)).collect(); + let r = run(&mut s, "solid.mirror", json!({"bodies": ["Plate", "Block"], "plane": "YZ"})); + let copies: Vec = r["created_bodies"].as_array().unwrap().iter().map(|n| n.as_str().unwrap().to_string()).collect(); + run(&mut s, "solid.remove", json!({"bodies": ["Plate", "Block"]})); + run(&mut s, "component.from_bodies", json!({"bodies": copies})); + run(&mut s, "file.insert_step", json!({"path": file, "name": "B"})); + let _ = std::fs::remove_dir_all(&dir); + for r in &s.model.results { + assert!(r.error.is_none(), "{}: {:?}", r.name, r.error); + } + for (copy, want) in copies.iter().zip(wanted) { + assert_box(world_box(&s, copy), want); + } +} + +/// Moving an occurrence the mirror does not depend on leaves the mirror alone: before, any +/// occurrence move evaluated it again, and every later command paid for one more mirror. +#[test] +fn moving_an_unrelated_occurrence_does_not_evaluate_the_mirror_again() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 5, "corner": [10, 0, 0], "body_name": "A"})); + run(&mut s, "solid.box", json!({"length": 8, "width": 8, "height": 8, "corner": [30, 0, 0], "body_name": "B"})); + run(&mut s, "component.from_bodies", json!({"bodies": ["A", "B"]})); + let occurrences: Vec = s.doc.occurrences.iter().map(|o| o.id).collect(); + assert_eq!(occurrences.len(), 2, "{:?}", s.doc.occurrences); + let a = s.doc.body_frames(&s.model.state()).into_iter().find(|(name, ..)| name == "A").map(|(_, _, path, _)| path).unwrap(); + let (mine, other) = if a.contains(&occurrences[0]) { (occurrences[0], occurrences[1]) } else { (occurrences[1], occurrences[0]) }; + run(&mut s, "occurrence.move", json!({"occurrence": mine, "translate": [0, 5, 0]})); + let copy = created(&run(&mut s, "solid.mirror", json!({"bodies": ["A"], "plane": "YZ"}))); + for _ in 0..3 { + run(&mut s, "occurrence.move", json!({"occurrence": other, "translate": [0, 0.1, 0]})); + assert_eq!(s.model.last_recomputed, 0, "an unrelated move evaluated features again"); + } + // Moving the mirrored body's own occurrence does evaluate it, and the copy follows. + run(&mut s, "occurrence.move", json!({"occurrence": mine, "translate": [0, 1, 0]})); + assert!(s.model.last_recomputed > 0); + assert_box(world_box(&s, ©), mirrored_yz(&s, "A")); +} + +/// Two mirrored copies of overlapping bodies of a placed component intersect as their sources do. +#[test] +fn mirrored_copies_of_a_placed_component_intersect() { + let mut s = Session::default(); + let c = run(&mut s, "component.create", json!({"name": "Pair"})); + let occurrence = c["occurrence"].as_u64().unwrap(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [10, 0, 0], "body_name": "P"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [15, 5, 5], "body_name": "Q"})); + run(&mut s, "component.activate", json!({"component": 0})); + run(&mut s, "occurrence.move", json!({"occurrence": occurrence, "axis": [0, 0, 1], "angle": "30 deg", "translate": [5, 20, 0]})); + let r = run(&mut s, "solid.mirror", json!({"bodies": ["P", "Q"], "plane": "YZ"})); + let copies: Vec = r["created_bodies"].as_array().unwrap().iter().map(|n| n.as_str().unwrap().to_string()).collect(); + let i = run(&mut s, "inspect.interference", json!({})); + let pair = i["interferences"].as_array().unwrap().iter().find(|x| x["a"] == copies[0].as_str() || x["b"] == copies[0].as_str()).cloned(); + let pair = pair.unwrap_or_else(|| panic!("{i}")); + assert!((pair["volume_mm3"].as_f64().unwrap() - 125.0).abs() < 1e-6, "{i}"); + run(&mut s, "solid.combine", json!({"target": copies[0], "tools": [copies[1]], "operation": "intersect", "keep_tools": true})); + let v = run(&mut s, "inspect.measure", json!({"bodies": [copies[0]]}))["total"]["volume_mm3"].as_f64().unwrap(); + assert!((v - 125.0).abs() < 1e-6, "{v}"); +} + +/// A saved placement that leads to another component (a stale or edited path) no longer shows the +/// mirrored body: the mirror reports that, instead of mirroring it where the other one is placed. +#[test] +fn a_placement_leading_to_another_component_is_reported_lost() { + let mut s = Session::default(); + moved_arm(&mut s); + let other = run(&mut s, "component.create", json!({"name": "Other"}))["occurrence"].as_u64().unwrap(); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "body_name": "OtherBody"})); + run(&mut s, "component.activate", json!({"component": 0})); + run(&mut s, "occurrence.move", json!({"occurrence": other, "translate": [-500, 0, 0]})); + let copy = created(&run(&mut s, "solid.mirror", json!({"bodies": ["ArmBody"], "plane": "YZ"}))); + let mirror = s.doc.features.last().unwrap().id; + if let Some(f) = std::sync::Arc::make_mut(&mut s.doc).feature_mut(mirror) + && let solidcraft_doc::FeatureKind::Mirror { placements, .. } = &mut f.kind + { + *placements = vec![vec![other]]; + } + s.refresh(); + let e = s.model.result(mirror).and_then(|r| r.error.clone()).unwrap_or_else(|| panic!("mirrored at the wrong placement")); + assert!(e.contains("no longer exists"), "{e}"); + assert!(s.world_state().body(©).is_none()); +} From 5e05d925e07c0486e92f6e981a66178dcdc311ad Mon Sep 17 00:00:00 2001 From: amolinari-autotex Date: Wed, 21 Oct 2026 18:56:38 +0000 Subject: [PATCH 02/25] Tapped Hole: keep Custom selection and edit nominal diameter (#2440) (#2441) * claim: #2440 * feat: choose ISO metric tapped-hole sizes and derive the drill diameter * fix: label the tap drill and hide the unused diameter editor * test: cover tapped hole catalogue and drill sizing * fix: omit coarse metric pitch from generated designations * Keep custom tapped-hole nominal diameter and pitch editable Preserve Custom as dialog state, derive the existing metric designation from numeric inputs, and refuse invalid drafts without applying the last valid size. Retain manual text editing, physical tap-drill geometry and saved-design compatibility. * fix(i18n): register custom tapped hole labels in source catalogs * Adapt tapped-hole Custom fields to the current form kit * fix: preserve tapped designation focus with dynamic custom rows --- assets/locales/en.json | 4 + assets/locales/it.json | 3 + assets/locales/ja.json | 4 + assets/locales/zh.json | 4 + crates/ui-egui/src/dialogs.rs | 25 +- crates/ui-egui/src/dialogs_dense.rs | 6 +- crates/ui-egui/src/dialogs_thread.rs | 371 +++++++++++++++++++++++++- crates/ui-egui/src/preselect_tests.rs | 5 +- docs/thread-designations.md | 7 + 9 files changed, 418 insertions(+), 11 deletions(-) create mode 100644 docs/thread-designations.md diff --git a/assets/locales/en.json b/assets/locales/en.json index 35de93051..9d184597a 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -102,6 +102,7 @@ "Curv. Comb": "Curv. Comb", "Curvature (G2)": "Curvature (G2)", "Curvature change (G3)": "Curvature change (G3)", + "Custom": "Custom", "Customize Toolbar": "Customize Toolbar", "Delete": "Delete", "Delete all": "Delete all", @@ -233,6 +234,7 @@ "No matching appearance presets.": "No matching appearance presets.", "No matching appearances": "No matching appearances", "No visible bodies to export.": "No visible bodies to export.", + "Nominal diameter": "Nominal diameter", "None": "None", "Not available yet": "Not available yet", "Notch": "Notch", @@ -256,6 +258,7 @@ "Pick the tool bodies": "Pick the tool bodies", "Picked": "Picked", "Picked point": "Picked point", + "Pitch": "Pitch", "Place at the origin instead": "Place at the origin instead", "Plastic Rules": "Plastic Rules", "Playback": "Playback", @@ -361,6 +364,7 @@ "TRIM": "TRIM", "Tangent (G1)": "Tangent (G1)", "Tangent Chain": "Tangent Chain", + "Tap drill diameter": "Tap drill diameter", "Tear": "Tear", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.", "The saved author occurrence is missing. Select a valid author placement before rebinding.": "The saved author occurrence is missing. Select a valid author placement before rebinding.", diff --git a/assets/locales/it.json b/assets/locales/it.json index 233e5846f..76bc619d3 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -102,6 +102,7 @@ "Curv. Comb": "Pettine curv.", "Curvature (G2)": "Curvatura (G2)", "Curvature change (G3)": "Variazione di curvatura (G3)", + "Custom": "Personalizzato", "Customize Toolbar": "Personalizza barra degli strumenti", "Delete": "Elimina", "Delete all": "Elimina tutto", @@ -233,6 +234,7 @@ "No matching appearance presets.": "Nessun predefinito di aspetto corrispondente.", "No matching appearances": "Nessun aspetto corrispondente", "No visible bodies to export.": "Nessun corpo visibile da esportare.", + "Nominal diameter": "Diametro nominale", "None": "Nessuno", "Not available yet": "Non ancora disponibile", "Notch": "Intaglio", @@ -256,6 +258,7 @@ "Pick the tool bodies": "Seleziona i corpi utensile", "Picked": "Selezionato", "Picked point": "Punto selezionato", + "Pitch": "Passo", "Place at the origin instead": "Posiziona invece nell'origine", "Plastic Rules": "Regole per plastica", "Playback": "Riproduzione", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 7b64c07d6..7a80e4b68 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -102,6 +102,7 @@ "Curv. Comb": "曲率コーム", "Curvature (G2)": "曲率 (G2)", "Curvature change (G3)": "曲率変化 (G3)", + "Custom": "カスタム", "Customize Toolbar": "ツールバーのカスタマイズ", "Delete": "削除", "Delete all": "すべて削除", @@ -233,6 +234,7 @@ "No matching appearance presets.": "一致する外観プリセットはありません。", "No matching appearances": "一致する外観がありません", "No visible bodies to export.": "出力する表示中のボディがありません。", + "Nominal diameter": "呼び径", "None": "なし", "Not available yet": "まだ利用できません", "Notch": "ノッチ", @@ -256,6 +258,7 @@ "Pick the tool bodies": "ツールボディを選択", "Picked": "選択したもの", "Picked point": "選択した点", + "Pitch": "ピッチ", "Place at the origin instead": "代わりに原点に配置", "Plastic Rules": "樹脂ルール", "Playback": "再生", @@ -361,6 +364,7 @@ "TRIM": "トリム", "Tangent (G1)": "接線 (G1)", "Tangent Chain": "正接チェーン", + "Tap drill diameter": "タップ下穴径", "Tear": "引き裂き", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "破線のスケッチは保存された平面ガイドです。新しい面を選択してアタッチメントを修復してください。", "The saved author occurrence is missing. Select a valid author placement before rebinding.": "保存された作成元のオカレンスが見つかりません。再バインドする前に有効な作成元配置を選択してください。", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index f6851834b..ac79a95c7 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -102,6 +102,7 @@ "Curv. Comb": "曲率梳", "Curvature (G2)": "曲率 (G2)", "Curvature change (G3)": "曲率变化 (G3)", + "Custom": "自定义", "Customize Toolbar": "自定义工具栏", "Delete": "删除", "Delete all": "全部删除", @@ -233,6 +234,7 @@ "No matching appearance presets.": "没有匹配的外观预设。", "No matching appearances": "没有匹配的外观", "No visible bodies to export.": "没有可导出的可见实体。", + "Nominal diameter": "公称直径", "None": "无", "Not available yet": "暂不可用", "Notch": "缺口", @@ -256,6 +258,7 @@ "Pick the tool bodies": "选择工具实体", "Picked": "所选", "Picked point": "选取的点", + "Pitch": "螺距", "Place at the origin instead": "改为放置在原点", "Plastic Rules": "塑料规则", "Playback": "播放", @@ -361,6 +364,7 @@ "TRIM": "修剪", "Tangent (G1)": "相切 (G1)", "Tangent Chain": "相切链", + "Tap drill diameter": "攻丝底孔直径", "Tear": "撕裂", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "虚线草图是已保存的平面引导。选择一个新面以修复附着。", "The saved author occurrence is missing. Select a valid author placement before rebinding.": "保存的作者实例缺失。重新绑定前请选择有效的作者放置。", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f331fda05..69b83ca21 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -386,11 +386,13 @@ pub struct HoleOpts { /// Tap type: tapped (a cosmetic thread) instead of simple. pub tapped: bool, pub thread: String, + /// Custom nominal diameter and pitch being edited, separate from the saved designation. + pub custom_thread: Option, } impl Default for HoleOpts { fn default() -> Self { - HoleOpts { multiple: false, all: false, angled: true, tip_angle: "118 deg".into(), tapped: false, thread: "M5".into() } + HoleOpts { multiple: false, all: false, angled: true, tip_angle: "118 deg".into(), tapped: false, thread: "M5".into(), custom_thread: None } } } @@ -851,7 +853,9 @@ impl Dialog { } *of = picks.to_vec(); *suggested = picks.first().and_then(|sel| match sel { - Sel::Face { point, .. } => solidcraft_engine::doc::suggested_thread(&s.world_state(), *point).ok(), + Sel::Face { point, .. } => solidcraft_engine::doc::suggested_thread(&s.world_state(), *point).ok().map(|value| { + solidcraft_engine::doc::parse_metric_thread(&value).map(|(d, p)| crate::dialogs_thread::designation(d, p)).unwrap_or(value) + }), _ => None, }); *designation = suggested.clone().unwrap_or_default(); @@ -949,7 +953,12 @@ impl Dialog { } Kind::Shell { thickness } => ("Thickness", ValueKind::Length, thickness), Kind::Draft { angle } => ("Angle", ValueKind::Angle, angle), - Kind::Hole { diameter, .. } => ("Diameter", ValueKind::Length, diameter), + Kind::Hole { diameter, opts, .. } => { + if opts.tapped { + return None; + } + ("Diameter", ValueKind::Length, diameter) + } // A move's main value follows its type: a distance along X for the ones that // translate, the angle for Rotate. Point to Point is two picks with nothing to type. Kind::Move { mode, x, angle, .. } => match *mode { @@ -3607,7 +3616,9 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S let mut out = Vec::new(); for place in places { let mut params = place; - params["diameter"] = json!(diameter); + if !opts.tapped { + params["diameter"] = json!(diameter); + } params["type"] = json!(ty); if to_object_on(&d.inputs) { params["to"] = to_object_point(&d.inputs).ok_or("select the object to drill to")?; @@ -3617,7 +3628,11 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S if ty == "drilled" { params["tip_angle"] = json!(opts.tip_angle); } - if opts.tapped && !opts.thread.trim().is_empty() { + if opts.tapped { + if let Some(error) = opts.custom_thread.as_ref().and_then(|draft| draft.error.as_ref()) { + return Err(error.clone()); + } + solidcraft_engine::doc::parse_metric_thread(&opts.thread).ok_or("select a valid metric thread size")?; params["thread"] = json!(opts.thread.trim()); } match *kind { diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 3ed097db7..a58e1d511 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -511,7 +511,7 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: opts.tapped = tap == 1; }); if opts.tapped { - enter |= expr_row(ui, "Size", &mut opts.thread); + enter |= crate::dialogs_thread::hole_rows(ui, &app.session.doc, &mut opts.thread, &mut opts.custom_thread); } if *kind == 0 { form_row(ui, "Drill Point", |ui| { @@ -526,7 +526,9 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: if *kind == 0 && opts.angled { enter |= expr_row(ui, "Tip Angle", &mut opts.tip_angle); } - enter |= expr_row(ui, "Diameter", diameter); + if !opts.tapped { + enter |= expr_row(ui, "Diameter", diameter); + } if *kind == 1 { enter |= expr_row(ui, "Counterbore Ø", cb_diameter); enter |= expr_row(ui, "Counterbore depth", cb_depth); diff --git a/crates/ui-egui/src/dialogs_thread.rs b/crates/ui-egui/src/dialogs_thread.rs index f765c4c3c..a680fa6fb 100644 --- a/crates/ui-egui/src/dialogs_thread.rs +++ b/crates/ui-egui/src/dialogs_thread.rs @@ -1,7 +1,7 @@ //! Metric thread choices use the document's sizing table and the existing designation //! parameter. Browsing choices does not edit the model or freeze an automatic feature. -use solidcraft_engine::doc::{metric_thread_sizes, parse_metric_thread}; +use solidcraft_engine::doc::{Document, metric_thread_sizes, parse_metric_thread}; use crate::dialogs::{combo, form_row}; use crate::i18n::tr; @@ -11,6 +11,109 @@ use crate::ui_kit::text_row; /// The coarse and current pitches are included separately; custom pairs remain editable. const PITCHES: &[f64] = &[0.2, 0.25, 0.35, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0]; +/// Generated metric designations omit only the shared catalogue's coarse pitch. +/// Authored designation text is never rewritten just by displaying a dialog. +pub(crate) fn designation(diameter: f64, pitch: f64) -> String { + let coarse = metric_thread_sizes().iter().any(|(d, p)| (d - diameter).abs() < 1e-9 && (p - pitch).abs() < 1e-9); + if coarse { format!("M{diameter}") } else { format!("M{diameter}x{pitch}") } +} + +/// Unsaved numeric inputs for a custom metric designation. The document still stores only +/// the existing designation; an invalid draft must not apply its last valid value. +#[derive(Clone, Debug, PartialEq)] +pub struct HoleThreadDraft { + source: String, + diameter: String, + pitch: String, + pub(crate) error: Option, +} + +impl HoleThreadDraft { + fn new(source: &str) -> Self { + let (diameter, pitch) = match parse_metric_thread(source) { + Some((d, p)) => (format!("{d} mm"), format!("{p} mm")), + None => (String::new(), String::new()), + }; + Self { source: source.into(), diameter, pitch, error: None } + } + + fn update(&mut self, doc: &Document, authored: &mut String) { + let candidate = || -> Result { + let d = doc.eval(&self.diameter, solidcraft_engine::doc::expr::Kind::Length).map_err(|e| format!("nominal diameter: {e}"))?; + let p = doc.eval(&self.pitch, solidcraft_engine::doc::expr::Kind::Length).map_err(|e| format!("pitch: {e}"))?; + let text = designation(d, p); + parse_metric_thread(&text).ok_or("use a positive nominal diameter and a pitch smaller than it")?; + Ok(text) + }; + match candidate() { + Ok(text) => { + *authored = text; + self.source = authored.clone(); + self.error = None; + } + Err(error) => self.error = Some(error), + } + } +} + +/// Tapped holes use the existing metric catalogue; the engine derives the tap drill. +/// Custom remains a dialog mode even when its current values match a catalogue size. +pub(crate) fn hole_rows(ui: &mut egui::Ui, doc: &Document, designation: &mut String, custom: &mut Option) -> bool { + let designation_id = ui.make_persistent_id("hole_thread_designation"); + form_row(ui, "Profile", |ui| { + ui.label(tr("ISO metric")); + }); + + let sizes = metric_thread_sizes(); + let current = parse_metric_thread(designation); + let catalogue = current.and_then(|pair| sizes.iter().position(|s| *s == pair)); + if custom.as_ref().is_some_and(|draft| draft.source != *designation) || (custom.is_none() && catalogue.is_none()) { + *custom = Some(HoleThreadDraft::new(designation)); + } + form_row(ui, "Size", |ui| { + let mut selected = if custom.is_some() { sizes.len() } else { catalogue.unwrap_or(sizes.len()) }; + let before = selected; + let mut labels: Vec = sizes.iter().map(|(d, p)| self::designation(*d, *p)).collect(); + labels.push("Custom".to_string()); + let labels: Vec<&str> = labels.iter().map(String::as_str).collect(); + combo(ui, "hole_thread_catalogue", &labels, &mut selected); + if selected != before { + if let Some((d, p)) = sizes.get(selected) { + *designation = self::designation(*d, *p); + *custom = None; + } else { + *custom = Some(HoleThreadDraft::new(designation)); + } + } + }); + + let mut enter = false; + if let Some(draft) = custom { + let (diameter_enter, diameter_changed) = text_row(ui, "Nominal diameter", &mut draft.diameter, ""); + let (pitch_enter, pitch_changed) = text_row(ui, "Pitch", &mut draft.pitch, ""); + if diameter_changed || pitch_changed { + draft.update(doc, designation); + } + enter |= diameter_enter || pitch_enter; + } + + let response = form_row(ui, "Designation", |ui| crate::ui_kit::cell_editor(ui, designation_id, designation, "M5 or M5x0.5", false)); + if response.changed() && custom.is_some() { + *custom = Some(HoleThreadDraft::new(designation)); + } + form_row(ui, "Tap drill diameter", |ui| { + match parse_metric_thread(designation).filter(|_| custom.as_ref().is_none_or(|draft| draft.error.is_none())) { + Some((d, p)) => { + ui.label(format!("{:.3} mm", d - p)); + } + None => { + ui.label(tr("Select size")); + } + } + }); + enter || (response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) +} + /// Returns (Enter pressed, automatic sizing requested). pub(crate) fn rows(ui: &mut egui::Ui, designation: &mut String, suggested: &mut Option, modeled: &mut bool, full: &mut bool) -> (bool, bool) { form_row(ui, "Profile", |ui| { @@ -54,7 +157,7 @@ pub(crate) fn rows(ui: &mut egui::Ui, designation: &mut String, suggested: &mut && let Some(d) = diameters.get(selected) && let Some((_, coarse)) = metric_thread_sizes().iter().find(|(n, _)| n == d) { - *designation = format!("M{d}x{coarse}"); + *designation = self::designation(*d, *coarse); *suggested = None; } }); @@ -79,7 +182,7 @@ pub(crate) fn rows(ui: &mut egui::Ui, designation: &mut String, suggested: &mut if selected != before && let (Some((d, _)), Some(p)) = (current, pitches.get(selected)) { - *designation = format!("M{d}x{p}"); + *designation = self::designation(d, *p); *suggested = None; } }); @@ -94,3 +197,265 @@ pub(crate) fn rows(ui: &mut egui::Ui, designation: &mut String, suggested: &mut } (enter, reset) } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod contribution_tests { + use super::*; + use crate::{ + Services, SolveApp, + dialogs::{Dialog, Kind, apply_commands}, + }; + use serde_json::json; + use solidcraft_engine::{Sel, Session, geom::Vec3}; + fn hole() -> (SolveApp, Dialog) { + let mut app = SolveApp::new(Session::default(), Services::default()); + app.run("solid.box", json!({"length":20,"width":20,"height":10,"body_name":"Plate"})).unwrap(); + app.session.selection = vec![Sel::Face { body: "Plate".into(), index: 5, point: Vec3::new(10.0, 10.0, 10.0) }]; + let d = Dialog::for_command(&app, "solid.hole").unwrap(); + (app, d) + } + fn custom_hole_widget() -> crate::scenario::Harness { + let (app, dialog) = hole(); + let mut h = crate::scenario::Harness::new(); + h.app = app; + h.app.dialog = Some(dialog); + h.frames(3); + h.step(&json!({"click":{"handle":"dialog:Hole Tap Type"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Hole Tap Type:Tapped"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Size"}})).unwrap(); + let at = crate::scenario::handle_at("dialog:Size:M5").unwrap(); + h.call("ui.scroll", json!({"x":at.x,"y":at.y,"delta":-2000})); + h.frames(20); + h.step(&json!({"widget":"Custom"})).unwrap(); + h.frames(3); + h + } + + fn replace_field(h: &mut crate::scenario::Harness, field: &str, value: &str) { + h.step(&json!({"click":{"handle":format!("dialog:{field}")}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":value})).unwrap(); + h.frames(2); + } + + #[test] + fn custom_tapped_size_keeps_its_choice_and_exposes_nominal_diameter() { + let h = custom_hole_widget(); + assert!(h.widget("Custom").is_some(), "Custom must remain the selected size after the popup closes"); + assert!(crate::scenario::handle_at("dialog:Nominal diameter").is_some(), "a custom tapped hole needs an editable nominal diameter"); + let card = crate::scenario::rect_of("dialog:card").unwrap(); + for label in ["Profile", "Size", "Nominal diameter", "Pitch", "Designation", "Tap drill diameter"] { + let row = crate::scenario::rect_of(&format!("dialog:row:{label}")).unwrap(); + let control = crate::scenario::rect_of(&format!("dialog:control:{label}")).unwrap(); + assert_eq!(row.height(), crate::theme::Tokens::get().control_height, "{label}"); + assert!(card.contains_rect(row) && row.contains_rect(control), "{label}: {row:?} {control:?} outside {card:?}"); + } + } + + #[test] + fn custom_nominal_diameter_and_pitch_change_the_real_hole_and_reopen() { + let mut h = custom_hole_widget(); + replace_field(&mut h, "Nominal diameter", "8.5 mm"); + replace_field(&mut h, "Pitch", "1 mm"); + let commands = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["thread"], "M8.5x1"); + assert!(commands[0].1.get("diameter").is_none(), "the nominal size must reach the engine through the thread designation"); + h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap(); + h.frames(3); + assert!(h.app.dialog.is_none()); + let faces = h.app.run("model.faces", json!({"body":"Plate"})).unwrap(); + assert!( + faces["faces"].as_array().unwrap().iter().any(|face| { face["cylinder"]["radius"].as_f64().is_some_and(|r| (r - 3.75).abs() < 1e-9) }), + "the physical tap drill must be 8.5 - 1 = 7.5 mm" + ); + let saved = h.app.session.doc.to_json(); + let reopened = Session::new(Document::from_json(&saved).unwrap()); + let world = reopened.world_state(); + assert_eq!(world.threads.len(), 1); + assert_eq!(world.threads[0].designation, "M8.5x1"); + assert!((world.threads[0].pitch - 1.).abs() < 1e-9); + } + + #[test] + fn an_invalid_custom_pitch_blocks_the_old_valid_size_and_cancel_keeps_the_model() { + let mut h = custom_hole_widget(); + let before = h.app.session.doc.to_json(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + replace_field(&mut h, "Pitch", "5 mm"); + assert!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).is_err()); + assert_eq!(crate::scenario::count_of("dialog:ok:enabled"), Some(0.0)); + h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap(); + assert!(h.app.dialog.is_some(), "an invalid custom draft must keep the dialog open"); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(h.app.dialog.is_none()); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + } + + #[test] + fn manual_designation_keeps_keyboard_focus_when_custom_fields_appear() { + let (app, dialog) = hole(); + let mut h = crate::scenario::Harness::new(); + h.app = app; + h.app.dialog = Some(dialog); + h.frames(3); + h.step(&json!({"click":{"handle":"dialog:Hole Tap Type"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Hole Tap Type:Tapped"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Designation"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + for text in ["M", "8", "x", "1"] { + h.step(&json!({"text":text})).unwrap(); + h.frames(2); + } + assert_eq!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap()[0].1["thread"], "M8x1"); + assert!(crate::scenario::handle_at("dialog:Nominal diameter").is_some()); + } + + #[test] + fn custom_lengths_use_explicit_units_and_invalid_drafts_never_apply_stale_values() { + let (mut app, mut dialog) = hole(); + app.run("document.units", json!({"units":"in"})).unwrap(); + let Kind::Hole { opts, .. } = &mut dialog.kind else { panic!("not a hole") }; + opts.tapped = true; + opts.all = true; + let mut draft = HoleThreadDraft::new(&opts.thread); + draft.diameter = "0.25 in".into(); + draft.pitch = "0.05 in".into(); + draft.update(&app.session.doc, &mut opts.thread); + assert!(draft.error.is_none()); + let (d, p) = parse_metric_thread(&opts.thread).unwrap(); + assert!((d - 6.35).abs() < 1e-9 && (p - 1.27).abs() < 1e-9); + opts.custom_thread = Some(draft); + let commands = apply_commands(&app, &dialog).unwrap(); + app.run(&commands[0].0, commands[0].1.clone()).unwrap(); + let Kind::Hole { opts, .. } = &mut dialog.kind else { panic!("not a hole") }; + for invalid in ["", "0", "-1 mm", "unknown_size", "NaN"] { + let draft = opts.custom_thread.as_mut().unwrap(); + draft.diameter = invalid.into(); + draft.update(&app.session.doc, &mut opts.thread); + assert!(draft.error.is_some(), "{invalid}"); + } + assert!(apply_commands(&app, &dialog).is_err()); + } + #[test] + fn contribution_tapped_holes_derive_the_drill_from_the_catalogue() { + for (designation, expected) in [("M5", 4.2), ("M6x1", 5.0), ("M5x0.5", 4.5)] { + let (mut app, mut d) = hole(); + if let Kind::Hole { diameter, opts, .. } = &mut d.kind { + *diameter = "17 mm".into(); + opts.tapped = true; + opts.all = true; + opts.thread = designation.into(); + } + assert!(d.primary().is_none(), "no independent diameter editor for a tapped hole"); + let commands = apply_commands(&app, &d).unwrap(); + let (id, p) = &commands[0]; + assert!(p.get("diameter").is_none()); + assert_eq!(p["thread"], designation); + let out = app.run(id, p.clone()).unwrap(); + let f = app.session.doc.feature(out["feature"].as_u64().unwrap()).unwrap(); + let solidcraft_engine::doc::FeatureKind::Hole { diameter, .. } = &f.kind else { panic!("not a Hole") }; + let drill = app.session.doc.eval(diameter, solidcraft_engine::doc::expr::Kind::Length).unwrap(); + assert!((drill - expected).abs() < 1e-9, "{designation}: {drill}"); + } + } + #[test] + fn contribution_invalid_tapped_holes_are_refused_and_plain_holes_keep_diameter() { + let (app, mut d) = hole(); + assert!(d.primary().is_some()); + assert!(apply_commands(&app, &d).unwrap()[0].1.get("diameter").is_some()); + for designation in ["", "M0", "M5x5", "M5xNaN", "not a thread"] { + if let Kind::Hole { opts, .. } = &mut d.kind { + opts.tapped = true; + opts.thread = designation.into(); + } + assert!(apply_commands(&app, &d).is_err(), "{designation}"); + } + } + #[test] + fn contribution_thread_catalogue_is_parseable_and_rendering_keeps_custom_designations() { + for (d, p) in metric_thread_sizes() { + assert_eq!(parse_metric_thread(&format!("M{d}")), Some((*d, *p))); + assert_eq!(parse_metric_thread(&format!("M{d}x{p}")), Some((*d, *p))); + } + let ctx = egui::Context::default(); + for original in ["M5", "M5x0.5", "M33x1", "invalid"] { + let mut designation = original.to_string(); + let mut custom = None; + let doc = Document::default(); + let _ = ctx.run_ui(Default::default(), |ui| { + egui::Grid::new("hole_catalogue").show(ui, |ui| { + hole_rows(ui, &doc, &mut designation, &mut custom); + }); + }); + assert_eq!(designation, original); + } + } + + #[test] + fn contribution_metric_designation_omits_only_the_catalogue_coarse_pitch() { + for &(d, p) in metric_thread_sizes() { + assert_eq!(designation(d, p), format!("M{d}")); + assert_eq!(parse_metric_thread(&designation(d, p)), Some((d, p))); + assert_eq!(parse_metric_thread(&designation(d, p / 2.)), Some((d, p / 2.))); + assert!(designation(d, p / 2.).contains('x')); + } + assert_eq!(designation(8., 1.25), "M8"); + assert_eq!(designation(8., 1.), "M8x1"); + assert_eq!(designation(5., 0.5), "M5x0.5"); + assert_eq!(designation(33., 1.), "M33x1"); + assert_eq!(designation(8., 1.25 + 1e-12), "M8"); + assert!(designation(8., 1.25 + 1e-6).contains('x')); + } + + #[test] + fn contribution_metric_designation_rendering_preserves_authored_legacy_and_custom_text() { + let context = egui::Context::default(); + crate::fonts::setup_bundled_fonts(&context); + for original in ["M8x1.25", "M8x1", "M33x1", "M5×0.5", " m8x1.25 ", "invalid"] { + let mut hole = original.to_string(); + let mut thread = original.to_string(); + let mut suggested = None; + let mut modeled = false; + let mut full = true; + let mut custom = None; + let doc = Document::default(); + let _ = context.run_ui(Default::default(), |ui| { + egui::Grid::new("authored_hole").show(ui, |ui| { + hole_rows(ui, &doc, &mut hole, &mut custom); + }); + egui::Grid::new("authored_thread").show(ui, |ui| { + rows(ui, &mut thread, &mut suggested, &mut modeled, &mut full); + }); + }); + assert_eq!(hole, original); + assert_eq!(thread, original); + } + } + + #[test] + fn contribution_metric_designation_keeps_domain_pitch_drill_units_and_reopen() { + for (diameter, pitch, drill) in [(8., 1.25, 6.75), (8., 1., 7.), (5., 0.5, 4.5)] { + let (mut app, mut dialog) = hole(); + app.run("document.units", json!({"units":"in"})).unwrap(); + if let Kind::Hole { opts, .. } = &mut dialog.kind { + opts.tapped = true; + opts.all = true; + opts.thread = designation(diameter, pitch); + } + let commands = apply_commands(&app, &dialog).unwrap(); + let result = app.run(&commands[0].0, commands[0].1.clone()).unwrap(); + let feature = app.session.doc.feature(result["feature"].as_u64().unwrap()).unwrap(); + let solidcraft_engine::doc::FeatureKind::Hole { diameter, .. } = &feature.kind else { panic!("not a hole") }; + assert!((app.session.doc.eval(diameter, solidcraft_engine::doc::expr::Kind::Length).unwrap() - drill).abs() < 1e-9); + let saved = app.session.doc.to_json(); + let reopened = Session::new(solidcraft_engine::doc::Document::from_json(&saved).unwrap()); + let state = reopened.world_state(); + assert_eq!(state.threads.len(), 1); + assert!((state.threads[0].pitch - pitch).abs() < 1e-9); + } + } +} diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index 85c2daef9..9d62a25af 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -1361,7 +1361,10 @@ fn thread_choices_can_start_without_a_face_and_recover_from_invalid_text() { h.call("ui.scroll", json!({"x":first.x,"y":first.y,"delta":-60})); h.frames(12); h.step(&json!({"click":{"handle":"dialog:Size:8 mm"}})).unwrap(); - assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Thread { designation, .. } if designation == "M8x1.25")); + assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Thread { designation, .. } if designation == "M8")); + if let Kind::Thread { designation, .. } = &h.app.dialog.as_ref().unwrap().kind { + assert_eq!(solidcraft_engine::doc::parse_metric_thread(designation), Some((8.0, 1.25))); + } assert!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).is_err(), "a face is still required"); } diff --git a/docs/thread-designations.md b/docs/thread-designations.md new file mode 100644 index 000000000..f27a93eaf --- /dev/null +++ b/docs/thread-designations.md @@ -0,0 +1,7 @@ +# Metric thread designations + +Generated size choices use the shared metric catalogue. Its coarse pitch is omitted from the designation: **M8** means diameter 8 mm and coarse pitch 1.25 mm. A fine or custom pitch remains explicit, for example **M8x1**. Hole catalogue choices and generated Thread size/pitch choices follow the same rule. + +This changes generated UI text, not the resolved numerical pitch or geometry. Existing authored designation text, including explicit legacy coarse pitches, is retained when a dialog is merely displayed. Custom and fine designations remain editable. Catalogue dimensions are millimetres regardless of the design's display units. + +Tapped Hole continues to derive its existing tap-drill diameter from nominal diameter minus pitch: M8 gives 6.75 mm, while M8x1 gives 7 mm. Saving and reopening retains the resolved pitch. Only the currently supported ISO metric family is offered; other thread families and a complete fine-pitch catalogue are not added by this change. From 57c3e94df6336675c977994de1c85c412e04f958 Mon Sep 17 00:00:00 2001 From: phanoob Date: Wed, 21 Oct 2026 18:56:39 +0000 Subject: [PATCH 03/25] Parameters: a new parameter's expression starts blank, and Tab selects a field (#2919) (#3096) * claim: #2919 Co-Authored-By: Claude Opus 5.5 * Parameters: a new parameter's expression starts blank, and Tab selects a box of the add row (#2919) Co-Authored-By: Claude Opus 5.5 * Parameters tests: the add row's blank expression in the manage dialog tests (#2919) The two inventory tests typed a name and pressed Enter, counting on the 10 mm the expression used to start with; they now type it. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Phanoob Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/manage_dialogs_tests.rs | 7 +- crates/ui-egui/src/params_dialog.rs | 82 +++++++++++++++++++--- crates/ui-egui/tests/parameter_enter.rs | 6 ++ 3 files changed, 85 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/manage_dialogs_tests.rs b/crates/ui-egui/src/manage_dialogs_tests.rs index aacd94d3c..47eecd921 100644 --- a/crates/ui-egui/src/manage_dialogs_tests.rs +++ b/crates/ui-egui/src/manage_dialogs_tests.rs @@ -296,8 +296,11 @@ fn parameter_inventory_remains_reachable_with_regular_draft_rows() { for label in ["name", "unit", "expression", "comment"] { assert!(scenario::handle_at(&format!("param:new:{label}")).is_some()); } - assert_eq!(h.app.params.as_ref().unwrap().new_expr, "10 mm"); + assert_eq!(h.app.params.as_ref().unwrap().new_expr, "", "a new parameter's expression starts blank (#2919)"); h.step(&json!({"text":"pitch"})).unwrap(); + // Enter after the name goes on to the blank expression, and Enter there adds the parameter. + h.step(&json!({"key":"Enter"})).unwrap(); + h.step(&json!({"text":"10 mm"})).unwrap(); h.step(&json!({"key":"Enter"})).unwrap(); assert_eq!(h.app.session.doc.param("pitch").unwrap().expr, "10 mm"); assert!(h.app.params.is_some()); @@ -482,6 +485,8 @@ fn parameters_open_at_top_retain_user_scroll_and_reveal_only_requested_drafts() h.step(&json!({"text":"pitch"})).unwrap(); assert_eq!(h.app.params.as_ref().unwrap().new_name, "pitch"); h.step(&json!({"key":"Enter"})).unwrap(); + h.step(&json!({"text":"10 mm"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); assert_eq!(h.app.session.doc.param("pitch").unwrap().expr, "10 mm"); } } diff --git a/crates/ui-egui/src/params_dialog.rs b/crates/ui-egui/src/params_dialog.rs index dd82d0d67..8241b8bca 100644 --- a/crates/ui-egui/src/params_dialog.rs +++ b/crates/ui-egui/src/params_dialog.rs @@ -17,8 +17,6 @@ use crate::SolveApp; use crate::ui_kit::{self, Column}; const UNITS: [&str; 9] = ["mm", "cm", "m", "in", "ft", "deg", "rad", "", "um"]; -/// The expression a new parameter row starts with. -const NEW_EXPR: &str = "10 mm"; /// Dialog state (what is being typed; the parameters themselves live in the document). #[derive(Default)] @@ -52,8 +50,10 @@ pub struct ParamsDialog { } impl ParamsDialog { + /// The add row starts blank, its expression too (#2919): a value put there for the user was + /// almost never the one wanted, and had to be erased first. pub fn new() -> Self { - ParamsDialog { reset_scroll: true, new_expr: NEW_EXPR.into(), ..Default::default() } + ParamsDialog { reset_scroll: true, ..Default::default() } } /// The command the live preview should run (a valid expression being edited). pub fn preview_commands(&self) -> Option> { @@ -481,6 +481,7 @@ fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, table: &mut ui_kit::Table<'_>, row.cell(|_| {}); row.cell(|ui| { let response = ui_kit::cell_editor(ui, name_id, &mut d.new_name, "new parameter", false); + select_all_on_tab(ui, &response, &d.new_name); crate::scenario::publish_handle("param:new:name", response.rect.center()); if d.focus_new { response.request_focus(); @@ -495,15 +496,17 @@ fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, table: &mut ui_kit::Table<'_>, }); let unit = UNITS.get(d.new_unit).copied().unwrap_or("mm"); row.cell(|ui| { - let invalid = new_check(app, d, unit).is_err(); + // A blank expression is not yet an error: nothing to show, and nothing to add. + let invalid = !d.new_expr.trim().is_empty() && new_check(app, d, unit).is_err(); let response = ui_kit::cell_editor(ui, expr_id, &mut d.new_expr, "Expression", invalid); + select_all_on_tab(ui, &response, &d.new_expr); crate::scenario::publish_handle("param:new:expression", response.rect.center()); let completed = complete(ui, &response, &mut d.new_expr); submit = !completed && enter_for(ui, focused_id.is_some()); left |= !completed && response.lost_focus(); }); row.cell(|ui| { - let live = new_check(app, d, unit); + let live = if d.new_expr.trim().is_empty() { Ok(String::new()) } else { new_check(app, d, unit) }; let (value, invalid) = match live { Ok(v) => (v, false), Err(e) => (e, true), @@ -512,6 +515,7 @@ fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, table: &mut ui_kit::Table<'_>, }); row.cell(|ui| { let response = ui_kit::cell_editor(ui, comment_id, &mut d.new_comment, "Comment", false); + select_all_on_tab(ui, &response, &d.new_comment); crate::scenario::publish_handle("param:new:comment", response.rect.center()); left |= response.lost_focus(); submit |= enter_for(ui, focused_id.is_some()); @@ -524,7 +528,8 @@ fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, table: &mut ui_kit::Table<'_>, table.reveal_row(response.rect); } let unit = UNITS.get(d.new_unit).copied().unwrap_or("mm"); - let live = new_check(app, d, unit); + let blank = d.new_expr.trim().is_empty(); + let live = if blank { Err(String::new()) } else { new_check(app, d, unit) }; let valid = !d.new_name.trim().is_empty() && live.is_ok(); crate::scenario::publish_count("param:new:valid", f64::from(valid)); let abandoned = d.new_name.trim().is_empty() @@ -534,8 +539,17 @@ fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, table: &mut ui_kit::Table<'_>, d.adding = false; d.new_name.clear(); d.new_comment.clear(); - d.new_expr = NEW_EXPR.into(); + d.new_expr.clear(); } else if submit || (left && valid) { + if blank { + // Enter after a name, before an expression is typed: on to the expression box. On an + // empty row (as after an add), the box keeps the focus a single-line Enter gives up. + let to = if d.new_name.trim().is_empty() { focused_id } else { Some(expr_id) }; + if let Some(id) = to { + ui.memory_mut(|m| m.request_focus(id)); + } + return; + } if let Err(error) = live { d.error = Some(error); if let Some(id) = focused_id { @@ -548,7 +562,7 @@ fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, table: &mut ui_kit::Table<'_>, Ok(_) => { d.new_name.clear(); d.new_comment.clear(); - d.new_expr = NEW_EXPR.into(); + d.new_expr.clear(); d.error = None; d.adding = true; d.focus_new = submit; @@ -563,6 +577,19 @@ fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, table: &mut ui_kit::Table<'_>, } } +/// A box of the add row entered with Tab selects its text, so typing replaces it (#2919); a click +/// puts the caret where it clicks, as anywhere else. The parameters' own boxes keep the caret at +/// the end, where an edit of the value usually starts. +fn select_all_on_tab(ui: &egui::Ui, resp: &egui::Response, text: &str) { + if !resp.gained_focus() || ui.input(|i| i.pointer.any_down() || i.pointer.any_released()) { + return; + } + let n = text.chars().count(); + let mut state = egui::text_edit::TextEditState::load(ui.ctx(), resp.id).unwrap_or_default(); + state.cursor.set_char_range(Some(egui::text_selection::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(n)))); + state.store(ui.ctx(), resp.id); +} + /// A completion offered under an expression box. #[derive(Clone, Debug)] pub struct Suggestion { @@ -745,14 +772,51 @@ mod tests { eprintln!("params frame time: closed {closed:.2} ms, open {open:.2} ms"); } + /// #2919: the add row starts blank; a blank expression shows no error and adds nothing, and + /// Enter after the name goes on to it; after an add the row is blank again; Tab into a box + /// selects its text, so typing replaces it. + #[test] + fn the_add_row_starts_blank_and_tab_selects_a_box() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.start", json!({"command": "parameters.change"})); + h.frames(3); + h.step(&json!({"click": {"handle": "dialog:table:user:add"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.params.as_ref().unwrap().new_expr, "", "a new parameter's expression starts blank"); + h.step(&json!({"click": {"handle": "param:new:name"}})).unwrap(); + h.step(&json!({"text": "width"})).unwrap(); + h.step(&json!({"key": "Enter"})).unwrap(); + h.frames(2); + assert!(h.app.session.doc.params.iter().all(|p| p.name != "width"), "no expression: nothing added"); + assert_eq!(h.app.params.as_ref().unwrap().error, None, "and nothing wrong is said"); + h.step(&json!({"text": "25 mm"})).unwrap(); + assert_eq!(h.app.params.as_ref().unwrap().new_expr, "25 mm", "Enter went on to the expression"); + h.step(&json!({"key": "Enter"})).unwrap(); + h.frames(2); + assert!(h.app.session.doc.params.iter().any(|p| p.name == "width" && p.expr == "25 mm")); + let d = h.app.params.as_ref().unwrap(); + assert_eq!((d.new_name.as_str(), d.new_expr.as_str()), ("", ""), "blank again after an add"); + // A value already in the expression box: Tab into it (past the unit) and type, and the + // value is replaced. + h.app.params.as_mut().unwrap().new_expr = "5 mm".into(); + h.step(&json!({"click": {"handle": "param:new:name"}})).unwrap(); + h.step(&json!({"key": "Tab"})).unwrap(); + h.step(&json!({"key": "Tab"})).unwrap(); + h.step(&json!({"text": "2"})).unwrap(); + assert_eq!(h.app.params.as_ref().unwrap().new_expr, "2", "Tab selected the expression, typing replaced it"); + } + /// An open window lists and checks once per revision of the design, not once per frame /// (#2723), and shows a change at once. #[test] fn the_window_does_not_re_evaluate_every_frame() { let mut h = big_design(); h.step(&json!({"start": "parameters.change"})).unwrap(); - // The redesign only checks a new expression while its inline draft is open. + // The redesign only checks a new expression while its inline draft is open, and a blank + // one isn't checked (#2919). h.app.params.as_mut().unwrap().adding = true; + h.app.params.as_mut().unwrap().new_expr = "10 mm".into(); h.frames(30); let d = h.app.params.as_ref().unwrap(); assert_eq!((d.lists, d.checks), (1, 1), "30 frames of an unchanged design"); diff --git a/crates/ui-egui/tests/parameter_enter.rs b/crates/ui-egui/tests/parameter_enter.rs index de7d7e10c..a04985b17 100644 --- a/crates/ui-egui/tests/parameter_enter.rs +++ b/crates/ui-egui/tests/parameter_enter.rs @@ -43,6 +43,12 @@ fn parameter_enter_adds_once_and_focuses_next_name() { // Name has focus after successful creation; no mouse needed for the next name. h.run(&json!([{"text":"height"}])).unwrap(); assert_eq!(h.app.params.as_ref().unwrap().new_name, "height"); + // The new row's expression starts blank: Enter after the name goes on to it, and Enter + // there adds the parameter. + enter(&mut h, false); + assert_eq!(h.app.session.undo.len(), undo + 1, "nothing added without an expression"); + h.run(&json!([{"text":"10 mm"}])).unwrap(); + assert_eq!(h.app.params.as_ref().unwrap().new_expr, "10 mm"); enter(&mut h, false); assert_eq!(h.app.session.undo.len(), undo + 2); let result = h.app.session.execute("parameters.list", &json!({})).unwrap(); From e1daf0a8b66232ac5dc5a9f786b31a58e203e92a Mon Sep 17 00:00:00 2001 From: phanoob Date: Wed, 21 Oct 2026 18:56:41 +0000 Subject: [PATCH 04/25] Clicking a parameter suggestion inserts it (#3257) (#3260) * claim: #3257 Co-Authored-By: Claude Opus 5.5 * Clicking a parameter suggestion inserts it (#3257) A press on a suggestion took the focus from the expression box before the list could see the click: the list stopped drawing, the click never landed, and the box gave up what was typed. The rows are kept from the frame before; a press on one picks it and gives the box its focus back (again on the release, which the box takes as a click away). The rows are no longer focusable. The completion tests' frames now drop their texture updates on purpose, so they run where egui checks that. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Phanoob Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/expression_complete.rs | 60 +++++++++++++++++++++-- crates/ui-egui/src/sketch_dims_tests.rs | 26 ++++++++++ crates/ui-egui/src/ui_kit/choice.rs | 9 +++- 3 files changed, 88 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/expression_complete.rs b/crates/ui-egui/src/expression_complete.rs index 0ef4f7de6..db52278c9 100644 --- a/crates/ui-egui/src/expression_complete.rs +++ b/crates/ui-egui/src/expression_complete.rs @@ -17,6 +17,8 @@ struct Popup { accept: bool, dismissed: bool, explicit: bool, + /// Where each suggestion was drawn, for a press on one (see [`complete`]). + rows: Vec, } fn popup_id() -> egui::Id { @@ -95,7 +97,21 @@ pub(crate) fn begin_frame(ctx: &egui::Context) { pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut String) -> bool { let ctx = ui.ctx().clone(); - if !ctx.memory(|m| m.has_focus(resp.id)) { + // A press on a suggestion takes the focus from the editor before the list can see it + // clicked, and the editor then gives up what was typed (#3257). The press picks the + // suggestion under it, and the editor gets its focus back below. + let pressed_row = ctx + .input(|i| i.pointer.primary_pressed().then(|| i.pointer.interact_pos()).flatten()) + .and_then(|at| ctx.data(|d| d.get_temp::(popup_id())).filter(|p| p.editor == resp.id)?.rows.iter().position(|r| r.contains(at))); + // Its release is a click away from the editor, which gives up the focus again: take it back, + // and don't let the list take that release as a click on another row. + let picked_by_press = resp.id.with("completion_picked_by_press"); + let released_after_press = ctx.data(|d| d.get_temp::(picked_by_press)).is_some() && ctx.input(|i| i.pointer.any_released()); + if released_after_press { + ctx.data_mut(|d| d.remove::(picked_by_press)); + resp.request_focus(); + } + if !ctx.memory(|m| m.has_focus(resp.id)) && pressed_row.is_none() { return false; } let state = egui::TextEdit::load_state(&ctx, resp.id); @@ -112,6 +128,7 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri accept: false, dismissed: false, explicit: false, + rows: Vec::new(), }); let list = suggestions_for(&ctx, &popup.word, popup.explicit); popup.frame = ctx.cumulative_frame_nr(); @@ -121,7 +138,11 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri ctx.data_mut(|d| d.insert_temp(popup_id(), popup)); return false; } - let mut pick = if popup.accept { list.get(popup.selected).map(|s| s.text.clone()) } else { None }; + let mut pick = match pressed_row { + Some(row) => list.get(row).map(|s| s.text.clone()), + None if popup.accept => list.get(popup.selected).map(|s| s.text.clone()), + None => None, + }; popup.accept = false; let t = Tokens::get(); let options: Vec<_> = list @@ -143,16 +164,20 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri }, }) .collect(); + let list_id = resp.id.with("completions"); if let Some(index) = ui_kit::popup_list( &ctx, - resp.id.with("completions"), + list_id, resp.rect, popup.selected, &options, crate::i18n::tr_label("↑ ↓ choose · Enter / Tab complete · Esc dismiss"), - ) { + ) && pick.is_none() + && !released_after_press + { pick = list.get(index).map(|suggestion| suggestion.text.clone()); } + popup.rows = ctx.data(|d| d.get_temp::>(list_id.with("rows"))).unwrap_or_default(); ctx.data_mut(|d| d.insert_temp(popup_id(), popup)); let Some(pick) = pick else { return false }; let chars: Vec = text.chars().collect(); @@ -163,6 +188,9 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri state.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(start + pick.chars().count())))); state.store(&ctx, resp.id); resp.request_focus(); + if pressed_row.is_some() { + ctx.data_mut(|d| d.insert_temp(picked_by_press, true)); + } // Do not leave the accepted popup owning Enter on the next frame. ctx.data_mut(|d| d.remove::(popup_id())); true @@ -206,7 +234,7 @@ mod tests { fn frame(&mut self, events: Vec) { self.accepted = false; self.leaked.clear(); - let _ = self.ctx.run_ui( + let mut output = self.ctx.run_ui( egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0))), events, @@ -229,6 +257,8 @@ mod tests { }); }, ); + // Nothing paints these frames: drop their texture updates on purpose. + output.textures_delta.clear(); } fn key(&mut self, key: Key) { @@ -266,6 +296,26 @@ mod tests { assert!(e.ctx.memory(|m| m.has_focus(e.id))); } + /// #3257: a click on a suggestion inserts it, though the press takes the focus from the + /// editor first; the editor keeps its focus and its caret goes after the inserted name. + #[test] + fn clicking_a_suggestion_inserts_it() { + let mut e = Editor::new("2 * wi"); + let list = suggestions(&e.ctx, "wi"); + let rows = e.ctx.data(|d| d.get_temp::(popup_id())).unwrap().rows; + assert_eq!(rows.len(), list.len()); + let at = rows[1].center(); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + e.frame(vec![egui::Event::PointerMoved(at)]); + e.frame(vec![button(true)]); + assert!(e.accepted, "the press picked the suggestion under it"); + e.frame(vec![button(false)]); + assert_eq!(e.text, format!("2 * {}", list[1].text)); + assert!(e.ctx.memory(|m| m.has_focus(e.id)), "the editor keeps the focus"); + assert_eq!(e.cursor(), e.text.chars().count()); + } + #[test] fn tab_accepts_selection_filtering_resets_it_and_escape_dismisses() { let mut e = Editor::new("wi"); diff --git a/crates/ui-egui/src/sketch_dims_tests.rs b/crates/ui-egui/src/sketch_dims_tests.rs index 5f6033c93..b0fd1d543 100644 --- a/crates/ui-egui/src/sketch_dims_tests.rs +++ b/crates/ui-egui/src/sketch_dims_tests.rs @@ -128,6 +128,32 @@ fn forward_tab_completes_expression_then_cycles_and_shift_tab_moves_back() { assert!((sketch.profiles[0].area - 120.0).abs() < 1e-6); } +/// #3257: clicking a parameter suggestion under a line's length box puts the name in the box, +/// which keeps the focus; the click places nothing, and Enter draws the line that long. +#[test] +fn clicking_a_parameter_suggestion_fills_the_length_box() { + let mut h = drawing("sketch.line"); + h.app.run("parameters.add", json!({"name": "width", "expression": "24 mm"})).unwrap(); + h.frames(2); + type_value(&mut h, "wid"); + h.frames(1); + h.step(&json!({"click": {"handle": "dialog:suggestion:0"}})).unwrap(); + h.frames(1); + assert_focus(&h, 0); + assert_eq!(h.app.tool.as_ref().unwrap().dims[0].value, "width"); + let sketch = |h: &Harness| h.app.session.world_state().sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.curves.len(); + assert_eq!(sketch(&h), 0, "the click on the list placed no point"); + h.step(&json!({"key": "Enter"})).unwrap(); + let state = h.app.session.world_state(); + let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; + assert_eq!(sk.curves.len(), 1); + let length = sk.shape(0).map(|s| match s { + solidcraft_engine::sketch::Shape::Line { a, b } => a.dist(b), + _ => 0.0, + }); + assert!(length.is_some_and(|l| (l - 24.0).abs() < 1e-6), "{length:?}"); +} + #[test] fn inch_live_lengths_use_design_units_and_typed_four_digits_commit_in_inches() { let mut h = Harness::new(); diff --git a/crates/ui-egui/src/ui_kit/choice.rs b/crates/ui-egui/src/ui_kit/choice.rs index 7d9ca3558..bb518beb8 100644 --- a/crates/ui-egui/src/ui_kit/choice.rs +++ b/crates/ui-egui/src/ui_kit/choice.rs @@ -348,7 +348,9 @@ pub(crate) struct PopupOption<'a> { pub color: egui::Color32, } -/// Focus-neutral suggestion popup. The owner handles navigation and completion semantics. +/// Focus-neutral suggestion popup. The owner handles navigation and completion semantics. Its +/// rows take no focus, and where they were drawn is kept under `id.with("rows")`, so an owner +/// can act on a press before the click lands (#3257). /// Tokens: space_2, form_label_width, control_height, text_dim, scope control/font tokens. pub(crate) fn popup_list( ctx: &egui::Context, @@ -360,6 +362,7 @@ pub(crate) fn popup_list( ) -> Option { let t = crate::theme::Tokens::get(); let mut chosen = None; + let mut rows = Vec::with_capacity(options.len()); let area = crate::frame::area(id).order(egui::Order::Tooltip).fixed_pos(anchor.left_bottom() + egui::vec2(0.0, t.space_2)).show(ctx, |ui| { egui::Frame::popup(ui.style()) .fill(t.control_fill) @@ -370,7 +373,8 @@ pub(crate) fn popup_list( super::scope(ui, |ui| { ui.set_width(anchor.width().max(t.form_card_width - t.space_16 * 2.0 - t.space_2)); for (index, option) in options.iter().enumerate() { - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), t.control_height), egui::Sense::click()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), t.control_height), egui::Sense::CLICK); + rows.push(rect); let picked = index == selected; if picked || response.hovered() { ui.painter().rect_filled(rect, t.control_radius, if picked { t.selected_bg } else { t.hover }); @@ -413,6 +417,7 @@ pub(crate) fn popup_list( }); }); crate::scenario::publish_rect("dialog:suggestions", area.response.rect); + ctx.data_mut(|d| d.insert_temp(id.with("rows"), rows)); chosen } From ac1768e08b83ed33212459951f5b50aa7a57cddc Mon Sep 17 00:00:00 2001 From: phanoob Date: Wed, 21 Oct 2026 18:56:43 +0000 Subject: [PATCH 05/25] Center circle through a snapped point stays on it (#3099) (#3277) * claim: #3099 Co-Authored-By: Claude Opus 5.5 * Centre circle: a second click snapped to a point keeps the circle on it (#3099) The tool sent the centre's snap reference but only a radius for the second click, so a circle drawn from a line's midpoint through its end was left free to change size. sketch.circle.center takes through: a point reference, kept on the circle (PointOnCurve), and the tool passes it when its second click snapped to a point. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Phanoob Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/sketch.rs | 16 +++++++++-- crates/engine/src/cmd/sketch_modify_tests.rs | 24 ++++++++++++++++ crates/ui-egui/src/sketch_corner_ui_tests.rs | 30 ++++++++++++++++++++ crates/ui-egui/src/tools.rs | 9 +++++- 4 files changed, 76 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 04505396a..198106807 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -67,7 +67,11 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("circle") .key("C") .enabled(in_sketch) - .params(concat!("center: [x,y] or point ref, radius | diameter: number", connect_doc!(), created_doc!())), + .params(concat!( + "center: [x,y] or point ref, radius | diameter: number; through?: point ref (a point the circle passes through, kept on it: where the tool's second click snapped)", + connect_doc!(), + created_doc!() + )), CommandSpec::new("sketch.circle.two_point", "2-Point Circle", circle_two) .at("SKETCH", "CREATE") .icon("circle2") @@ -1143,7 +1147,15 @@ fn circle_center(s: &mut Session, p: &Value) -> Result { let c = req_parg(sk, doc, p, "center", cmd)?; let ci = sk.add_circle(c.pos(), r, c.idx(), id.as_deref())?; mark_construction(sk, &[ci], p); - Ok((ids_of(sk, &[ci]), Vec::new())) + // A point the circle was drawn through stays on it (#3099): with a placed centre, that + // sets the radius. + let mut cons = Vec::new(); + if let Some(v) = p.get("through") + && let PArg::Ref(q, _) = parg(sk, doc, v, cmd)? + { + cons.push(add_c(sk, ConstraintKind::PointOnCurve { p: q, c: ci })?); + } + Ok((ids_of(sk, &[ci]), cons)) })?; Ok(result(out, info)) } diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index 63de01fec..f5dafa37a 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -483,6 +483,30 @@ fn two_tangent_circle_from_a_click_on_a_curve_leaves_the_curves_as_drawn() { } } +/// #3099: a centre circle drawn through a point stays on it. Centred on a line's midpoint and +/// through its end, the circle's radius follows the line when the line is dimensioned. +#[test] +fn centre_circle_through_a_point_keeps_it_on_the_circle() { + let mut s = new_sketch(); + let l = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 30], [40, 30]]}))["curves"])[0].clone(); + let r = run(&mut s, "sketch.circle.center", json!({"center": format!("mid:{l}"), "radius": 20, "through": format!("{l}.end")})); + let c = ids(&r["curves"])[0].clone(); + let sk = sketch(&s); + let (li, ci) = (sk.curve_index(&l).unwrap(), sk.curve_index(&c).unwrap()); + let end = sk.resolve_point(&format!("{l}.end")).unwrap(); + assert!(sk.constraints.iter().any(|k| k.kind == ConstraintKind::PointOnCurve { p: end, c: ci }), "{:?}", sk.constraints); + run(&mut s, "sketch.dimension", json!({"entities": [l], "value": 60})); + let sk = sketch(&s); + let line = sk.shape(li).unwrap(); + let solidcraft_sketch::Shape::Line { a, b } = line else { panic!("{line:?}") }; + assert!(close(a.dist(b), 60.0)); + assert!(close(sk.radius(ci).unwrap(), 30.0), "the circle followed the line's end: {:?}", sk.radius(ci)); + // Through a plain position: nothing to keep it on. + let r = run(&mut s, "sketch.circle.center", json!({"center": [100, 0], "radius": 5, "through": [105, 0]})); + let ci = sketch(&s).curve_index(&ids(&r["curves"])[0]).unwrap(); + assert!(!sketch(&s).constraints.iter().any(|k| matches!(k.kind, ConstraintKind::PointOnCurve { c, .. } if c == ci))); +} + #[test] fn ellipse_splines_conic() { let pi = std::f64::consts::PI; diff --git a/crates/ui-egui/src/sketch_corner_ui_tests.rs b/crates/ui-egui/src/sketch_corner_ui_tests.rs index d0b602123..bc9bb338f 100644 --- a/crates/ui-egui/src/sketch_corner_ui_tests.rs +++ b/crates/ui-egui/src/sketch_corner_ui_tests.rs @@ -679,3 +679,33 @@ fn two_tangent_circle_clicked_on_two_sides_fits_the_corner_and_moves_nothing() { assert!(before.iter().zip(&after).all(|(a, b)| a.dist(*b) < 1e-9), "fixed {fixed}: the rectangle moved: {after:?}"); } } + +/// #3099: the centre circle tool, its centre snapped to a line's midpoint and its second click +/// to the line's end, keeps the circle through that end: nothing is left free. +#[test] +fn centre_circle_clicked_through_a_line_end_stays_on_it() { + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[0,30],[40,30]]})).unwrap(); + h.step(&json!({"call":"ui.view","params":{"view":"fit"}})).unwrap(); + h.settle(); + let sid = h.app.session.active_sketch.unwrap(); + h.step(&json!({"start":"sketch.circle.center"})).unwrap(); + for at in [[20, 30, 0], [40, 30, 0]] { + h.step(&json!({"move":{"world":at}})).unwrap(); + h.step(&json!({"click":{"world":at}})).unwrap(); + } + let sk = h.app.session.model.state().sketch(sid).unwrap().sketch.clone(); + let circle = sk.curves.iter().position(|c| matches!(c.kind, CurveKind::Circle { .. })).unwrap(); + let end = sk.resolve_point("l1.end").unwrap(); + assert!( + sk.constraints.iter().any(|k| matches!(k.kind, solidcraft_engine::sketch::ConstraintKind::Midpoint { l: 0, .. })), + "{:?}", + sk.constraints + ); + assert!( + sk.constraints.iter().any(|k| k.kind == solidcraft_engine::sketch::ConstraintKind::PointOnCurve { p: end, c: circle }), + "the circle stays on the line's end: {:?}", + sk.constraints + ); +} diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index e205dced0..bbe7bbcd6 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -424,7 +424,14 @@ fn run_shape(app: &mut SolveApp, t: &Tool) -> Result, String> { json!({"p0": xy(&p[0]), "p1": xy(&p[1]), "radius": crate::sketch_dims::rounded_radius_value(app, t, p[0].0, p[1].0)}) } "sketch.rectangle.three_point" => json!({"p0": xy(&p[0]), "p1": xy(&p[1]), "p2": xy(&p[2])}), - "sketch.circle.center" => json!({"center": arg(&p[0]), "radius": d(0, 1)}), + "sketch.circle.center" => { + // A second click snapped to a point keeps the circle on that point (#3099). + let mut v = json!({"center": arg(&p[0]), "radius": d(0, 1)}); + if p[1].1.is_some() { + v["through"] = arg(&p[1]); + } + v + } "sketch.circle.two_point" => json!({"p0": xy(&p[0]), "p1": xy(&p[1])}), "sketch.circle.three_point" => json!({"p0": xy(&p[0]), "p1": xy(&p[1]), "p2": xy(&p[2])}), "sketch.arc.three_point" => json!({"start": arg(&p[0]), "end": arg(&p[1]), "through": arg(&p[2])}), From 915ee8a178fa3403e9e631fb4ff407bef608d876 Mon Sep 17 00:00:00 2001 From: Tyler Chiriboga Date: Wed, 21 Oct 2026 18:56:51 +0000 Subject: [PATCH 06/25] Fuzzer: a chamfer may add material, as a fillet may (#3868) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The fuzzer chamfers randomly picked edges and expected every chamfer to shrink the body, so a chamfer of a concave edge, which fills the corner, was reported as a wrong volume: 53 of the 6,000 designs of a run (seed 7100465: a box, a shell, a chamfer of an inside edge). Fillets already expect any volume change for the same reason; chamfers now do too. The regression test checks both directions on a shelled 20 mm box (an inside-edge chamfer of 1 mm adds 8 mm³, an outside one takes 10 mm³ away) and that seed 7100465 is no longer a volume finding. Co-authored-by: Tyler Chiriboga <18270301+Tyler-Chiriboga@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/fuzz.rs | 4 +++- crates/engine/src/tests/robustness.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/fuzz.rs b/crates/engine/src/fuzz.rs index c1f51c5f3..2219c5ed6 100644 --- a/crates/engine/src/fuzz.rs +++ b/crates/engine/src/fuzz.rs @@ -246,7 +246,9 @@ fn next_step(r: &mut Rng, s: &Session, last_feature: &Option) -> Option< let edges = body.body.edges(tol).ok()?; let n = 1 + r.below(3); let picks: Vec<[f64; 3]> = (0..n).filter_map(|_| edges.get(r.below(edges.len()))).map(|e| [e.mid.x, e.mid.y, e.mid.z]).collect(); - step("chamfer", Expect::Shrink, vec![("solid.chamfer", json!({"edges": picks, "distance": r.pick(&[0.5, 1.0, 2.0])?}))]) + // Any, as for fillets: the edges are picked at random, and a chamfer on a concave edge + // fills the corner, so it adds material. + step("chamfer", Expect::Any, vec![("solid.chamfer", json!({"edges": picks, "distance": r.pick(&[0.5, 1.0, 2.0])?}))]) } 8 => { let faces: Vec<_> = body.body.faces(tol).ok()?.into_iter().filter(|f| f.plane_normal.is_some()).collect(); diff --git a/crates/engine/src/tests/robustness.rs b/crates/engine/src/tests/robustness.rs index 217e1cc4b..7e71d95cb 100644 --- a/crates/engine/src/tests/robustness.rs +++ b/crates/engine/src/tests/robustness.rs @@ -575,3 +575,30 @@ fn seed_33_display_plan_and_measure_agree() { assert!((planned - measured).abs() < 2e-5 * measured, "{}: planned {planned}, measured {measured}", b.name); } } + +/// A chamfer on a concave edge fills the corner, so it adds material, as a fillet there does. The +/// fuzzer expected every chamfer to shrink the body and reported these as a wrong volume (about +/// 1 % of the designs of a 6,000-seed run; seed 7100465: a box, a shell, a chamfer of an inside +/// edge). On a shelled 20 mm box, a 1 mm chamfer of an inside bottom edge adds its 16 mm long +/// half-square prism, and one of an outside bottom edge takes 20 mm of it away. +#[test] +fn chamfer_of_a_concave_edge_adds_material() { + let shelled = || { + vec![ + json!({"command": "solid.box", "params": {"corner": [0, 0, 0], "length": 20, "width": 20, "height": 20}}), + json!({"command": "solid.shell", "params": {"faces": [[10, 10, 20]], "thickness": 2}}), + ] + }; + let base = total_volume(&script(Value::Array(shelled()))); + let chamfered = |edge: [f64; 3]| { + let mut steps = shelled(); + steps.push(json!({"command": "solid.chamfer", "params": {"edges": [edge], "distance": 1}})); + total_volume(&script(Value::Array(steps))) + }; + let inside = chamfered([10.0, 2.0, 2.0]); + let outside = chamfered([10.0, 0.0, 0.0]); + assert!((inside - (base + 16.0 * 0.5)).abs() < 1e-6, "inside edge: {base} -> {inside}"); + assert!((outside - (base - 20.0 * 0.5)).abs() < 1e-6, "outside edge: {base} -> {outside}"); + let r = fuzz::run(7100465, 8); + assert!(r.outcome.kind != "volume", "seed 7100465: {:?}\n{}", r.outcome, r.script()); +} From 9acff62422df6e71d6d55f7f9c42b02b8b0f7903 Mon Sep 17 00:00:00 2001 From: raykholo Date: Wed, 21 Oct 2026 18:56:53 +0000 Subject: [PATCH 07/25] Sketch trim and extend refuse an offset's ends instead of undoing silently (#3918) An offset's output curves have their ends recomputed from the source curves on every solve. Trimming a piece off one reported success and left the curve whole, because the refresh pulled the new end straight back. Extending one was refused as "connected to other geometry", which does not say why. Both now refuse with the reason and the way out: edit the source curves, or break the offset association first. Trimming away a whole offset curve, which removes it from its association, still works. --- crates/engine/src/cmd/sketch_modify.rs | 18 +++++++++++++ crates/engine/src/cmd/sketch_modify_tests.rs | 27 ++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index bf74a90d7..23fa04871 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -345,6 +345,22 @@ pub fn trim_piece(sk: &Sketch, curve: &str, at: Vec2) -> Option> { Some((0..=n).map(|i| sh.point(a + (b - a) * f64::from(i) / f64::from(n))).collect()) } +/// Trim and extend refuse an offset's output: its ends are recomputed from its source curves on +/// every solve, so a new end there would be pulled straight back (the trim reported success and +/// left the curve whole). +fn refuse_offset_ends(sk: &Sketch, ci: usize, what: &str, cmd: &str) -> Result<()> { + match sk.curves.get(ci).filter(|c| sk.offset_distance(&c.id).is_some()) { + Some(c) => Err(bad( + cmd, + format!( + "`{}` is an offset, and its ends follow its source curves: {what} the source curves instead, or break the offset association first", + c.id + ), + )), + None => Ok(()), + } +} + fn trim(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.trim"; let at = req_vec2(cmd, p, "at")?; @@ -383,6 +399,7 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valu sk.remove_curves(&[ci]); return Ok((json!({"deleted": id}), removed)); } + refuse_offset_ends(sk, ci, "trim", cmd)?; release_extent(sk, ci); let ts: Vec = cuts.iter().map(|c| c.0).collect(); let (pieces, pts) = split_at(sk, ci, &ts)?; @@ -590,6 +607,7 @@ fn extend(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, rep.failure(|_| "solve the existing sketch constraints before extending".into()))); } let ci = curve_arg(sk, p, cmd)?; + refuse_offset_ends(sk, ci, "extend", cmd)?; let sh = sk.shape(ci).ok_or_else(|| bad(cmd, "curve"))?; let (pa, pb) = match sk.curves.get(ci).map(|c| c.kind.clone()) { Some(CurveKind::Line { a, b }) | Some(CurveKind::Arc { a, b, .. }) => (a, b), diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index f5dafa37a..a8254db29 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -1814,3 +1814,30 @@ fn trim_piece_is_what_a_trim_there_takes_away() { let piece = super::trim_piece(&sketch(&s), &lone, Vec2::new(3.0, 0.0)).unwrap(); assert!(near(piece[0], [0.0, 0.0]) && near(piece[piece.len() - 1], [8.0, 0.0]), "{piece:?}"); } + +/// An offset's ends follow its source curves, so trimming a piece off it or extending it is +/// refused (the trim used to report success and leave the curve whole). Trimming away a whole +/// offset curve still works, and once the association is broken the trim cuts it. +#[test] +fn trim_and_extend_refuse_an_offsets_ends_until_its_association_is_broken() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + let out = ids(&run(&mut s, "sketch.offset", json!({"curves": ["l1", "l2", "l3", "l4"], "distance": "2 mm", "side": [-5, -5]}))["curves"]); + assert_eq!(out, ["l5", "l6", "l7", "l8"]); + run(&mut s, "sketch.line", json!({"points": [[20, -10], [20, 10]]})); + let before = serde_json::to_value(sketch(&s)).unwrap(); + let e = s.execute("sketch.trim", &json!({"curve": "l5", "at": [30, -2]})).unwrap_err().to_string(); + assert!(e.contains("offset") && e.contains("break the offset association"), "{e}"); + let e = s.execute("sketch.extend", &json!({"curve": "l5", "at": [42, -2]})).unwrap_err().to_string(); + assert!(e.contains("offset"), "{e}"); + assert_eq!(serde_json::to_value(sketch(&s)).unwrap(), before, "a refused trim changes nothing"); + + run(&mut s, "sketch.offset.break", json!({"curve": "l5"})); + run(&mut s, "sketch.trim", json!({"curve": "l5", "at": [30, -2]})); + let sk = sketch(&s); + let sh = sk.shape(sk.curve_index("l5").unwrap()).unwrap(); + assert!( + matches!(sh, solidcraft_sketch::Shape::Line { a, b } if a.dist(Vec2::new(-2.0, -2.0)) < 1e-9 && b.dist(Vec2::new(20.0, -2.0)) < 1e-9), + "{sh:?}" + ); +} From 63f210b49fa1d3eba4c2fb540d02c7465969b838 Mon Sep 17 00:00:00 2001 From: Nathan Dane Date: Wed, 21 Oct 2026 18:56:55 +0000 Subject: [PATCH 08/25] Restyle the vertical history sidebar (#2028) (#3953) * Vertical history strip: left of the browser, compact rows, hollow-circle marker, collapsed rail hover * Vertical history strip: seam handle to expand and collapse names, drag to resize with snap * Vertical history strip: no empty gap below the transport * Show the history seam arrow only on hover (#2028) * Extract a shared panel drag grip * Rebuild responsive history sizing and three-way docking * Share browser and History collapse hover styling * Show the History title as soon as its text fits * Animate stacked browser and History expansion and collapse * Make panel folding responsive and independent of frame delays * Let folding panel contents shrink continuously to header height * Use four explicit History transport actions in every layout * Resize the shared Browser and History column from either card --- ROADMAP.md | 2 +- assets/locales/cs.json | 6 + assets/locales/da.json | 6 + assets/locales/de.json | 6 + assets/locales/en.json | 16 +- assets/locales/es.json | 6 + assets/locales/fr.json | 6 + assets/locales/gl.json | 6 + assets/locales/hu.json | 6 + assets/locales/id.json | 6 + assets/locales/it.json | 6 + assets/locales/ja.json | 16 +- assets/locales/ko.json | 6 + assets/locales/ms.json | 6 + assets/locales/nl.json | 6 + assets/locales/pl.json | 6 + assets/locales/pt-BR.json | 6 + assets/locales/ro.json | 6 + assets/locales/ru.json | 6 + assets/locales/sv.json | 6 + assets/locales/tr.json | 6 + assets/locales/uk.json | 6 + assets/locales/vi.json | 6 + assets/locales/zh-TW.json | 6 + assets/locales/zh.json | 16 +- crates/engine/src/cmd/view_navigation.rs | 40 + crates/ui-egui/src/agent_chat/panel.rs | 10 +- crates/ui-egui/src/browser.rs | 167 ++-- crates/ui-egui/src/browser_card_tests.rs | 57 ++ crates/ui-egui/src/control.rs | 2 +- crates/ui-egui/src/lib.rs | 52 +- crates/ui-egui/src/prefs.rs | 25 +- crates/ui-egui/src/shell.rs | 10 + crates/ui-egui/src/shell_tests.rs | 19 +- crates/ui-egui/src/timeline.rs | 143 ++-- crates/ui-egui/src/timeline_left.rs | 942 +++++++++++++++++++---- crates/ui-egui/src/ui_kit/disclosure.rs | 15 +- crates/ui-egui/src/ui_kit/gallery.rs | 210 ++++- crates/ui-egui/src/ui_kit/history.rs | 687 +++++++++++++++++ crates/ui-egui/src/ui_kit/mod.rs | 4 +- crates/ui-egui/src/ui_kit/panel.rs | 6 + crates/ui-egui/tests/icon_audit.rs | 8 +- docs/book/src/guide/ui-tour.md | 5 +- docs/control-protocol.md | 1 + docs/ui-kit.md | 33 + 45 files changed, 2232 insertions(+), 380 deletions(-) create mode 100644 crates/ui-egui/src/ui_kit/history.rs diff --git a/ROADMAP.md b/ROADMAP.md index c269a33ec..592b07a55 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -55,7 +55,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | M3 | General fillets and chamfers (curved edges, chains, vertex blends); saddle rolling-ball surfaces now use continuous seam sections and arc-length fitting with shared contact boundaries and bounded accuracy checks; tiny rim edges remain selected instead of nearby wall seams when filleting (#2498) | in progress | 30 | | M4 | Files: STEP import (done — [docs/step-import.md](docs/step-import.md)), FreeCAD/Rhino solids through cadmpeg (done, desktop and CLI), 3MF export and 3MF/STL import as mesh bodies (done), 3MF with B-rep face tags ([docs/formats/3mf-face-tags.md](docs/formats/3mf-face-tags.md), done), constant-section parametric mesh reconstruction, DXF sketches, OBJ import | in progress | 6 | | M5 | Persistent naming of faces and edges (docs/book/src/dev/naming.md): faces named from their exact kernel-reported history (sketch curve sides, caps, revolve sections, primitive sides, blends, shell inner walls, pattern/mirror copies; split pieces told apart by the faces around them, lumps of a cut body named after their faces), edges by their faces; fillets/chamfers, sketches on faces, shell/draft/offset/replace faces, hole placements, joint origins and face appearances resolve by name first and warn when the entity split or vanished: done. sheet metal edges by base sketch line and flange side, shell inner faces, sweep and loft roles: done. kernel-reported face history: done (merged faces answer to every name; operations without history yet fall back to geometric names, flagged unverified; format 14 keeps older designs' geometric names). Left: history through sheet metal, plastic, surface and emboss features; FaceSource certificates through history | in progress | 20 | -| M6 | UI depth: selection feedback and origin (done), timeline editing (done: hover and selection highlight modifier faces, including fillets and chamfers; edit feature, history marker drag, dependency-checked single and multi-item reorder, suppress, rename, delete with dependents, re-resolved references; redefining selections refreshes persistent edge/face references while retaining feature identity and dimension names; optional compact named left feature history with rollback bar, multi-selection and persistent folders above the parts browser), right-docked dialogs (done), live previews for every feature dialog (done), keyboard-first commands with on-canvas value boxes and sketch inline dimensions (done), drag manipulators with automatic join/cut (done: extrude incl. two sides, fillet, shell, hole depth, move, pattern spacing, revolve rotator, extrude taper), dark theme (done), right-click menu with Repeat (done), measure tool (done), section analysis (done), selection filter (done), drag-solve of sketch points (done); appearance controls now preserve body/face/component targeting, named transparent looks, reuse/search and override removal; preferences | in progress | 6 | +| M6 | UI depth: selection feedback and origin (done), timeline editing (done: hover and selection highlight modifier faces, including fillets and chamfers; edit feature, history marker drag, dependency-checked single and multi-item reorder, suppress, rename, delete with dependents, re-resolved references; redefining selections refreshes persistent edge/face references while retaining feature identity and dimension names; responsive feature history with width-driven icons/names/title, snapping width resize, bottom/left/browser-stack docking, shared-column collapse, rollback bar, multi-selection and persistent folders), right-docked dialogs (done), live previews for every feature dialog (done), keyboard-first commands with on-canvas value boxes and sketch inline dimensions (done), drag manipulators with automatic join/cut (done: extrude incl. two sides, fillet, shell, hole depth, move, pattern spacing, revolve rotator, extrude taper), dark theme (done), right-click menu with Repeat (done), measure tool (done), section analysis (done), selection filter (done), drag-solve of sketch points (done); appearance controls now preserve body/face/component targeting, named transparent looks, reuse/search and override removal; preferences | in progress | 6 | | M7 | Thin extrude (walls along open or closed curves: centre, inside, outside or two sides; mitred corners, crossing walls joined; #721), sweep, loft (incl. to a point), rib and web (to next / depth), emboss (planar faces and exact radial emboss/deboss of bounded orthogonal profiles on complete exterior cylinders/sleeves), thread (cosmetic, and modelled M3–M20 outside and inside: the ISO profile screwed in as a faceted cut), coil (smooth B-spline helical walls), pipe, pattern on path, patterns of bodies and components, replace face (parallel), align, remove, feature copy/paste: done. Unique eligible cylindrical targets are inferred for new Emboss features. Left: general curved-face emboss and exact (unfaceted) modelled threads | in progress | 12 | | M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane, a face or sketch curves swept onto the surface, keeping a side or the picked regions; mutual trim of two surfaces, extended to meet and stitched, #767), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764: edge chains along one or several faces, closed rims paired seam to seam or from picked seams, a dialog), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two sketch curves exact with G0–G3, three or four as the flat patch of their loop, and curve networks: Coons and Gordon surfaces through sketch, 3D-sketch or edge curves, a point for a three-sided side, G1/G2 against the faces along one direction's edges, joined into their body on request; G1/G2 on two sides that meet at a corner waits for the Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770; a toolbar tool with edge markers and a legend, and curvature combs along face isocurves) and a multi-section **loft** with per-end continuity and crown, and guide rails on solid and surface lofts (one or two, scaling or stretching the sections between; #201). Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), and every remaining #757–#772 item | deferred | — | | M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), cams (`joint.cam`: a revolute cam drives a slider or revolute follower along a closed sketch profile or the cam's edges, knife, roller or flat followers, worked out again when the profile changes; drives, studies, closed loops, contact sets), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), motion analysis (joint values and a point's path charted over a study as value, velocity and acceleration; the parts that collide along a study, with the steps where they do), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Cam and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | diff --git a/assets/locales/cs.json b/assets/locales/cs.json index 260faad8e..bbd15354e 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -167,6 +167,7 @@ "HISTORY": "HISTORIE", "Height": "Výška", "Hidden edges": "Skryté hrany", + "History layout": "Rozložení historie", "Holes": "Otvory", "Holes (edges on them)": "Otvory (jejich hrany)", "Home view": "Výchozí pohled", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Skrýt počátek", "ui.hidePlanes": "Skrýt roviny", "ui.hideProfile": "Skrýt profil", + "ui.history_back": "O krok zpět", + "ui.history_below_browser": "Pod prohlížečem", + "ui.history_first": "Přejít na začátek", + "ui.history_forward": "O krok vpřed", + "ui.history_last": "Přejít na konec", "ui.history_title": "Historie", "ui.hole": "Otvor", "ui.hole_tap_type": "Typ závitu otvoru", diff --git a/assets/locales/da.json b/assets/locales/da.json index 759299242..74781809a 100644 --- a/assets/locales/da.json +++ b/assets/locales/da.json @@ -167,6 +167,7 @@ "HISTORY": "HISTORIK", "Height": "Højde", "Hidden edges": "Skjulte kanter", + "History layout": "Historiklayout", "Holes": "Huller", "Holes (edges on them)": "Huller (kanterne omkring dem)", "Home view": "Hjemmevisning", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Skjul nulpunkt", "ui.hidePlanes": "Skjul planer", "ui.hideProfile": "Skjul profil", + "ui.history_back": "Gå ét trin tilbage", + "ui.history_below_browser": "Under browseren", + "ui.history_first": "Gå til begyndelsen", + "ui.history_forward": "Gå ét trin frem", + "ui.history_last": "Gå til slutningen", "ui.history_title": "Historik", "ui.hole": "Hul", "ui.hole_tap_type": "Hullets gevindtype", diff --git a/assets/locales/de.json b/assets/locales/de.json index 3c586cdd7..b242a26d9 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -167,6 +167,7 @@ "HISTORY": "VERLAUF", "Height": "Höhe", "Hidden edges": "Verdeckte Kanten", + "History layout": "Verlaufslayout", "Holes": "Löcher", "Holes (edges on them)": "Löcher (ihre Kanten)", "Home view": "Startansicht", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Ursprung ausblenden", "ui.hidePlanes": "Ebenen ausblenden", "ui.hideProfile": "Profil ausblenden", + "ui.history_back": "Einen Schritt zurück", + "ui.history_below_browser": "Unter dem Browser", + "ui.history_first": "Zum Anfang", + "ui.history_forward": "Einen Schritt vor", + "ui.history_last": "Zum Ende", "ui.history_title": "Verlauf", "ui.hole": "Bohrung", "ui.hole_tap_type": "Gewindetyp", diff --git a/assets/locales/en.json b/assets/locales/en.json index 9d184597a..32faca657 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -168,6 +168,8 @@ "HISTORY": "HISTORY", "Height": "Height", "Hidden edges": "Hidden edges", + "History layout": "History layout", + "History names": "History names", "Holes": "Holes", "Holes (edges on them)": "Holes (edges on them)", "Home view": "Home view", @@ -1538,7 +1540,19 @@ "ui.hideOrigin": "Hide Origin", "ui.hidePlanes": "Hide Planes", "ui.hideProfile": "Hide Profile", + "ui.history_back": "Go back one step", + "ui.history_below_browser": "Below browser", + "ui.history_edge_hint": "double-click the edge", + "ui.history_first": "Go to beginning", + "ui.history_forward": "Go forward one step", + "ui.history_hide_names": "Hide names", + "ui.history_last": "Go to end", + "ui.history_marker_tip": "History marker: drag to roll the model back; new features go here", + "ui.history_names": "Names", + "ui.history_play": "Play to the end", + "ui.history_show_names": "Show names", "ui.history_title": "History", + "ui.history_toggle_names": "Show or hide feature names", "ui.hole": "Hole", "ui.hole_tap_type": "Hole Tap Type", "ui.hole_type": "Hole Type", @@ -1832,7 +1846,7 @@ "ui.tie_ends": "Tie", "ui.tie_ends_tip": "Constrain all untied ends", "ui.timeline_bottom": "Bottom timeline", - "ui.timeline_left_note": "The left layout shows the rollback bar above the parts and scene browser.", + "ui.timeline_left_note": "The vertical history sits to the left of the browser. Toggle feature names on the strip.", "ui.timeline_left_sidebar": "Left sidebar", "ui.tip_angle": "Tip Angle", "ui.to_object": "To Object", diff --git a/assets/locales/es.json b/assets/locales/es.json index bd09496fc..77c44315d 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -167,6 +167,7 @@ "HISTORY": "HISTORIAL", "Height": "Altura", "Hidden edges": "Aristas ocultas", + "History layout": "Disposición del historial", "Holes": "Agujeros", "Holes (edges on them)": "Agujeros (aristas que contienen)", "Home view": "Vista de inicio", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Ocultar origen", "ui.hidePlanes": "Ocultar planos", "ui.hideProfile": "Ocultar perfil", + "ui.history_back": "Retroceder un paso", + "ui.history_below_browser": "Debajo del explorador", + "ui.history_first": "Ir al principio", + "ui.history_forward": "Avanzar un paso", + "ui.history_last": "Ir al final", "ui.history_title": "Historial", "ui.hole": "Agujero", "ui.hole_tap_type": "Tipo de roscado del agujero", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 1d4821ed6..9f54fcfbe 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -167,6 +167,7 @@ "HISTORY": "HISTORIQUE", "Height": "Hauteur", "Hidden edges": "Arêtes cachées", + "History layout": "Disposition de l’historique", "Holes": "Trous", "Holes (edges on them)": "Trous (par leurs arêtes)", "Home view": "Vue d'accueil", @@ -1532,6 +1533,11 @@ "ui.hideOrigin": "Masquer l'origine", "ui.hidePlanes": "Masquer les plans", "ui.hideProfile": "Masquer le profil", + "ui.history_back": "Reculer d’une étape", + "ui.history_below_browser": "Sous le navigateur", + "ui.history_first": "Aller au début", + "ui.history_forward": "Avancer d’une étape", + "ui.history_last": "Aller à la fin", "ui.history_title": "Historique", "ui.hole": "Perçage", "ui.hole_tap_type": "Type de taraudage", diff --git a/assets/locales/gl.json b/assets/locales/gl.json index 5f9c5b23c..a4a3d36d3 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -167,6 +167,7 @@ "HISTORY": "HISTORIAL", "Height": "Altura", "Hidden edges": "Arestas ocultas", + "History layout": "Disposición do historial", "Holes": "Furados", "Holes (edges on them)": "Furados (arestas sobre eles)", "Home view": "Vista de inicio", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Ocultar a orixe", "ui.hidePlanes": "Ocultar os planos", "ui.hideProfile": "Ocultar o perfil", + "ui.history_back": "Retroceder un paso", + "ui.history_below_browser": "Debaixo do explorador", + "ui.history_first": "Ir ao comezo", + "ui.history_forward": "Avanzar un paso", + "ui.history_last": "Ir ao final", "ui.history_title": "Historial", "ui.hole": "Furado", "ui.hole_tap_type": "Tipo de roscado do furado", diff --git a/assets/locales/hu.json b/assets/locales/hu.json index a7889ffc1..f7ac25b92 100644 --- a/assets/locales/hu.json +++ b/assets/locales/hu.json @@ -167,6 +167,7 @@ "HISTORY": "ELŐZMÉNYEK", "Height": "Magasság", "Hidden edges": "Rejtett élek", + "History layout": "Előzmények elrendezése", "Holes": "Furatok", "Holes (edges on them)": "Furatok (rajtuk lévő élek)", "Home view": "Kezdőnézet", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Origó elrejtése", "ui.hidePlanes": "Síkok elrejtése", "ui.hideProfile": "Profil elrejtése", + "ui.history_back": "Egy lépéssel vissza", + "ui.history_below_browser": "Böngésző alatt", + "ui.history_first": "Ugrás az elejére", + "ui.history_forward": "Egy lépéssel előre", + "ui.history_last": "Ugrás a végére", "ui.history_title": "Előzmények", "ui.hole": "Furat", "ui.hole_tap_type": "Furat menettípusa", diff --git a/assets/locales/id.json b/assets/locales/id.json index 18759b05c..7b8c2d9cc 100644 --- a/assets/locales/id.json +++ b/assets/locales/id.json @@ -167,6 +167,7 @@ "HISTORY": "RIWAYAT", "Height": "Tinggi", "Hidden edges": "Tepi tersembunyi", + "History layout": "Tata letak riwayat", "Holes": "Lubang", "Holes (edges on them)": "Lubang (tepi di atasnya)", "Home view": "Tampilan awal", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Sembunyikan Origin", "ui.hidePlanes": "Sembunyikan Bidang", "ui.hideProfile": "Sembunyikan Profil", + "ui.history_back": "Mundur satu langkah", + "ui.history_below_browser": "Di bawah browser", + "ui.history_first": "Ke awal", + "ui.history_forward": "Maju satu langkah", + "ui.history_last": "Ke akhir", "ui.history_title": "Riwayat", "ui.hole": "Lubang", "ui.hole_tap_type": "Tipe Tap Lubang", diff --git a/assets/locales/it.json b/assets/locales/it.json index 76bc619d3..360991eb3 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -168,6 +168,7 @@ "HISTORY": "CRONOLOGIA", "Height": "Altezza", "Hidden edges": "Spigoli nascosti", + "History layout": "Disposizione cronologia", "Holes": "Fori", "Holes (edges on them)": "Fori (spigoli dei fori)", "Home view": "Vista iniziale", @@ -1529,6 +1530,11 @@ "ui.hideOrigin": "Nascondi origine", "ui.hidePlanes": "Nascondi piani", "ui.hideProfile": "Nascondi profilo", + "ui.history_back": "Indietro di un passaggio", + "ui.history_below_browser": "Sotto il browser", + "ui.history_first": "Vai all’inizio", + "ui.history_forward": "Avanti di un passaggio", + "ui.history_last": "Vai alla fine", "ui.history_title": "Cronologia", "ui.hole": "Foro", "ui.hole_tap_type": "Tipo di maschiatura del foro", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 7a80e4b68..62bd497dc 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -168,6 +168,8 @@ "HISTORY": "履歴", "Height": "高さ", "Hidden edges": "隠線", + "History layout": "履歴のレイアウト", + "History names": "履歴名", "Holes": "穴", "Holes (edges on them)": "穴(そのエッジ)", "Home view": "ホームビュー", @@ -1538,7 +1540,19 @@ "ui.hideOrigin": "原点を非表示", "ui.hidePlanes": "平面を非表示", "ui.hideProfile": "プロファイルを非表示", + "ui.history_back": "1ステップ戻る", + "ui.history_below_browser": "ブラウザーの下", + "ui.history_edge_hint": "端をダブルクリック", + "ui.history_first": "先頭に移動", + "ui.history_forward": "1ステップ進む", + "ui.history_hide_names": "名前を非表示", + "ui.history_last": "末尾に移動", + "ui.history_marker_tip": "履歴マーカー:ドラッグしてモデルをロールバックします。新しいフィーチャーはここに追加されます", + "ui.history_names": "名前", + "ui.history_play": "最後まで再生", + "ui.history_show_names": "名前を表示", "ui.history_title": "履歴", + "ui.history_toggle_names": "フィーチャー名を表示・非表示", "ui.hole": "穴", "ui.hole_tap_type": "ねじ穴タイプ", "ui.hole_type": "穴タイプ", @@ -1832,7 +1846,7 @@ "ui.tie_ends": "拘束", "ui.tie_ends_tip": "未拘束をすべて拘束", "ui.timeline_bottom": "下部タイムライン", - "ui.timeline_left_note": "左レイアウトでは、ロールバックバーがパーツとシーンブラウザーの上に表示されます。", + "ui.timeline_left_note": "縦の履歴はブラウザーの左に表示されます。ストリップでフィーチャー名の表示を切り替えられます。", "ui.timeline_left_sidebar": "左サイドバー", "ui.tip_angle": "先端角度", "ui.to_object": "オブジェクトまで", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index bc8fdc434..9f5d16bb7 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -167,6 +167,7 @@ "HISTORY": "이력", "Height": "높이", "Hidden edges": "숨겨진 모서리", + "History layout": "기록 레이아웃", "Holes": "구멍", "Holes (edges on them)": "구멍 (구멍의 모서리)", "Home view": "홈 뷰", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "원점 숨기기", "ui.hidePlanes": "평면 숨기기", "ui.hideProfile": "윤곽 숨기기", + "ui.history_back": "한 단계 뒤로", + "ui.history_below_browser": "브라우저 아래", + "ui.history_first": "처음으로 이동", + "ui.history_forward": "한 단계 앞으로", + "ui.history_last": "끝으로 이동", "ui.history_title": "기록", "ui.hole": "구멍", "ui.hole_tap_type": "탭 유형", diff --git a/assets/locales/ms.json b/assets/locales/ms.json index 9ccabe2df..e94a45751 100644 --- a/assets/locales/ms.json +++ b/assets/locales/ms.json @@ -167,6 +167,7 @@ "HISTORY": "SEJARAH", "Height": "Ketinggian", "Hidden edges": "Tepi tersembunyi", + "History layout": "Susun atur sejarah", "Holes": "Lubang", "Holes (edges on them)": "Lubang (tepi lubang)", "Home view": "Pandangan utama", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Sembunyi Titik Asal", "ui.hidePlanes": "Sembunyi Satah", "ui.hideProfile": "Sembunyi Profil", + "ui.history_back": "Undur satu langkah", + "ui.history_below_browser": "Di bawah pelayar", + "ui.history_first": "Pergi ke permulaan", + "ui.history_forward": "Maju satu langkah", + "ui.history_last": "Pergi ke penghujung", "ui.history_title": "Sejarah", "ui.hole": "Lubang", "ui.hole_tap_type": "Jenis Bebenang Lubang", diff --git a/assets/locales/nl.json b/assets/locales/nl.json index eca13bcb1..4ad7d7000 100644 --- a/assets/locales/nl.json +++ b/assets/locales/nl.json @@ -167,6 +167,7 @@ "HISTORY": "GESCHIEDENIS", "Height": "Hoogte", "Hidden edges": "Verborgen randen", + "History layout": "Geschiedenisindeling", "Holes": "Gaten", "Holes (edges on them)": "Gaten (randen erop)", "Home view": "Beginweergave", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Oorsprong verbergen", "ui.hidePlanes": "Vlakken verbergen", "ui.hideProfile": "Profiel verbergen", + "ui.history_back": "Eén stap terug", + "ui.history_below_browser": "Onder de browser", + "ui.history_first": "Naar het begin", + "ui.history_forward": "Eén stap vooruit", + "ui.history_last": "Naar het einde", "ui.history_title": "Geschiedenis", "ui.hole": "Gat", "ui.hole_tap_type": "Type tapgat", diff --git a/assets/locales/pl.json b/assets/locales/pl.json index cf1d39e25..2acada1e9 100644 --- a/assets/locales/pl.json +++ b/assets/locales/pl.json @@ -167,6 +167,7 @@ "HISTORY": "HISTORIA", "Height": "Wysokość", "Hidden edges": "Krawędzie niewidoczne", + "History layout": "Układ historii", "Holes": "Otwory", "Holes (edges on them)": "Otwory (krawędzie na nich)", "Home view": "Widok główny", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Ukryj początek układu", "ui.hidePlanes": "Ukryj płaszczyzny", "ui.hideProfile": "Ukryj profil", + "ui.history_back": "Cofnij o jeden krok", + "ui.history_below_browser": "Pod przeglądarką", + "ui.history_first": "Przejdź do początku", + "ui.history_forward": "Przejdź o jeden krok do przodu", + "ui.history_last": "Przejdź do końca", "ui.history_title": "Historia", "ui.hole": "Otwór", "ui.hole_tap_type": "Typ gwintu otworu", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index 278ecbd0b..964727458 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -167,6 +167,7 @@ "HISTORY": "HISTÓRICO", "Height": "Altura", "Hidden edges": "Arestas ocultas", + "History layout": "Layout do histórico", "Holes": "Furos", "Holes (edges on them)": "Furos (arestas neles)", "Home view": "Vista inicial", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Ocultar origem", "ui.hidePlanes": "Ocultar planos", "ui.hideProfile": "Ocultar perfil", + "ui.history_back": "Voltar uma etapa", + "ui.history_below_browser": "Abaixo do navegador", + "ui.history_first": "Ir para o início", + "ui.history_forward": "Avançar uma etapa", + "ui.history_last": "Ir para o fim", "ui.history_title": "Histórico", "ui.hole": "Furo", "ui.hole_tap_type": "Tipo de rosca do furo", diff --git a/assets/locales/ro.json b/assets/locales/ro.json index 24e40fc1d..4c535f3b4 100644 --- a/assets/locales/ro.json +++ b/assets/locales/ro.json @@ -167,6 +167,7 @@ "HISTORY": "ISTORIC", "Height": "Înălțime", "Hidden edges": "Muchii ascunse", + "History layout": "Aspectul istoricului", "Holes": "Găuri", "Holes (edges on them)": "Găuri (muchiile lor)", "Home view": "Vizualizare de start", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Ascunde originea", "ui.hidePlanes": "Ascunde planele", "ui.hideProfile": "Ascunde profilul", + "ui.history_back": "Un pas înapoi", + "ui.history_below_browser": "Sub navigator", + "ui.history_first": "Mergi la început", + "ui.history_forward": "Un pas înainte", + "ui.history_last": "Mergi la sfârșit", "ui.history_title": "Istoric", "ui.hole": "Gaură", "ui.hole_tap_type": "Tip de filetare gaură", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index bfcee7c0d..d2156fa15 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -167,6 +167,7 @@ "HISTORY": "ИСТОРИЯ", "Height": "Высота", "Hidden edges": "Скрытые рёбра", + "History layout": "Расположение истории", "Holes": "Отверстия", "Holes (edges on them)": "Отверстия (рёбра на них)", "Home view": "Главный вид", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Скрыть начало координат", "ui.hidePlanes": "Скрыть плоскости", "ui.hideProfile": "Скрыть профиль", + "ui.history_back": "На один шаг назад", + "ui.history_below_browser": "Под браузером", + "ui.history_first": "Перейти в начало", + "ui.history_forward": "На один шаг вперёд", + "ui.history_last": "Перейти в конец", "ui.history_title": "История", "ui.hole": "Отверстие", "ui.hole_tap_type": "Тип резьбы отверстия", diff --git a/assets/locales/sv.json b/assets/locales/sv.json index ad0a19dc6..e6b07be92 100644 --- a/assets/locales/sv.json +++ b/assets/locales/sv.json @@ -167,6 +167,7 @@ "HISTORY": "HISTORIK", "Height": "Höjd", "Hidden edges": "Dolda kanter", + "History layout": "Historiklayout", "Holes": "Hål", "Holes (edges on them)": "Hål (kanter på dem)", "Home view": "Hemvy", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Dölj origo", "ui.hidePlanes": "Dölj plan", "ui.hideProfile": "Dölj profil", + "ui.history_back": "Gå ett steg bakåt", + "ui.history_below_browser": "Under webbläsaren", + "ui.history_first": "Gå till början", + "ui.history_forward": "Gå ett steg framåt", + "ui.history_last": "Gå till slutet", "ui.history_title": "Historik", "ui.hole": "Hål", "ui.hole_tap_type": "Typ av gängning för hål", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index 52db14dc4..2b41a5d58 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -167,6 +167,7 @@ "HISTORY": "GEÇMİŞ", "Height": "Yükseklik", "Hidden edges": "Gizli kenarlar", + "History layout": "Geçmiş düzeni", "Holes": "Delikler", "Holes (edges on them)": "Delikler (kenarları)", "Home view": "Başlangıç görünümü", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Orijini gizle", "ui.hidePlanes": "Düzlemleri gizle", "ui.hideProfile": "Profili gizle", + "ui.history_back": "Bir adım geri git", + "ui.history_below_browser": "Tarayıcının altında", + "ui.history_first": "Başlangıca git", + "ui.history_forward": "Bir adım ileri git", + "ui.history_last": "Sona git", "ui.history_title": "Geçmiş", "ui.hole": "Delik", "ui.hole_tap_type": "Diş türü", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 720bff257..1879b9de1 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -167,6 +167,7 @@ "HISTORY": "ІСТОРІЯ", "Height": "Висота", "Hidden edges": "Приховані ребра", + "History layout": "Розташування історії", "Holes": "Отвори", "Holes (edges on them)": "Отвори (ребра на них)", "Home view": "Головний вид", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Приховати початок координат", "ui.hidePlanes": "Приховати площини", "ui.hideProfile": "Приховати профіль", + "ui.history_back": "На один крок назад", + "ui.history_below_browser": "Під браузером", + "ui.history_first": "Перейти на початок", + "ui.history_forward": "На один крок уперед", + "ui.history_last": "Перейти в кінець", "ui.history_title": "Історія", "ui.hole": "Отвір", "ui.hole_tap_type": "Тип різьби отвору", diff --git a/assets/locales/vi.json b/assets/locales/vi.json index 66f2d32d7..74b71bba4 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -167,6 +167,7 @@ "HISTORY": "LỊCH SỬ", "Height": "Chiều cao", "Hidden edges": "Nét khuất", + "History layout": "Bố cục lịch sử", "Holes": "Lỗ", "Holes (edges on them)": "Lỗ (các cạnh trên lỗ)", "Home view": "Góc nhìn chuẩn (Home)", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "Ẩn Gốc tọa độ", "ui.hidePlanes": "Ẩn các mặt phẳng", "ui.hideProfile": "Ẩn biên dạng", + "ui.history_back": "Lùi một bước", + "ui.history_below_browser": "Bên dưới trình duyệt", + "ui.history_first": "Về đầu", + "ui.history_forward": "Tiến một bước", + "ui.history_last": "Đến cuối", "ui.history_title": "Lịch sử", "ui.hole": "Tạo lỗ", "ui.hole_tap_type": "Kiểu ta-rô ren lỗ", diff --git a/assets/locales/zh-TW.json b/assets/locales/zh-TW.json index 8c177f277..13d847e07 100644 --- a/assets/locales/zh-TW.json +++ b/assets/locales/zh-TW.json @@ -167,6 +167,7 @@ "HISTORY": "歷程記錄", "Height": "高度", "Hidden edges": "隱藏線", + "History layout": "歷程配置", "Holes": "孔", "Holes (edges on them)": "孔(孔上的邊)", "Home view": "主檢視", @@ -1526,6 +1527,11 @@ "ui.hideOrigin": "隱藏原點", "ui.hidePlanes": "隱藏平面", "ui.hideProfile": "隱藏輪廓", + "ui.history_back": "後退一步", + "ui.history_below_browser": "瀏覽器下方", + "ui.history_first": "移至開頭", + "ui.history_forward": "前進一步", + "ui.history_last": "移至結尾", "ui.history_title": "歷程記錄", "ui.hole": "孔", "ui.hole_tap_type": "攻牙類型", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index ac79a95c7..65dcd1fc6 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -168,6 +168,8 @@ "HISTORY": "历史", "Height": "高度", "Hidden edges": "隐藏线", + "History layout": "历史布局", + "History names": "历史名称", "Holes": "孔", "Holes (edges on them)": "孔(孔上的边)", "Home view": "主视图", @@ -1538,7 +1540,19 @@ "ui.hideOrigin": "隐藏原点", "ui.hidePlanes": "隐藏平面", "ui.hideProfile": "隐藏轮廓", + "ui.history_back": "后退一步", + "ui.history_below_browser": "浏览器下方", + "ui.history_edge_hint": "双击边缘", + "ui.history_first": "转到开头", + "ui.history_forward": "前进一步", + "ui.history_hide_names": "隐藏名称", + "ui.history_last": "转到末尾", + "ui.history_marker_tip": "历史标记:拖动以回退模型;新特征将在此处添加", + "ui.history_names": "名称", + "ui.history_play": "播放至末尾", + "ui.history_show_names": "显示名称", "ui.history_title": "历史", + "ui.history_toggle_names": "显示或隐藏特征名称", "ui.hole": "孔", "ui.hole_tap_type": "孔攻丝类型", "ui.hole_type": "孔类型", @@ -1832,7 +1846,7 @@ "ui.tie_ends": "约束", "ui.tie_ends_tip": "约束全部未约束端点", "ui.timeline_bottom": "底部时间轴", - "ui.timeline_left_note": "左侧布局下,回退条显示在零件和场景浏览器的上方。", + "ui.timeline_left_note": "垂直历史位于浏览器左侧。可在历史条上切换特征名称的显示。", "ui.timeline_left_sidebar": "左侧边栏", "ui.tip_angle": "尖端角度", "ui.to_object": "到对象", diff --git a/crates/engine/src/cmd/view_navigation.rs b/crates/engine/src/cmd/view_navigation.rs index a2d0bb643..0a3fde2f4 100644 --- a/crates/engine/src/cmd/view_navigation.rs +++ b/crates/engine/src/cmd/view_navigation.rs @@ -7,6 +7,8 @@ use crate::params::{bad, num, req_vec2, req_vec3, vec3}; use crate::{Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ +CommandSpec::new("view.history_layout", "History layout", history_layout) + .icon("settings").noundo().doc_only().params("width?: 1..1000000; dock?: bottom|left|under_browser; collapsed?: bool → validated layout request; display only, never opens a dialog"), CommandSpec::new("view.graphics_preset", "Graphics Preset", graphics_preset) .icon("settings").noundo().doc_only().params("preset: performance|quality → preset, enabled, display_quality, supersampling, supersampling_adaptive; Quality: AO, Fine, adaptive 2x SSAA; Performance: no AO, Normal, no SSAA"), CommandSpec::new("view.ambient_occlusion", "Ambient Occlusion", ambient_occlusion) @@ -17,6 +19,30 @@ CommandSpec::new("view.navigate", "Navigate View", navigate) .doc_only() .params("camera: Camera; direction?: [x,y,z] in the camera's up-axis frame; or action: left|right|up|down|clockwise|counterclockwise|home|fit, degrees?: 0..180 (how far left|right|up|down turn; default 90); or motion: pan|orbit|zoom, delta?: [dx,dy] (pixels, each ±10000), viewport?: [width,height] (1..1000000, required for pan or pivot), pivot?: [x,y,z], factor?: 0.05..20 (required for zoom), anchor?: [x,y,z] → camera, fit, continuous?")]; +fn history_layout(_s: &mut Session, p: &Value) -> Result { + let cmd = "view.history_layout"; + let mut result = serde_json::Map::new(); + if let Some(value) = p.get("width") { + let width = value + .as_f64() + .filter(|v| v.is_finite() && (1.0..=1_000_000.0).contains(v)) + .ok_or_else(|| bad(cmd, "width must be finite and within 1..1000000"))?; + result.insert("width".into(), json!(width)); + } + if let Some(value) = p.get("dock") { + let dock = value + .as_str() + .filter(|v| matches!(*v, "bottom" | "left" | "under_browser")) + .ok_or_else(|| bad(cmd, "dock must be bottom, left or under_browser"))?; + result.insert("dock".into(), json!(dock)); + } + if let Some(value) = p.get("collapsed") { + let collapsed = value.as_bool().ok_or_else(|| bad(cmd, "collapsed must be a boolean"))?; + result.insert("collapsed".into(), json!(collapsed)); + } + Ok(Value::Object(result)) +} + fn navigate(_s: &mut Session, p: &Value) -> Result { let cmd = "view.navigate"; let mut cam: Camera = @@ -349,3 +375,17 @@ mod graphics_preset_tests { assert!(s.undo.is_empty()); } } + +#[cfg(test)] +#[test] +fn history_layout_validates_geometry_without_changing_the_design() { + let mut s = Session::default(); + let doc = s.doc.clone(); + let request = json!({"width":240.0,"dock":"under_browser","collapsed":true}); + assert_eq!(s.execute("view.history_layout", &request).unwrap(), request); + for p in [json!({"width":-1}), json!({"width":1e20}), json!({"width":"wide"}), json!({"dock":"nowhere"}), json!({"collapsed":42})] { + assert!(s.execute("view.history_layout", &p).is_err()); + } + assert_eq!(s.doc, doc); + assert!(s.undo.is_empty()); +} diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 39309352c..a85fa1517 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -445,19 +445,11 @@ fn strip(app: &mut SolveApp, ui: &mut egui::Ui) { /// Pop out (or Dock, in its own window), Minimise and Close. In its own window the system moves /// and minimises it, so there is no grip and no Minimise. fn header(app: &mut SolveApp, ui: &mut egui::Ui, left: bool) { - let t = Tokens::get(); let state = app.agent_chat.state(); let popped = app.preferences.agent_chat_popped; ui.horizontal(|ui| { let title = { - let (grip, _) = ui.allocate_exact_size(vec2(if popped { 0.0 } else { 10.0 }, 18.0), Sense::hover()); - if !popped { - for row in 0..3 { - for col in 0..2 { - ui.painter().circle_filled(grip.left_top() + vec2(2.5 + col as f32 * 5.0, 4.0 + row as f32 * 5.0), 1.1, t.text_dim); - } - } - } + let grip = if popped { ui.allocate_exact_size(vec2(0.0, 18.0), Sense::hover()).0 } else { ui_kit::panel_grip(ui).rect }; let l = ui.label( RichText::new(tr("ui.agent_chat")).semibold().color(crate::theme::Tokens::get().text).size(crate::theme::Tokens::get().font_heading), ); diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index c78c3ea98..a2c9791fc 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -278,7 +278,7 @@ pub fn group_action(app: &mut SolveApp, action: &str, p: &Value) { // Drawing // --------------------------------------------------------------------------------------------- -const ROW_H: f32 = 26.0; +const ROW_H: f32 = crate::ui_kit::TREE_ROW_HEIGHT; /// The floating card's inner margin: the header highlight sits this far from the card's top, left /// and right edges, so its corners are concentric with the card's. const CARD_INSET: f32 = 4.0; @@ -663,12 +663,7 @@ fn lit_row((selected, hovered): (bool, bool)) -> (bool, Mark) { } pub fn browser(app: &mut SolveApp, ui: &mut egui::Ui) { - browser_panel(app, ui, false); -} - -/// The left-sidebar layout: feature history first, parts and scene browser below it. -pub fn browser_below_timeline(app: &mut SolveApp, ui: &mut egui::Ui) { - browser_panel(app, ui, true); + browser_panel(app, ui); } /// How narrow the browser sidebar may be dragged, and how wide (the viewport keeps the rest). @@ -679,7 +674,7 @@ const BROWSER_RAIL: f32 = 6.0; /// How opaque the floating browser's card is; the workspace shows through the rest. const BROWSER_FLOAT_ALPHA: f32 = 0.4; -fn browser_panel(app: &mut SolveApp, ui: &mut egui::Ui, timeline_above: bool) { +fn browser_panel(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); app.tree.order.clear(); DRAWN.with(|d| d.borrow_mut().clear()); @@ -691,76 +686,28 @@ fn browser_panel(app: &mut SolveApp, ui: &mut egui::Ui, timeline_above: bool) { .resizable(false) .frame(egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin::symmetric(t.space_6 as i8, t.space_6 as i8))) .show(ui, |ui| { - if timeline_above { - let available = ui.available_height(); - let browser_collapsed = app.preferences.timeline_left_browser_collapsed; - let max_timeline_height = (available - if browser_collapsed { 30.0 } else { 130.0 }).max(150.0); - let remembered = app.preferences.timeline_left_height; - let timeline_height = - if remembered.is_finite() { remembered.clamp(150.0, max_timeline_height) } else { 360.0_f32.clamp(150.0, max_timeline_height) }; - ui.allocate_ui_with_layout(vec2(ui.available_width(), timeline_height), egui::Layout::top_down(egui::Align::Min), |ui| { - crate::timeline_left::left_timeline(app, ui) - }); - if !browser_collapsed { - let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 8.0), egui::Sense::hover()); - let response = ui - .interact(rect, egui::Id::new("left_history_divider"), egui::Sense::drag()) - .on_hover_cursor(egui::CursorIcon::ResizeVertical); - if response.dragged() { - let delta = ui.input(|input| input.pointer.delta().y); - if delta.is_finite() { - app.preferences.timeline_left_height = (timeline_height + delta).clamp(150.0, max_timeline_height); - } - } - ui.painter().hline(rect.x_range(), rect.center().y, egui::Stroke::new(1.0, t.border)); - crate::scenario::publish_handle("left-history-divider", rect.center()); - } - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), crate::ui_kit::row_height()), Sense::click()); - crate::ui_kit::disclosure( - ui.painter(), - pos2(rect.left() + t.form_section_icon_size / 2.0, rect.center().y), - !browser_collapsed, - t.text_dim, - ); - ui.painter().text( - pos2(rect.left() + t.form_section_icon_size + t.space_8, rect.center().y), - egui::Align2::LEFT_CENTER, - "BROWSER", - crate::fonts::semibold(t.font_small), - t.text_dim, - ); - response - .widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, ui.is_enabled(), !browser_collapsed, "BROWSER")); - crate::scenario::publish_handle("left-browser-toggle", response.rect.center()); - if response.clicked() { - app.preferences.timeline_left_browser_collapsed = !browser_collapsed; - } - if !browser_collapsed { - ui.add_space(t.space_4); - browser_rows(app, ui, &mut acts); - } - } else { - browser_contents(app, ui, &mut acts, false); - } + browser_contents(app, ui, &mut acts, false); }); - resize_browser(app, ui, panel.response.rect, width); + resize_column(app, ui, panel.response.rect, width, "left-browser-rail"); finish_browser(app, ui, acts); } -fn browser_width(remembered: f32) -> f32 { +pub(crate) fn browser_width(remembered: f32) -> f32 { if remembered.is_finite() { remembered.clamp(MIN_BROWSER_WIDTH, MAX_BROWSER_WIDTH) } else { crate::prefs::DEFAULT_BROWSER_WIDTH } } -fn resize_browser(app: &mut SolveApp, ui: &egui::Ui, rect: Rect, width: f32) { +/// Either card in a stacked column changes the same remembered width. +pub(crate) fn resize_column(app: &mut SolveApp, ui: &egui::Ui, rect: Rect, width: f32, handle: &'static str) { let rail = Rect::from_x_y_ranges(rect.right() - BROWSER_RAIL..=rect.right(), rect.y_range()); - let response = ui.interact(rail, egui::Id::new("sc_browser_rail"), Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeHorizontal); + let response = + ui.interact(rail, egui::Id::new(("sc_shared_column_rail", handle)), Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeHorizontal); if response.dragged() { let delta = ui.input(|input| input.pointer.delta().x); if delta.is_finite() { app.preferences.browser_width = (width + delta).clamp(MIN_BROWSER_WIDTH, MAX_BROWSER_WIDTH); } } - crate::scenario::publish_handle("left-browser-rail", pos2(rect.right() - BROWSER_RAIL / 2.0, rect.center().y)); + crate::scenario::publish_handle(handle, pos2(rect.right() - BROWSER_RAIL / 2.0, rect.center().y)); } /// One browser card for the floating shell and the docked shell's optional overlay. @@ -774,7 +721,21 @@ pub fn floating(app: &mut SolveApp, ui: &mut egui::Ui, available: Rect) { let gap = crate::shell::SHELL_GAP; let top_gap = if app.ui.layout == crate::shell::LayoutMode::Docked { gap } else { 0.0 }; let width = browser_width(app.preferences.browser_width); - let bounds = floating_bounds(available, app.shell.history, width, top_gap); + let vertical = app.ui.show_timeline && app.preferences.timeline_left; + let mut available = available; + let stacked = crate::timeline_left::stacked(app); + if vertical + && !stacked + && let Some(history) = app.shell.history + { + available.min.x = (history.right() + gap).min(available.right()) - gap; + } + let collapsed = vertical && !stacked && app.preferences.timeline_left_browser_collapsed; + let bounds = if stacked { + crate::timeline_left::stacked_rects(app, available).0 + } else { + floating_bounds(available, if vertical { None } else { app.shell.history }, if collapsed { t.space_24 + t.space_10 } else { width }, top_gap) + }; app.shell.browser = None; let min_height = HEADER_H + 2.0 * (CARD_INSET + 1.0); if bounds.is_positive() && bounds.height() >= min_height { @@ -786,9 +747,19 @@ pub fn floating(app: &mut SolveApp, ui: &mut egui::Ui, available: Rect) { let response = frame.show(ui, |ui| { ui.set_width(inner_width); ui.set_max_height(inner_height); - browser_contents(app, ui, &mut acts, true); + if stacked { + ui.set_min_height(inner_height); + ui.set_clip_rect(ui.clip_rect().intersect(Rect::from_min_size(ui.max_rect().min, vec2(inner_width, inner_height)))); + } + if collapsed { + browser_collapsed_rail(app, ui); + } else { + browser_contents(app, ui, &mut acts, true); + } }); - resize_browser(app, ui, response.response.rect, width); + if !collapsed { + resize_column(app, ui, response.response.rect, width, "left-browser-rail"); + } }); let rect = card.response.rect; app.shell.browser = Some(rect); @@ -801,7 +772,34 @@ pub fn floating(app: &mut SolveApp, ui: &mut egui::Ui, available: Rect) { finish_browser(app, ui, acts); } -fn floating_bounds(available: Rect, history: Option, width: f32, top_gap: f32) -> Rect { +fn browser_collapsed_rail(app: &mut SolveApp, ui: &mut egui::Ui) { + let t = Tokens::get(); + let title_top = t.space_24 + ui.spacing().item_spacing.y; + let height = title_top + t.space_24 * 4.0 + t.space_8; + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); + // Include the card margin in the hit target; keep the tint inside that margin. + let response = + ui.interact(rect.expand(CARD_INSET + 1.0), ui.id().with("browser_header"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); + if response.hovered() || response.has_focus() { + crate::ui_kit::panel_header_hover(ui.painter(), rect); + } + let disclosure = Rect::from_min_size(rect.min, vec2(rect.width(), t.space_24)); + crate::ui_kit::disclosure(ui.painter(), disclosure.center(), false, t.text_dim); + crate::scenario::publish_handle("left-browser-toggle", disclosure.center()); + crate::scenario::publish_target("browser:header", disclosure); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), crate::i18n::tr("ui.browser_title"))); + if response.on_hover_text(crate::i18n::tr("ui.browser_expand")).clicked() { + app.preferences.timeline_left_browser_collapsed = false; + } + let galley = ui.painter().layout_no_wrap(crate::i18n::tr("ui.browser_title").to_owned(), crate::fonts::semibold(t.font_body), t.text); + let title = Rect::from_min_max(rect.min + vec2(0.0, title_top), rect.max); + ui.painter().add( + egui::epaint::TextShape::new(title.center() - galley.size() / 2.0, galley, t.text) + .with_angle_and_anchor(std::f32::consts::FRAC_PI_2, egui::Align2::CENTER_CENTER), + ); +} + +pub(crate) fn floating_bounds(available: Rect, history: Option, width: f32, top_gap: f32) -> Rect { let gap = crate::shell::SHELL_GAP; let min = available.min + vec2(gap, top_gap); let right = (available.right() - gap).max(min.x); @@ -813,12 +811,20 @@ fn browser_contents(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions, c let t = Tokens::get(); // Only the floating card folds; the docked column keeps its full height. browser_header(app, ui, collapsible); - if collapsible && app.tree.panel_collapsed { + let stacked = crate::timeline_left::stacked(app); + if collapsible + && (if stacked { + (app.preferences.timeline_left_browser_collapsed && app.shell.history_folding.is_none_or(|p| p[0] >= 1.0)) + || ui.available_height() <= t.space_3 + } else { + app.tree.panel_collapsed && !(app.ui.show_timeline && app.preferences.timeline_left) + }) + { return; } ui.painter().hline(ui.max_rect().x_range(), ui.cursor().top() + 1.0, egui::Stroke::new(1.0, t.toolbar.lerp_to_gamma(t.border, 0.5))); ui.add_space(t.space_3); - if collapsible { + if collapsible && !stacked { browser_rows_hugging(app, ui, acts); } else { browser_rows(app, ui, acts); @@ -832,9 +838,14 @@ fn browser_header(app: &mut SolveApp, ui: &mut egui::Ui, collapsible: bool) { let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), HEADER_H), Sense::hover()); let response = ui.interact(rect, ui.id().with("browser_header"), if collapsible { Sense::click() } else { Sense::hover() }); crate::scenario::publish_target("browser:header", rect); - let collapsed = collapsible && app.tree.panel_collapsed; + let vertical = app.ui.show_timeline && app.preferences.timeline_left; + let stacked = crate::timeline_left::stacked(app); + let collapsed = collapsible && if stacked { app.preferences.timeline_left_browser_collapsed } else { !vertical && app.tree.panel_collapsed }; + if vertical { + crate::scenario::publish_handle("left-browser-toggle", rect.center()); + } if collapsible && (response.hovered() || response.has_focus()) { - ui.painter().rect_filled(rect, t.radius_lg.saturating_sub(CARD_INSET as u8), t.hover); + crate::ui_kit::panel_header_hover(ui.painter(), rect); } let title = crate::i18n::tr("ui.browser_title").to_string(); let kind = if collapsible { egui::WidgetType::Button } else { egui::WidgetType::Label }; @@ -853,8 +864,14 @@ fn browser_header(app: &mut SolveApp, ui: &mut egui::Ui, collapsible: bool) { ui.painter().galley(pos2(right - galley.size().x, rect.center().y - galley.size().y / 2.0), galley, t.text_dim); if collapsible { let tip = crate::i18n::tr(if collapsed { "ui.browser_expand" } else { "ui.browser_collapse" }); - if response.on_hover_text(tip).clicked() { - app.tree.panel_collapsed = !app.tree.panel_collapsed; + if response.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(tip).clicked() { + if stacked { + app.preferences.timeline_left_browser_collapsed = !app.preferences.timeline_left_browser_collapsed; + } else if vertical { + app.preferences.timeline_left_browser_collapsed = true; + } else { + app.tree.panel_collapsed = !app.tree.panel_collapsed; + } } } } @@ -925,6 +942,8 @@ fn rows_scrolling(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions, shr prepare_model(app); acts.lit = Lit::of(app); egui::ScrollArea::vertical() + // The card may animate all the way down to its header. + .min_scrolled_height(0.0) .auto_shrink([false, shrink_height]) .scroll_source(egui::scroll_area::ScrollSource { scroll_bar: true, mouse_wheel: true, ..egui::scroll_area::ScrollSource::NONE }) .show(ui, |ui| { diff --git a/crates/ui-egui/src/browser_card_tests.rs b/crates/ui-egui/src/browser_card_tests.rs index d3e72973b..263a40b02 100644 --- a/crates/ui-egui/src/browser_card_tests.rs +++ b/crates/ui-egui/src/browser_card_tests.rs @@ -252,3 +252,60 @@ fn a_long_body_name_stays_inside_the_card_and_ends_in_an_ellipsis() { assert!(label.right() <= card.right(), "{label:?} spills out of {card:?}"); assert!(label.width() > 100.0, "the name keeps the room it has: {label:?}"); } + +#[test] +fn collapsed_rail_shares_header_hover_inset_and_expands_from_its_whole_card() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + for collapsed in [false, true] { + let ctx = crate::fonts::test_context(); + ctx.global_style_mut(|style| style.animation_time = 0.0); + let mut app = SolveApp::new(Default::default(), Default::default()); + app.ui.tab = "SURFACE".into(); + app.preferences.timeline_left = true; + app.preferences.timeline_left_browser_collapsed = collapsed; + crate::theme::TabAccent::publish(&app, &ctx); + let bounds = Rect::from_min_size(Pos2::ZERO, vec2(600.0, 700.0)); + let draw = |app: &mut SolveApp, events| { + crate::test_support::frame(&ctx, egui::RawInput { screen_rect: Some(bounds), events, ..Default::default() }, |ui| { + floating(app, ui, bounds); + }) + }; + for _ in 0..3 { + draw(&mut app, vec![]); + } + let card = rect_of("browser:card").unwrap(); + let header = rect_of("browser:header").unwrap(); + // Hover at the bottom margin, far away from the disclosure and rotated title. + let at = if collapsed { card.center_bottom() - vec2(0.0, 2.0) } else { header.center() }; + draw(&mut app, vec![egui::Event::PointerMoved(at)]); + let output = draw(&mut app, vec![egui::Event::PointerMoved(at)]); + assert_eq!(output.platform_output.cursor_icon, egui::CursorIcon::PointingHand); + let accent = crate::theme::TabAccent::current(&ctx); + let mut hover = None; + for shape in &output.shapes { + crate::test_support::each_shape(&shape.shape, &mut |shape| { + if let egui::Shape::Rect(rect) = shape + && rect.fill == accent.soft + { + hover = Some(rect.clone()); + } + }); + } + let hover = + hover.unwrap_or_else(|| panic!("dark={dark}, collapsed={collapsed}, at={at:?}, accent={accent:?}, shapes={:?}", output.shapes)); + let inset = CARD_INSET + 1.0; // shared frame's inner margin and border + assert_eq!(hover.rect, if collapsed { card.shrink(inset) } else { header }); + assert_eq!(hover.rect.left() - card.left(), inset); + assert_eq!(card.right() - hover.rect.right(), inset); + assert_eq!(hover.corner_radius, egui::CornerRadius::same(Tokens::get().radius_lg.saturating_sub(CARD_INSET as u8))); + if collapsed { + draw(&mut app, crate::test_support::pointer(at, true)); + draw(&mut app, crate::test_support::pointer(at, false)); + assert!(!app.preferences.timeline_left_browser_collapsed, "the bottom margin expands the rail"); + } + } + } + crate::theme::set_dark(previous); +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index f45bb1aab..7b2a6d52d 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -101,7 +101,7 @@ fn key_from(name: &str) -> Option { fn execute(app: &mut SolveApp, id: &str, params: Value) -> Result { let r = app.run(id, params); if r.is_ok() - && !matches!(id, "view.navigate" | "view.ambient_occlusion" | "view.graphics_preset") + && !matches!(id, "view.navigate" | "view.ambient_occlusion" | "view.graphics_preset" | "view.history_layout") && app.session.active_sketch.is_none() && app.session.world_state().bodies.len() == 1 && app.session.undo.len() <= 2 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d2085b7dc..9abe87c57 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -743,6 +743,20 @@ impl SolveApp { let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); self.big_operation |= now_ms() - t0 >= recovery_ui::BIG_OPERATION_MS; if let Ok(v) = &r { + if id == "view.history_layout" { + if let Some(width) = v.get("width").and_then(Value::as_f64) { + self.preferences.timeline_left_width = ui_kit::history_snap_width(width as f32); + } + if let Some(dock) = v.get("dock").and_then(Value::as_str) { + self.preferences.timeline_left = dock != "bottom"; + self.preferences.timeline_under_browser = dock == "under_browser"; + self.preferences.timeline_collapsed = false; + self.preferences.timeline_left_browser_collapsed = false; + } + if let Some(collapsed) = v.get("collapsed").and_then(Value::as_bool) { + self.preferences.timeline_collapsed = collapsed; + } + } if matches!(id, "view.ambient_occlusion" | "view.graphics_preset") { self.preferences.ambient_occlusion = v.get("enabled").and_then(Value::as_bool).unwrap_or(false); if id == "view.graphics_preset" { @@ -872,6 +886,10 @@ impl SolveApp { return; } // A display toggle leaves the current modelling tool and camera in place. + if id == "view.history_layout" { + let _ = self.run(id, json!({})); + return; + } if id == "view.ambient_occlusion" { let _ = self.run(id, json!({"enabled": !self.preferences.ambient_occlusion})); return; @@ -1529,6 +1547,7 @@ impl SolveApp { let floating = self.ui.layout == shell::LayoutMode::Floating; let show_timeline = self.ui.show_timeline && !render_workspace::active(self); let left_timeline = show_timeline && self.preferences.timeline_left; + timeline_left::animate_folds(self, ui.ctx()); if !floating { toolbar::toolbar(self, ui); } @@ -1537,16 +1556,23 @@ impl SolveApp { timeline::timeline(self, ui); } // A floating browser keeps the workspace the whole width and covers viewport input. - let browser_float = self.ui.show_browser && (self.preferences.browser_float || (floating && !left_timeline)); + let browser_float = self.ui.show_browser && (self.preferences.browser_float || floating || left_timeline); if !browser_float { self.shell.browser = None; } - self.shell.history = None; + if floating || left_timeline || !show_timeline { + self.shell.history = None; + } let full = ui.available_rect_before_wrap(); if floating { let cards = shell::Cards::new(full, self.ui.layout); self.shell.cards = vec![cards.workspace, cards.ribbon]; - self.shell.history = (show_timeline && !left_timeline).then(|| timeline::floating_rect(full)); + self.shell.history = if left_timeline { + let below_ribbon = egui::Rect::from_min_max(egui::pos2(full.left(), cards.bottom), full.max); + Some(timeline_left::floating_rect(self, below_ribbon)) + } else { + show_timeline.then(|| timeline::floating_rect(full)) + }; // Draw the scene first, then let the unchanged panel layouts cover it. The // viewport keeps its full projection even underneath the browser and cards. preview::update(self, ui.ctx()); @@ -1572,15 +1598,12 @@ impl SolveApp { if floating && show_timeline && !left_timeline { timeline::timeline(self, ui); } - if self.ui.show_browser && !browser_float { - if left_timeline { - browser::browser_below_timeline(self, ui); - } else { - browser::browser(self, ui); - } - } else if left_timeline { + if left_timeline { timeline_left::left_panel(self, ui); } + if self.ui.show_browser && !browser_float { + browser::browser(self, ui); + } if render_workspace::active(self) { render_workspace::panel(self, ui); } @@ -1590,13 +1613,20 @@ impl SolveApp { let viewport = ui.available_rect_before_wrap(); browser::floating(self, ui, viewport); } + if !floating && timeline_left::stacked(self) { + let width = browser::browser_width(self.preferences.browser_width) + shell::SHELL_GAP * 2.0; + egui::Panel::left("sc_history_browser_column").exact_size(width).resizable(false).frame(egui::Frame::NONE).show(ui, |_| {}); + } egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| { if floating { let panel_content = ui.max_rect(); let mut content = panel_content; - if let Some(history) = self.shell.history { + if let Some(history) = self.shell.history.filter(|_| !left_timeline) { content.max.y = (history.top() - shell::SHELL_GAP).max(content.top()); } + if left_timeline && let Some(history) = self.shell.history { + content.min.x = (history.right() + shell::SHELL_GAP).min(content.right()); + } if let Some(browser) = self.shell.browser { content.min.x = (browser.right() + shell::SHELL_GAP).min(content.right()); } diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index ed56a365d..595f6cab8 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -444,14 +444,19 @@ preference_settings! { /// Interface font: an installed font family (or a font file), or empty for the built-in one /// (#1290). Menus, dialogs and labels use it; glyphs it lacks fall back as before. ui_font: String = String::new(), 0; - /// Put the feature history above the parts browser in the left sidebar instead of along the - /// bottom of the viewport. + /// Put the feature history to the left of the browser instead of below the viewport. timeline_left: bool = false, 0; - /// Height of the feature-history section when it shares the left sidebar with the browser. + /// Measured outer width; the contents react to this width without a names mode. + timeline_left_width: f32 = 130.0, 0; + /// Share the browser column, vertically, instead of a separate left column. + timeline_under_browser: bool = false, 0; + /// Fold the shared-column history to its header. + timeline_collapsed: bool = false, 0; + /// Legacy shared-column height, retained for preference compatibility. timeline_left_height: f32 = 360.0, 0; - /// Whether the browser below the left feature history is collapsed. + /// Whether the browser beside the vertical history is collapsed to its rail. timeline_left_browser_collapsed: bool = false, 0; - /// Width of the left sidebar holding the browser (and the feature history above it), which + /// Width of the browser sidebar, which /// the user drags wider or narrower at its right edge. browser_width: f32 = DEFAULT_BROWSER_WIDTH, 0; /// Draw the parts browser on a translucent card over the 3D view instead of a column of its @@ -1138,14 +1143,18 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { ui_kit::row(ui, app.tr_label("Interface font"), |ui| ui_font_row(app, ui)); } ui_kit::row(ui, app.tr("ui.feature_history"), |ui| { - let mut selected = usize::from(app.preferences.timeline_left); + let mut selected = if app.preferences.timeline_left { if app.preferences.timeline_under_browser { 2 } else { 1 } } else { 0 }; if ui_kit::segmented( ui, &mut selected, - &[crate::i18n::tr("ui.timeline_bottom"), crate::i18n::tr("ui.timeline_left_sidebar")], + &[ + crate::i18n::tr("ui.timeline_bottom"), + crate::i18n::tr("ui.timeline_left_sidebar"), + crate::i18n::tr("ui.history_below_browser"), + ], Default::default(), ) { - app.preferences.timeline_left = selected == 1; + let _ = app.run("view.history_layout", json!({"dock": match selected { 1=>"left",2=>"under_browser",_=>"bottom" }})); } }); ui_kit::text(ui, app.tr("ui.timeline_left_note"), ui_kit::Text::Note("timeline")); diff --git a/crates/ui-egui/src/shell.rs b/crates/ui-egui/src/shell.rs index 42a8771ec..48f6d34eb 100644 --- a/crates/ui-egui/src/shell.rs +++ b/crates/ui-egui/src/shell.rs @@ -80,6 +80,13 @@ pub(crate) struct State { pub panels: Vec, pub browser: Option, pub history: Option, + /// In-memory seam drag width, never serialized as a preference. + pub history_drag_width: Option, + /// Unreserved canvas bounds used by History docking targets. + pub history_dock_space: Option, + /// Browser/history collapse progress shared by both cards for this frame. + pub history_folding: Option<[f32; 2]>, + pub history_fold_motion: Option<[crate::timeline_left::FoldMotion; 2]>, pub content: Option, } @@ -91,6 +98,9 @@ pub(crate) fn covered_rects(app: &SolveApp) -> Vec { rects.extend(app.shell.panels.iter().copied()); rects.extend(app.shell.history); } + if app.ui.show_timeline && app.preferences.timeline_left { + rects.extend(app.shell.history.map(|card| crate::ui_kit::HistorySeam::new(card).pill)); + } rects.extend(app.shell.browser.filter(|_| app.ui.show_browser)); rects.extend(app.viewport.palette_rect.filter(|_| app.session.active_sketch.is_some())); rects.extend(app.viewport.dialog_rect.filter(|_| app.dialog.is_some() || app.tree.redefine.is_some())); diff --git a/crates/ui-egui/src/shell_tests.rs b/crates/ui-egui/src/shell_tests.rs index aa9d52349..238eaf800 100644 --- a/crates/ui-egui/src/shell_tests.rs +++ b/crates/ui-egui/src/shell_tests.rs @@ -230,9 +230,9 @@ fn floating_browser_clears_cards_shields_input_and_can_dock_again() { assert!(crate::browser::drawn_rows().iter().any(|(name, _, _, open)| name == "Origin" && *open == Some(true))); h.app.preferences.browser_float = false; h.settle(); - assert_eq!(h.app.shell.browser.is_some(), mode == LayoutMode::Floating && !timeline_left); + assert_eq!(h.app.shell.browser.is_some(), mode == LayoutMode::Floating || timeline_left); assert!(rect_of("browser:float").is_none()); - assert_eq!(rect_of("browser:card").is_some(), mode == LayoutMode::Floating && !timeline_left); + assert_eq!(rect_of("browser:card").is_some(), mode == LayoutMode::Floating || timeline_left); // The saved width follows both the floating card and the docked column. let rail = crate::scenario::handle_at("left-browser-rail").unwrap(); let width = h.app.preferences.browser_width; @@ -284,7 +284,7 @@ fn browser_and_history_cards_block_input_while_their_gaps_and_space_below_browse } #[test] -fn left_history_keeps_the_existing_column_in_both_modes() { +fn left_history_and_browser_share_the_left_edge_without_moving_right_controls() { for mode in [LayoutMode::Floating, LayoutMode::Docked] { let mut h = Harness::new(); h.app.ui.layout = mode; @@ -292,14 +292,21 @@ fn left_history_keeps_the_existing_column_in_both_modes() { h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"name":"First"})).unwrap(); h.settle(); assert!(rect_of("history:card").is_none()); - assert!(rect_of("browser:card").is_none()); + let history = rect_of("history:vertical").unwrap(); + let browser = rect_of("browser:card").unwrap(); + assert!(history.right() < browser.left()); assert!(crate::scenario::handle_at("timeline:First").is_some()); let viewport = h.app.viewport.rect.unwrap(); let content = content_rect(&h.app, viewport); - assert_eq!(content.left(), 250.0); + assert_eq!(viewport.left(), if mode == LayoutMode::Floating { 0.0 } else { crate::ui_kit::history_width(true) }); + assert_eq!(content.left(), if mode == LayoutMode::Floating { browser.right() + SHELL_GAP } else { viewport.left() }); assert_eq!(content.bottom(), viewport.bottom()); if mode == LayoutMode::Floating { - assert!(covered(&h.app, pos2(125.0, content.center().y))); + assert!(covered(&h.app, history.center())); + assert!(covered(&h.app, browser.center())); + let gap_x = (history.right() + browser.left()) / 2.0; + assert!(covered(&h.app, pos2(gap_x, history.center().y)), "the seam pill shields viewport input"); + assert!(!covered(&h.app, pos2(gap_x, history.top() + 4.0)), "the rest of the shell gap remains available"); } } } diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index 1303b7171..03f82296f 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -1,6 +1,5 @@ //! The timeline (bottom): features in order, the rollback marker, errors and warnings. -pub(crate) use crate::icons::glyphs::transport_glyph; use egui::{Rect, Sense, Stroke, UiBuilder, pos2, vec2}; use serde_json::{Value, json}; use solidcraft_engine::doc::{ @@ -8,8 +7,23 @@ use solidcraft_engine::doc::{ construct::{AxisDef, PointDef}, }; +use crate::SolveApp; use crate::theme::Tokens; -use crate::{SolveApp, icons}; + +/// Apply transport actions from the current marker; endpoints stay bounded, including an +/// empty design. All orientations reach the same rollback command. +pub(crate) fn run_transport(app: &mut SolveApp, control: crate::ui_kit::HistoryTransport) { + let n = app.session.doc.features.len(); + let marker = app.session.doc.marker.unwrap_or(n); + let position = match control { + crate::ui_kit::HistoryTransport::First => 0, + crate::ui_kit::HistoryTransport::Back => marker.saturating_sub(1), + crate::ui_kit::HistoryTransport::Forward => marker.saturating_add(1).min(n), + crate::ui_kit::HistoryTransport::Last => n, + }; + let params = if position < n { json!({"position":position}) } else { json!({}) }; + let _ = app.run_heavy("timeline.roll_to", params); +} // Snapshot only the data used by timeline interactions. Cloning FeatureKind here would // also copy imported mesh vertices and triangles on every frame. @@ -255,6 +269,7 @@ fn toggle_feature(app: &mut SolveApp, id: u64) { pub fn timeline(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); + app.shell.history_dock_space = Some(ui.available_rect_before_wrap()); if app.ui.layout == crate::shell::LayoutMode::Floating { let rect = floating_rect(ui.available_rect_before_wrap()); // A window too short for the card (the ribbon already fills it) leaves the history out @@ -273,6 +288,7 @@ pub fn timeline(app: &mut SolveApp, ui: &mut egui::Ui) { let response = egui::Panel::bottom("sc_timeline").exact_size(40.0).frame(egui::Frame::NONE.fill(t.timeline)).show(ui, |ui| { timeline_contents(app, ui, false); }); + app.shell.history = Some(response.response.rect); crate::scenario::publish_rect("history:strip", response.response.rect); } } @@ -295,36 +311,27 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { let marker = app.session.doc.marker.unwrap_or(n); // Playback controls. let mut x = r.left() + t.space_10; - if floating { - let label = p.layout_no_wrap(crate::i18n::tr("ui.history_title").to_string(), egui::FontId::proportional(t.font_label), t.text); - p.galley(pos2(x, r.center().y - label.size().y / 2.0), label.clone(), t.text); + let grip_rect = Rect::from_center_size(pos2(x + t.space_10 / 2.0, r.center().y), vec2(t.space_10, t.space_16 + t.space_2)); + let mut grip_ui = ui.new_child(UiBuilder::new().max_rect(grip_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); + let grip = crate::ui_kit::panel_grip(&mut grip_ui).rect; + x += t.space_10 + t.space_8; + let mut drag_rect = grip; + let label = p.layout_no_wrap(crate::i18n::tr("ui.history_title").to_string(), crate::fonts::semibold(t.font_heading), t.text); + if x + label.size().x + t.space_12 + crate::ui_kit::history_transport_width() <= r.right() { + let title_rect = Rect::from_min_size(pos2(x, r.center().y - label.size().y / 2.0), label.size()); + p.galley(title_rect.min, label.clone(), t.text); + drag_rect = drag_rect.union(title_rect); x += label.size().x + t.space_12; } - let controls = [("first", Some(0usize)), ("back", Some(marker.saturating_sub(1))), ("forward", Some((marker + 1).min(n))), ("last", None)]; - for (what, target) in controls { - let br = Rect::from_center_size(pos2(x + 11.0, r.center().y), vec2(22.0, 22.0)); - crate::scenario::publish_handle(&format!("history:{what}"), br.center()); - let resp = ui.interact(br, ui.id().with(("tl", what)), Sense::click()); - if resp.hovered() { - p.rect_filled(br, 3.0, t.hover); + let response = ui.interact(drag_rect, egui::Id::new("sc_history_dock_grip"), Sense::drag()); + crate::scenario::publish_handle("history:grip", drag_rect.center()); + crate::timeline_left::dock_drag(app, ui, &response); + for control in crate::ui_kit::HistoryTransport::ALL { + let br = Rect::from_center_size(pos2(x + t.space_24 / 2.0, r.center().y), vec2(t.space_24, t.space_24)); + if control.show(ui, br).clicked() { + run_transport(app, control); } - transport_glyph(&p, br.center(), what, t.icon); - if resp - .on_hover_text(match what { - "first" => "Roll back to the start", - "back" => "Step back one feature", - "forward" => "Step forward one feature", - _ => "Play to the end", - }) - .clicked() - { - let pos = match target { - Some(k) if k < n => json!({"position": k}), - _ => json!({}), - }; - let _ = app.run_heavy("timeline.roll_to", pos); - } - x += 24.0; + x += t.space_24 + t.space_2; } x += 14.0; // The features scroll horizontally in the space right of the playback controls. @@ -360,8 +367,8 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { let mut marker_rect: Option = None; for (i, (id, name, icon, suppressed, ty, kind)) in feats.iter().enumerate() { if i == marker { - marker_rect = Some(Rect::from_min_size(pos2(x, r.top() + 5.0), vec2(6.0, r.height() - 10.0))); - x += 10.0; + marker_rect = Some(Rect::from_min_size(pos2(x, r.top() + 5.0), vec2(t.space_12, r.height() - 10.0))); + x += t.space_16; } xs.push(x); let br = Rect::from_min_size(pos2(x, r.top() + 6.0), vec2(28.0, 28.0)); @@ -376,49 +383,19 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { if resp.hovered() { hovered = Some(*id); } - let bg = if err.is_some() { - t.timeline_item_error - } else if sel || (floating && marker > 0 && i == marker - 1) { - accent.soft - } else if resp.hovered() || from_view == Some(*id) { - t.hover - } else { - t.timeline_item - }; - let edge = if err.is_some() { - t.error - } else if from_view == Some(*id) || (floating && marker > 0 && i == marker - 1) { - accent.color - } else { - t.border - }; - p.rect(br, 3.0, bg, Stroke::new(1.0, edge), egui::StrokeKind::Inside); - let ink = if rolled || *suppressed { t.border } else { t.icon }; - icons::paint( - &p, - br.shrink(4.0), + crate::ui_kit::HistoryChip { icon, - ink, - if rolled { t.panel_header } else { t.icon_fill }, - if rolled { t.border } else { t.accent }, - ); - if *suppressed { - p.line_segment([br.left_bottom() + vec2(4.0, -4.0), br.right_top() + vec2(-4.0, 4.0)], Stroke::new(1.5, t.text_dim)); - } - // A failed feature has a mark of its own, not only its colour (#972). - if err.is_some() { - icons::paint(&p, Rect::from_min_size(br.right_top() - vec2(10.0, 0.0), vec2(10.0, 10.0)), "error", t.panel, t.error, t.error); - } - if warn.is_some() && err.is_none() { - icons::paint( - &p, - Rect::from_min_size(br.right_top() - vec2(10.0, 0.0), vec2(10.0, 10.0)), - "warning", - t.icon, - t.warning, - t.warning, - ); + name, + kind: ty, + selected: sel || (floating && marker > 0 && i == marker - 1), + hovered: resp.hovered() || from_view == Some(*id), + dim: rolled, + suppressed: *suppressed, + error: err.is_some(), + warning: warn.is_some(), + accent, } + .paint(&p, br, crate::ui_kit::HistoryStyle::Bottom); let mut tip = status_text(name, ty, err.as_deref(), warn.as_deref()); if let Some(r) = res { tip += &format!("\n{:.1} ms", r.ms); @@ -488,7 +465,7 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { } let end = x; if marker >= feats.len() { - marker_rect = Some(Rect::from_min_size(pos2(x, r.top() + 5.0), vec2(6.0, r.height() - 10.0))); + marker_rect = Some(Rect::from_min_size(pos2(x, r.top() + 5.0), vec2(t.space_12, r.height() - 10.0))); } // The history marker: drag it to roll the model back or forward. if let Some(mr) = marker_rect { @@ -497,14 +474,7 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { if resp.drag_started() { drag = Some(Drag::Marker); } - let col = if resp.hovered() || drag == Some(Drag::Marker) { - accent.color - } else if !floating && accent.color == t.accent { - t.timeline_marker - } else { - accent.color - }; - p.rect_filled(mr, 1.0, col); + crate::ui_kit::history_marker(&p, mr, false, accent); resp.on_hover_text("History marker: drag to roll the model back; new features go here"); } let content_end = crate::dialogs_assembly::timeline_joints(app, ui, &p, end + 10.0, r); @@ -514,9 +484,11 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { if let (Some(dg), Some(pp)) = (drag.as_ref(), pointer) { let slot = slot_at(&xs, end, pp.x); let sx = xs.get(slot).copied().unwrap_or(end) - 4.0; - p.line_segment( - [pos2(sx, r.top() + 3.0), pos2(sx, r.bottom() - 3.0)], - Stroke::new(2.0, if matches!(dg, Drag::Marker) { accent.color } else { t.sketch_accent }), + crate::ui_kit::history_drop_bar( + &p, + Rect::from_min_max(pos2(sx, r.top() + 3.0), pos2(sx, r.bottom() - 3.0)), + false, + if matches!(dg, Drag::Marker) { accent.color } else { t.sketch_accent }, ); } let released = ui.input(|i| i.pointer.any_released()); @@ -852,6 +824,7 @@ mod tests { assert_eq!(chips.last().unwrap().fill, accent.soft); assert_eq!(chips.last().unwrap().stroke.color, accent.color); let marker = crate::scenario::rect_of("history:marker").unwrap(); - assert!(out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.rect == marker && r.fill == accent.color))); + assert!(out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Circle(c) + if marker.contains(c.center) && c.fill == t.timeline && c.stroke == egui::Stroke::new(t.space_2, accent.color)))); } } diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs index 8a6c84594..50f0232e9 100644 --- a/crates/ui-egui/src/timeline_left.rs +++ b/crates/ui-egui/src/timeline_left.rs @@ -1,13 +1,10 @@ //! The left feature-history panel: named rows, folders, rollback and drag-and-drop. -use crate::fonts::RichTextExt as _; -use egui::{Color32, Rect, RichText, Sense, Stroke, pos2, vec2}; +use egui::{Rect, Sense, Stroke, pos2, vec2}; use serde_json::json; use crate::theme::Tokens; -use crate::timeline::{ - TimelineKind, clipboard_buttons, delete_feature, delete_features, icon_of, message_button, selected_feature_ids, transport_glyph, -}; +use crate::timeline::{TimelineKind, clipboard_buttons, delete_feature, delete_features, icon_of, message_button, selected_feature_ids}; use crate::{SolveApp, icons}; const FOLDER_INDENT: f32 = 14.0; @@ -58,76 +55,350 @@ impl TimelineItem { } } -/// A standalone left feature-history panel, used when the parts browser is hidden. +/// Saved width; contents are selected from the actual available width at render time. +pub(crate) fn strip_width(app: &SolveApp) -> f32 { + app.shell + .history_drag_width + .map(crate::ui_kit::history_clamp_width) + .unwrap_or_else(|| crate::ui_kit::history_snap_width(app.preferences.timeline_left_width)) +} + +pub(crate) fn stacked(app: &SolveApp) -> bool { + app.ui.show_timeline && app.preferences.timeline_left && app.preferences.timeline_under_browser +} + +fn header_outer_height() -> f32 { + let t = Tokens::get(); + crate::ui_kit::TREE_ROW_HEIGHT + t.space_8 + t.space_2 +} + +/// Small, allocation-free transition. Wall-clock progress avoids accumulating lag when +/// a frame is delayed; retargeting starts at the visible value, including mid-flight. +#[derive(Clone, Copy, Debug)] +pub(crate) struct FoldMotion { + from: f32, + to: f32, + started: f64, +} + +impl FoldMotion { + fn value(self, now: f64, duration: f32) -> f32 { + if duration <= 0.0 { + return self.to; + } + let elapsed = ((now - self.started) / f64::from(duration)).clamp(0.0, 1.0) as f32; + egui::lerp(self.from..=self.to, egui::emath::easing::cubic_out(elapsed)) + } + + fn advance(&mut self, target: f32, now: f64, duration: f32) -> f32 { + let value = self.value(now, duration); + if self.to != target { + *self = Self { from: value, to: target, started: now }; + } + self.value(now, duration) + } +} + +/// Calculate only two scalars per frame; cards and input geometry share the result. +pub(crate) fn animate_folds(app: &mut SolveApp, ctx: &egui::Context) { + if !stacked(app) { + app.shell.history_folding = None; + app.shell.history_fold_motion = None; + return; + } + let duration = ctx.global_style().animation_time.clamp(0.0, 0.12); + let now = ctx.input(|input| input.time); + let targets = [f32::from(app.preferences.timeline_left_browser_collapsed), f32::from(app.preferences.timeline_collapsed)]; + let motions = app.shell.history_fold_motion.get_or_insert_with(|| targets.map(|to| FoldMotion { from: to, to, started: now })); + let progress = [motions[0].advance(targets[0], now, duration), motions[1].advance(targets[1], now, duration)]; + app.shell.history_folding = Some(progress); + if progress != targets { + ctx.request_repaint(); + } +} + +/// Shared bounds keep browser and history at exactly the same width. Their split is half +/// the available height. One folded header gives the other the remainder; two folded +/// headers sit together at the top. +pub(crate) fn stacked_rects(app: &SolveApp, available: Rect) -> (Rect, Rect) { + let progress = app + .shell + .history_folding + .unwrap_or([f32::from(app.preferences.timeline_left_browser_collapsed), f32::from(app.preferences.timeline_collapsed)]); + column_rects_at(app, available, progress[0], progress[1]) +} + +fn column_rects(app: &SolveApp, available: Rect, browser_collapsed: bool, history_collapsed: bool) -> (Rect, Rect) { + column_rects_at(app, available, f32::from(browser_collapsed), f32::from(history_collapsed)) +} + +fn column_rects_at(app: &SolveApp, available: Rect, browser_fold: f32, history_fold: f32) -> (Rect, Rect) { + let gap = crate::shell::SHELL_GAP; + let top_gap = if app.ui.layout == crate::shell::LayoutMode::Docked { gap } else { 0.0 }; + let column = crate::browser::floating_bounds(available, None, crate::browser::browser_width(app.preferences.browser_width), top_gap); + if !app.ui.show_browser { + let height = egui::lerp(column.height()..=header_outer_height().min(column.height()), history_fold); + let history = Rect::from_min_size(column.min, vec2(column.width(), height)); + return (Rect::NOTHING, history); + } + let budget = (column.height() - gap).max(0.0); + let header = header_outer_height().min(budget / 2.0); + let expanded_browser = egui::lerp(budget / 2.0..=(budget - header).max(0.0), history_fold); + let browser_height = egui::lerp(expanded_browser..=header, browser_fold); + let browser = Rect::from_min_size(column.min, vec2(column.width(), browser_height)); + let history_top = (browser.bottom() + gap).min(column.bottom()); + let history_height = egui::lerp((column.bottom() - history_top).max(0.0)..=header, history_fold); + let history = Rect::from_min_size(pos2(column.left(), history_top), vec2(column.width(), history_height)); + (browser, history) +} + +pub(crate) fn floating_rect(app: &SolveApp, available: Rect) -> Rect { + if stacked(app) { + return stacked_rects(app, available).1; + } + let gap = crate::shell::SHELL_GAP; + let top_gap = if app.ui.layout == crate::shell::LayoutMode::Docked { gap } else { 0.0 }; + let min = pos2((available.left() + gap).min(available.right()), (available.top() + top_gap).min(available.bottom())); + Rect::from_min_max(min, pos2((min.x + strip_width(app)).min((available.right() - gap).max(min.x)), (available.bottom() - gap).max(min.y))) +} + +/// Full-height left card, or a card sharing the browser column below it. pub fn left_panel(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); - egui::Panel::left("sc_timeline_left") - .exact_size(250.0) - .resizable(false) - .frame(egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin::symmetric(6, 6))) - .show(ui, |ui| left_timeline(app, ui)); -} - -/// Vertical feature history with named rows, folders and a horizontal rollback bar. The caller -/// gives this a bounded height so the parts and scene browser can use the space below it. -pub fn left_timeline(app: &mut SolveApp, ui: &mut egui::Ui) { - let t = Tokens::get(); - let groups = app.session.doc.timeline_groups.clone(); - ui.horizontal(|ui| { - // Reserve the selection menu's measured height even when no features are selected. - let font = egui::TextStyle::Button.resolve(ui.style()); - let menu_height = ui.fonts_mut(|fonts| fonts.row_height(&font)) + 2.0 * ui.spacing().button_padding.y; - ui.set_min_height(menu_height.ceil().max(22.0)); - ui.label(RichText::new("FEATURE HISTORY").size(crate::theme::Tokens::get().font_small).semibold().color(t.text_dim)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let count = selected_feature_ids(app).len() + app.tree.picked_timeline_groups.len(); - if count > 0 { - crate::ui_kit::Menu::button(ui, format!("{count} selected"), |ui| selection_actions(app, ui, &groups)); + let available = ui.available_rect_before_wrap(); + app.shell.history_dock_space = Some(available); + if app.ui.layout == crate::shell::LayoutMode::Floating || stacked(app) { + let bounds = floating_rect(app, available); + app.shell.history = None; + if !bounds.is_finite() || bounds.width() < crate::ui_kit::history_width(false) || bounds.height() < t.control_height { + return; + } + let frame = crate::frame::shell_card(t.panel).inner_margin(t.space_4); + let inner = (bounds.size() - frame.total_margin().sum()).max(egui::Vec2::ZERO); + let card = crate::frame::area(egui::Id::new("sc_timeline_left_card")).fixed_pos(bounds.min).order(egui::Order::Middle).show(ui.ctx(), |ui| { + let response = frame.show(ui, |ui| { + ui.set_min_size(inner); + ui.set_max_size(inner); + ui.set_clip_rect(ui.clip_rect().intersect(Rect::from_min_size(ui.max_rect().min, inner))); + left_timeline(app, ui); + }); + if stacked(app) { + let width = crate::browser::browser_width(app.preferences.browser_width); + crate::browser::resize_column(app, ui, response.response.rect, width, "left-history-rail"); } }); - }); - timeline_transport(app, ui); - ui.separator(); - - egui::ScrollArea::vertical() - .id_salt("sc_left_timeline_scroll") - .auto_shrink([false, false]) - .scroll_source(egui::scroll_area::ScrollSource { scroll_bar: true, mouse_wheel: true, ..egui::scroll_area::ScrollSource::NONE }) - .show(ui, |ui| vertical_features(app, ui)); + app.shell.history = Some(card.response.rect); + crate::scenario::publish_rect("history:vertical", card.response.rect); + if !stacked(app) { + seam_handle(app, ui, card.response.rect); + } + } else { + let width = strip_width(app).min(ui.available_width().max(0.0)); + if width < crate::ui_kit::history_width(false) { + return; + } + let response = egui::Panel::left("sc_timeline_left") + .exact_size(width) + .resizable(false) + .frame(egui::Frame::NONE.fill(t.panel).inner_margin(t.space_4)) + .show(ui, |ui| left_timeline(app, ui)); + crate::scenario::publish_rect("history:vertical", response.response.rect); + app.shell.history = Some(response.response.rect); + seam_handle(app, ui, response.response.rect); + } } -fn timeline_transport(app: &mut SolveApp, ui: &mut egui::Ui) { +fn names_fit(width: f32) -> bool { let t = Tokens::get(); - let n = app.session.doc.features.len(); - let marker = app.session.doc.marker.unwrap_or(n); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - let controls = [("first", Some(0usize)), ("back", Some(marker.saturating_sub(1))), ("forward", Some((marker + 1).min(n))), ("last", None)]; - for (what, target) in controls { - let (rect, response) = ui.allocate_exact_size(vec2(24.0, 22.0), Sense::click()); - if response.hovered() { - ui.painter().rect_filled(rect, 3.0, t.hover); - } - transport_glyph(ui.painter(), rect.center(), what, t.icon); - if response - .on_hover_text(match what { - "first" => "Roll back to the start", - "back" => "Step back one feature", - "forward" => "Step forward one feature", - _ => "Play to the end", - }) - .clicked() - { - let params = match target { - Some(position) if position < n => json!({"position": position}), - _ => json!({}), - }; - let _ = app.run_heavy("timeline.roll_to", params); + width >= crate::ui_kit::history_width(true) - (t.space_8 + t.space_2) +} + +fn seam_handle(app: &mut SolveApp, ui: &mut egui::Ui, card: Rect) { + let seam = crate::ui_kit::HistorySeam::new(card); + let bounds = seam.edge.union(seam.pill); + crate::frame::area(egui::Id::new("history_seam_overlay")).order(egui::Order::Foreground).fixed_pos(bounds.min).show(ui.ctx(), |ui| { + ui.set_min_size(bounds.size()); + ui.set_clip_rect(ui.ctx().content_rect()); + let result = crate::ui_kit::history_seam(ui, card, card.width() >= crate::ui_kit::history_width(true)); + if let Some(width) = result.width { + app.shell.history_drag_width = Some(width); + ui.ctx().request_repaint(); + if result.released { + let _ = app.run("view.history_layout", json!({"width": width})); + app.shell.history_drag_width = None; } + } else if result.toggle { + let width = crate::ui_kit::history_width(card.width() < crate::ui_kit::history_width(true)); + let _ = app.run("view.history_layout", json!({"width":width})); + ui.ctx().request_repaint(); } }); } +/// Width alone chooses icons, names, horizontal transport and the optional title. +pub fn left_timeline(app: &mut SolveApp, ui: &mut egui::Ui) { + let t = Tokens::get(); + let names = names_fit(ui.available_width()); + timeline_transport(app, ui, names); + if stacked(app) + && ((app.preferences.timeline_collapsed && app.shell.history_folding.is_none_or(|p| p[1] >= 1.0)) || ui.available_height() <= t.space_3) + { + return; + } + ui.painter().hline(ui.max_rect().x_range(), ui.cursor().top(), Stroke::new(1.0, t.border)); + ui.add_space(t.space_3); + egui::ScrollArea::vertical() + .id_salt("sc_left_timeline_scroll") + // The animated card owns its height, including the last few closing frames. + .min_scrolled_height(0.0) + .auto_shrink([false, false]) + .scroll_source(egui::scroll_area::ScrollSource { scroll_bar: true, mouse_wheel: true, ..egui::scroll_area::ScrollSource::NONE }) + .show(ui, |ui| vertical_features(app, ui, names)); +} + +fn timeline_transport(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { + let t = Tokens::get(); + let count = crate::ui_kit::HistoryTransport::ALL.len() as f32; + let height = if names { crate::ui_kit::TREE_ROW_HEIGHT } else { t.control_height * count + t.space_2 * (count - 1.0) }; + let (header, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); + crate::scenario::publish_rect("history:transport", header); + crate::scenario::publish_rect("history:header", header); + let mut controls_right = header.right(); + if names && stacked(app) { + let fold = Rect::from_center_size(pos2(controls_right - t.space_24 / 2.0, header.center().y), vec2(t.space_24, t.space_24)); + let response = crate::ui_kit::panel_disclosure_button_at( + ui, + fold, + !app.preferences.timeline_collapsed, + crate::i18n::tr(if app.preferences.timeline_collapsed { "ui.expand" } else { "ui.collapse" }), + ); + crate::scenario::publish_handle("history:collapse", fold.center()); + if response.clicked() { + let _ = app.run("view.history_layout", json!({"collapsed":!app.preferences.timeline_collapsed})); + } + controls_right = fold.left() - t.space_2; + } + if names { + let mut grip = ui.new_child( + egui::UiBuilder::new() + .max_rect(Rect::from_min_size(header.min, vec2(t.space_10, height))) + .layout(egui::Layout::left_to_right(egui::Align::Center)), + ); + let handle = crate::ui_kit::panel_grip(&mut grip).rect; + let controls_width = crate::ui_kit::history_transport_width(); + let title = crate::i18n::tr("ui.history_title"); + let galley = ui.painter().layout_no_wrap(title.to_owned(), crate::fonts::semibold(t.font_heading), t.text); + let text_left = handle.right() + t.space_8; + let text_right = controls_right - controls_width - t.space_8; + let drag_rect = if text_right - text_left >= galley.size().x { + let title_rect = Rect::from_min_max(pos2(text_left, header.top()), pos2(text_right, header.bottom())); + ui.painter().galley(pos2(text_left, header.center().y - galley.size().y / 2.0), galley, t.text); + crate::scenario::publish_rect("history:title", title_rect); + handle.union(title_rect) + } else { + handle + }; + let drag = ui.interact(drag_rect, egui::Id::new("sc_history_dock_grip"), Sense::drag()); + crate::scenario::publish_handle("history:grip", drag_rect.center()); + dock_drag(app, ui, &drag); + } + for (i, control) in crate::ui_kit::HistoryTransport::ALL.into_iter().enumerate() { + let side = if names { t.space_24 } else { t.control_height }; + let rect = if names { + Rect::from_min_size( + pos2(controls_right - crate::ui_kit::history_transport_width() + i as f32 * (side + t.space_2), header.center().y - side / 2.0), + vec2(side, side), + ) + } else { + Rect::from_min_size(pos2(header.center().x - side / 2.0, header.top() + i as f32 * (side + t.space_2)), vec2(side, side)) + }; + if control.show(ui, rect).clicked() { + crate::timeline::run_transport(app, control); + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Dock { + Bottom, + Left, + UnderBrowser, +} + +impl Dock { + fn id(self) -> &'static str { + match self { + Self::Bottom => "bottom", + Self::Left => "left", + Self::UnderBrowser => "under_browser", + } + } +} + +fn dock_target(app: &SolveApp, available: Rect, at: egui::Pos2) -> Option { + let t = Tokens::get(); + if !available.contains(at) { + return None; + } + if at.y >= available.bottom() - t.space_24 * 2.0 { + return Some(Dock::Bottom); + } + if at.x <= available.left() + t.space_24 * 2.0 { + return Some(Dock::Left); + } + let column = stacked_rects(app, available).0; + if app.ui.show_browser && at.x <= column.right() && at.y >= column.top() + header_outer_height() { Some(Dock::UnderBrowser) } else { None } +} + +pub(crate) fn dock_drag(app: &mut SolveApp, ui: &egui::Ui, drag: &egui::Response) { + if drag.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); + } + let Some(available) = app.shell.history_dock_space else { + return; + }; + let target = ui.ctx().pointer_latest_pos().and_then(|at| dock_target(app, available, at)); + if drag.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + if let Some(target) = target { + let zone = match target { + Dock::Bottom => { + if app.ui.layout == crate::shell::LayoutMode::Floating { + crate::timeline::floating_rect(available) + } else { + Rect::from_min_max(pos2(available.left(), (available.bottom() - 40.0).max(available.top())), available.max) + } + } + Dock::Left => { + let mut rect = available; + let gap = if app.ui.layout == crate::shell::LayoutMode::Floating { crate::shell::SHELL_GAP } else { 0.0 }; + rect.min.x += gap; + rect.max.x = (rect.left() + strip_width(app)).min(available.right() - gap); + rect.max.y -= gap; + rect + } + Dock::UnderBrowser => column_rects(app, available, false, false).1, + }; + let t = Tokens::get(); + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("history_dock_preview"))); + painter.rect(zone, t.radius_lg, t.accent.gamma_multiply(0.18), Stroke::new(t.space_2, t.accent), egui::StrokeKind::Inside); + crate::scenario::publish_rect("history:dock_preview", zone); + crate::scenario::publish_rect(&format!("history:dock:{}", target.id()), zone); + let label = crate::i18n::tr(match target { + Dock::Bottom => "ui.timeline_bottom", + Dock::Left => "ui.timeline_left_sidebar", + Dock::UnderBrowser => "ui.history_below_browser", + }); + painter.text(zone.center(), egui::Align2::CENTER_CENTER, label, crate::fonts::semibold(t.font_heading), t.text); + } + } + if drag.drag_stopped() + && let Some(target) = target + { + let _ = app.run("view.history_layout", json!({"dock":target.id()})); + } +} + fn nearest_vertical_slot(slots: &[VerticalSlot], y: f32) -> Option { slots.iter().min_by(|a, b| (a.y - y).abs().total_cmp(&(b.y - y).abs())).copied() } @@ -197,17 +468,14 @@ fn vertical_drop_bar_left(panel_left: f32, target: Option, groups: &[solidc fn vertical_marker(app: &mut SolveApp, ui: &mut egui::Ui, drag: &mut Option) { let t = Tokens::get(); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 7.0), Sense::drag()); - let line = Rect::from_min_max(pos2(rect.left() + 8.0, rect.center().y - 1.5), pos2(rect.right() - 5.0, rect.center().y + 1.5)); - let colour = crate::theme::TabAccent::for_tab(&t, &app.ui.tab).color; - ui.painter().rect_filled(line, 1.5, colour); - ui.painter().circle_filled(pos2(line.right(), line.center().y), 4.0, colour); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), t.space_12), Sense::drag()); + crate::ui_kit::history_marker(ui.painter(), rect, true, crate::theme::TabAccent::for_tab(&t, &app.ui.tab)); crate::scenario::publish_handle("timeline:rollback", rect.center()); + crate::scenario::publish_rect("history:marker", rect); if response.drag_started() { *drag = Some(Drag::Marker); } - response.on_hover_text("Rollback bar: drag to roll the model back; new features are inserted here"); - let _ = app; + response.on_hover_text(crate::i18n::tr("ui.history_marker_tip")); } fn group_for(groups: &[solidcraft_engine::doc::TimelineGroup], feature: u64) -> Option { @@ -496,12 +764,16 @@ fn timeline_group_name( group: &solidcraft_engine::doc::TimelineGroup, rect: Rect, offset: f32, + names: bool, t: &Tokens, ) -> bool { let editing = matches!(app.menu.rename.as_ref().map(|rename| &rename.what), Some(crate::context_menu::RenameWhat::TimelineGroup(id)) if *id == group.id); if !editing { - ui.painter().text( + if !names { + return false; + } + ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())).text( pos2(rect.left() + 40.0 + offset, rect.center().y), egui::Align2::LEFT_CENTER, &group.name, @@ -540,6 +812,7 @@ fn timeline_group_name( fn vertical_group_row( app: &mut SolveApp, + names: bool, ui: &mut egui::Ui, group: &solidcraft_engine::doc::TimelineGroup, groups: &[solidcraft_engine::doc::TimelineGroup], @@ -562,18 +835,18 @@ fn vertical_group_row( group: group.parent, indent_group: previous_visible_group.filter(|previous| Some(*previous) != group.parent), }); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 23.0), Sense::click_and_drag()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), crate::ui_kit::TREE_ROW_HEIGHT), Sense::click_and_drag()); drop_zones.push((rect, group.id)); slots.push(VerticalSlot { y: rect.bottom(), position: if open { position } else { end_position }, group: Some(group.id), indent_group: None }); if selected || response.hovered() { ui.painter().rect_filled(rect, 3.0, if selected { crate::theme::TabAccent::current(ui.ctx()).soft } else { t.hover }); } - let offset = depth as f32 * 14.0; + let offset = if names { depth as f32 * 14.0 } else { 0.0 }; let centre = pos2(rect.left() + 9.0 + offset, rect.center().y); crate::ui_kit::disclosure(ui.painter(), centre, open, t.text_dim); let icon = Rect::from_center_size(pos2(rect.left() + 27.5 + offset, rect.center().y), vec2(17.0, 17.0)); icons::paint(ui.painter(), icon, "folder", t.icon, t.icon_fill, t.accent); - let renaming = timeline_group_name(app, ui, group, rect, offset, &t); + let renaming = timeline_group_name(app, ui, group, rect, offset, names, &t); crate::scenario::publish_handle(&format!("timeline-folder:{}", group.name), rect.center()); let fold_rect = Rect::from_min_max(pos2(rect.left() + offset, rect.top()), pos2(rect.left() + offset + 18.0, rect.bottom())); crate::scenario::publish_handle(&format!("timeline-folder-fold:{}", group.name), fold_rect.center()); @@ -611,9 +884,9 @@ fn vertical_group_row( open } -fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui) { +fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { let t = Tokens::get(); - ui.spacing_mut().item_spacing.y = 0.0; + ui.spacing_mut().item_spacing.y = if names { t.space_2 } else { t.space_4 }; let features: Vec<_> = app .session .doc @@ -665,6 +938,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui) { if group_ancestors_are_open(app, &groups, group.id) && shown_groups.insert(group.id) { vertical_group_row( app, + names, ui, group, &groups, @@ -694,62 +968,44 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui) { let has_patterns = matches!(kind, TimelineKind::Sketch) && crate::sketch_pattern_tree::has_patterns(app, *id); let pattern_key = format!("timeline/sketch/{id}/patterns"); let patterns_open = crate::browser::is_open(app, &pattern_key, true); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click_and_drag()); + let style = if names { crate::ui_kit::HistoryStyle::Names } else { crate::ui_kit::HistoryStyle::Icons }; + let (row, response) = ui.allocate_exact_size(vec2(ui.available_width(), style.height()), Sense::click_and_drag()); + let rect = if style == crate::ui_kit::HistoryStyle::Icons { + Rect::from_center_size(row.center(), vec2(style.height(), style.height())) + } else { + row + }; + crate::scenario::publish_rect(&format!("history:feature:{name}"), rect); let fold_rect = Rect::from_min_size(rect.left_top() + vec2(indent, 0.0), vec2(16.0, rect.height())); let on_fold = has_patterns && response.interact_pointer_pos().is_some_and(|p| fold_rect.contains(p)); crate::scenario::publish_handle(&format!("timeline:{name}"), rect.center()); let result = app.session.model.result(*id); + let elapsed = result.map(|r| r.ms); let error = result.and_then(|result| result.error.clone()); let warning = result.and_then(|result| result.warning.clone()); let rolled = index >= marker; let selected = app.session.selection.iter().any(|selection| matches!(selection, solidcraft_engine::Sel::Feature { id: selected } if selected == id)); - let background = if error.is_some() { - t.timeline_item_error - } else if selected { - crate::theme::TabAccent::current(ui.ctx()).soft - } else if response.hovered() || from_view == Some(*id) { - t.hover - } else { - Color32::TRANSPARENT - }; - if background != Color32::TRANSPARENT { - ui.painter().rect_filled(rect, 3.0, background); + // Folder and sketch-pattern disclosure targets retain their original handles. + let inset = if names { indent + if has_patterns { 16.0 } else { 0.0 } } else { 0.0 }; + let chip = Rect::from_min_max(rect.min + vec2(inset.min(rect.width()), 0.0), rect.max); + crate::ui_kit::HistoryChip { + icon, + name, + kind: ty, + selected, + hovered: response.hovered() || from_view == Some(*id), + dim: rolled, + suppressed: *suppressed, + error: error.is_some(), + warning: warning.is_some(), + accent: crate::theme::TabAccent::for_tab(&t, &app.ui.tab), } + .paint(ui.painter(), chip, style); if has_patterns { crate::ui_kit::disclosure(ui.painter(), fold_rect.center(), patterns_open, t.text_dim); crate::scenario::publish_handle(&format!("timeline-sketch-fold:{name}"), fold_rect.center()); } - let icon_rect = - Rect::from_center_size(pos2(rect.left() + 13.0 + indent + if has_patterns { 16.0 } else { 0.0 }, rect.center().y), vec2(18.0, 18.0)); - let ink = if rolled || *suppressed { t.border } else { t.icon }; - icons::paint(ui.painter(), icon_rect, icon, ink, if rolled { t.panel_header } else { t.icon_fill }, if rolled { t.border } else { t.accent }); - if *suppressed { - ui.painter().line_segment([icon_rect.left_bottom(), icon_rect.right_top()], Stroke::new(1.5, t.text_dim)); - } - let text_colour = if rolled || *suppressed { t.text_dim } else { t.text }; - ui.painter().text( - pos2(icon_rect.right() + 7.0, rect.center().y), - egui::Align2::LEFT_CENTER, - name, - egui::FontId::proportional(crate::theme::Tokens::get().font_body), - text_colour, - ); - // A failed feature has a mark of its own, not only its colour (#972). - if error.is_some() { - let at = Rect::from_min_size(pos2(rect.right() - 15.0, rect.center().y - 6.0), vec2(12.0, 12.0)); - icons::paint(ui.painter(), at, "error", t.panel, t.error, t.error); - } - if warning.is_some() && error.is_none() { - icons::paint( - ui.painter(), - Rect::from_min_size(pos2(rect.right() - 15.0, rect.center().y - 6.0), vec2(12.0, 12.0)), - "warning", - t.icon, - t.warning, - t.warning, - ); - } if response.hovered() { hovered = Some(*id); } @@ -760,9 +1016,23 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui) { let origin_x = drag_press_x(&response, rect.center().x); drag = Some(Drag::Items(selected_drag_items(app, origin_x, group_id))); } - let mut tip = crate::timeline::status_text(name, ty, error.as_deref(), warning.as_deref()); - tip.push_str("\nDouble-click to edit · drag to reorder · right-click for more"); - let response = response.on_hover_text(tip); + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip.popup.align(egui::RectAlign::RIGHT_START); + tooltip.show(|ui| { + let summary = app + .session + .doc + .features + .get(index) + .and_then(|f| f.kind.expressions().first().map(ToString::to_string)) + .unwrap_or_else(|| elapsed.map_or_else(String::new, |ms| format!("{ms:.1} ms"))); + let kind = crate::i18n::tr_label(ty.strip_suffix("Feature").unwrap_or(ty)); + let mut tip = format!("{name} · {kind} · {summary}"); + if error.is_some() || warning.is_some() { + tip.push_str(&format!("\n{}", crate::timeline::status_text(name, ty, error.as_deref(), warning.as_deref()))); + } + crate::ui_kit::text(ui, &tip, crate::ui_kit::Text::Value("history", false)); + }); if response.clicked() && on_fold { crate::browser::toggle(app, &pattern_key, true); } else if response.clicked() { @@ -809,7 +1079,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui) { ui.close(); } }); - if has_patterns && patterns_open { + if names && has_patterns && patterns_open { let depth = group_id.map_or(1, |group| group_depth(&groups, group) + 2); crate::sketch_pattern_tree::rows(app, ui, *id, depth, "timeline", None, false); } @@ -821,6 +1091,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui) { if group_ancestors_are_open(app, &groups, group.id) && shown_groups.insert(group.id) { vertical_group_row( app, + names, ui, group, &groups, @@ -859,9 +1130,11 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui) { ui.painter().rect_stroke(rect.shrink(1.0), 3.0, Stroke::new(2.0, t.sketch_accent), egui::StrokeKind::Inside); } else { let left = vertical_drop_bar_left(ui.min_rect().left(), folder_target, &groups); - ui.painter().line_segment( - [pos2(left, slot.y), pos2(ui.max_rect().right() - 5.0, slot.y)], - Stroke::new(2.0, if matches!(active, Drag::Marker) { crate::theme::TabAccent::current(ui.ctx()).color } else { t.sketch_accent }), + crate::ui_kit::history_drop_bar( + ui.painter(), + Rect::from_min_max(pos2(left, slot.y), pos2(ui.max_rect().right() - 5.0, slot.y)), + true, + if matches!(active, Drag::Marker) { crate::theme::TabAccent::current(ui.ctx()).color } else { t.sketch_accent }, ); } } @@ -913,45 +1186,394 @@ mod tests { use crate::scenario::{Harness, handle_at}; #[test] - fn left_history_shows_named_features_and_folders_above_the_browser() { - let mut harness = Harness::new(); - harness.app.preferences.timeline_left = true; - harness.app.run("solid.box", json!({"length": 20, "width": 15, "height": 10, "name": "Base"})).unwrap(); - harness.app.run("solid.fillet", json!({"edges": [[20, 7.5, 10]], "radius": 1, "name": "Round"})).unwrap(); - harness.app.run("timeline.group", json!({"name": "Housing", "features": ["Base", "Round"]})).unwrap(); - harness.frames(4); - - let folder = handle_at("timeline-folder:Housing").unwrap(); - let base = handle_at("timeline:Base").unwrap(); - let round = handle_at("timeline:Round").unwrap(); - let browser = handle_at("row:Untitled").unwrap(); - assert!(folder.x < 250.0 && base.x < 250.0 && round.x < 250.0); - assert!(folder.y < base.y && base.y < round.y); - assert!(round.y < browser.y, "the parts/scene browser belongs below the feature history"); + fn docking_previews_match_all_three_destinations_and_stacked_collapse_shares_height() { + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.layout = mode; + h.call("ui.resize", json!({"width":1400,"height":1000})); + h.app.preferences.timeline_left = true; + h.app.preferences.timeline_left_width = 240.0; + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"name":"First"})).unwrap(); + h.frames(6); + let design = h.app.session.doc.to_json(); + let projection = h.app.viewport.rect; + for (dock, point) in [("bottom", pos2(700.0, 990.0)), ("left", pos2(10.0, 400.0)), ("under_browser", pos2(130.0, 700.0))] { + let grip = handle_at("history:grip").expect("dock grip"); + h.app.synthetic.push(egui::Event::PointerMoved(grip)); + h.frame(); + h.app.synthetic.push(egui::Event::PointerButton { + pos: grip, + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }); + h.frame(); + h.app.synthetic.push(egui::Event::PointerMoved(point)); + h.frames(2); + let preview = crate::scenario::rect_of("history:dock_preview").expect("dock preview"); + h.app.synthetic.push(egui::Event::PointerButton { + pos: point, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.frames(6); + assert_eq!(h.app.preferences.timeline_left, dock != "bottom"); + assert_eq!(h.app.preferences.timeline_under_browser, dock == "under_browser"); + let card = h.app.shell.history.expect("history bounds"); + assert!( + (preview.min - card.min).length() < 1.0 && (preview.max - card.max).length() < 1.0, + "{mode:?} {dock}: preview={preview:?} card={card:?}" + ); + assert_eq!(h.app.session.doc.to_json(), design); + if mode == crate::shell::LayoutMode::Floating { + assert_eq!(h.app.viewport.rect, projection); + } + } + let browser = h.app.shell.browser.unwrap(); + let history = h.app.shell.history.unwrap(); + assert!((browser.width() - history.width()).abs() < 1.0); + assert!((browser.height() - history.height()).abs() < 1.0); + assert!(browser.bottom() < history.top()); + let at = handle_at("history:collapse").unwrap(); + h.call("ui.click", json!({"x":at.x,"y":at.y})); + h.frames(5); + assert!(h.app.shell.history.unwrap().height() <= header_outer_height() + 1.0); + assert!(h.app.shell.browser.unwrap().height() > browser.height() * 1.5); + let at = handle_at("left-browser-toggle").unwrap(); + h.call("ui.click", json!({"x":at.x,"y":at.y})); + h.frames(5); + assert!(h.app.preferences.timeline_left_browser_collapsed); + assert!(h.app.preferences.timeline_collapsed); + let folded_browser = h.app.shell.browser.unwrap(); + let folded_history = h.app.shell.history.unwrap(); + assert!(folded_browser.height() <= header_outer_height() + 1.0); + assert!(folded_history.height() <= header_outer_height() + 1.0); + assert!((folded_history.top() - folded_browser.bottom() - crate::shell::SHELL_GAP).abs() < 1.0); + let at = handle_at("history:collapse").unwrap(); + h.call("ui.click", json!({"x":at.x,"y":at.y})); + h.frames(5); + assert!(h.app.preferences.timeline_left_browser_collapsed); + assert!(!h.app.preferences.timeline_collapsed); + assert!(h.app.shell.history.unwrap().height() > history.height() * 1.5); + h.app.preferences.browser_width = 310.0; + h.frames(5); + assert!((h.app.shell.history.unwrap().width() - 310.0).abs() < 1.0); + assert!((h.app.shell.browser.unwrap().width() - 310.0).abs() < 1.0); + // Browser-first collapse must also leave both independent folded headers at the top. + let at = handle_at("history:collapse").unwrap(); + h.call("ui.click", json!({"x":at.x,"y":at.y})); + h.frames(5); + assert!(h.app.preferences.timeline_left_browser_collapsed && h.app.preferences.timeline_collapsed); + assert!((h.app.shell.browser.unwrap().top() - browser.top()).abs() < 1.0); + assert!(h.app.shell.history.unwrap().bottom() < browser.top() + header_outer_height() * 2.0 + crate::shell::SHELL_GAP + 1.0); + } } #[test] - fn history_browser_divider_resizes_and_browser_collapses() { - let mut harness = Harness::new(); - harness.app.preferences.timeline_left = true; - harness.app.preferences.timeline_left_height = 180.0; - harness.frames(4); + fn folding_cards_follow_their_bounds_through_the_last_animation_frame() { + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.layout = mode; + h.app.preferences.timeline_left = true; + h.app.preferences.timeline_under_browser = true; + h.app.preferences.browser_width = 220.0; + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.frames(6); + // Both closing orders, expansion, and reversal before a transition completes. + for (browser, history, frames) in + [(true, false, 12), (true, true, 12), (false, true, 12), (false, false, 12), (true, true, 3), (false, false, 12)] + { + h.app.preferences.timeline_left_browser_collapsed = browser; + h.app.preferences.timeline_collapsed = history; + for frame in 0..frames { + h.frame(); + let available = h.app.shell.history_dock_space.unwrap(); + let expected = stacked_rects(&h.app, available); + for (name, actual, target) in + [("Browser", h.app.shell.browser.unwrap(), expected.0), ("History", h.app.shell.history.unwrap(), expected.1)] + { + assert!( + (actual.min - target.min).length() < 1.0 && (actual.max - target.max).length() < 1.0, + "{mode:?} {name}, frame {frame}, folds ({browser}, {history}): {actual:?} != {target:?}" + ); + } + } + } + } + } - let divider = handle_at("left-history-divider").unwrap(); - let before = harness.app.preferences.timeline_left_height; - harness.step(&json!({"drag": [[divider.x, divider.y], [divider.x, divider.y + 40.0]]})).unwrap(); - assert!( - harness.app.preferences.timeline_left_height > before + 20.0, - "dragging the divider should remember a taller history section: {before} -> {}", - harness.app.preferences.timeline_left_height - ); + #[test] + fn all_four_transport_buttons_move_to_their_named_positions_in_every_layout() { + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + for (dock, width) in + [("bottom", 130.0), ("left", 56.0), ("left", crate::ui_kit::history_width(true)), ("left", 320.0), ("under_browser", 170.0)] + { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.layout = mode; + h.app.preferences.browser_width = 170.0; + h.app.run("view.history_layout", json!({"dock":dock,"width":width})).unwrap(); + for i in 0..3 { + h.app + .run( + "solid.box", + json!({"length":10,"width":10,"height":10,"corner":[i*20,0,0],"operation":"new_body","name":format!("Step {i}")}), + ) + .unwrap(); + } + h.settle(); + let features = h.app.session.doc.features.clone(); + for control in crate::ui_kit::HistoryTransport::ALL { + let button = crate::scenario::rect_of(&format!("history:{}", control.id())).unwrap(); + let header = crate::scenario::rect_of(if dock == "bottom" { + if mode == crate::shell::LayoutMode::Floating { "history:card" } else { "history:strip" } + } else { + "history:header" + }) + .unwrap(); + assert!(header.contains_rect(button), "{mode:?} {dock} {width}: transport button {button:?} outside {header:?}"); + } + for (control, position) in [ + ("first", Some(0)), + ("back", Some(0)), + ("forward", Some(1)), + ("forward", Some(2)), + ("back", Some(1)), + ("last", None), + ("back", Some(2)), + ("back", Some(1)), + ("forward", Some(2)), + ("forward", None), + ("forward", None), + ("first", Some(0)), + ("last", None), + ] { + h.step(&json!({"click":{"handle":format!("history:{control}")}})).unwrap(); + h.settle(); + assert_eq!(h.app.session.doc.marker, position, "{mode:?} {dock} {width}: {control}"); + assert_eq!(h.app.session.model.state().bodies.len(), position.unwrap_or(3)); + assert_eq!(h.app.session.doc.features, features, "transport only moves the marker"); + } + } + } + } - harness.step(&json!({"click": {"handle": "left-browser-toggle"}})).unwrap(); - assert!(harness.app.preferences.timeline_left_browser_collapsed); - assert!(handle_at("row:Untitled").is_none(), "the collapsed browser should hide its rows"); - harness.step(&json!({"click": {"handle": "left-browser-toggle"}})).unwrap(); - assert!(!harness.app.preferences.timeline_left_browser_collapsed); - assert!(handle_at("row:Untitled").is_some(), "expanding the browser should restore its rows"); + #[test] + fn seam_snaps_only_between_thin_and_medium_and_persists_free_widths() { + let medium = crate::ui_kit::history_width(true); + for (width, delta, expected) in [(56.0, 40.0, medium), (medium, -40.0, 56.0), (medium, 63.0, medium + 63.0), (320.0, -41.0, 279.0)] { + let mut h = Harness::new(); + h.app.preferences.timeline_left = true; + h.app.preferences.timeline_left_width = width; + h.settle(); + let card = crate::scenario::rect_of("history:vertical").unwrap(); + let start = pos2(card.right() - 4.0, card.top() + 12.0); + h.step(&json!({"drag":[[start.x,start.y],[start.x+delta,start.y]]})).unwrap(); + h.settle(); + assert!((h.app.preferences.timeline_left_width - expected).abs() < 1.0); + assert!(h.app.shell.history_drag_width.is_none()); + assert!((crate::scenario::rect_of("history:vertical").unwrap().width() - expected).abs() < 1.0); + assert!(h.app.dialog.is_none()); + let mut restored = Harness::new(); + restored.app.load_prefs(&h.app.prefs()); + assert_eq!(restored.app.preferences.timeline_left_width, expected); + } + } + + #[test] + fn contents_follow_measured_width_without_a_names_setting() { + for width in [56.0, crate::ui_kit::history_width(true), 168.0, 213.0, 320.0] { + let mut h = Harness::new(); + h.app.preferences.timeline_left = true; + h.app.preferences.timeline_left_width = width; + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"name":"First"})).unwrap(); + h.settle(); + let row = crate::scenario::rect_of("history:feature:First").unwrap(); + let back = handle_at("history:back").unwrap(); + let play = handle_at("history:last").unwrap(); + assert_eq!(row.height(), if width < crate::ui_kit::history_width(true) { 38.0 } else { crate::ui_kit::TREE_ROW_HEIGHT }); + assert_eq!(handle_at("history:grip").is_some(), width >= crate::ui_kit::history_width(true)); + assert_eq!(back.y == play.y, width >= crate::ui_kit::history_width(true)); + if width == crate::ui_kit::history_width(true) { + assert!(crate::scenario::rect_of("history:title").is_none()); + } + if width >= 213.0 { + assert!(crate::scenario::rect_of("history:title").is_some()); + } + assert!(!crate::shortcut_box::search(&h.app, "history names").iter().any(|row| row.0 == "view.history_names")); + } + } + + #[test] + fn transport_to_first_item_gap_is_at_most_twelve_points() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + for names in [false, true] { + let mut h = Harness::new(); + h.app.ui.dark = dark; + h.app.preferences.theme = if dark { "dark" } else { "light" }.into(); + h.app.ui.layout = mode; + h.app.preferences.timeline_left = true; + h.app.preferences.timeline_left_width = crate::ui_kit::history_width(names); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"name":"First"})).unwrap(); + for selected in [false, true] { + if selected { + let id = h.app.session.doc.features.first().unwrap().id; + h.app.run("select.set", json!({"items":[{"type":"feature","id":id}]})).unwrap(); + } + h.settle(); + assert_eq!(crate::theme::is_dark(), dark); + let transport = crate::scenario::rect_of("history:transport").unwrap(); + let first = crate::scenario::rect_of("history:feature:First").unwrap(); + let gap = first.top() - transport.bottom(); + assert!((0.0..=12.0).contains(&gap), "gap={gap} dark={dark} mode={mode:?} names={names} selected={selected}"); + } + } + } + } + crate::theme::set_dark(previous); + } + + #[test] + fn rendered_strip_content_never_exceeds_the_viewport_during_resize() { + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + for width in [70.0, 100.0, 130.0, 200.0] { + for drag_width in [None, Some(60.0), Some(112.0), Some(160.0)] { + let ctx = crate::fonts::test_context(); + let mut app = crate::test_support::sample_app(); + app.ui.layout = mode; + app.preferences.timeline_left = true; + app.shell.history_drag_width = drag_width; + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 600.0)); + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| left_panel(&mut app, ui)); + out.textures_delta.clear(); + } + if let Some(card) = app.shell.history { + assert!(screen.contains_rect(card), "mode={mode:?} viewport={screen:?} card={card:?}"); + } + } + } + } + } + + #[test] + fn history_seam_widths_stay_inside_small_viewports() { + let mut app = crate::test_support::sample_app(); + for names in [false, true] { + app.preferences.timeline_left_width = crate::ui_kit::history_width(names); + for drag in [None, Some(112.0), Some(f32::INFINITY)] { + app.shell.history_drag_width = drag; + for width in [0.0, 20.0, 56.0, 100.0, 200.0, 800.0] { + let available = Rect::from_min_size(pos2(15.0, 30.0), vec2(width, 300.0)); + assert!(available.contains_rect(floating_rect(&app, available))); + } + } + } + } + + #[test] + fn both_widths_keep_selection_reorder_marker_transport_and_feature_menus() { + for names in [false, true] { + let mut h = Harness::new(); + h.app.preferences.timeline_left = true; + h.app.preferences.timeline_left_width = crate::ui_kit::history_width(names); + for (name, x) in [("First", 0), ("Second", 20)] { + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"corner":[x,0,0],"operation":"new_body","name":name})).unwrap(); + } + h.settle(); + h.step(&json!({"click":{"handle":"timeline:First"}})).unwrap(); + h.step(&json!({"click":{"handle":"timeline:Second"},"ctrl":true})).unwrap(); + assert_eq!(selected_feature_ids(&h.app).len(), 2); + h.step(&json!({"click":{"handle":"timeline:Second"},"button":"right"})).unwrap(); + h.step(&json!({"widget":"Copy"})).unwrap(); + assert_eq!(h.app.session.clipboard.len(), 2); + h.app.run("select.clear", json!({})).unwrap(); + h.settle(); + let first = handle_at("timeline:First").unwrap(); + h.step(&json!({"drag":[{"handle":"timeline:Second"},[first.x,first.y-15.0]]})).unwrap(); + h.settle(); + assert_eq!(h.app.session.doc.features.first().unwrap().name, "Second"); + let first = handle_at("timeline:Second").unwrap(); + h.step(&json!({"drag":[{"handle":"timeline:rollback"},[first.x,first.y-15.0]]})).unwrap(); + h.settle(); + assert_eq!(h.app.session.doc.marker, Some(0)); + h.step(&json!({"click":{"handle":"history:forward"}})).unwrap(); + h.settle(); + assert_eq!(h.app.session.doc.marker, Some(1)); + h.step(&json!({"click":{"handle":"history:last"}})).unwrap(); + h.settle(); + assert_eq!(h.app.session.doc.marker, None); + h.frames(40); + h.step(&json!({"click":{"handle":"timeline:First"},"double":true})).unwrap(); + h.frames(3); + assert!(h.app.dialog.is_some(), "double-click edits the feature, names={names}"); + } + } + + #[test] + fn history_is_left_of_the_browser_in_both_layouts_widths_and_browser_states() { + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + for names in [false, true] { + for collapsed in [false, true] { + let mut h = Harness::new(); + h.app.ui.layout = mode; + h.app.preferences.timeline_left = true; + h.app.preferences.timeline_left_width = crate::ui_kit::history_width(names); + h.app.preferences.timeline_left_browser_collapsed = collapsed; + h.app.run("solid.box", json!({"length":20,"width":15,"height":10,"name":"Base"})).unwrap(); + h.app.run("solid.fillet", json!({"edges":[[20,7.5,10]],"radius":1,"name":"Round"})).unwrap(); + h.app.run("timeline.group", json!({"name":"Housing","features":["Base","Round"]})).unwrap(); + h.settle(); + let history = crate::scenario::rect_of("history:vertical").unwrap(); + let browser = crate::scenario::rect_of("browser:card").unwrap(); + assert!(history.right() < browser.left(), "{mode:?}, names={names}, collapsed={collapsed}: {history:?}, {browser:?}"); + assert_eq!(history.width(), crate::ui_kit::history_width(names)); + assert_eq!(handle_at("row:Untitled").is_none(), collapsed); + let folder = handle_at("timeline-folder:Housing").unwrap(); + let base = handle_at("timeline:Base").unwrap(); + let round = handle_at("timeline:Round").unwrap(); + assert!(folder.y < base.y && base.y < round.y); + let row = crate::scenario::rect_of("history:feature:Base").unwrap(); + assert_eq!(row.height(), if names { crate::ui_kit::TREE_ROW_HEIGHT } else { 38.0 }); + if names && !collapsed { + let browser_row = crate::browser::drawn_rows().into_iter().find(|r| r.0 == "Untitled").unwrap().1; + assert_eq!(row.height(), browser_row.height()); + } + } + } + } + } + + #[test] + fn history_width_toggle_and_browser_rail_persist_independently() { + let mut h = Harness::new(); + h.app.preferences.timeline_left = true; + h.settle(); + h.step(&json!({"click":{"handle":"history:names"}})).unwrap(); + assert!(h.app.preferences.timeline_left_width < crate::ui_kit::history_width(true)); + h.step(&json!({"click":{"handle":"left-browser-toggle"}})).unwrap(); + assert!(h.app.preferences.timeline_left_browser_collapsed); + assert!(handle_at("row:Untitled").is_none()); + let mut restored = Harness::new(); + restored.app.load_prefs(&h.app.prefs()); + assert!(restored.app.preferences.timeline_left_width < crate::ui_kit::history_width(true)); + assert!(restored.app.preferences.timeline_left_browser_collapsed); + h.settle(); + h.step(&json!({"click":{"handle":"left-browser-toggle"}})).unwrap(); + assert!(!h.app.preferences.timeline_left_browser_collapsed); + assert!(handle_at("row:Untitled").is_some()); + h.step(&json!({"click":{"handle":"history:names"}})).unwrap(); + assert!(h.app.preferences.timeline_left_width >= crate::ui_kit::history_width(true)); + h.step(&json!({"key":"Enter"})).unwrap(); + assert!(h.app.preferences.timeline_left_width < crate::ui_kit::history_width(true), "focused seam handles Enter in the app"); + h.step(&json!({"key":"Space"})).unwrap(); + assert!(h.app.preferences.timeline_left_width >= crate::ui_kit::history_width(true), "focused seam handles Space in the app"); } #[test] @@ -1179,7 +1801,7 @@ mod tests { harness.frames(4); harness.step(&json!({"click": {"handle": "timeline:Feature"}})).unwrap(); - harness.step(&json!({"widget": "1 selected"})).unwrap(); + harness.step(&json!({"click": {"handle": "timeline:Feature"}, "button": "right"})).unwrap(); harness.step(&json!({"widget": "Add to New Folder"})).unwrap(); harness.frames(2); diff --git a/crates/ui-egui/src/ui_kit/disclosure.rs b/crates/ui-egui/src/ui_kit/disclosure.rs index 62ed11754..34d12c622 100644 --- a/crates/ui-egui/src/ui_kit/disclosure.rs +++ b/crates/ui-egui/src/ui_kit/disclosure.rs @@ -13,13 +13,26 @@ pub(crate) fn disclosure(painter: &Painter, center: Pos2, open: bool, ink: Color /// Fold action in existing chrome. Stable identity across state changes, with the caller's /// translated tooltip and scenario handles. Tokens: control_radius, hover, form_ink/dim. pub(crate) fn disclosure_button_at(ui: &mut Ui, rect: Rect, open: bool, label: &str) -> Response { + disclosure_button_with_hover(ui, rect, open, label, false) +} + +/// Panel fold action with the browser's shared blue hover tint. +pub(crate) fn panel_disclosure_button_at(ui: &mut Ui, rect: Rect, open: bool, label: &str) -> Response { + disclosure_button_with_hover(ui, rect, open, label, true) +} + +fn disclosure_button_with_hover(ui: &mut Ui, rect: Rect, open: bool, label: &str, panel: bool) -> Response { let t = Tokens::get(); let response = ui.interact(rect, ui.make_persistent_id("disclosure_button"), egui::Sense::click()); if response.clicked() { response.request_focus(); } if response.hovered() { - ui.painter().rect_filled(rect, t.control_radius, t.hover); + if panel { + super::panel_header_hover(ui.painter(), rect); + } else { + ui.painter().rect_filled(rect, t.control_radius, t.hover); + } } disclosure(ui.painter(), rect.center(), open, if response.hovered() || response.has_focus() { t.form_ink } else { t.form_dim }); response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, ui.is_enabled(), open, label)); diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs index f002e7dc8..84808167a 100644 --- a/crates/ui-egui/src/ui_kit/gallery.rs +++ b/crates/ui-egui/src/ui_kit/gallery.rs @@ -28,6 +28,32 @@ macro_rules! element { // One entry per element/variant: names, rendering and geometry expectations stay together. const ELEMENTS: &[Element] = &[ + element!("history_transport", |ui, _| { + ui.horizontal(|ui| { + let side = Tokens::get().space_24; + for control in HistoryTransport::ALL { + let (rect, _) = ui.allocate_exact_size(vec2(side, side), egui::Sense::hover()); + control.show(ui, rect); + } + }); + }), + element!("history_marker", |ui, _| { + let t = Tokens::get(); + let accent = crate::theme::TabAccent::for_tab(&t, "SURFACE"); + ui.horizontal(|ui| { + let (rect, _) = ui.allocate_exact_size(vec2(t.space_24 * 7.0, t.space_12), egui::Sense::hover()); + ui.painter().rect_filled(rect, 0.0, t.panel); + history_marker(ui.painter(), rect, true, accent); + let (rect, _) = ui.allocate_exact_size(vec2(t.space_12, t.control_height), egui::Sense::hover()); + ui.painter().rect_filled(rect, 0.0, t.timeline); + history_marker(ui.painter(), rect, false, accent); + }); + }), + element!("history_seam_rest", |ui, _| history_seam_example(ui, HistoryHandleState::Rest)), + element!("history_seam_hover", |ui, _| history_seam_example(ui, HistoryHandleState::Hover)), + element!("history_seam_drag", |ui, _| history_seam_example(ui, HistoryHandleState::Drag)), + element!("history_icons", |ui, _| history_example(ui, false)), + element!("history_names", |ui, _| history_example(ui, true)), element!("command_search", |ui, _| { let mut query = "fillet".to_owned(); CommandSearch::field( @@ -441,6 +467,13 @@ const ELEMENTS: &[Element] = &[ ui.push_id(open, |ui| disclosure_button_at(ui, rect, open, crate::i18n::tr_label(if open { "Collapse" } else { "Expand" }))); } }), + element!("panel_disclosure_button_at", |ui, _| { + let t = Tokens::get(); + for open in [true, false] { + let (rect, _) = ui.allocate_exact_size(vec2(t.form_close_size, t.form_close_size), egui::Sense::hover()); + ui.push_id(open, |ui| panel_disclosure_button_at(ui, rect, open, crate::i18n::tr_label(if open { "Collapse" } else { "Expand" }))); + } + }), element!("dropdown_indicator", |ui, _| { let t = Tokens::get(); let (rect, _) = ui.allocate_exact_size(vec2(t.form_section_icon_size, t.form_section_icon_size), egui::Sense::hover()); @@ -713,7 +746,7 @@ const ELEMENTS: &[Element] = &[ fn example(ui: &mut Ui, element: &Element) -> (&'static str, Option<&'static str>) { let mut sample = Sample { value: "12 mm".into(), second: "25 mm".into(), selected: 0, checked: true }; let rect = ui.scope(|ui| (element.draw)(ui, &mut sample)).response.rect; - if matches!(element.name, "menu" | "menu_submenu" | "rename_menu" | "workspace_menu" | "command_search") { + if matches!(element.name, "menu" | "menu_submenu" | "rename_menu" | "workspace_menu" | "command_search" | "history_icons" | "history_names") { // A popup's elevation is painted outside its layout rectangle. Reserve those // actual shadow bounds as part of the gallery sample, keeping the paint guard strict. ui.expand_to_include_rect(rect + Menu::frame().shadow.margin()); @@ -1070,6 +1103,112 @@ fn gallery_covers_every_inline_element() { } } +#[cfg(test)] +fn history_seam_example(ui: &mut Ui, state: HistoryHandleState) { + let t = Tokens::get(); + let allocation = ui.allocate_space(vec2(280.0, 250.0)).1; + for (names, offset) in [(false, 0.0), (true, 125.0)] { + let width = if state == HistoryHandleState::Drag { 112.0 } else { history_width(names) }; + // Separate samples vertically so the guide/chip fits within the gallery allocation. + let card = egui::Rect::from_min_size(allocation.min + vec2(t.space_8, offset + t.space_8), vec2(width, 104.0)); + ui.painter().rect(card, t.radius_lg, t.panel, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + HistorySeam::new(card).paint(ui.painter(), card, names, state); + } +} + +#[cfg(test)] +fn history_example(ui: &mut Ui, names: bool) { + let mut app = crate::test_support::sample_app(); + app.preferences.timeline_left = true; + app.preferences.timeline_left_width = crate::ui_kit::history_width(names); + app.run("timeline.roll_to", serde_json::json!({"position":3})).unwrap(); + let feature = app.session.doc.features.get(2).unwrap().id; + app.run("select.set", serde_json::json!({"items":[{"type":"feature","id":feature}]})).unwrap(); + let width = crate::timeline_left::strip_width(&app); + let rect = ui.allocate_space(vec2(width, 650.0)).1; + ui.scope_builder(egui::UiBuilder::new().max_rect(rect.shrink(5.0)), |ui| { + ui.painter().add(crate::frame::shell_card(Tokens::get().panel).paint(rect)); + crate::timeline_left::left_timeline(&mut app, ui); + }); +} + +/// CPU captures of the actual vertical strip and browser, in both themes and widths. +#[test] +fn history_board_in_both_themes_and_widths() { + use super::checks::tests::{raster, textures_update}; + use std::collections::HashMap; + let previous = crate::theme::is_dark(); + for dark in [false, true] { + for names in [false, true] { + for collapsed in [false, true] { + for state in [HistoryHandleState::Rest, HistoryHandleState::Hover, HistoryHandleState::Drag] { + crate::theme::set_dark(dark); + let ctx = crate::fonts::test_context(); + ctx.set_visuals(if dark { egui::Visuals::dark() } else { egui::Visuals::light() }); + ctx.global_style_mut(|style| style.animation_time = 0.0); + let mut app = crate::test_support::sample_app(); + app.preferences.timeline_left = true; + app.preferences.timeline_left_width = crate::ui_kit::history_width(names); + app.preferences.timeline_left_browser_collapsed = collapsed; + app.run("timeline.roll_to", serde_json::json!({"position":3})).unwrap(); + let feature = app.session.doc.features.get(2).unwrap().id; + app.run("select.set", serde_json::json!({"items":[{"type":"feature","id":feature}]})).unwrap(); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(560.0, 680.0)); + let mut textures = HashMap::new(); + let mut image = None; + let mut drag_start = None; + for pass in 0..9 { + let mut events = vec![]; + if pass >= 2 { + let card = app.shell.history.unwrap(); + if state == HistoryHandleState::Hover { + events.push(egui::Event::PointerMoved(card.right_center())); + } else if state == HistoryHandleState::Drag { + let start = *drag_start.get_or_insert(egui::pos2(card.right() - 4.0, card.top() + 12.0)); + if pass == 2 { + events = crate::test_support::pointer(start, true); + } else if pass == 3 { + events.push(egui::Event::PointerMoved(start + vec2(112.0 - history_width(names), 0.0))); + } + } + } + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(bounds), time: Some(pass as f64 * 0.2), focused: true, events, ..Default::default() }, + |ui| { + ui.painter().rect_filled(bounds, 0.0, Tokens::get().viewport_top); + crate::timeline_left::left_panel(&mut app, ui); + crate::browser::floating(&mut app, ui, bounds); + }, + ); + textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + image = Some(raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures)); + } + if state == HistoryHandleState::Drag { + assert_eq!(app.shell.history_drag_width, Some(112.0)); + assert_eq!(app.shell.history.unwrap().width(), 112.0); + } + assert!(app.shell.history.unwrap().right() < app.shell.browser.unwrap().left()); + if let Ok(dir) = std::env::var("SOLIDCRAFT_HISTORY_EVIDENCE") { + std::fs::create_dir_all(&dir).unwrap(); + image + .unwrap() + .save(std::path::Path::new(&dir).join(format!( + "history-{}-{}-{}-{:?}.png", + if names { "names" } else { "icons" }, + if collapsed { "rail" } else { "browser" }, + if dark { "dark" } else { "light" }, + state + ))) + .unwrap(); + } + } + } + } + } + crate::theme::set_dark(previous); +} + /// Render actual egui geometry without a desktop window. Opt-in PNGs are reviewer evidence. #[test] fn menu_board_in_both_themes() { @@ -1186,20 +1325,20 @@ fn command_search_board_in_both_themes() { } /// Exercise the actual surface painters, including deliberately shared artwork whose -/// own accent differs from its tone or tab. +/// own accent differs from its tone, tab or feature kind. #[test] -fn confirm_radial_and_menu_danger_keep_multitone_artwork() { +fn confirm_radial_and_history_rows_keep_multitone_artwork() { let previous = crate::theme::is_dark(); for dark in [false, true] { crate::theme::set_dark(dark); let mut cases = vec![ - ("warning", "extrude", "MODEL", Some("construction"), 20), - ("danger", "extrude", "MODEL", Some("constraint"), 20), - ("info", "extrude", "MODEL", None, 20), - ("warning", "status_warning", "MODEL", Some("construction"), 20), - ("danger", "delete", "MODEL", Some("constraint"), 20), - ("danger_menu", "delete", "MODEL", Some("constraint"), 16), - ("info", "surface_extrude", "MODEL", None, 20), + ("warning", "extrude", "", "MODEL", Some("construction"), 20), + ("danger", "extrude", "", "MODEL", Some("constraint"), 20), + ("info", "extrude", "", "MODEL", None, 20), + ("warning", "status_warning", "", "MODEL", Some("construction"), 20), + ("danger", "delete", "", "MODEL", Some("constraint"), 20), + ("danger_menu", "delete", "", "MODEL", Some("constraint"), 16), + ("info", "surface_extrude", "", "MODEL", None, 20), ]; for (tab, ramp) in [ ("SKETCH", Some("sketch")), @@ -1212,11 +1351,26 @@ fn confirm_radial_and_menu_danger_keep_multitone_artwork() { ("unknown", None), ] { for surface in ["radial", "radial_hover"] { - cases.push((surface, "extrude", tab, ramp, 24)); + cases.push((surface, "extrude", "", tab, ramp, 24)); } } + for (kind, ramp) in [ + ("Sketch", Some("sketch")), + ("SurfaceExtrudeFeature", Some("surface")), + ("MeshFeature", Some("mesh")), + ("FormFeature", Some("form")), + ("ExtrudeFeature", None), + ] { + for (surface, side) in [("history_names", 15), ("history_icons", 19)] { + cases.push((surface, "extrude", kind, "MODEL", ramp, side)); + } + } + // Surface feature names without the Surface prefix use the same alias rule + // as the browser's timeline::icon_of assignments. + cases.push(("history_names", "surface_extrude", "ExtrudeFeature", "MODEL", Some("surface"), 15)); + cases.push(("history_names", "continuity", "MatchFeature", "MODEL", Some("surface"), 15)); let mut dominant_accents: std::collections::HashMap<&str, std::collections::HashSet> = std::collections::HashMap::new(); - for (surface, icon, tab, ramp, side) in cases { + for (surface, icon, kind, tab, ramp, side) in cases { let ctx = crate::fonts::test_context(); ctx.set_visuals(if dark { egui::Visuals::dark() } else { egui::Visuals::light() }); let mut app = crate::SolveApp::new(Default::default(), Default::default()); @@ -1239,6 +1393,26 @@ fn confirm_radial_and_menu_danger_keep_multitone_artwork() { item.danger = true; item.show(ui); } + "history_names" | "history_icons" => { + let style = if surface == "history_names" { HistoryStyle::Names } else { HistoryStyle::Icons }; + HistoryChip { + icon, + name: "Extrude1", + kind, + selected: false, + hovered: false, + dim: false, + suppressed: false, + error: false, + warning: false, + accent: crate::theme::TabAccent::for_tab(&Tokens::get(), "MODEL"), + } + .paint( + ui.painter(), + egui::Rect::from_min_size(egui::pos2(20.0, 20.0), vec2(158.0, style.height())), + style, + ); + } _ => { let tone = match surface { "warning" => Tone::Warning, @@ -1260,7 +1434,7 @@ fn confirm_radial_and_menu_danger_keep_multitone_artwork() { }) .expect("the surface must upload its icon texture"); let colours: std::collections::HashSet<_> = image.pixels.iter().filter(|pixel| pixel.a() == 255).copied().collect(); - assert!(colours.len() >= 2, "{surface}/{icon}/{tab}, dark={dark}: opaque artwork is a silhouette"); + assert!(colours.len() >= 2, "{surface}/{icon}/{kind}/{tab}, dark={dark}: opaque artwork is a silhouette"); let resolved = crate::icon_svg::resolve(icon); assert!(!resolved.placeholder, "{icon} needs a master"); let look = crate::icon_svg::Look { dark, accent: ramp.and_then(crate::icon_svg::accent_index), vision: crate::theme::vision() }; @@ -1282,7 +1456,7 @@ fn confirm_radial_and_menu_danger_keep_multitone_artwork() { assert_eq!( image.as_ref(), &egui::ColorImage::from_rgba_premultiplied([side, side], expected.data()), - "{surface}/{tab}: preserve roles with {ramp:?}" + "{surface}/{kind}/{tab}: preserve roles with {ramp:?}" ); if icon == "extrude" { let dominant = ["active-1", "active-2", "active-3"] @@ -1293,7 +1467,7 @@ fn confirm_radial_and_menu_danger_keep_multitone_artwork() { .into_iter() .max_by_key(|(count, _)| *count) .unwrap(); - assert!(dominant.0 > 0, "{surface}/{tab}: missing accent pixels"); + assert!(dominant.0 > 0, "{surface}/{kind}/{tab}: missing accent pixels"); let group = if matches!(surface, "warning" | "danger" | "info") { "confirm" } else { surface }; dominant_accents.entry(group).or_default().insert(dominant.1); } @@ -1302,11 +1476,13 @@ fn confirm_radial_and_menu_danger_keep_multitone_artwork() { super::checks::tests::textures_update(&mut textures, &output.textures_delta); let capture = super::checks::tests::raster(&ctx, output.shapes.clone(), output.pixels_per_point, bounds, &textures); std::fs::create_dir_all(&dir).unwrap(); - capture.save(std::path::Path::new(&dir).join(format!("{surface}-{icon}-{tab}-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + capture + .save(std::path::Path::new(&dir).join(format!("{surface}-{icon}-{kind}-{tab}-{}.png", if dark { "dark" } else { "light" }))) + .unwrap(); } output.textures_delta.clear(); } - for (group, count) in [("confirm", 3), ("radial", 5), ("radial_hover", 5)] { + for (group, count) in [("confirm", 3), ("radial", 5), ("radial_hover", 5), ("history_names", 5), ("history_icons", 5)] { assert_eq!(dominant_accents[group].len(), count, "{group}, dark={dark}: dominant accent pixels must differ across mappings"); } } diff --git a/crates/ui-egui/src/ui_kit/history.rs b/crates/ui-egui/src/ui_kit/history.rs new file mode 100644 index 000000000..4272f89c0 --- /dev/null +++ b/crates/ui-egui/src/ui_kit/history.rs @@ -0,0 +1,687 @@ +//! Shared history chips, dense name rows, drop bars and rollback markers. +use crate::{ + icons, + theme::{TabAccent, Tokens}, +}; +use egui::{Painter, Rect, Stroke, pos2, vec2}; + +/// Browser and named history rows use the same density. +pub(crate) const TREE_ROW_HEIGHT: f32 = 26.0; + +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum HistoryStyle { + Bottom, + Icons, + Names, +} + +impl HistoryStyle { + pub fn height(self) -> f32 { + let t = Tokens::get(); + match self { + Self::Bottom => t.control_height, + Self::Icons => t.control_height + t.space_10, + Self::Names => TREE_ROW_HEIGHT, + } + } +} + +pub(crate) struct HistoryChip<'a> { + pub icon: &'a str, + pub name: &'a str, + pub kind: &'a str, + pub selected: bool, + pub hovered: bool, + pub dim: bool, + pub suppressed: bool, + pub error: bool, + pub warning: bool, + pub accent: TabAccent, +} + +/// Share the feature classification across chips and name rows. Surface aliases also +/// cover Patch/Stitch/Thicken and other surface features without a Surface-prefixed kind. +fn feature_icon_accent(kind: &str, icon: &str) -> Option<&'static str> { + let tab = if kind.starts_with("Sketch") { + "SKETCH" + } else if kind.starts_with("Surface") || icon.starts_with("surface_") || icon == "continuity" { + "SURFACE" + } else if kind.starts_with("Mesh") { + "MESH" + } else if kind.starts_with("Form") { + "FORM" + } else { + "MODEL" + }; + crate::theme::icon_accent_for_tab(tab) +} + +impl HistoryChip<'_> { + /// All strip variants use this painter; no connections are drawn between features. + pub fn paint(&self, painter: &Painter, rect: Rect, style: HistoryStyle) { + let t = Tokens::get(); + let mut p = painter.clone(); + if self.dim || self.suppressed { + p.multiply_opacity(0.42); + } + let fill = if self.error { + t.form_error_fill + } else if self.selected { + self.accent.soft + } else if self.hovered { + t.hover + } else if style == HistoryStyle::Names { + egui::Color32::TRANSPARENT + } else { + t.timeline_item + }; + let edge = if self.error { + t.form_error + } else if self.selected || self.hovered { + self.accent.color + } else { + t.border + }; + let radius = if style == HistoryStyle::Icons { t.radius_lg } else { t.radius_sm }; + if style != HistoryStyle::Names || self.error { + let weight = if style == HistoryStyle::Icons && (self.selected || self.error) { 1.5 } else { 1.0 }; + p.rect(rect, radius, fill, Stroke::new(weight, edge), egui::StrokeKind::Inside); + } else { + p.rect_filled(rect, radius, fill); + } + let names = style == HistoryStyle::Names; + let side = if names { + t.space_14 + 1.0 + } else if style == HistoryStyle::Icons { + t.space_16 + t.space_3 + } else { + rect.height() - t.space_8 + }; + let icon = + Rect::from_center_size(if names { pos2(rect.left() + t.space_8 + side / 2.0, rect.center().y) } else { rect.center() }, vec2(side, side)); + icons::paint_accented(&p, icon, self.icon, feature_icon_accent(self.kind, self.icon), 1.0); + if names { + let ink = if self.selected { self.accent.ink } else { t.text }; + let font = if self.selected { crate::fonts::semibold(t.font_body) } else { egui::FontId::proportional(t.font_body) }; + let text_rect = Rect::from_min_max( + pos2(icon.right() + t.space_6 + 1.0, rect.top()), + pos2(rect.right() - if self.error || self.warning { t.space_16 } else { t.space_8 }, rect.bottom()), + ); + let galley = p.layout_no_wrap(self.name.to_owned(), font, ink); + p.with_clip_rect(text_rect.intersect(p.clip_rect())).galley(pos2(text_rect.left(), rect.center().y - galley.size().y / 2.0), galley, ink); + } + if self.suppressed { + p.line_segment([icon.left_bottom(), icon.right_top()], Stroke::new(1.5, t.text_dim)); + } + if self.error || self.warning { + let side = if names { t.space_12 } else { t.space_10 }; + let at = if names { pos2(rect.right() - t.space_3 - side, rect.center().y - side / 2.0) } else { rect.right_top() - vec2(side, 0.0) }; + icons::paint_icon(&p, Rect::from_min_size(at, vec2(side, side)), if self.error { "error" } else { "warning" }, 1.0); + } + } +} + +/// A single drop indicator in either strip orientation. +pub(crate) fn history_drop_bar(p: &Painter, rect: Rect, vertical: bool, colour: egui::Color32) { + let points = if vertical { + [pos2(rect.left(), rect.center().y), pos2(rect.right(), rect.center().y)] + } else { + [pos2(rect.center().x, rect.top()), pos2(rect.center().x, rect.bottom())] + }; + p.line_segment(points, Stroke::new(Tokens::get().space_2, colour)); +} + +/// Rollback line and hollow end circle; a vertical strip uses a horizontal line. +pub(crate) fn history_marker(p: &Painter, rect: Rect, vertical: bool, accent: TabAccent) { + let t = Tokens::get(); + let outer_radius = t.space_10 / 2.0; + let centre = if vertical { pos2(rect.right() - outer_radius, rect.center().y) } else { pos2(rect.center().x, rect.bottom() - outer_radius) }; + let direction = if vertical { vec2(1.0, 0.0) } else { vec2(0.0, 1.0) }; + let start = if vertical { rect.left_center() } else { rect.center_top() }; + // The line reaches one point inside the circle's outer edge, as on the reference board. + let end = centre - direction * (outer_radius - 1.0); + p.line_segment([start, end], Stroke::new(t.space_2, accent.color)); + // Circle strokes are centred on their radius: inset by half the stroke for a 10 pt outside diameter. + p.circle(centre, outer_radius - t.space_2 / 2.0, if vertical { t.panel } else { t.timeline }, Stroke::new(t.space_2, accent.color)); +} + +/// The same four rollback controls are used in every History orientation. +#[derive(Clone, Copy)] +pub(crate) enum HistoryTransport { + First, + Back, + Forward, + Last, +} + +impl HistoryTransport { + pub const ALL: [Self; 4] = [Self::First, Self::Back, Self::Forward, Self::Last]; + + pub fn id(self) -> &'static str { + match self { + Self::First => "first", + Self::Back => "back", + Self::Forward => "forward", + Self::Last => "last", + } + } + + fn label(self) -> &'static str { + crate::i18n::tr(match self { + Self::First => "ui.history_first", + Self::Back => "ui.history_back", + Self::Forward => "ui.history_forward", + Self::Last => "ui.history_last", + }) + } + + pub fn show(self, ui: &mut egui::Ui, rect: Rect) -> egui::Response { + let t = Tokens::get(); + let response = ui.interact(rect, ui.id().with(("history_transport", self.id())), egui::Sense::click()); + crate::scenario::publish_target(&format!("history:{}", self.id()), rect); + if response.hovered() { + ui.painter().rect_filled(rect, t.radius_sm, t.hover); + } + icons::glyphs::transport_glyph(ui.painter(), rect.center(), self.id(), t.icon); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), self.label())); + response.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(self.label()) + } +} + +pub(crate) fn history_transport_width() -> f32 { + let t = Tokens::get(); + t.space_24 * HistoryTransport::ALL.len() as f32 + t.space_2 * (HistoryTransport::ALL.len() - 1) as f32 +} + +/// Thin and minimum named widths; wider named panels retain their measured width. +pub(crate) fn history_width(names: bool) -> f32 { + let t = Tokens::get(); + if names { history_transport_width() + t.space_10 * 2.0 + t.space_8 } else { t.control_height * 2.0 } +} + +pub(crate) fn history_clamp_width(width: f32) -> f32 { + if width.is_finite() { width.clamp(history_width(false), Tokens::get().space_24 * 26.0) } else { history_width(false) } +} + +/// Only the gap between thin and medium snaps. Every larger width is retained. +pub(crate) fn history_snap_width(width: f32) -> f32 { + let width = history_clamp_width(width); + if width < (history_width(false) + history_width(true)) / 2.0 { history_width(false) } else { width.max(history_width(true)) } +} + +/// The same six-dot grip is used by Assistant and History headers. +pub(crate) fn panel_grip(ui: &mut egui::Ui) -> egui::Response { + let t = Tokens::get(); + let (rect, response) = ui.allocate_exact_size(vec2(t.space_10, t.space_16 + t.space_2), egui::Sense::hover()); + for row in 0..3 { + for col in 0..2 { + ui.painter().circle_filled(rect.left_top() + vec2(2.5 + col as f32 * 5.0, 4.0 + row as f32 * 5.0), 1.1, t.text_dim); + } + } + response +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum HistoryHandleState { + Rest, + Hover, + Drag, +} + +/// Seam geometry is independent of the strip's contents and consumes no layout space. +pub(crate) struct HistorySeam { + pub grip: Rect, + pub pill: Rect, + pub edge: Rect, +} + +impl HistorySeam { + pub fn new(card: Rect) -> Self { + let t = Tokens::get(); + Self { + grip: Rect::from_center_size(pos2(card.right() - t.space_2 - t.space_3 / 2.0, card.center().y), vec2(t.space_3, TREE_ROW_HEIGHT)), + pill: Rect::from_center_size(card.right_center(), vec2(t.space_16 + t.space_2, t.control_height + t.space_16)), + edge: Rect::from_min_max(pos2(card.right() - t.space_10, card.top()), card.right_bottom()), + } + } + + pub fn paint(&self, p: &Painter, card: Rect, names: bool, state: HistoryHandleState) { + let t = Tokens::get(); + let accent = TabAccent::current(p.ctx()); + match state { + HistoryHandleState::Rest => { + p.rect_filled(self.grip, t.space_2, t.control_border); + } + HistoryHandleState::Hover => { + p.rect(self.pill, self.pill.width() / 2.0, accent.soft, Stroke::new(1.0, accent.color), egui::StrokeKind::Inside); + let c = self.pill.center(); + let dir = if names { -1.0 } else { 1.0 }; + p.add(egui::Shape::line( + vec![c + vec2(-dir * t.space_2, -t.space_4), c + vec2(dir * t.space_2, 0.0), c + vec2(-dir * t.space_2, t.space_4)], + Stroke::new(t.space_2, accent.color), + )); + } + HistoryHandleState::Drag => { + p.rect_stroke(card, t.radius_lg, Stroke::new(1.0, accent.color), egui::StrokeKind::Inside); + } + } + } +} + +pub(crate) struct HistorySeamResponse { + pub toggle: bool, + pub width: Option, + pub released: bool, + #[cfg(test)] + pub response: egui::Response, +} + +/// Focusable seam button and edge gesture, shared by the panel and CPU interaction tests. +pub(crate) fn history_seam(ui: &mut egui::Ui, card: Rect, names: bool) -> HistorySeamResponse { + let seam = HistorySeam::new(card); + let id = ui.id().with("history_seam"); + let edge = ui.interact(seam.edge, id.with("edge"), egui::Sense::CLICK | egui::Sense::DRAG); + let button = ui.interact(seam.pill, id, egui::Sense::click_and_drag()); + let label = crate::i18n::tr(if names { "ui.collapse" } else { "ui.expand" }); + button.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), label)); + if button.clicked() { + button.request_focus(); + } + let drag = if button.dragged() || button.drag_started() || button.drag_stopped() { &button } else { &edge }; + let start_id = id.with("start_width"); + if drag.drag_started() { + let press_x = ui.input(|i| i.pointer.press_origin()).map_or(card.right(), |p| p.x); + ui.data_mut(|d| d.insert_temp(start_id, (card.width(), press_x))); + } + let width = if drag.dragged() || drag.drag_stopped() { + let (start_width, press_x) = ui.data(|d| d.get_temp::<(f32, f32)>(start_id)).unwrap_or((card.width(), card.right())); + let pointer_x = ui.input(|i| i.pointer.latest_pos()).map_or(press_x, |p| p.x); + Some(history_clamp_width(start_width + pointer_x - press_x)) + } else { + None + }; + if drag.drag_stopped() { + ui.data_mut(|d| d.remove::<(f32, f32)>(start_id)); + } + let dragging = width.is_some(); + if dragging || edge.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); + } + if !dragging && button.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); + } + let hovered = edge.hovered() || button.hovered(); + let state = if dragging { + HistoryHandleState::Drag + } else if hovered { + HistoryHandleState::Hover + } else { + HistoryHandleState::Rest + }; + seam.paint(ui.painter(), card, names, state); + let response = button.clone().union(edge.clone()); + if hovered && !dragging { + let mut tip = egui::Tooltip::for_widget(&response); + let t = Tokens::get(); + let frame = egui::Frame::NONE + .fill(t.dialog_body) + .stroke(Stroke::new(1.0, t.dialog_border)) + .corner_radius(t.radius_md) + .inner_margin(egui::Margin::symmetric(t.space_8 as i8, t.space_4 as i8)) + .shadow(t.shell_shadow()); + tip.popup = tip.popup.anchor(seam.pill).align(egui::RectAlign::RIGHT_START).frame(frame); + tip.show(|ui| { + let t = Tokens::get(); + ui.label(egui::RichText::new(label).font(crate::fonts::semibold(t.font_body)).color(t.text)); + ui.label(egui::RichText::new(crate::i18n::tr("ui.history_edge_hint")).size(t.font_small).color(t.text_dim)); + }); + } + crate::scenario::publish_handle("history:names", seam.pill.center()); + crate::scenario::publish_rect("history:seam", seam.edge); + crate::scenario::publish_rect("history:handle", seam.pill); + // egui's click response includes Enter and Space for a focused button. + HistorySeamResponse { + toggle: button.clicked() || edge.double_clicked(), + width, + released: drag.drag_stopped(), + #[cfg(test)] + response, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn seam_geometry_and_paint_states_follow_tokens_in_both_themes() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + for names in [false, true] { + let card = Rect::from_min_size(pos2(20.0, 30.0), vec2(history_width(names), 280.0)); + let seam = HistorySeam::new(card); + assert_eq!(seam.grip.size(), vec2(3.0, 26.0)); + assert_eq!(seam.grip.center().y, card.center().y); + assert_eq!(seam.grip.right(), card.right() - 2.0); + assert_eq!(seam.pill.size(), vec2(18.0, 44.0)); + assert_eq!(seam.pill.center(), card.right_center()); + assert_eq!(seam.edge.width(), 10.0); + for state in [HistoryHandleState::Rest, HistoryHandleState::Hover, HistoryHandleState::Drag] { + let ctx = crate::fonts::test_context(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| seam.paint(ui.painter(), card, names, state)); + out.textures_delta.clear(); + let t = Tokens::get(); + let accent = TabAccent::current(&ctx); + let rect = out + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Rect(r) => Some(r), + _ => None, + }) + .unwrap(); + match state { + HistoryHandleState::Rest => { + assert_eq!(rect.rect, seam.grip); + assert_eq!(rect.fill, t.control_border); + } + HistoryHandleState::Hover => { + assert_eq!(rect.rect, seam.pill); + assert_eq!(rect.fill, accent.soft); + assert_eq!(rect.stroke.color, accent.color); + } + HistoryHandleState::Drag => { + assert_eq!(rect.rect, card); + assert_eq!(rect.stroke.color, accent.color); + assert!(!out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Text(_)))); + assert!(!out.shapes.iter().any(|s| matches!(s.shape, egui::Shape::LineSegment { .. }))); + } + } + } + } + } + crate::theme::set_dark(previous); + } + + struct SeamHarness { + ctx: egui::Context, + names: bool, + width: f32, + time: f64, + focused: bool, + } + + impl SeamHarness { + fn new(names: bool) -> Self { + let mut h = Self { ctx: crate::fonts::test_context(), names, width: history_width(names), time: 0.0, focused: false }; + h.frame(vec![]); + h.frame(vec![]); + h + } + + fn card(&self) -> Rect { + Rect::from_min_size(pos2(20.0, 20.0), vec2(self.width, 280.0)) + } + + fn frame(&mut self, events: Vec) -> egui::FullOutput { + self.time += 0.05; + let card = self.card(); + let mut out = self.ctx.run_ui( + egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0))), + time: Some(self.time), + focused: true, + events, + ..Default::default() + }, + |ui| { + let result = history_seam(ui, card, self.names); + self.focused = result.response.has_focus(); + if let Some(width) = result.width { + self.width = width; + if result.released { + self.names = history_snap_width(width) >= history_width(true); + self.width = history_snap_width(width); + } + } else if result.toggle { + self.names = !self.names; + self.width = history_width(self.names); + } + }, + ); + out.textures_delta.clear(); + out + } + } + + #[test] + fn seam_edge_cursor_pill_click_double_click_and_keyboard_toggle() { + use crate::test_support::{key, pointer}; + let mut h = SeamHarness::new(false); + let edge = pos2(h.card().right() - 4.0, h.card().top() + 30.0); + assert_eq!(h.frame(vec![egui::Event::PointerMoved(edge)]).platform_output.cursor_icon, egui::CursorIcon::ResizeHorizontal); + let pill = h.card().right_center(); + assert_eq!(h.frame(vec![egui::Event::PointerMoved(pill)]).platform_output.cursor_icon, egui::CursorIcon::PointingHand); + h.frame(pointer(pill, true)); + h.frame(pointer(pill, false)); + assert!(h.names); + let mut h = SeamHarness::new(false); + for _ in 0..2 { + h.frame(pointer(edge, true)); + h.frame(pointer(edge, false)); + } + assert!(h.names, "double-click toggles once"); + let mut h = SeamHarness::new(false); + h.ctx.enable_accesskit(); + let focus = h.frame(key(egui::Key::Tab)); + assert!( + focus + .platform_output + .events + .iter() + .any(|e| matches!(e, egui::output::OutputEvent::FocusGained(info) if info.label.as_deref() == Some("Expand"))) + ); + h.frame(vec![]); + assert!(h.focused, "Tab reaches the seam button"); + h.frame(key(egui::Key::Enter)); + assert!(h.names); + h.frame(key(egui::Key::Space)); + assert!(!h.names); + } + + #[test] + fn seam_drag_resizes_continuously_and_snaps_both_directions() { + use crate::test_support::pointer; + for (names, delta, expected) in [(false, 40.0, true), (false, 20.0, false), (true, -40.0, false), (true, -20.0, true)] { + for pill in [false, true] { + let mut h = SeamHarness::new(names); + let start = if pill { h.card().right_center() } else { pos2(h.card().right() - 4.0, h.card().top() + 30.0) }; + let end = start + vec2(delta, 0.0); + h.frame(pointer(start, true)); + h.frame(vec![egui::Event::PointerMoved(start + vec2(delta / 2.0, 0.0))]); + h.frame(vec![egui::Event::PointerMoved(end)]); + assert_eq!(h.width, history_width(names) + delta, "continuous width before release"); + h.frame(pointer(end, false)); + assert_eq!(h.names, expected); + assert_eq!(h.width, history_snap_width(history_width(names) + delta)); + } + } + for hostile in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1000.0, 10000.0] { + assert!((history_width(false)..=Tokens::get().space_24 * 26.0).contains(&history_clamp_width(hostile))); + } + } + + #[test] + fn chip_selection_error_and_rollback_use_tokens_in_both_themes() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + let t = Tokens::get(); + let accent = TabAccent::for_tab(&t, "SURFACE"); + for style in [HistoryStyle::Icons, HistoryStyle::Names] { + for (selected, error, dim) in [(true, false, false), (false, true, false), (true, false, true)] { + let rect = Rect::from_min_size(pos2(20.0, 20.0), vec2(158.0, style.height())); + let ctx = crate::fonts::test_context(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + HistoryChip { + icon: "surface_extrude", + name: "Offset1", + kind: "SurfaceOffsetFeature", + selected, + hovered: false, + dim, + suppressed: false, + error, + warning: false, + accent, + } + .paint(ui.painter(), rect, style) + }); + out.textures_delta.clear(); + let background = out + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Rect(r) if r.rect == rect => Some(r), + _ => None, + }) + .unwrap(); + let opacity = if dim { 0.42 } else { 1.0 }; + assert_eq!(background.fill, if error { t.form_error_fill } else { accent.soft }.gamma_multiply(opacity)); + if style == HistoryStyle::Icons || error { + assert_eq!(background.stroke.color, if error { t.form_error } else { accent.color }.gamma_multiply(opacity)); + } + if style == HistoryStyle::Names { + let text = out + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Text(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(text.galley.text(), "Offset1"); + assert_eq!(text.fallback_color, if selected { accent.ink } else { t.text }.gamma_multiply(opacity)); + } + } + } + } + crate::theme::set_dark(previous); + } + + #[test] + fn chips_have_no_connector_shapes_in_either_theme_or_width() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + let t = Tokens::get(); + for style in [HistoryStyle::Bottom, HistoryStyle::Icons, HistoryStyle::Names] { + let ctx = crate::fonts::test_context(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + for index in 0..3 { + let rect = Rect::from_min_size( + pos2(20.0, 20.0 + index as f32 * (style.height() + t.space_4)), + vec2(if style == HistoryStyle::Names { 158.0 } else { style.height() }, style.height()), + ); + HistoryChip { + icon: "box", + name: "Box", + kind: "BoxFeature", + selected: index == 0, + hovered: false, + dim: index == 2, + suppressed: false, + error: false, + warning: false, + accent: TabAccent::for_tab(&t, "MODEL"), + } + .paint(ui.painter(), rect, style); + } + }); + out.textures_delta.clear(); + let mut connections = 0; + for clipped in out.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if matches!(shape, egui::Shape::LineSegment { .. } | egui::Shape::Path(_)) { + connections += 1; + } + }); + } + assert_eq!(connections, 0, "dark={dark}"); + } + } + crate::theme::set_dark(previous); + } + + #[test] + fn both_strip_orientations_share_the_drop_bar_and_marker_geometry() { + let t = Tokens::get(); + let accent = TabAccent::for_tab(&t, "SURFACE"); + for vertical in [false, true] { + let rect = Rect::from_min_size(pos2(20.0, 20.0), if vertical { vec2(160.0, 12.0) } else { vec2(12.0, 28.0) }); + let ctx = crate::fonts::test_context(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| history_drop_bar(ui.painter(), rect, vertical, accent.color)); + out.textures_delta.clear(); + let lines: Vec<_> = out + .shapes + .iter() + .filter_map(|s| if let egui::Shape::LineSegment { points, stroke } = s.shape { Some((points, stroke)) } else { None }) + .collect(); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0].1, Stroke::new(t.space_2, accent.color)); + assert_eq!(lines[0].0, if vertical { [rect.left_center(), rect.right_center()] } else { [rect.center_top(), rect.center_bottom()] }); + } + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + let t = Tokens::get(); + let accent = TabAccent::for_tab(&t, "SURFACE"); + // Both vertical widths retain the 12 pt marker row; the bottom strip rotates it. + for (vertical, size) in [(true, vec2(46.0, 12.0)), (true, vec2(158.0, 12.0)), (false, vec2(12.0, 28.0))] { + let rect = Rect::from_min_size(pos2(20.0, 20.0), size); + let ctx = crate::fonts::test_context(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| history_marker(ui.painter(), rect, vertical, accent)); + out.textures_delta.clear(); + let lines: Vec<_> = out + .shapes + .iter() + .filter_map(|s| match s.shape { + egui::Shape::LineSegment { points, stroke } => Some((points, stroke)), + _ => None, + }) + .collect(); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0].1, Stroke::new(2.0, accent.color)); + let circles: Vec<_> = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Circle(c) => Some(c), + _ => None, + }) + .collect(); + assert_eq!(circles.len(), 1); + let circle = circles[0]; + assert_eq!(circle.stroke, Stroke::new(2.0, accent.color)); + assert_eq!(circle.fill, if vertical { t.panel } else { t.timeline }); + assert_ne!(circle.fill, accent.color); + let outer = circle.radius + circle.stroke.width / 2.0; + assert_eq!(outer * 2.0, 10.0); + let bounds = Rect::from_center_size(circle.center, vec2(outer * 2.0, outer * 2.0)); + assert!(rect.contains_rect(bounds)); + assert_eq!(lines[0].0[0], if vertical { rect.left_center() } else { rect.center_top() }); + if vertical { + assert_eq!(rect.height(), 12.0); + assert_eq!(bounds.right(), rect.right()); + assert_eq!(lines[0].0[1], pos2(bounds.left() + 1.0, circle.center.y)); + } else { + assert_eq!(bounds.bottom(), rect.bottom()); + assert_eq!(lines[0].0[1], pos2(circle.center.x, bounds.top() + 1.0)); + } + assert!(!out.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Path(_))), "no arrowheads"); + } + } + crate::theme::set_dark(previous); + } +} diff --git a/crates/ui-egui/src/ui_kit/mod.rs b/crates/ui-egui/src/ui_kit/mod.rs index 16efb3126..0c5bb13a9 100644 --- a/crates/ui-egui/src/ui_kit/mod.rs +++ b/crates/ui-egui/src/ui_kit/mod.rs @@ -8,6 +8,7 @@ mod color; mod confirm; mod disclosure; mod fields; +mod history; mod layout; mod menu; mod metrics; @@ -26,10 +27,11 @@ pub(crate) use color::*; pub(crate) use confirm::{Confirm, Tone}; pub(crate) use disclosure::*; pub(crate) use fields::*; +pub(crate) use history::*; pub(crate) use layout::*; pub(crate) use menu::{Menu, MenuItem, rename_menu, workspace_menu}; pub(crate) use metrics::{ContentWidth, header_height, row_height, table_row_height}; -pub(crate) use panel::{ComputeStatus, FeatureOptions, Panel, Part, Window, WindowPage}; +pub(crate) use panel::{ComputeStatus, FeatureOptions, Panel, Part, Window, WindowPage, panel_header_hover}; #[cfg(test)] pub(crate) use panel::{collapsible_header, header}; pub(crate) use radial::{RADIAL_RADIUS, radial_menu}; diff --git a/crates/ui-egui/src/ui_kit/panel.rs b/crates/ui-egui/src/ui_kit/panel.rs index 66221d944..6bc0de46b 100644 --- a/crates/ui-egui/src/ui_kit/panel.rs +++ b/crates/ui-egui/src/ui_kit/panel.rs @@ -3,6 +3,12 @@ use super::{actions::icon_button_at, metrics::*, text::paint_text}; use crate::{scenario, theme::Tokens}; use egui::{Ui, vec2}; +/// Shared active-tab hover tint for the browser and collapsible panel chrome. +pub(crate) fn panel_header_hover(painter: &egui::Painter, rect: egui::Rect) { + let t = Tokens::get(); + painter.rect_filled(rect, t.radius_lg.saturating_sub(t.space_4 as u8), crate::theme::TabAccent::current(painter.ctx()).soft); +} + /// Feature title/icon/close band. Tokens: `form_header_height, form_icon_size, form_close_size, form_inset, font_label, text, dialog_rule, space_8/10; icon_button_at tokens`. pub(crate) fn header(ui: &mut Ui, icon: &str, title: &str, on_close: impl FnOnce()) { header_impl(ui, icon, title, None, on_close); diff --git a/crates/ui-egui/tests/icon_audit.rs b/crates/ui-egui/tests/icon_audit.rs index 79359e409..c642a4a8e 100644 --- a/crates/ui-egui/tests/icon_audit.rs +++ b/crates/ui-egui/tests/icon_audit.rs @@ -210,6 +210,10 @@ fn requested_menu_icons_have_artwork_and_match_manifest() { history.frames(3); context_rows(&mut history, "timeline:", &mut requested); } + // The seam has its own checked display menu, independent of feature and folder rows. + history.step(&json!({"click":{"handle":"history:names"},"button":"right"})).unwrap(); + collect(&mut history, "history seam", &mut requested); + escape(&mut history); let features = history.app.session.doc.features.iter().take(2).map(|f| f.id).collect::>(); let group = history.app.run("timeline.group", json!({"features":features,"name":"Audit history folder"})).unwrap()["group"].as_u64().unwrap(); history.frames(3); @@ -217,13 +221,13 @@ fn requested_menu_icons_have_artwork_and_match_manifest() { history.app.tree.picked_timeline_groups.clear(); history.app.run("select.set", json!({"items":features.iter().map(|id| json!({"type":"feature","id":id})).collect::>()})).unwrap(); history.frames(3); - history.step(&json!({"widget":"2 selected"})).unwrap(); + history.step(&json!({"click":{"handle":"timeline:History A"},"button":"right"})).unwrap(); collect(&mut history, "history feature selection", &mut requested); escape(&mut history); history.app.run("select.clear", json!({})).unwrap(); history.app.tree.picked_timeline_groups = vec![group]; history.frames(3); - history.step(&json!({"widget":"1 selected"})).unwrap(); + history.step(&json!({"click":{"handle":"timeline-folder:Audit history folder"},"button":"right"})).unwrap(); collect(&mut history, "history folder selection", &mut requested); escape(&mut history); history.app.tree.picked_timeline_groups.clear(); diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md index f3e270834..ea62b84e5 100644 --- a/docs/book/src/guide/ui-tour.md +++ b/docs/book/src/guide/ui-tour.md @@ -66,7 +66,10 @@ - **Dialogs** dock on the right with a live preview. Most features also show drag handles and a value box in the viewport. - **Timeline** (bottom). Every feature in order. Double-click to edit, drag the marker to roll - back, and drag features to reorder them. + back, and drag features to reorder them. Preferences can put the timeline vertically at the + far left of the viewport, beside the browser. Its seam handle switches between icon + chips and compact feature names; the browser can collapse to a rail beside either width. + Previous, Play and Next sit at the top. Double-click Previous to roll to the start. - **Command search (S).** Click the ribbon search field or press S to open the search popup below it. Results group commands by their ribbon path and show matching features and user parameters from this design. With an empty query, recent commands appear first, followed by diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 48d56c985..50609e6d7 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -209,6 +209,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox. | `ui.capture` | `action?`: `capture`, `revert`, `cancel` | answers the Capture Position question (asked when a command starts or the design is saved while components were moved without capturing); without `action`, what waits | | `ui.window` | `action`: minimize, maximize, restore, toggle, close | what the title bar's caption buttons do (on Windows and Linux the application bar is the title bar); close asks about unsaved designs first | | `ui.agent_cursor` | `show` (bool), `speed`: a number from 1 to 5 (times the normal speed) or `"instant"` (no animation: the command runs at once and the pointer jumps to where it acted), `follow_camera` (bool); all optional | the settings. While the cursor is shown, `engine.execute` first glides to the command's toolbar button and to each pick, then runs and replies; later requests wait their turn. `"animate": false` on a call skips it | +| `engine.execute` → `view.history_layout` | `width?`, `dock?`: `bottom`, `left`, `under_browser`, `collapsed?` | Resize/dock the history without opening a dialog or changing the design. Contents respond to measured width; browser-stacked history shares its width and splits height equally. One folded header gives the expanded card the rest; two folded headers stay at the top. | | `ui.agent_chat` | `features?`, `toolbar_button?`, `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp` or `api`, `command` or `base_url` + `model`}; no keys), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `model?` (one of its models), `open?`, `side?` (`left`, `right`), `minimized?`, `popped?` (in its own window), `width?`, `picker?`, `refresh?`, `connect?`, `stop?`, `attach?`: a file's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once), `remove_file?` (index of a file on the next message), `send?`: text (files alone make a message too), `attach_view?`, `permission?`: an option id or `"cancel"` (the newest question of the agent's own), `approve?`: true, false or `"always"` (the oldest request held for Allow/Deny), `cancel?` (Stop: the queue stays), `send_now?` (stop the running step, then send the queued messages), `remove_pending?` (index), `new_chat?` (clear the chat, new session), `undo?` (the last message's changes) | the chat's state: `features`, `agents` (found and added), `currentAgent`, `state` (off, starting, ready, busy, auth, exited), `popped`, `window` (its place and size), `agent`, `modes`, `mode`, `models`, `model`, `authMethods`, `toolsPort`, `pid`, `waiting`, `turn`, `pending` (queued messages, with their `files`), `attachments` (the files on the next message, by name), `loading` (pictures still being read for it, by name), `stopped`, `detection` and the conversation (`items`). With `features` off only the settings apply. Desktop only; see [Agent chat](agent-chat.md) | | `ui.resize` | `width`, `height` | | | `app.quit` | `force?` (quit without asking about unsaved designs) | `quitting` (the window closes), `asking` (a "save changes?" prompt is open) | diff --git a/docs/ui-kit.md b/docs/ui-kit.md index a90f6fb13..241fa580e 100644 --- a/docs/ui-kit.md +++ b/docs/ui-kit.md @@ -57,6 +57,7 @@ table. Panel/Window/Confirm compositions also have dedicated geometry and intera | Module / element | Use and options | Main tokens | | --- | --- | --- | +| history: `HistoryChip`, `HistoryStyle`, `history_drop_bar`, `history_marker`, `HistorySeam`, `history_seam` | One painter family for bottom chips, 38 pt vertical icon chips and single-line 26 pt name rows (the browser's shared `TREE_ROW_HEIGHT`). Selected items use the active tab tint/ink/border; all variants retain multi-tone feature artwork using one shared kind-to-accent rule (Sketch green, Surface orange, Mesh yellow, Form purple, solids base blue); rolled-back items have 42% opacity. Error/warning badges, suppression strikes, horizontal/vertical drop bars and rollback line/hollow circle are shared. No connector lines. | `control_height`, `space_2/3/4/6/8/10/12/14/16/24`, radii, typography, `TabAccent`, `timeline_item`, `control_border`, `text/dim`, `form_error/fill` | | search: `CommandSearch`, `MenuItem::search_row` | Ribbon search composition: one persistent ribbon editor expands from 28 to 40 pt and to 520 pt wide with its right edge anchored, magnifier and S/Esc keycap, 38 pt two-line menu row with 26 pt icon tile, accent bold substring, path, shortcut/kind keycap, counts, JSON detail box and footer. The ordinary 30 pt menu row cannot fit a second line; this variant keeps its enabled/selected states and scenario IDs. Ranking and dispatch stay with the caller. | `form_card_width × 2 − space_8` (520 pt), `control_height`, `space_2/3/4/6/8/10/12/14/16/24`, `radius_xl/control_radius`, `control_fill`, `dialog_body/footer/rule/border`, `form_ink/dim/primary/error/error_fill/success/success_fill`, `selected_ink`, `accent_soft`, typography | | menu: `Menu`, `MenuItem` | Shared popup, 30 pt rows, 28 pt icon column, clipped labels, right-aligned mono shortcuts, submenu chevrons, checked/unchecked and document swatches, inert 40% disabled rows and danger ink; headings and separators; ribbon drag/pin targets retained | `dialog_body/border/rule`, `radius_xl`, `control_height/radius`, `form_ink/dim/primary/error`, `accent_soft`, typography and spacing | | radial: `radial_menu` | Eight rounded annular sectors, parallel 4 pt gaps, 9 pt circular corner joins, tab-accent artwork and hover, centre label/key; existing hold/flick/release dispatch | `dialog_body/border`, `form_ink/dim`, `TabAccent`, icon palette, font/spacing tokens | @@ -108,6 +109,38 @@ table. Panel/Window/Confirm compositions also have dedicated geometry and intera | status: `status_header`, `StatusHeader` | Supplied icon/name/status and constraint meter | `font_label`, `text/dim`, `accent`, sketch/header tokens | | `progress` | Clamped determinate progress | `space_3/6`, `dialog_rule`, `accent` | +History contents are selected from measured panel width. A 56 pt thin strip shows icons +and four vertical transport controls: beginning, back, forward and end. The minimum named +width is 130 pt; it adds horizontal transport and the same six-dot window grip as Assistant. +When the remaining header space fits its measured text, **History** appears between grip +and transport. No names-mode flag +or command selects these layouts. The seam snaps between 56 and 130 pt; widths from 130 +through 624 pt remain continuous and persist as `timeline_left_width`. + +Drag the grip or title to dock along the bottom, at the full-height left edge, or beneath +the browser. Either card's right edge resizes their shared width. This position divides +available column height equally. Folding either card leaves its header visible and gives the remainder to +the other. If both are folded, their headers sit together at the top of the column. +Expansion and collapse share a smooth cubic transition capped at 120 ms, respecting +the interface’s instant-animation setting. Their collapse controls share the same active-tab blue hover tint. Browser resizing also resizes History. +The `view.history_layout` command validates width, docking and collapse requests without +altering the design or opening dialogs. Floating mode preserves viewport projection. + +The seam handle overlays the strip's right edge without taking layout space. Its grip is +visible at rest; the arrow appears only on hover. Click, double-click the edge, or use +Enter/Space on the focused handle to resize between thin and minimum named widths. Drag +freely above the named minimum; resizing draws no dotted guide or name label. Header/title dragging +and the edge width gesture are separate from feature/folder and rollback dragging. +The rollback marker is 12 pt high. +Its 2 pt line uses the active tab fill and ends in a 10 pt hollow circle with a 2 pt accent +border and the card/panel surface inside. The circle overlaps the line end by 1 pt. The bottom +strip uses the same painter, rotated. Folder selection, range selection, context menus, +sketch-pattern children, drag reordering and command JSON retain their existing behavior and handles. +`history_icons`, `history_names`, `history_marker` and the `history_seam_rest/hover/drag` states +have light/dark gallery references. The CPU +board test captures both strip widths with expanded and collapsed browsers +(`SOLIDCRAFT_HISTORY_EVIDENCE`). + `text(ui, text, options)` supports the existing text behaviors and the new error band: | Option | Layout and scenario publication | From 17ece2edc04762ed38155600631a87e23f56591b Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:28:26 +0000 Subject: [PATCH 09/25] Regenerate THIRD-PARTY-LICENSES.txt and docs/features.md [skip ci] --- docs/features.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/features.md b/docs/features.md index a4d8d8843..6be345f8d 100644 --- a/docs/features.md +++ b/docs/features.md @@ -591,6 +591,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Restore Named View | `view.apply` | – | | Delete Named View | `view.delete` | – | | Graphics Preset | `view.graphics_preset` | – | +| History layout | `view.history_layout` | – | | List Named Views | `view.list` | – | | Navigate View | `view.navigate` | – | | Rename Named View | `view.rename` | – | From 84ec512d7a68ff04f29feefa3117ee6457cc5281 Mon Sep 17 00:00:00 2001 From: Mauznemo <90456457+Mauznemo@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:36:29 +0000 Subject: [PATCH 10/25] fix: midpoint tool rejects two lines (#3836) --- crates/engine/src/cmd/sketch.rs | 64 +++++++++-- .../src/cmd/sketch_constraints_tests.rs | 103 ++++++++++++++++++ crates/ui-egui/src/context_menu.rs | 3 +- crates/ui-egui/src/delete.rs | 17 ++- crates/ui-egui/src/sketch_tools.rs | 89 +++++++++++++-- crates/ui-egui/src/tools.rs | 5 +- .../tests/point_constraint_preselection.rs | 102 ++++++++++++++++- docs/book/src/guide/sketching.md | 4 +- 8 files changed, 359 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 198106807..6dbbc2218 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -156,7 +156,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SKETCH", "CONSTRAINTS") .icon("c_midpoint") .enabled(in_sketch) - .params("point, line"), + .params("point, line | a, b in pick order: a point and a line (either way round), or two lines whose midpoints meet (the first stays, the second moves)"), CommandSpec::new("sketch.constraint.concentric", "Concentric", c_concentric) .at("SKETCH", "CONSTRAINTS") .icon("c_concentric") @@ -1637,6 +1637,15 @@ pub(super) fn residual_of(sk: &Sketch, id: &str) -> Option { sk.constraints.iter().position(|c| c.id == id).and_then(|ci| solidcraft_sketch::constraint_residual(sk, ci)) } +/// The point already tied to the middle of line `l`, including one created by drawing. +/// Coincident coordinates alone are not enough: the Midpoint relationship must exist. +fn existing_midpoint(sk: &Sketch, l: usize) -> Option { + sk.constraints.iter().find_map(|c| match c.kind { + ConstraintKind::Midpoint { p, l: line } if line == l && !c.driven => Some(p), + _ => None, + }) +} + /// Temporary pick intent. Saved sketches use ordinary points and constraints only. #[derive(Clone, Copy, PartialEq, Eq)] enum AlignmentTarget { @@ -1645,19 +1654,13 @@ enum AlignmentTarget { } impl AlignmentTarget { - fn materialize(self, sk: &mut Sketch) -> Result { + fn materialize(self, sk: &mut Sketch, cmd: &str) -> Result { match self { Self::Point(p) => Ok(p), Self::Midpoint(l) => { - // Reuse an existing associative midpoint, including one created by drawing. - // Coincident coordinates alone are insufficient: its relationship must exist. - if let Some(p) = sk.constraints.iter().find_map(|c| match c.kind { - ConstraintKind::Midpoint { p, l: line } if line == l && !c.driven => Some(p), - _ => None, - }) { + if let Some(p) = existing_midpoint(sk, l) { return Ok(p); } - let cmd = "sketch.constraint.horizontal_vertical"; let (a, b) = line_pts(sk, l).ok_or_else(|| bad(cmd, "a midpoint reference needs a line"))?; let p = sk.add_point((a + b) * 0.5, None)?; add_c(sk, ConstraintKind::Midpoint { p, l })?; @@ -1693,8 +1696,8 @@ fn c_horizontal_vertical(s: &mut Session, p: &Value) -> Result { if a == b { return Err(bad(cmd, "alignment needs two distinct point references")); } - let a = a.materialize(sk)?; - let b = b.materialize(sk)?; + let a = a.materialize(sk, cmd)?; + let b = b.materialize(sk, cmd)?; if a == b { return Err(bad(cmd, "alignment needs two distinct points")); } @@ -1826,9 +1829,46 @@ fn c_collinear(s: &mut Session, p: &Value) -> Result { fn c_midpoint(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.constraint.midpoint"; constrain(s, p, cmd, |sk| { - Ok(ConstraintKind::Midpoint { p: point_ref(sk, p.get("point"), cmd, "point")?, l: curve_ref(sk, p.get("line"), cmd, "line")? }) + if p.get("a").is_none() && p.get("b").is_none() { + return Ok(ConstraintKind::Midpoint { p: point_ref(sk, p.get("point"), cmd, "point")?, l: curve_ref(sk, p.get("line"), cmd, "line")? }); + } + // `a` and `b` in pick order: a point and a line either way round, or two lines. + let entity = |k: &str| -> Result { + let r = p.get(k).and_then(Value::as_str).ok_or_else(|| bad(cmd, format!("`{k}` must be a point or line id")))?; + match sk.resolve_point(r) { + Some(i) => Ok(Ent::Point(i)), + None => sk.curve_index(r).map(Ent::Curve).ok_or_else(|| bad(cmd, format!("unknown sketch point or curve `{r}`"))), + } + }; + let is_line = |sk: &Sketch, c: usize| matches!(sk.curves.get(c).map(|c| &c.kind), Some(CurveKind::Line { .. })); + match (entity("a")?, entity("b")?) { + (Ent::Point(q), Ent::Curve(l)) | (Ent::Curve(l), Ent::Point(q)) if is_line(sk, l) => Ok(ConstraintKind::Midpoint { p: q, l }), + // Two lines: their midpoints meet. One point sits at the middle of both, reusing + // a midpoint either line already has, so nothing new is saved in the design. + (Ent::Curve(a), Ent::Curve(b)) if is_line(sk, a) && is_line(sk, b) => { + if a == b { + return Err(bad(cmd, "pick two different lines")); + } + let (q, l) = match (existing_midpoint(sk, a), existing_midpoint(sk, b)) { + (Some(q), _) => (q, b), + (None, Some(q)) => (q, a), + (None, None) => (AlignmentTarget::Midpoint(a).materialize(sk, cmd)?, b), + }; + if existing_midpoint_of(sk, q, l) { + return Err(bad(cmd, "these lines already share their midpoint")); + } + Ok(ConstraintKind::Midpoint { p: q, l }) + } + _ => Err(bad(cmd, "MidPoint needs a point and a line, or two lines")), + } }) } + +/// Point `q` is already tied to the middle of line `l`. +fn existing_midpoint_of(sk: &Sketch, q: usize, l: usize) -> bool { + sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { p, l: line } if p == q && line == l) && !c.driven) +} + /// The centre of a symmetry about a point (#1075): `point`, or `line` naming a point rather than /// a curve or a sketch axis (the origin picked as the third entity). fn symmetry_center(sk: &Sketch, p: &Value, cmd: &str) -> Result> { diff --git a/crates/engine/src/cmd/sketch_constraints_tests.rs b/crates/engine/src/cmd/sketch_constraints_tests.rs index 795ce0fad..1e4c08746 100644 --- a/crates/engine/src/cmd/sketch_constraints_tests.rs +++ b/crates/engine/src/cmd/sketch_constraints_tests.rs @@ -632,3 +632,106 @@ fn midpoint_alignment_remaps_after_unrelated_geometry_is_deleted() { run(&mut s, "sketch.delete", json!({"entities":[result["created"]["points"][0]]})); assert!(sketch(&s).constraints.is_empty()); } + +fn line_ends(sk: &solidcraft_sketch::Sketch, id: &str) -> (Vec2, Vec2) { + let solidcraft_sketch::CurveKind::Line { a, b } = sk.curves[sk.curve_index(id).unwrap()].kind else { panic!("expected line") }; + (sk.point(a).unwrap(), sk.point(b).unwrap()) +} + +#[test] +fn midpoint_of_two_lines_centres_the_second_on_the_first() { + use solidcraft_sketch::ConstraintKind; + for reverse in [false, true] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[0,0],[60,0]],"infer":false,"connect":false})); + run(&mut s, "sketch.line", json!({"points":[[5,-10],[25,-10]],"infer":false,"connect":false})); + let (first, second) = if reverse { ("l2", "l1") } else { ("l1", "l2") }; + let stays = line_ends(&sketch(&s), first); + let length = { + let (a, b) = line_ends(&sketch(&s), second); + a.dist(b) + }; + let before = s.doc.to_json(); + let undo = s.undo.len(); + let result = run(&mut s, "sketch.constraint.midpoint", json!({"a":first,"b":second})); + assert_eq!(result["created"]["points"].as_array().unwrap().len(), 1); + assert_eq!(result["created"]["constraints"].as_array().unwrap().len(), 2); + assert_eq!(s.undo.len(), undo + 1); + let sk = sketch(&s); + assert_eq!(line_ends(&sk, first), stays, "the first pick stays put"); + let (a, b) = line_ends(&sk, second); + assert!((a.dist(b) - length).abs() < 1e-6, "the second keeps its length"); + assert!(line_midpoint(&sk, first).dist(line_midpoint(&sk, second)) < 1e-6); + assert_eq!(sk.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).count(), 2); + + // Saved as ordinary points and constraints: it reopens and keeps holding. + let after = s.doc.to_json(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc.to_json(), after); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&after).unwrap()); + reopened.active_sketch = s.active_sketch; + run(&mut reopened, "sketch.move_point", json!({"point":"l1.end","to":[80,15]})); + let sk = sketch(&reopened); + assert!(line_midpoint(&sk, "l1").dist(line_midpoint(&sk, "l2")) < 1e-6); + } +} + +#[test] +fn midpoint_takes_a_point_and_a_line_in_either_pick_order() { + for (a, b) in [("p", "l1"), ("l1", "p")] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[0,0],[40,0]],"infer":false,"connect":false})); + run(&mut s, "sketch.point", json!({"point":[7,9],"id":"p"})); + run(&mut s, "sketch.constraint.midpoint", json!({"a":a,"b":b})); + let sk = sketch(&s); + let p = sk.point(sk.resolve_point("p").unwrap()).unwrap(); + assert!(p.dist(line_midpoint(&sk, "l1")) < 1e-6, "{a} then {b}"); + } +} + +#[test] +fn midpoint_of_two_lines_reuses_an_existing_midpoint() { + use solidcraft_sketch::ConstraintKind; + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[0,0],[60,0]],"infer":false,"connect":false})); + run(&mut s, "sketch.line", json!({"points":[[5,-10],[25,-10]],"infer":false,"connect":false})); + // l3 starts at the midpoint of l2: that point is reused, not duplicated. + run(&mut s, "sketch.line", json!({"points":["mid:l2",[15,-30]],"infer":false,"connect":false})); + let count = sketch(&s).points.len(); + let result = run(&mut s, "sketch.constraint.midpoint", json!({"a":"l1","b":"l2"})); + assert!(result["created"]["points"].as_array().unwrap().is_empty()); + let sk = sketch(&s); + assert_eq!(sk.points.len(), count); + assert_eq!(sk.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).count(), 2); + assert!(line_midpoint(&sk, "l1").dist(line_midpoint(&sk, "l2")) < 1e-6); + // Applying it again finds nothing to add. + let before = s.doc.to_json(); + assert!(s.execute("sketch.constraint.midpoint", &json!({"a":"l2","b":"l1"})).is_err()); + assert_eq!(s.doc.to_json(), before); +} + +#[test] +fn midpoint_rejects_wrong_picks_without_changing_the_sketch() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[0,0],[60,0]],"infer":false,"connect":false})); + run(&mut s, "sketch.circle.center", json!({"center":[40,50],"radius":3})); + run(&mut s, "sketch.point", json!({"point":[7,9],"id":"p"})); + for params in [ + json!({"a":"l1","b":"l1"}), + json!({"a":"l1","b":"c1"}), + json!({"a":"c1","b":"l1"}), + json!({"a":"p","b":"origin"}), + json!({"a":"p","b":"c1"}), + json!({"a":"l1","b":"missing"}), + json!({"a":"l1"}), + json!({"a":12,"b":"l1"}), + ] { + let before = s.doc.to_json(); + let undo = s.undo.len(); + assert!(s.execute("sketch.constraint.midpoint", ¶ms).is_err(), "{params}"); + assert_eq!(s.doc.to_json(), before, "{params}"); + assert_eq!(s.undo.len(), undo, "{params}"); + } +} diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 67fb16df3..803a9daae 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -926,7 +926,8 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { c.push(cmd(app, "sketch.constraint.parallel", "Parallel").with(ab.clone())); c.push(cmd(app, "sketch.constraint.perpendicular", "Perpendicular").with(ab.clone())); c.push(cmd(app, "sketch.constraint.collinear", "Collinear").with(ab.clone())); - c.push(cmd(app, "sketch.constraint.equal", "Equal").with(ab)); + c.push(cmd(app, "sketch.constraint.equal", "Equal").with(ab.clone())); + c.push(cmd(app, "sketch.constraint.midpoint", "MidPoint").with(ab)); } if r == 2 && n == 2 { let ab = json!({ "a": rounds[0], "b": rounds[1] }); diff --git a/crates/ui-egui/src/delete.rs b/crates/ui-egui/src/delete.rs index 31e1ce404..0ad438a6f 100644 --- a/crates/ui-egui/src/delete.rs +++ b/crates/ui-egui/src/delete.rs @@ -20,8 +20,21 @@ pub struct Pending { /// What Delete acts on now: the selection (bodies not locked), plus the components picked in /// the browser (their occurrences). pub fn selection_params(app: &SolveApp) -> Value { - let items: Vec<&solidcraft_engine::Sel> = - app.session.selection.iter().filter(|s| !matches!(s, solidcraft_engine::Sel::Body { name } if app.ui.locked_bodies.contains(name))).collect(); + use solidcraft_engine::Sel; + let mut items: Vec = Vec::new(); + for s in app.session.selection.iter().filter(|s| !matches!(s, Sel::Body { name } if app.ui.locked_bodies.contains(name))) { + // A MidPoint glyph shared by lines whose midpoints meet removes every constraint it + // shows, and the point they shared when nothing else holds it. + let group = match s { + Sel::SketchConstraint { id } => crate::sketch_tools::active_glyph_deletion(app, id), + _ => vec![s.clone()], + }; + for g in group { + if !items.contains(&g) { + items.push(g); + } + } + } let occurrences: Vec = app.tree.picked_components.iter().filter_map(|c| app.session.doc.occurrence_of(*c).map(|o| o.id)).collect(); json!({ "items": items, "occurrences": occurrences, "canvases": app.tree.picked_canvases, "joints": app.tree.picked_joints }) } diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index a8e90d846..c3f162241 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -467,6 +467,50 @@ pub fn refine_snap( }) } +/// The constraints one glyph stands for. A point that is the midpoint of several lines (their +/// midpoints meet) shows a single MidPoint glyph, the first constraint's, for all of them; +/// any other constraint stands for itself. +pub fn glyph_group(sk: &solidcraft_engine::sketch::Sketch, id: &str) -> Vec { + use solidcraft_engine::sketch::ConstraintKind::Midpoint; + match sk.constraints.iter().find(|c| c.id == id).map(|c| (c.kind.clone(), c.driven)) { + Some((Midpoint { p, .. }, false)) => { + sk.constraints.iter().filter(|c| !c.driven && matches!(c.kind, Midpoint { p: q, .. } if q == p)).map(|c| c.id.clone()).collect() + } + _ => vec![id.to_string()], + } +} + +/// What deleting glyph `id` removes: the constraints it stands for, and, for one MidPoint glyph +/// shared by several lines, their common point once nothing else holds it (it only tied the +/// midpoints together, so it would be left floating). +pub fn glyph_deletion(sk: &solidcraft_engine::sketch::Sketch, id: &str) -> Vec { + use solidcraft_engine::{Sel, sketch::ConstraintKind::Midpoint}; + let group = glyph_group(sk, id); + let shared = match sk.constraints.iter().find(|c| c.id == id).map(|c| &c.kind) { + Some(Midpoint { p, .. }) if group.len() > 1 => Some(*p), + _ => None, + }; + let orphan = shared.filter(|&p| { + !sk.curves.iter().any(|c| c.kind.uses(p)) + && !sk.constraints.iter().any(|c| !group.contains(&c.id) && c.kind.indices().0.contains(&p)) + && sk.points.get(p).is_some_and(|q| !q.fixed && q.link.is_none() && q.exprs.is_none()) + }); + let mut out: Vec = group.into_iter().map(|id| Sel::SketchConstraint { id }).collect(); + if let Some(q) = orphan.and_then(|p| sk.points.get(p)) { + out.push(Sel::SketchPoint { id: q.id.clone() }); + } + out +} + +/// [`glyph_deletion`] in the active sketch. +pub fn active_glyph_deletion(app: &SolveApp, id: &str) -> Vec { + let st = app.session.world_state(); + match active_sketch(app).and_then(|s| st.sketch(s)) { + Some(ss) => glyph_deletion(&ss.sketch, id), + None => vec![solidcraft_engine::Sel::SketchConstraint { id: id.to_string() }], + } +} + /// The constraint glyph under a screen position (its constraint id). pub fn glyph_at(pos: Pos2) -> Option { GLYPHS.with(|g| g.borrow().iter().find(|(_, c)| c.distance(pos) <= GLYPH * 0.6).map(|(id, _)| id.clone())) @@ -494,7 +538,14 @@ pub fn click_glyph(app: &mut SolveApp, _proj: &Proj, pos: Pos2) -> bool { /// Delete the selected constraint glyph (true when one was selected). pub fn delete_glyph(app: &mut SolveApp) -> bool { let Some(id) = PICKED.with(|p| p.borrow_mut().take()) else { return false }; - let _ = app.run("sketch.delete", json!({"entities": [id]})); + let entities: Vec = active_glyph_deletion(app, &id) + .into_iter() + .filter_map(|s| match s { + solidcraft_engine::Sel::SketchConstraint { id } | solidcraft_engine::Sel::SketchPoint { id } => Some(id), + _ => None, + }) + .collect(); + let _ = app.run("sketch.delete", json!({ "entities": entities })); true } @@ -1170,10 +1221,20 @@ fn glyphs(app: &SolveApp, painter: &egui::Painter, proj: &Proj, hover: Option = Vec::new(); + // The point of each MidPoint glyph drawn so far: lines whose midpoints meet share one glyph. + let mut midpoints: Vec = Vec::new(); for c in &ss.sketch.constraints { if c.kind.is_dimension() { continue; } + if let solidcraft_engine::sketch::ConstraintKind::Midpoint { p, .. } = c.kind + && !c.driven + { + if midpoints.contains(&p) { + continue; + } + midpoints.push(p); + } if matches!( c.kind, solidcraft_engine::sketch::ConstraintKind::PatternPoint { .. } | solidcraft_engine::sketch::ConstraintKind::PatternRadius { .. } @@ -1213,10 +1274,16 @@ fn glyphs(app: &SolveApp, painter: &egui::Painter, proj: &Proj, hover: Option = Vec::new(); for (id, sp, base) in &placed { let Some(c) = ss.sketch.constraints.iter().find(|c| &c.id == id) else { continue }; - let failing = ss.report.failing.contains(id); + let group = glyph_group(&ss.sketch, id); + let failing = group.iter().any(|g| ss.report.failing.contains(g)); // Redundant (already implied by the others, but holding): dimmed, not an error. - let redundant = !failing && ss.report.redundant.contains(id); + let redundant = !failing && group.iter().all(|g| ss.report.redundant.contains(g)); let selected = picked.as_deref() == Some(id.as_str()) - || app.session.selection.iter().any(|s| matches!(s, solidcraft_engine::Sel::SketchConstraint { id: x } if x == id)); + || app.session.selection.iter().any(|s| matches!(s, solidcraft_engine::Sel::SketchConstraint { id: x } if group.contains(x))); let lit = selected || hovered.as_deref() == Some(id.as_str()); let col = if failing { tk.error @@ -1276,10 +1344,11 @@ fn glyphs(app: &SolveApp, painter: &egui::Painter, proj: &Proj, hover: Option String { "sketch.dimension" => "Dimension: pick one or two entities and type the value (or click to place it first); Enter applies".into(), "sketch.constraint.horizontal_vertical" => "Horizontal/Vertical: pick a line or two points; hold Shift to pick a line midpoint".into(), "sketch.slot.center_to_center" | "sketch.slot.overall" => "Slot: click both ends, then the width".into(), + "sketch.constraint.midpoint" => "MidPoint: pick a point and a line, or two lines to centre the second on the first".into(), _ if id.starts_with("sketch.constraint.") => "Constraint: pick the sketch entities".into(), _ => crate::sketch_tools::hint(id).unwrap_or_else(|| "Click in the sketch".into()), } @@ -494,6 +495,7 @@ pub(crate) fn constraint_preselection(command: &str, selection: &[solidcraft_eng "sketch.constraint.midpoint", [SketchPoint { id: point }, SketchCurve { id: line }] | [SketchCurve { id: line }, SketchPoint { id: point }], ) => Some(json!({"point":point,"line":line})), + ("sketch.constraint.midpoint", [SketchCurve { id: a }, SketchCurve { id: b }]) if a != b => Some(json!({"a":a,"b":b})), ("sketch.constraint.symmetry", [a, b, c]) => { let mut points = Vec::new(); let mut lines = Vec::new(); @@ -567,7 +569,8 @@ fn run_pick(app: &mut SolveApp, t: &Tool) { let params = match t.cmd { "sketch.constraint.fix" => json!({"entity": k[0]}), "sketch.constraint.coincident" => json!({"a": k[0], "b": k[1]}), - "sketch.constraint.midpoint" => json!({"point": k[0], "line": k[1]}), + // In pick order: a point and a line either way round, or two lines to centre. + "sketch.constraint.midpoint" => json!({"a": k[0], "b": k[1]}), "sketch.constraint.symmetry" => json!({"a": k[0], "b": k[1], "line": k[2]}), _ => json!({"a": k[0], "b": k[1]}), }; diff --git a/crates/ui-egui/tests/point_constraint_preselection.rs b/crates/ui-egui/tests/point_constraint_preselection.rs index 2d431cd2d..7c0765347 100644 --- a/crates/ui-egui/tests/point_constraint_preselection.rs +++ b/crates/ui-egui/tests/point_constraint_preselection.rs @@ -1,5 +1,5 @@ use serde_json::json; -use solidcraft_engine::{Sel, sketch::ConstraintKind}; +use solidcraft_engine::{Sel, geom::Vec2, sketch::ConstraintKind}; use solidcraft_ui_egui::scenario::Harness; fn setup() -> Harness { @@ -86,3 +86,103 @@ fn rejected_and_ambiguous_preselection_preserve_document_and_selection() { assert_eq!(h.app.session.doc.to_json(), before); } } + +// MidPoint centres one line on another when the tool picks two lines. +fn two_lines() -> Harness { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[0,0],[60,0]],"infer":false,"connect":false})).unwrap(); + h.app.run("sketch.line", json!({"points":[[5,-10],[25,-10]],"infer":false,"connect":false})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + h +} + +fn line_ends(h: &Harness, id: &str) -> (Vec2, Vec2) { + let state = h.app.session.world_state(); + let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; + let p = |end: &str| sk.point(sk.resolve_point(&format!("{id}.{end}")).unwrap()).unwrap(); + (p("start"), p("end")) +} + +fn assert_centred(h: &Harness, undo: usize) { + assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", h.app.status); + assert_eq!(h.app.session.undo.len(), undo + 1); + let (a, b) = line_ends(h, "l1"); + assert_eq!((a, b), (Vec2::new(0.0, 0.0), Vec2::new(60.0, 0.0)), "the first line stays"); + let (c, d) = line_ends(h, "l2"); + assert!(((a + b) * 0.5).dist((c + d) * 0.5) < 1e-6); + assert!((c.dist(d) - 20.0).abs() < 1e-6); +} + +#[test] +fn midpoint_tool_clicking_two_lines_centres_them() { + let mut h = two_lines(); + let undo = h.app.session.undo.len(); + h.step(&json!({"start":"sketch.constraint.midpoint"})).unwrap(); + h.step(&json!({"click":{"sketch":[45,0]}})).unwrap(); + h.step(&json!({"click":{"sketch":[10,-10]}})).unwrap(); + assert_centred(&h, undo); +} + +#[test] +fn midpoint_tool_takes_two_preselected_lines() { + let mut h = two_lines(); + h.step(&json!({"click":{"sketch":[45,0]}})).unwrap(); + h.step(&json!({"click":{"sketch":[10,-10]},"shift":true})).unwrap(); + assert_eq!(h.app.session.selection.len(), 2); + let undo = h.app.session.undo.len(); + h.step(&json!({"start":"sketch.constraint.midpoint"})).unwrap(); + assert!(h.app.tool.is_none()); + assert_centred(&h, undo); +} + +fn midpoint_ids(h: &Harness) -> Vec { + let state = h.app.session.world_state(); + let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; + sk.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).map(|c| c.id.clone()).collect() +} + +fn point_count(h: &Harness) -> usize { + let state = h.app.session.world_state(); + state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.points.len() +} + +/// Centre l2 on l1 with the MidPoint tool, then click its glyph and press Delete. +fn centre_then_delete_glyph(h: &mut Harness) { + h.step(&json!({"start":"sketch.constraint.midpoint"})).unwrap(); + h.step(&json!({"click":{"sketch":[45,0]}})).unwrap(); + h.step(&json!({"click":{"sketch":[10,-10]}})).unwrap(); + h.step(&json!({"key":"Escape"})).unwrap(); + let ids = midpoint_ids(h); + assert!(ids.len() >= 2, "one point at the middle of both lines"); + let glyphs: Vec<_> = solidcraft_ui_egui::sketch_tools::glyph_positions().into_iter().filter(|(id, _)| ids.contains(id)).collect(); + assert_eq!(glyphs.len(), 1, "one MidPoint glyph for both lines: {glyphs:?}"); + let at = glyphs[0].1; + h.step(&json!({"click":[at.x, at.y]})).unwrap(); + h.step(&json!({"key":"Delete"})).unwrap(); + for _ in 0..20 { + if midpoint_ids(h).is_empty() { + break; + } + h.frames(1); + } + assert!(midpoint_ids(h).is_empty(), "deleting the glyph removes both constraints: {:?}", midpoint_ids(h)); +} + +#[test] +fn centred_lines_show_one_midpoint_glyph_that_deletes_both_constraints_and_their_point() { + let mut h = two_lines(); + let points = point_count(&h); + centre_then_delete_glyph(&mut h); + assert_eq!(point_count(&h), points, "the point that only tied the midpoints goes too"); +} + +#[test] +fn deleting_the_shared_midpoint_glyph_keeps_a_point_another_line_uses() { + let mut h = two_lines(); + // l3 starts at the midpoint of l2: centring reuses that point, and deleting keeps it. + h.app.run("sketch.line", json!({"points":["mid:l2",[15,-30]],"infer":false,"connect":false})).unwrap(); + let points = point_count(&h); + centre_then_delete_glyph(&mut h); + assert_eq!(point_count(&h), points); +} diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md index 08752de01..090de552c 100644 --- a/docs/book/src/guide/sketching.md +++ b/docs/book/src/guide/sketching.md @@ -240,7 +240,9 @@ You can also start the constraint first and then pick its curves. An incomplete selection leaves the tool ready for ordinary picking. Coincident accepts an exact selection of two points or a point and a curve. Midpoint -accepts one point and one line, in either selection order. Symmetry accepts two distinct +accepts one point and one line, in either selection order, or two lines: the second line +moves (keeping its length) until its midpoint sits on the first line's midpoint, +and stays centred there as either line changes. Symmetry accepts two distinct points and one symmetry line, regardless of where the line occurs in the selection. Successful constraints clear the selection; rejected constraints preserve it. From c54b711345401cfb41e0285db0dc0cbc8ffa9ea9 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:39:30 +0000 Subject: [PATCH 11/25] CLI: --help prints usage to stdout and exits 0 (#1818) (#1828) * claim: #1818 * claim: #1818 * fix(cli): --help, -h and help print usage to stdout and exit 0 (#1818) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- apps/solidcraft-cli/src/main.rs | 6 ++++++ apps/solidcraft-cli/tests/help_output.rs | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 apps/solidcraft-cli/tests/help_output.rs diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index fbeb6500a..e122683e4 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -140,6 +140,12 @@ fn main() -> ExitCode { println!("solidcraft-cli {}", env!("CARGO_PKG_VERSION")); Ok(()) } + // Asked-for help is not an error: usage on stdout, exit 0. + Some("--help" | "-h" | "help") => { + use std::io::Write as _; + let _ = std::io::stdout().lock().write_all(USAGE.as_bytes()); + Ok(()) + } _ => Err(USAGE.to_string()), }; match r { diff --git a/apps/solidcraft-cli/tests/help_output.rs b/apps/solidcraft-cli/tests/help_output.rs new file mode 100644 index 000000000..2fda831e5 --- /dev/null +++ b/apps/solidcraft-cli/tests/help_output.rs @@ -0,0 +1,23 @@ +//! An explicit help request prints usage to stdout and succeeds; an unknown command still fails. + +use std::process::Command; + +#[test] +fn help_prints_usage_and_succeeds() { + for arg in ["--help", "-h", "help"] { + let output = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")).arg(arg).output().unwrap(); + assert!(output.status.success(), "{arg}: {}", String::from_utf8_lossy(&output.stderr)); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.starts_with("usage:"), "{arg}: {stdout}"); + assert!(stdout.contains("solidcraft-cli run"), "{arg}: {stdout}"); + assert!(output.stderr.is_empty(), "{arg}: {}", String::from_utf8_lossy(&output.stderr)); + } +} + +#[test] +fn unknown_command_still_fails_with_usage() { + let output = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")).arg("--not-a-command").output().unwrap(); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + assert!(String::from_utf8_lossy(&output.stderr).starts_with("error: usage:")); +} From 4ab3a85323ddd762e42e3d77377c82e612207a53 Mon Sep 17 00:00:00 2001 From: takuto-NA Date: Wed, 21 Oct 2026 21:49:11 +0000 Subject: [PATCH 12/25] Bug report: clarify the form and retain margins on resize (#2244) (#2246) * claim: #2244 * fix(ui): guide bug reports with a bounded, labelled form * fix(ui): export bug reports after processing current-frame edits --------- Co-authored-by: bherbruck Co-authored-by: Claude Sonnet 5.5 --- assets/locales/en.json | 19 ++ assets/locales/ja.json | 19 ++ assets/locales/zh.json | 19 ++ crates/ui-egui/src/issue_report.rs | 394 +++++++++++++++--------- crates/ui-egui/src/issue_report/form.rs | 214 +++++++++++++ crates/ui-egui/src/toolbar.rs | 2 + 6 files changed, 520 insertions(+), 147 deletions(-) create mode 100644 crates/ui-egui/src/issue_report/form.rs diff --git a/assets/locales/en.json b/assets/locales/en.json index 32faca657..8124c4930 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -28,6 +28,7 @@ "Also deletes": "Also deletes", "Angle 2": "Angle 2", "Animate": "Animate", + "App/system information and command settings are included. Review private details before sharing.": "App/system information and command settings are included. Review private details before sharing.", "Appearance name": "Appearance name", "Applied Radius": "Applied Radius", "Apply To": "Apply To", @@ -83,6 +84,7 @@ "Contact": "Contact", "Contact Sets": "Contact Sets", "Contact sets": "Contact sets", + "Continue on GitHub": "Continue on GitHub", "Continuity": "Continuity", "Copy Error Message": "Copy Error Message", "Copy Warning Message": "Copy Warning Message", @@ -111,6 +113,8 @@ "Delete the set": "Delete the set", "Density": "Density", "Dependents": "Dependents", + "Describe the problem you saw": "Describe the problem you saw", + "Describe what happened before continuing.": "Describe what happened before continuing.", "Designs you open or save appear here.": "Designs you open or save appear here.", "Determined by To Object. Choose Angle to edit the angular extent.": "Determined by To Object. Choose Angle to edit the angular extent.", "Direction": "Direction", @@ -128,6 +132,7 @@ "Enabled": "Enabled", "End bulge": "End bulge", "End continuity": "End continuity", + "Expected result (optional)": "Expected result (optional)", "Explode": "Explode", "Explode Text": "Explode Text", "Export Animation…": "Export Animation…", @@ -245,6 +250,8 @@ "Open GitHub draft": "Open GitHub draft", "Open local libraries in the desktop app. You can export this design's library here.": "Open local libraries in the desktop app. You can export this design's library here.", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.", + "Opens your browser and copies the report text for you to paste into GitHub.": "Opens your browser and copies the report text for you to paste into GitHub.", + "Opens your browser. Review and submit your report on GitHub.": "Opens your browser. Review and submit your report on GitHub.", "Operator": "Operator", "Other side": "Other side", "Other surface (mutual trim)": "Other surface (mutual trim)", @@ -294,6 +301,8 @@ "Remove the track": "Remove the track", "Remove this point": "Remove this point", "Report a bug — review a screenshot and open a GitHub draft": "Report a bug — review a screenshot and open a GitHub draft", + "Report text copied. Paste it into GitHub and submit your report there.": "Report text copied. Paste it into GitHub and submit your report there.", + "Reports are public. A GitHub account is required.": "Reports are public. A GitHub account is required.", "Reset Toolbar": "Reset Toolbar", "Resize Part": "Resize Part", "Restore View": "Restore View", @@ -308,6 +317,7 @@ "Revert Pos.": "Revert Pos.", "Revert Position": "Revert Position", "Review the report and screenshot before opening GitHub.": "Review the report and screenshot before opening GitHub.", + "Review your report on GitHub and click Submit new issue to publish it.": "Review your report on GitHub and click Submit new issue to publish it.", "Rim Edge": "Rim Edge", "Roll History Marker Here": "Roll History Marker Here", "Round": "Round", @@ -318,10 +328,12 @@ "SURFACE QUALITY": "SURFACE QUALITY", "Save Rule": "Save Rule", "Save View": "Save View", + "Save screenshot…": "Save screenshot…", "Save the study as an animated GIF, seen as the viewport shows it": "Save the study as an animated GIF, seen as the viewport shows it", "Saved preview. Geometry is being checked before editing.": "Saved preview. Geometry is being checked before editing.", "Scale factor": "Scale factor", "Scene": "Scene", + "Screenshot (optional)": "Screenshot (optional)", "Search": "Search", "Search commands": "Search commands", "Search this library": "Search this library", @@ -356,10 +368,12 @@ "Start continuity": "Start continuity", "Step": "Step", "Steps": "Steps", + "Steps to reproduce (optional)": "Steps to reproduce (optional)", "Stitch the kept pieces": "Stitch the kept pieces", "Stitch to both bodies": "Stitch to both bodies", "Study": "Study", "Style": "Style", + "Summary": "Summary", "Suppressed": "Suppressed", "Surface": "Surface", "Swap Ends": "Swap Ends", @@ -368,6 +382,7 @@ "Tangent Chain": "Tangent Chain", "Tap drill diameter": "Tap drill diameter", "Tear": "Tear", + "Technical details": "Technical details", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.", "The saved author occurrence is missing. Select a valid author placement before rebinding.": "The saved author occurrence is missing. Select a valid author placement before rebinding.", "Then": "Then", @@ -379,6 +394,7 @@ "This child is shared. Deleting it removes it from every copy of its parent.": "This child is shared. Deleting it removes it from every copy of its parent.", "This child is shared. Position changes apply to every copy of its parent.": "This child is shared. Position changes apply to every copy of its parent.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.", + "This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.": "This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.", "To Offset": "To Offset", "To edges": "To edges", "Tolerance": "Tolerance", @@ -404,6 +420,9 @@ "Wall": "Wall", "Wall Location": "Wall Location", "Wall Thickness": "Wall Thickness", + "What did you do just before the problem? A short list is enough": "What did you do just before the problem? A short list is enough", + "What did you expect to see?": "What did you expect to see?", + "What happened?": "What happened?", "When": "When", "Width": "Width", "Will fail": "Will fail", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 62bd497dc..18ee80029 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -28,6 +28,7 @@ "Also deletes": "同時に削除される要素:", "Angle 2": "角度 2", "Animate": "アニメーション", + "App/system information and command settings are included. Review private details before sharing.": "アプリ・システム情報とコマンド設定が含まれます。共有前に非公開の情報を確認してください。", "Appearance name": "外観名", "Applied Radius": "適用半径", "Apply To": "適用先", @@ -83,6 +84,7 @@ "Contact": "接触", "Contact Sets": "接触セット", "Contact sets": "接触セット", + "Continue on GitHub": "GitHubで続ける", "Continuity": "連続性", "Copy Error Message": "エラーメッセージをコピー", "Copy Warning Message": "警告メッセージをコピー", @@ -111,6 +113,8 @@ "Delete the set": "セットを削除", "Density": "密度", "Dependents": "依存先", + "Describe the problem you saw": "発生した問題を説明してください", + "Describe what happened before continuing.": "続ける前に、何が起きたか記入してください。", "Designs you open or save appear here.": "開いたデザインや保存したデザインがここに表示されます。", "Determined by To Object. Choose Angle to edit the angular extent.": "「対象オブジェクトまで」により決定されます。角度範囲を編集するには「角度」を選択してください。", "Direction": "方向", @@ -128,6 +132,7 @@ "Enabled": "有効", "End bulge": "終了側の膨らみ", "End continuity": "終了側の連続性", + "Expected result (optional)": "期待した結果(任意)", "Explode": "分解", "Explode Text": "テキストを分解", "Export Animation…": "アニメーションをエクスポート…", @@ -245,6 +250,8 @@ "Open GitHub draft": "GitHubの下書きを開く", "Open local libraries in the desktop app. You can export this design's library here.": "ローカルライブラリはデスクトップアプリで開いてください。このデザインのライブラリはここで書き出せます。", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Rust製オープンソース・パラメトリック3D CAD。ライセンス: MIT または Apache-2.0。", + "Opens your browser and copies the report text for you to paste into GitHub.": "ブラウザーを開き、GitHubに貼り付ける報告本文をコピーします。", + "Opens your browser. Review and submit your report on GitHub.": "ブラウザーを開きます。GitHubで内容を確認して投稿してください。", "Operator": "演算子", "Other side": "反対側", "Other surface (mutual trim)": "相手のサーフェス(相互トリム)", @@ -294,6 +301,8 @@ "Remove the track": "トラックを削除", "Remove this point": "この点を削除", "Report a bug — review a screenshot and open a GitHub draft": "バグを報告 — スクリーンショットを確認してGitHub下書きを作成", + "Report text copied. Paste it into GitHub and submit your report there.": "報告本文をコピーしました。GitHubに貼り付けて投稿してください。", + "Reports are public. A GitHub account is required.": "報告は公開されます。GitHubアカウントが必要です。", "Reset Toolbar": "ツールバーをリセット", "Resize Part": "部品サイズ変更", "Restore View": "ビューを復元", @@ -308,6 +317,7 @@ "Revert Pos.": "位置を復元", "Revert Position": "位置を元に戻す", "Review the report and screenshot before opening GitHub.": "GitHubを開く前にレポートとスクリーンショットを確認してください。", + "Review your report on GitHub and click Submit new issue to publish it.": "GitHubで内容を確認し、Submit new issueをクリックすると公開されます。", "Rim Edge": "リムエッジ", "Roll History Marker Here": "履歴マーカーをここに移動", "Round": "丸め", @@ -318,10 +328,12 @@ "SURFACE QUALITY": "サーフェス品質", "Save Rule": "ルールを保存", "Save View": "ビューを保存", + "Save screenshot…": "スクリーンショットを保存…", "Save the study as an animated GIF, seen as the viewport shows it": "ビューポートの表示どおりにスタディをアニメーション GIF として保存", "Saved preview. Geometry is being checked before editing.": "保存済みのプレビューです。編集前にジオメトリを検証しています。", "Scale factor": "尺度係数", "Scene": "シーン", + "Screenshot (optional)": "スクリーンショット(任意)", "Search": "検索", "Search commands": "コマンドを検索", "Search this library": "このライブラリを検索", @@ -356,10 +368,12 @@ "Start continuity": "開始側の連続性", "Step": "ステップ", "Steps": "ステップ数", + "Steps to reproduce (optional)": "再現手順(任意)", "Stitch the kept pieces": "残した部分をステッチ", "Stitch to both bodies": "両方のボディにステッチ", "Study": "スタディ", "Style": "スタイル", + "Summary": "概要", "Suppressed": "抑制", "Surface": "サーフェス", "Swap Ends": "端点を入れ替え", @@ -368,6 +382,7 @@ "Tangent Chain": "正接チェーン", "Tap drill diameter": "タップ下穴径", "Tear": "引き裂き", + "Technical details": "技術情報", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "破線のスケッチは保存された平面ガイドです。新しい面を選択してアタッチメントを修復してください。", "The saved author occurrence is missing. Select a valid author placement before rebinding.": "保存された作成元のオカレンスが見つかりません。再バインドする前に有効な作成元配置を選択してください。", "Then": "次を実行 (Then)", @@ -379,6 +394,7 @@ "This child is shared. Deleting it removes it from every copy of its parent.": "この子要素は共有されています。削除すると親のすべてのコピーから削除されます。", "This child is shared. Position changes apply to every copy of its parent.": "この子要素は共有されています。位置の変更は親のすべてのコピーに適用されます。", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "この面は安定したアタッチメントを提供できません。別の面を選択するか、固定平面を明示的に使用してください。", + "This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.": "この画像はまだGitHubに添付されていません。コピーまたは保存し、GitHubで添付してください。", "To Offset": "オフセットまで", "To edges": "終了側エッジ", "Tolerance": "公差", @@ -404,6 +420,9 @@ "Wall": "肉厚", "Wall Location": "壁の位置", "Wall Thickness": "壁の厚さ", + "What did you do just before the problem? A short list is enough": "問題の直前に行った操作を簡単に記入してください", + "What did you expect to see?": "どのような結果を期待していましたか?", + "What happened?": "何が起きましたか?", "When": "条件 (When)", "Width": "幅", "Will fail": "失敗します", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 65dcd1fc6..a44b405ce 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -28,6 +28,7 @@ "Also deletes": "同时删除", "Angle 2": "角度 2", "Animate": "动画", + "App/system information and command settings are included. Review private details before sharing.": "报告包含应用和系统信息以及命令设置。共享前请检查私人信息。", "Appearance name": "外观名称", "Applied Radius": "应用半径", "Apply To": "应用于", @@ -83,6 +84,7 @@ "Contact": "接触", "Contact Sets": "接触集", "Contact sets": "接触集", + "Continue on GitHub": "在GitHub中继续", "Continuity": "连续性", "Copy Error Message": "复制错误消息", "Copy Warning Message": "复制警告消息", @@ -111,6 +113,8 @@ "Delete the set": "删除此集合", "Density": "密度", "Dependents": "依赖项", + "Describe the problem you saw": "请描述您遇到的问题", + "Describe what happened before continuing.": "继续之前,请描述发生了什么。", "Designs you open or save appear here.": "你打开或保存的设计会显示在此处。", "Determined by To Object. Choose Angle to edit the angular extent.": "由“到对象”确定。选择“角度”可编辑角度范围。", "Direction": "方向", @@ -128,6 +132,7 @@ "Enabled": "已启用", "End bulge": "终止鼓度", "End continuity": "终止连续性", + "Expected result (optional)": "预期结果(可选)", "Explode": "爆炸", "Explode Text": "分解文字", "Export Animation…": "导出动画…", @@ -245,6 +250,8 @@ "Open GitHub draft": "打开 GitHub 草稿", "Open local libraries in the desktop app. You can export this design's library here.": "请在桌面应用中打开本地库。您可以在此导出当前设计的库。", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "使用 Rust 编写的开源参数化 3D CAD。基于 MIT OR Apache-2.0 许可。", + "Opens your browser and copies the report text for you to paste into GitHub.": "打开浏览器,并复制报告文本以便粘贴到GitHub。", + "Opens your browser. Review and submit your report on GitHub.": "打开浏览器。请在GitHub中检查并提交报告。", "Operator": "运算符", "Other side": "另一侧", "Other surface (mutual trim)": "另一曲面(相互修剪)", @@ -294,6 +301,8 @@ "Remove the track": "移除轨迹", "Remove this point": "移除此点", "Report a bug — review a screenshot and open a GitHub draft": "报告缺陷 — 复核截图并开启 GitHub 草稿", + "Report text copied. Paste it into GitHub and submit your report there.": "报告文本已复制。请在GitHub中粘贴并提交。", + "Reports are public. A GitHub account is required.": "报告将公开发布。您需要GitHub账户。", "Reset Toolbar": "重置工具栏", "Resize Part": "调整零件大小", "Restore View": "恢复视图", @@ -308,6 +317,7 @@ "Revert Pos.": "还原位置", "Revert Position": "恢复位置", "Review the report and screenshot before opening GitHub.": "打开 GitHub 前请审阅报告和截图。", + "Review your report on GitHub and click Submit new issue to publish it.": "请在GitHub中检查报告,然后点击Submit new issue发布。", "Rim Edge": "轮缘边", "Roll History Marker Here": "将历史标记滚动到此处", "Round": "圆角", @@ -318,10 +328,12 @@ "SURFACE QUALITY": "曲面质量", "Save Rule": "保存规则", "Save View": "保存视图", + "Save screenshot…": "保存屏幕截图…", "Save the study as an animated GIF, seen as the viewport shows it": "按视口中的显示将研究保存为动画 GIF", "Saved preview. Geometry is being checked before editing.": "已保存预览。编辑前正在检查几何。", "Scale factor": "比例因子", "Scene": "场景", + "Screenshot (optional)": "屏幕截图(可选)", "Search": "搜索", "Search commands": "搜索命令", "Search this library": "搜索此库", @@ -356,10 +368,12 @@ "Start continuity": "起始连续性", "Step": "步骤", "Steps": "步数", + "Steps to reproduce (optional)": "重现步骤(可选)", "Stitch the kept pieces": "缝合保留的部分", "Stitch to both bodies": "缝合到两个实体", "Study": "研究", "Style": "样式", + "Summary": "摘要", "Suppressed": "已抑制", "Surface": "曲面", "Swap Ends": "交换端点", @@ -368,6 +382,7 @@ "Tangent Chain": "相切链", "Tap drill diameter": "攻丝底孔直径", "Tear": "撕裂", + "Technical details": "技术详情", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "虚线草图是已保存的平面引导。选择一个新面以修复附着。", "The saved author occurrence is missing. Select a valid author placement before rebinding.": "保存的作者实例缺失。重新绑定前请选择有效的作者放置。", "Then": "操作", @@ -379,6 +394,7 @@ "This child is shared. Deleting it removes it from every copy of its parent.": "此子项是共享的。删除它会从其父项的每个副本中移除。", "This child is shared. Position changes apply to every copy of its parent.": "此子项是共享的。位置更改会应用到其父项的每个副本。", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "此面无法提供持久附着。请选择其他面或显式使用固定平面。", + "This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.": "此图片尚未附加到GitHub。请复制或保存图片,然后在GitHub中附加。", "To Offset": "偏移", "To edges": "终止边", "Tolerance": "公差", @@ -404,6 +420,9 @@ "Wall": "壁厚", "Wall Location": "壁位置", "Wall Thickness": "壁厚度", + "What did you do just before the problem? A short list is enough": "问题发生前您进行了哪些操作?简要列出即可", + "What did you expect to see?": "您期望看到什么结果?", + "What happened?": "发生了什么?", "When": "条件", "Width": "宽度", "Will fail": "将失败", diff --git a/crates/ui-egui/src/issue_report.rs b/crates/ui-egui/src/issue_report.rs index a5834aec5..ee15ab23b 100644 --- a/crates/ui-egui/src/issue_report.rs +++ b/crates/ui-egui/src/issue_report.rs @@ -4,11 +4,16 @@ use std::fmt::Write as _; use std::hash::{Hash, Hasher}; use std::sync::Arc; -use egui::{ColorImage, TextureHandle, vec2}; +use egui::{ColorImage, TextureHandle}; -use crate::{SolveApp, dialogs, help, ui_kit}; +use crate::{SolveApp, dialogs, help}; +mod form; + +const MAX_ANSWER: usize = 2000; const MAX_BODY: usize = 24_000; +// Room for all three answers and the original bounded diagnostic context. +const MAX_REPORT: usize = 32_000; const MAX_IMAGE_PIXELS: usize = 16_000_000; const ISSUE_URL: &str = "https://github.com/tangency-labs/solidcraft/issues/new"; @@ -96,11 +101,64 @@ pub struct ReportState { pub struct Draft { pub title: String, + /// Collected technical context, separately reviewable and editable. pub body: String, + description: String, + steps: String, + expected: String, image: Option>, texture: Option, pub note: String, source_signature: u64, + focus_requested: bool, + missing_description: bool, + opened_github: bool, +} + +impl Draft { + fn new(title: String, body: String, source_signature: u64) -> Self { + Self { + title, + body, + description: String::new(), + steps: String::new(), + expected: String::new(), + image: None, + texture: None, + note: String::new(), + source_signature, + focus_requested: false, + missing_description: false, + opened_github: false, + } + } + + fn report_title(&self) -> String { + if self.title.trim().is_empty() { + limited(self.description.trim().lines().next().unwrap_or_default(), 160) + } else { + limited(&self.title, 160) + } + } + + fn report_body(&self) -> String { + let answer = |text: &str| if text.trim().is_empty() { "Not provided".to_string() } else { limited(text, MAX_ANSWER) }; + let mut report = format!( + "## Actual behavior\n{}\n\n## Reproduction\n{}\n\n## Expected behavior\n{}\n\n", + answer(&self.description), + answer(&self.steps), + answer(&self.expected) + ); + let room = MAX_REPORT.saturating_sub(report.len()); + if self.body.len() <= room { + report.push_str(&self.body); + } else { + let marker = "\n[technical details truncated]\n"; + report.push_str(&limited(&self.body, room.saturating_sub(marker.len()))); + report.push_str(marker); + } + report + } } struct Pending { @@ -270,14 +328,14 @@ pub fn draft_for(app: &SolveApp, dialog: Option<&dialogs::Dialog>, error: Option context.push_str(&format!("Feature error: {}\n", debug(&e, 1000))); } } - let actual = error.map(|e| debug(&e, 4000)).unwrap_or_else(|| "Describe the unexpected result shown in the view.".into()); + let actual = error.map(|e| debug(&e, 4000)).unwrap_or_else(|| "No command error was recorded.".into()); let image_state = if error.is_some() { "A failed preview may display the last valid geometry; that geometry is not evidence that the failed operation succeeded." } else { - "Describe what looks wrong in the current result." + "The screenshot shows the current view." }; let mut body = format!( - "## Expected behavior\nDescribe the intended result.\n\n## Actual behavior\n{actual}\n\n{image_state}\n\n## Reproduction\nDescribe the steps or a small public-safe example.\n\n## Settings and selection\n{context}\n## Environment\n{}\nRevision: {}\nCamera: {}\n\n## Visual context\nAttach the reviewed screenshot or a short example showing the problem.\n", + "## Operation context\n{actual}\n\n{image_state}\n\n## Settings and selection\n{context}\n## Environment\n{}\nRevision: {}\nCamera: {}\n\n## Visual context\nAttach the reviewed screenshot or a short example showing the problem.\n", block(&debug(&help::diagnostics(app), 2000)), app.session.revision, block(&debug(&app.cam, 1500)) @@ -288,7 +346,7 @@ pub fn draft_for(app: &SolveApp, dialog: Option<&dialogs::Dialog>, error: Option } let mut title = format!("{label}: {}", if error.is_some() { "operation failed" } else { "unexpected result" }); truncate(&mut title, 160); - Draft { title, body, image: None, texture: None, note: String::new(), source_signature: source_signature(app, dialog) } + Draft::new(title, body, source_signature(app, dialog)) } /// A draft from a crash report (`solidcraft_engine::crash`): what happened, where, the command @@ -357,7 +415,10 @@ pub fn crash_draft(report: &serde_json::Value) -> Draft { } let mut title = format!("Crash: {}", s("message").lines().next().unwrap_or_default()); truncate(&mut title, 160); - Draft { title, body, image: None, texture: None, note: String::new(), source_signature: 0 } + let mut draft = Draft::new(title, body, 0); + draft.description = + limited(&format!("{what}{}.", command.map(|c| format!(" while running `{}`", limited(c, 160))).unwrap_or_default()), MAX_ANSWER); + draft } /// Open a reviewed draft for a crash report (no screenshot: the view shows nothing of it). @@ -509,122 +570,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { return; } let Some(mut draft) = app.issue_report.draft.take() else { return }; - let mut retake = false; - let t = crate::theme::Tokens::get(); - let screen = ctx.content_rect(); - let cards = ((screen.width() - 2.0 * t.space_16) / t.form_card_width).clamp(0.5, 2.6); - // The card's own header, footer and margins come on top of the scrolling body. - let chrome = ui_kit::header_height() + t.form_footer_height + 6.0 * t.space_8; - let scroll = (screen.height() - 2.0 * t.space_16 - chrome).clamp(60.0, 640.0); - let mut link = None; - let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_issue_report"), "bug_report", crate::i18n::tr_label("Create Issue — review draft")) - .cards(cards) - .fields() - .keep_open_on_escape() - .actions(crate::i18n::tr_label("Open GitHub draft"), crate::i18n::tr_label("Close draft"), Some(crate::i18n::tr_label("Copy report"))) - .show(ctx, true, |ui| { - // Only the review scrolls: the submission actions stay in the footer even when a - // screenshot or a long report needs more room. - egui::ScrollArea::vertical().id_salt("issue-report-review").max_height(scroll).auto_shrink([false, true]).show(ui, |ui| { - ui_kit::text( - ui, - crate::i18n::tr_label("Review the report and screenshot before opening GitHub."), - ui_kit::Text::Report("review", false), - ); - ui.horizontal_wrapped(|ui| { - retake = ui_kit::button(ui, crate::i18n::tr_label("Retake screenshot"), ui_kit::Button::Normal).clicked(); - if ui_kit::button(ui, "Copy screenshot", ui_kit::Button::Enabled(draft.image.is_some())).clicked() - && let Some(image) = draft.image.as_ref() - { - ctx.copy_image((**image).clone()); - draft.note = crate::i18n::tr("issue.note_image_copied").into(); - } - if ui_kit::button( - ui, - crate::i18n::tr("issue.save_screenshot"), - ui_kit::Button::Enabled(draft.image.is_some() && app.services.pick_save.is_some()), - ) - .clicked() - && let Some(image) = draft.image.clone() - { - app.pick_save(&format!("solidcraft-issue-{}.png", app.shot_token), &["png"], move |app, path| { - let Some(path) = path else { return }; - let result = crate::control::save_screenshot(&image, Some(&path)); - if let Some(draft) = app.issue_report.draft.as_mut() { - draft.note = if result.get("ok").and_then(serde_json::Value::as_bool) == Some(true) { - crate::i18n::tr("issue.note_saved").into() - } else { - crate::i18n::format("issue.note_save_failed", &[("error", &debug(&result.get("error"), 1000))]) - }; - } - }); - } - if ui_kit::button(ui, "Remove screenshot", ui_kit::Button::Enabled(draft.image.is_some())).clicked() { - draft.image = None; - draft.texture = None; - draft.note = crate::i18n::tr("issue.note_removed").into(); - } - }); - ui_kit::cell_editor(ui, egui::Id::new("issue_report_title"), &mut draft.title, "Issue title", false); - egui::ScrollArea::vertical().id_salt("issue-report-body").max_height((screen.height() * 0.35).clamp(72.0, 240.0)).show(ui, |ui| { - ui_kit::text_area(ui, crate::i18n::tr("issue.body_label"), egui::Id::new("issue_report_body"), &mut draft.body, 5, MAX_BODY); - }); - truncate(&mut draft.title, 160); - truncate(&mut draft.body, MAX_BODY); - ui_kit::text(ui, crate::i18n::tr_label("Remove private design details or paths before sharing."), ui_kit::Text::Note("private")); - if !draft.note.is_empty() { - ui_kit::text(ui, &draft.note, ui_kit::Text::Note("note")); - } - if let Some(image) = draft.image.as_ref() { - let texture = - draft.texture.get_or_insert_with(|| ctx.load_texture("issue-report-frame", image.clone(), egui::TextureOptions::LINEAR)); - ui.add( - egui::Image::new(&*texture) - .max_size(vec2(ui.available_width(), (screen.height() * 0.25).clamp(60.0, 220.0))) - .maintain_aspect_ratio(true), - ); - } - ui_kit::divider(ui, "send"); - ui_kit::text(ui, crate::i18n::tr_label("Send your report on GitHub"), ui_kit::Text::Report("send", false)); - let (url, copy_needed) = draft_url(&draft.title, &draft.body); - link = Some((url, copy_needed)); - ui_kit::text( - ui, - crate::i18n::tr_label(if copy_needed { - "1. Open GitHub draft below, then paste the report copied to your clipboard." - } else { - "1. Open GitHub draft below. Your title and report will be filled in." - }), - ui_kit::Text::Report("step1", false), - ); - ui_kit::text( - ui, - crate::i18n::tr_label("2. Attach your screenshot: copy and paste it, or save and upload the PNG."), - ui_kit::Text::Report("step2", false), - ); - ui_kit::text( - ui, - crate::i18n::tr_label("3. Click Submit new issue on GitHub to send your report."), - ui_kit::Text::Report("step3", false), - ); - }); - }); - let open = !(closed || action == ui_kit::Action::Cancel); - match (action, link) { - (ui_kit::Action::Ok, Some((url, copy_needed))) => { - if copy_needed { - ctx.copy_text(draft.body.clone()); - } - ctx.open_url(egui::OpenUrl::new_tab(url)); - draft.note = crate::i18n::tr(if copy_needed { "issue.note_opened_copied" } else { "issue.note_opened" }).into(); - } - (ui_kit::Action::Apply, _) => { - ctx.copy_text(draft.body.clone()); - draft.note = crate::i18n::tr("issue.note_report_copied").into(); - } - _ => {} - } - if open { + let (retake, close) = form::show(app, &mut draft, ctx); + if !close { app.issue_report.draft = Some(draft); if retake { let dialog = app.dialog.clone(); @@ -672,6 +619,137 @@ mod tests { dialog.inputs.get_mut(1).unwrap().items = vec![Sel::Body { name: "Cutter".into() }]; } + fn click_commands(h: &mut crate::scenario::Harness, label: &str) -> Vec { + let [x, y] = h.widget(label).unwrap(); + assert_eq!(h.call("ui.move", json!({"x":x,"y":y}))["ok"], true); + let (request, _reply) = crate::control::ControlRequest::new("ui.click", json!({"x":x,"y":y})); + assert!(matches!(crate::control::handle(&mut h.app, &h.ctx, &request), crate::control::Outcome::Done(value) if value["ok"] == true)); + let mut commands = Vec::new(); + for _ in 0..12 { + h.frame(); + commands.extend(h.output.commands.clone()); + } + commands + } + + #[test] + fn issue_report_form_separates_user_answers_from_technical_context() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.issue_report.draft = Some(draft_for(&h.app, None, None)); + h.frames(4); + for label in ["What happened?", "Steps to reproduce (optional)", "Expected result (optional)", "Technical details", "Continue on GitHub"] { + assert!(h.widget(label).is_some(), "missing report form control: {label}"); + } + assert!(h.widget("Describe the intended result.").is_none(), "Markdown instructions must not be editable answers"); + } + + #[test] + fn issue_report_answers_preserve_the_reviewed_context_within_the_export_budget() { + let mut draft = draft_for(&app(), None, None); + draft.description = "a".repeat(MAX_ANSWER); + draft.steps = "b".repeat(MAX_ANSWER); + draft.expected = "c".repeat(MAX_ANSWER); + draft.body = format!("{}END_CONTEXT", "d".repeat(MAX_BODY - 11)); + let report = draft.report_body(); + assert!(report.len() <= MAX_REPORT && report.ends_with(&draft.body)); + for answer in [&draft.description, &draft.steps, &draft.expected] { + assert!(report.contains(answer)); + } + draft.description = "現象🚀".repeat(MAX_REPORT); + draft.body = "調査🚀".repeat(MAX_REPORT); + let bounded = draft.report_body(); + assert!(bounded.len() <= MAX_REPORT && bounded.ends_with("[technical details truncated]\n")); + } + + #[test] + fn issue_report_requires_an_answer_before_browser_handoff_without_changing_the_design() { + for (size, scale) in [([1600, 1000], 1.0), ([640, 480], 2.0)] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.preferences.ui_scale = scale; + h.call("ui.resize", json!({"width":size[0],"height":size[1]})); + h.app.issue_report.draft = Some(draft_for(&h.app, None, None)); + h.frames(16); + let before = (h.app.session.doc.to_json(), h.app.session.revision, h.app.session.undo.len()); + let commands = click_commands(&mut h, "Continue on GitHub"); + assert!(!commands.iter().any(|c| matches!(c, egui::OutputCommand::OpenUrl(_)))); + assert!(h.app.issue_report.draft.as_ref().unwrap().missing_description); + assert_eq!(h.ctx.memory(|m| m.focused()), Some(egui::Id::new("issue_report_body"))); + h.step(&json!({"text":"The preview disappeared"})).unwrap(); + let commands = click_commands(&mut h, "Continue on GitHub"); + assert!(commands.iter().any(|c| matches!(c, egui::OutputCommand::OpenUrl(url) if url.url.starts_with(ISSUE_URL)))); + assert!(h.app.issue_report.draft.as_ref().unwrap().description.contains("The preview disappeared")); + assert_eq!(before, (h.app.session.doc.to_json(), h.app.session.revision, h.app.session.undo.len())); + } + } + + #[test] + fn issue_report_handoff_includes_edits_from_the_click_frame() { + for field in ["issue_report_body", "issue_report_title", "issue_report_steps", "issue_report_expected", "issue_report_technical"] { + for clipboard in [false, true] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + let mut draft = Draft::new("Previous summary".into(), "Private diagnostic details".into(), 0); + if field != "issue_report_body" { + draft.description = "Previously reviewed problem".into(); + } + if clipboard { + draft.steps = "Reproduction context. ".repeat(100); + } + h.app.issue_report.draft = Some(draft); + h.frames(16); + if field == "issue_report_technical" { + h.call("ui.scroll", json!({"x":800,"y":600,"delta":-1000})); + h.step(&json!({"widget":"Technical details"})).unwrap(); + h.call("ui.scroll", json!({"x":800,"y":600,"delta":-1000})); + } + h.ctx.memory_mut(|m| m.request_focus(egui::Id::new(field))); + h.frames(1); + let [x, y] = h.widget("Continue on GitHub").unwrap(); + let pos = egui::pos2(x as f32, y as f32); + let modifiers = egui::Modifiers { ctrl: true, command: true, ..Default::default() }; + let raw = egui::RawInput { + screen_rect: Some(h.ctx.content_rect()), + focused: true, + events: vec![ + egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers }, + egui::Event::Paste("Latest reviewed content".into()), + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }, + ], + ..Default::default() + }; + let app = &mut h.app; + let mut output = h.ctx.run_ui(raw, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + let draft = h.app.issue_report.draft.as_ref().unwrap(); + let edited = match field { + "issue_report_body" => &draft.description, + "issue_report_title" => &draft.title, + "issue_report_steps" => &draft.steps, + "issue_report_expected" => &draft.expected, + _ => &draft.body, + }; + assert_eq!(edited, "Latest reviewed content", "{field}, clipboard={clipboard}"); + let body = draft.report_body(); + let (url, copy_needed) = draft_url(&draft.report_title(), &body); + assert!( + output.platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::OpenUrl(u) if u.url == url)), + "handoff must use this frame's edits: {field}, clipboard={clipboard}" + ); + if copy_needed { + assert!(output.platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(text) if text == &body))); + } + output.textures_delta.clear(); + assert!(draft.opened_github && !draft.missing_description); + } + } + } + #[test] fn crash_draft_marks_later_detection_without_losing_native_evidence() { let message = @@ -749,7 +827,7 @@ mod tests { let ctx = crate::fonts::test_context(); help::run(&mut app, &ctx, "report"); let draft = app.issue_report.draft.as_ref().unwrap(); - assert!(draft.body.contains("Describe the unexpected result")); + assert!(draft.description.is_empty(), "user answers start empty, without template instructions"); assert!(draft.body.contains(help::COMMIT)); assert!(draft.body.contains("combine") && draft.body.contains("keep_tools") && draft.body.contains("Cutter")); assert!(pending(&app), "Help must request real evidence, not just copy generic text"); @@ -801,27 +879,49 @@ mod tests { h.app.home.open = false; let mut draft = draft_for(&h.app, None, None); draft.body = "Reviewed context 🚀 &labels=private\n".repeat(120); - let reviewed = draft.body.clone(); + draft.description = "The preview disappeared after clicking Extrude.".into(); + draft.steps = "1. Select a face\n2. Start Extrude".into(); + draft.expected = "A preview of the extrusion".into(); + draft.image = Some(Arc::new(ColorImage::new([2, 2], vec![egui::Color32::GREEN; 4]))); + let reviewed = draft.report_body(); h.app.issue_report.draft = Some(draft); - h.frames(4); - assert!(h.widget("1. Open GitHub draft below, then paste the report copied to your clipboard.").is_some()); - assert!(h.widget("3. Click Submit new issue on GitHub to send your report.").is_some()); - let [x, y] = h.widget("Open GitHub draft").unwrap(); - assert_eq!(h.call("ui.move", json!({"x":x,"y":y}))["ok"], true); - let (request, _reply) = crate::control::ControlRequest::new("ui.click", json!({"x":x,"y":y})); - assert!(matches!(crate::control::handle(&mut h.app, &h.ctx, &request), crate::control::Outcome::Done(value) if value["ok"] == true)); - let mut commands = Vec::new(); - for _ in 0..12 { - h.frame(); - commands.extend(h.output.commands.clone()); - } + h.frames(16); + assert!(h.widget("Opens your browser and copies the report text for you to paste into GitHub.").is_some()); + assert!(h.widget("Reports are public. A GitHub account is required.").is_some()); + let commands = click_commands(&mut h, "Continue on GitHub"); assert!(commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(text) if text == &reviewed)), "commands: {commands:?}"); assert!( commands.iter().any(|c| matches!(c, egui::OutputCommand::OpenUrl(url) if url.url.starts_with(ISSUE_URL) && !url.url.contains("&body="))) ); - assert_eq!(h.app.issue_report.draft.as_ref().unwrap().body, reviewed); - assert!(h.app.issue_report.draft.as_ref().unwrap().note.starts_with("Report copied. Paste into the GitHub draft")); - assert!(h.app.issue_report.draft.as_ref().unwrap().note.contains("Submit new issue")); + assert_eq!(h.app.issue_report.draft.as_ref().unwrap().report_body(), reviewed); + assert!(h.app.issue_report.draft.as_ref().unwrap().opened_github); + click_commands(&mut h, "Copy screenshot"); + assert!(!h.app.issue_report.draft.as_ref().unwrap().opened_github, "copying an image replaces the report text on the clipboard"); + assert!(h.widget("Opens your browser and copies the report text for you to paste into GitHub.").is_some()); + click_commands(&mut h, "Continue on GitHub"); + click_commands(&mut h, "Remove screenshot"); + assert!(h.app.issue_report.draft.as_ref().unwrap().image.is_none()); + assert!(h.widget("Screenshot removed from this draft.").is_some()); + assert!(h.widget("Report text copied. Paste it into GitHub and submit your report there.").is_some()); + } + + #[test] + fn issue_report_blank_summary_uses_the_export_title_for_clipboard_guidance() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + let mut draft = draft_for(&h.app, None, None); + draft.title.clear(); + draft.description = "d".repeat(160); + draft.body = "x".repeat(1500); + let reviewed = draft.report_body(); + assert!(!draft_url("", &reviewed).1, "the fallback title must be what crosses the URL limit"); + assert!(draft_url(&draft.report_title(), &reviewed).1); + h.app.issue_report.draft = Some(draft); + h.frames(16); + assert!(h.widget("Opens your browser and copies the report text for you to paste into GitHub.").is_some()); + let commands = click_commands(&mut h, "Continue on GitHub"); + assert!(commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(text) if text == &reviewed))); + assert!(h.widget("Report text copied. Paste it into GitHub and submit your report there.").is_some()); } #[test] @@ -843,8 +943,8 @@ mod tests { let idle = rect(&h); assert!((idle.width() - settled.width()).abs() < 1.0, "size={size:?}: {settled:?} grew to {idle:?}"); assert!(idle.width() <= 790.0, "report must retain its width limit: {idle:?}"); - assert!(h.ctx.content_rect().contains_rect(idle), "size={size:?} scale={scale}: window must fit: {idle:?}"); - for label in ["Copy screenshot", "Save screenshot…", "Open GitHub draft", "Copy report", "Close draft"] { + assert!(h.ctx.content_rect().shrink(8.0).contains_rect(idle), "size={size:?} scale={scale}: retain an outer margin: {idle:?}"); + for label in ["Continue on GitHub", "Close draft"] { let [x, y] = h.widget(label).unwrap(); assert!(idle.contains(egui::pos2(x as f32, y as f32)), "{label} must stay visible: {idle:?}, {x}, {y}"); } @@ -873,7 +973,7 @@ mod tests { h.ctx.memory_mut(|m| m.surrender_focus(id)); } let draft = h.app.issue_report.draft.as_ref().unwrap(); - assert!(draft.title.contains("edited-report-marker") && draft.body.contains("edited-report-marker")); + assert!(draft.title.contains("edited-report-marker") && draft.description.contains("edited-report-marker")); for key in [json!({"key":"Enter"}), json!({"key":"Escape"}), json!({"key":"Z","cmd":true})] { h.step(&key).unwrap(); assert!(h.app.dialog.is_some() && h.app.issue_report.draft.is_some()); @@ -913,7 +1013,7 @@ mod tests { assert!(h.widget("Pending CAD text").is_some(), "report keys must not apply, edit or cancel the Text editor"); } let draft = h.app.issue_report.draft.as_ref().unwrap(); - assert!(draft.title.contains("report-only-marker") && draft.body.contains("report-only-marker")); + assert!(draft.title.contains("report-only-marker") && draft.description.contains("report-only-marker")); h.step(&json!({"widget":"Close draft"})).unwrap(); assert!(h.app.issue_report.draft.is_none()); h.frames(2); @@ -968,7 +1068,7 @@ mod tests { h.app.home.open = false; h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); h.app.run("sketch.line", json!({"points":[[0,0],[20,0]],"id":"line"})).unwrap(); - h.frames(3); + h.frames(16); let at = h.call("ui.at", json!({"sketch":[0,0]})); let p = egui::pos2(at["result"][0].as_f64().unwrap() as f32, at["result"][1].as_f64().unwrap() as f32); h.app.synthetic.push(egui::Event::PointerMoved(p)); @@ -999,7 +1099,7 @@ mod tests { assert_eq!(before, (h.app.session.doc.to_json(), h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision)); let token = h.app.issue_report.pending.as_ref().unwrap().token; receive(&mut h.app, token, Arc::new(ColorImage::new([2, 2], vec![egui::Color32::GREEN; 4]))); - h.frames(3); + h.frames(16); h.step(&json!({"widget":"Close draft"})).unwrap(); assert!(h.app.viewport.point_drag.is_none()); assert_eq!(before, (h.app.session.doc.to_json(), h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision)); @@ -1034,7 +1134,7 @@ mod tests { h.step(&json!({"key":"Escape"})).unwrap(); assert_eq!(before, (h.app.session.doc.to_json(), h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision)); assert!(crate::dim_view::editing() && h.widget("30 mm").is_some()); - assert!(h.app.issue_report.draft.as_ref().unwrap().body.contains("Typing here describes")); + assert!(h.app.issue_report.draft.as_ref().unwrap().description.contains("Typing here describes")); h.step(&json!({"widget":"Close draft"})).unwrap(); h.frames(2); assert_eq!(h.ctx.memory(|m| m.focused()), Some(egui::Id::new("sc_dim_edit"))); diff --git a/crates/ui-egui/src/issue_report/form.rs b/crates/ui-egui/src/issue_report/form.rs new file mode 100644 index 000000000..478330390 --- /dev/null +++ b/crates/ui-egui/src/issue_report/form.rs @@ -0,0 +1,214 @@ +//! The reviewed report form. User answers stay separate from collected diagnostics. + +use egui::{Id, Ui, vec2}; + +use super::{Draft, MAX_ANSWER, MAX_BODY, draft_url}; +use crate::{SolveApp, i18n::tr_label, ui_kit}; + +const ALL_GUIDANCE: [&str; 4] = [ + "Report text copied. Paste it into GitHub and submit your report there.", + "Review your report on GitHub and click Submit new issue to publish it.", + "Opens your browser and copies the report text for you to paste into GitHub.", + "Opens your browser. Review and submit your report on GitHub.", +]; + +fn answer(ui: &mut Ui, label: &str, hint: &str, text: &mut String, id: &str, rows: usize) -> egui::Response { + ui_kit::text(ui, tr_label(label), ui_kit::Text::Heading(label)); + ui_kit::text(ui, tr_label(hint), ui_kit::Text::Note(hint)); + let response = ui_kit::text_area(ui, tr_label(label), Id::new(id), text, rows, MAX_ANSWER); + crate::scenario::publish_handle(id, response.rect.center()); + super::truncate(text, MAX_ANSWER); + response +} + +fn screenshot_actions(app: &mut SolveApp, draft: &mut Draft, ui: &mut Ui) -> bool { + let mut retake = false; + ui.horizontal_wrapped(|ui| { + retake = ui_kit::button(ui, tr_label("Retake screenshot"), ui_kit::Button::Normal).clicked(); + if ui_kit::button(ui, tr_label("Remove screenshot"), ui_kit::Button::Enabled(draft.image.is_some())).clicked() { + draft.image = None; + draft.texture = None; + draft.note = "Screenshot removed from this draft.".into(); + } + }); + if draft.image.is_some() { + ui.horizontal_wrapped(|ui| { + if ui_kit::button(ui, tr_label("Copy screenshot"), ui_kit::Button::Normal).clicked() + && let Some(image) = draft.image.as_ref() + { + ui.ctx().copy_image((**image).clone()); + draft.opened_github = false; + draft.note = "Paste the image into the GitHub draft, or save the PNG if image copying is unavailable.".into(); + } + if ui_kit::button(ui, tr_label("Save screenshot…"), ui_kit::Button::Enabled(app.services.pick_save.is_some())).clicked() + && let Some(image) = draft.image.clone() + { + app.pick_save(&format!("solidcraft-issue-{}.png", app.shot_token), &["png"], move |app, path| { + let Some(path) = path else { return }; + let result = crate::control::save_screenshot(&image, Some(&path)); + if let Some(draft) = app.issue_report.draft.as_mut() { + draft.note = if result.get("ok").and_then(serde_json::Value::as_bool) == Some(true) { + "Screenshot saved. Attach the PNG in the GitHub draft.".into() + } else { + format!("Could not save screenshot: {}", super::debug(&result.get("error"), 1000)) + }; + } + }); + } + }); + } + if !draft.note.is_empty() { + ui_kit::text(ui, tr_label(&draft.note), ui_kit::Text::Note("note")); + } + retake +} + +fn screenshot(app: &mut SolveApp, draft: &mut Draft, ui: &mut Ui) -> bool { + ui_kit::text(ui, tr_label("Screenshot (optional)"), ui_kit::Text::Heading("Screenshot (optional)")); + let preview = draft.image.as_ref().map(|image| { + draft.texture.get_or_insert_with(|| ui.ctx().load_texture("issue-report-frame", image.clone(), egui::TextureOptions::LINEAR)).clone() + }); + let mut retake = false; + let guidance = |ui: &mut Ui| { + ui_kit::text( + ui, + tr_label("This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub."), + ui_kit::Text::Note("screenshot"), + ); + }; + if let Some(texture) = preview { + ui.add(egui::Image::new(&texture).max_size(vec2(ui.available_width(), 130.0)).maintain_aspect_ratio(true)); + guidance(ui); + } + retake |= screenshot_actions(app, draft, ui); + retake +} + +/// Returns whether to retake the screenshot and whether the user closed the form. +pub(super) fn show(app: &mut SolveApp, draft: &mut Draft, ctx: &egui::Context) -> (bool, bool) { + let mut retake = false; + let t = crate::theme::Tokens::get(); + let screen = ctx.content_rect(); + let cards = ((screen.width() - 2.0 * t.space_16) / t.form_card_width).clamp(0.5, 2.6); + let (closed, action) = ui_kit::Window::new(Id::new("sc_issue_report"), "bug_report", tr_label("Report a bug")) + .cards(cards) + .anchor(egui::Align2::CENTER_TOP, vec2(0.0, t.space_16)) + .fields() + .keep_open_on_escape() + .actions(tr_label("Continue on GitHub"), tr_label("Close draft"), Some(tr_label("Copy report"))) + .show(ctx, true, |ui| { + // The card's own header, footer and margins come on top of the scrolling body. + let chrome = ui_kit::header_height() + t.form_footer_height + 6.0 * t.space_8; + let scroll = (screen.height() - 2.0 * t.space_16 - chrome).clamp(60.0, 640.0); + // Sized outright, not from what is left: a card that fits its content grows frame by + // frame otherwise, and the footer moves under a click. + ui.allocate_ui(vec2(ui.available_width(), scroll), |ui| { + egui::ScrollArea::vertical() + .id_salt("issue-report-review") + .max_height(scroll) + .min_scrolled_height(scroll) + .auto_shrink([false, false]) + .show(ui, |ui| { + let body = draft.report_body(); + let (_, copy_needed) = draft_url(&draft.report_title(), &body); + let guidance = if draft.opened_github { + if copy_needed { + "Report text copied. Paste it into GitHub and submit your report there." + } else { + "Review your report on GitHub and click Submit new issue to publish it." + } + } else if copy_needed { + "Opens your browser and copies the report text for you to paste into GitHub." + } else { + "Opens your browser. Review and submit your report on GitHub." + }; + // Reserve the tallest wording, so the card (and its footer) keeps its height as the + // guidance changes under a click. + let width = ui.available_width(); + let font = egui::FontId::proportional(t.font_small); + let tallest = ALL_GUIDANCE + .iter() + .map(|g| ui.painter().layout(tr_label(g).to_string(), font.clone(), t.form_dim, width).size().y) + .fold(0.0_f32, f32::max); + ui.allocate_ui(vec2(width, tallest), |ui| { + ui_kit::text(ui, tr_label(guidance), ui_kit::Text::Note("guidance")); + }); + ui_kit::text(ui, tr_label("Reports are public. A GitHub account is required."), ui_kit::Text::Note("public")); + ui_kit::divider(ui, "report"); + ui_kit::text(ui, tr_label("Summary"), ui_kit::Text::Heading("Summary")); + let response = ui_kit::bounded_cell_editor(ui, Id::new("issue_report_title"), &mut draft.title, "", false, 160); + if response.changed() { + draft.opened_github = false; + } + super::truncate(&mut draft.title, 160); + let response = answer(ui, "What happened?", "Describe the problem you saw", &mut draft.description, "issue_report_body", 3); + if response.changed() { + draft.opened_github = false; + } + crate::scenario::publish_rect("report:description", response.rect); + if !draft.focus_requested || draft.missing_description { + response.scroll_to_me(Some(egui::Align::Center)); + response.request_focus(); + draft.focus_requested = true; + } + if draft.missing_description { + if draft.description.trim().is_empty() { + ui_kit::text(ui, tr_label("Describe what happened before continuing."), ui_kit::Text::Error("description")); + } else { + draft.missing_description = false; + } + } + let steps = answer( + ui, + "Steps to reproduce (optional)", + "What did you do just before the problem? A short list is enough", + &mut draft.steps, + "issue_report_steps", + 2, + ); + let expected = + answer(ui, "Expected result (optional)", "What did you expect to see?", &mut draft.expected, "issue_report_expected", 2); + if steps.changed() || expected.changed() { + draft.opened_github = false; + } + retake = screenshot(app, draft, ui); + ui_kit::text( + ui, + tr_label("App/system information and command settings are included. Review private details before sharing."), + ui_kit::Text::Note("private"), + ); + ui_kit::section(ui, "issue-report-technical", "Technical details", false, |ui| { + let response = + ui_kit::text_area(ui, tr_label("Technical details"), Id::new("issue_report_technical"), &mut draft.body, 8, MAX_BODY); + if response.changed() { + draft.opened_github = false; + } + super::truncate(&mut draft.body, MAX_BODY); + }); + }); + }); + }); + // TextEdit applies this frame's events while it is drawn. Export only after every editor + // has processed its input, including diagnostic redactions. + match action { + ui_kit::Action::Ok => { + draft.missing_description = draft.description.trim().is_empty(); + if !draft.missing_description { + let body = draft.report_body(); + let (url, copy_needed) = draft_url(&draft.report_title(), &body); + if copy_needed { + ctx.copy_text(body); + } + ctx.open_url(egui::OpenUrl::new_tab(url)); + draft.opened_github = true; + ctx.request_repaint(); + } + } + ui_kit::Action::Apply => { + ctx.copy_text(draft.report_body()); + draft.note = "Report copied. Paste it into the GitHub draft if needed.".into(); + } + _ => {} + } + (retake, closed || action == ui_kit::Action::Cancel) +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 013d0a5f5..94466c060 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -2252,6 +2252,8 @@ mod header_report_tests { assert!(crate::issue_report::pending(&h.app)); assert_eq!(before, (h.app.session.doc.to_json(), h.app.session.undo.len(), h.app.session.revision)); captured_frame(&mut h); + // The report card takes a few frames to reach its full height. + h.frames(16); // Existing review content scrolls vertically when the window is narrow. if width < 700.0 { let [x, y] = h.widget("Close draft").unwrap(); From 14b27f323ad779431658c72ab4fb44a16cc0a0c7 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:49:18 +0000 Subject: [PATCH 13/25] Dialogs picking a plane show the origin planes in the view (#2581) (#2618) * claim: #2581 * fix(view): dialogs picking a plane show the origin planes (#2581) Create Sketch showed the origin planes while it picked its plane; now any dialog whose active input takes origin planes does (Mirror's plane, Offset Plane, Midplane, the construct tools), so the plane can be picked in the view. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/ui-egui/src/lib.rs | 15 +++++++++++---- crates/ui-egui/src/viewport.rs | 30 +++++++++++++++++++++++++----- 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9abe87c57..7c73ef1be 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1147,11 +1147,11 @@ impl SolveApp { v } - /// Is the origin widget shown? Origin planes and axes are drawn and pickable. While Create - /// Sketch picks its plane the Origin is always shown, drawn through the model (a plane - /// inside a body stays visible), even when the browser hides it. + /// Is the origin widget shown? Origin planes and axes are drawn and pickable. While a dialog + /// picks a plane ([`SolveApp::picking_plane`]) the Origin is always shown, drawn through the + /// model (a plane inside a body stays visible), even when the browser hides it. pub fn origin_visible(&self) -> bool { - self.ui.show_origin || self.picking_sketch_plane() + self.ui.show_origin || self.picking_plane() } /// Is Create Sketch open, waiting for its plane? @@ -1159,6 +1159,13 @@ impl SolveApp { self.dialog.as_ref().is_some_and(|d| matches!(d.kind, dialogs::Kind::Sketch)) } + /// Is a dialog waiting for a plane: Create Sketch, or a dialog whose active input takes origin + /// planes (Mirror's plane, Offset Plane, Midplane, the construct tools)? The origin planes are + /// shown for it, so they can be picked in the view rather than only in the browser (#2581). + pub fn picking_plane(&self) -> bool { + self.picking_sketch_plane() || self.dialog.as_ref().is_some_and(|d| d.inputs.get(d.active).is_some_and(|i| i.accept & selection::PLANES != 0)) + } + /// Is the view drawn in perspective? The perspective preference, except while a sketch is /// open: a sketch is drawn and measured on its plane, so the view is parallel (no foreshortening). pub fn perspective_view(&self) -> bool { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index c6a6954e9..90903a003 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -965,9 +965,9 @@ pub fn origin_planes(app: &SolveApp) -> Vec<(&'static str, Vec3, [Vec3; 4])> { if !app.origin_visible() { return Vec::new(); } - // While the Origin is hidden, Create Sketch brings the planes back: then every plane; - // otherwise only those not hidden one by one. - let creating = !app.ui.show_origin && app.picking_sketch_plane(); + // While the Origin is hidden, a dialog picking a plane brings the planes back: then every + // plane; otherwise only those not hidden one by one. + let creating = !app.ui.show_origin && app.picking_plane(); origin_quads(origin_size(app.cam.half_height())) .into_iter() .filter(|(n, _, _)| creating || !app.session.visibility.hidden_origin.iter().any(|h| h == n)) @@ -1964,7 +1964,7 @@ fn highlight_geometry_key(app: &SolveApp) -> u64 { app.preview.effective_replaced().hash(&mut h); app.preview.rolled_back.hash(&mut h); app.origin_visible().hash(&mut h); - app.picking_sketch_plane().hash(&mut h); + app.picking_plane().hash(&mut h); app.session.visibility.hidden_origin.hash(&mut h); app.session.visibility.hidden_bodies.hash(&mut h); app.session.visibility.hidden_occurrences.hash(&mut h); @@ -2021,7 +2021,7 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { }; let mut planes: Vec<(String, [Vec3; 4], Color32)> = origin_planes(app).into_iter().map(|(n, _, q)| (n.to_string(), q, t.origin_plane)).collect(); planes.extend(construction_quads(app).into_iter().map(|(n, _, q)| (n, q, t.construction_plane))); - let through = app.picking_sketch_plane(); + let through = app.picking_plane(); for (name, q, base) in &planes { let (selected, hovered) = plane_state(name); let fill = if hovered { @@ -6860,6 +6860,26 @@ mod grid_plane_tests { assert!(sc.xray.is_empty() && !sc.guide_trans.is_empty(), "outside Create Sketch the planes are depth-tested"); } + /// #2581: a dialog waiting for a plane (here Mirror's plane) shows the origin planes in the + /// view as Create Sketch does, so the plane can be picked there; while it waits for its + /// objects it doesn't. + #[test] + fn a_dialog_picking_a_plane_shows_the_origin_planes() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.run("solid.box", json!({"length":40,"width":40,"height":40})).unwrap(); + app.ui.show_origin = false; + app.start("solid.mirror"); + let d = app.dialog.as_ref().expect("the Mirror dialog"); + assert_eq!(d.active, 0, "it starts on its objects"); + assert!(!app.picking_plane() && origin_planes(&app).is_empty(), "no planes while picking objects"); + app.dialog.as_mut().unwrap().active = 1; + assert!(app.picking_plane()); + assert_eq!(origin_planes(&app).len(), 3, "every origin plane is offered for the mirror plane"); + assert!(!build_highlight(&app).xray.is_empty(), "drawn through the model"); + app.dialog = None; + assert!(origin_planes(&app).is_empty()); + } + /// Primary rolls a live preview back for reselect, but not while a manipulator is dragged /// (same gate [`show`] uses via [`preview_should_roll_back`]). #[test] From 95b23f28d6eb199f7734533f4c6628973ce97927 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Wed, 21 Oct 2026 22:07:38 +0000 Subject: [PATCH 14/25] Rename box: Tab (and leaving the box) keeps the new name (#3313) (#3336) * claim: #3313 * fix(ui): the Rename box keeps the new name when it loses focus (#3313) Only Enter committed a rename: Tab (and anything else that moved focus away) dropped the typed name. Leaving the box now keeps it, as a click elsewhere already did; Escape still cancels. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/ui-egui/src/menu_tests.rs | 35 +++++++++++++++++++++++++++++++ crates/ui-egui/src/ui_kit/menu.rs | 3 ++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menu_tests.rs b/crates/ui-egui/src/menu_tests.rs index d4f7f1d68..c70b3e799 100644 --- a/crates/ui-egui/src/menu_tests.rs +++ b/crates/ui-egui/src/menu_tests.rs @@ -848,6 +848,41 @@ fn menus_near_the_window_corner_open_inward() { } } +/// #3313: renaming a body by typing in the Rename box and pressing Enter (or Tab) renames it. +#[test] +fn typing_a_new_body_name_and_enter_renames_it() { + for confirm in ["Enter", "Tab"] { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap(); + let b = h.app.session.model.state().bodies[0].name.clone(); + h.app.run("select.set", json!({"items": [{"type": "body", "name": b}]})).unwrap(); + h.frames(2); + h.step(&json!({"key": "F2"})).unwrap(); + h.frames(2); + assert!(h.app.menu.rename.is_some(), "F2 opens the Rename box"); + h.step(&json!({"text": "Lid"})).unwrap(); + h.frames(1); + h.step(&json!({"key": confirm})).unwrap(); + h.frames(2); + let names: Vec = h.app.session.model.state().bodies.iter().map(|b| b.name.clone()).collect(); + assert_eq!(names, ["Lid"], "{confirm} renames the body; status {:?}", h.app.status); + } + // Escape still cancels. + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap(); + let b = h.app.session.model.state().bodies[0].name.clone(); + h.app.run("select.set", json!({"items": [{"type": "body", "name": b.clone()}]})).unwrap(); + h.frames(2); + h.step(&json!({"key": "F2"})).unwrap(); + h.frames(2); + h.step(&json!({"text": "Lid"})).unwrap(); + h.frames(1); + h.step(&json!({"key": "Escape"})).unwrap(); + h.frames(2); + assert!(h.app.menu.rename.is_none()); + assert_eq!(h.app.session.model.state().bodies[0].name, b, "Escape keeps the old name"); +} + #[test] fn contribution_picked_faces_open_their_own_feature_after_later_modifiers() { use solidcraft_engine::{Sel, geom::Vec3}; diff --git a/crates/ui-egui/src/ui_kit/menu.rs b/crates/ui-egui/src/ui_kit/menu.rs index 4495b010e..c8f534dd1 100644 --- a/crates/ui-egui/src/ui_kit/menu.rs +++ b/crates/ui-egui/src/ui_kit/menu.rs @@ -375,7 +375,8 @@ pub(crate) fn rename_menu(ui: &mut Ui, value: &mut String, focused: &mut bool) - response.request_focus(); *focused = true; } - if ui.input(|i| i.key_pressed(egui::Key::Enter)) { + // Leaving the box with Tab keeps the new name as Enter does; only Escape cancels (#3313). + if ui.input(|i| i.key_pressed(egui::Key::Enter)) || (response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Tab))) { done = Some(true); } if ui.input(|i| i.key_pressed(egui::Key::Escape)) { From 2fdc105d879e9932c876fc866ffb5844660f9f3d Mon Sep 17 00:00:00 2001 From: bherbruck Date: Wed, 21 Oct 2026 22:26:43 +0000 Subject: [PATCH 15/25] IGES import: separate lumps of one part are separate solids (#3928) (#3972) Co-authored-by: Claude Opus 5.5 --- crates/kernel/src/iges_in.rs | 82 +++++++++++++++++++++------ crates/kernel/src/iges_in/assembly.rs | 4 +- crates/kernel/src/iges_in/tests.rs | 19 +++++++ 3 files changed, 84 insertions(+), 21 deletions(-) diff --git a/crates/kernel/src/iges_in.rs b/crates/kernel/src/iges_in.rs index ccdf1949b..c59b51d3e 100644 --- a/crates/kernel/src/iges_in.rs +++ b/crates/kernel/src/iges_in.rs @@ -1167,14 +1167,17 @@ fn color_of(t: &Tr, seq: i64) -> Option<[f32; 3]> { /// Write faces sewn by `sw` as a shell; the shell's id and whether it closes. fn write_shell(o: &mut Out, sw: &Sewer, faces: &[FaceB], styles: &mut Vec<(u64, [f32; 3])>) -> (u64, bool) { - let vids: Vec = sw - .verts - .iter() - .map(|p| { - let c = o.point(*p); - o.add(format!("VERTEX_POINT('',#{c})")) - }) - .collect(); + // Vertices are written as the shell's edges use them (a sewer may hold several shells). + let mut vids: HashMap = HashMap::new(); + let mut vertex = |o: &mut Out, i: usize| -> Option { + if let Some(id) = vids.get(&i) { + return Some(*id); + } + let c = o.point(*sw.verts.get(i)?); + let id = o.add(format!("VERTEX_POINT('',#{c})")); + vids.insert(i, id); + Some(id) + }; let mut eids: HashMap = HashMap::new(); let mut count: HashMap = HashMap::new(); for &(e, d) in faces.iter().flat_map(|f| f.loops.iter().flatten()) { @@ -1195,7 +1198,7 @@ fn write_shell(o: &mut Out, sw: &Sewer, faces: &[FaceB], styles: &mut Vec<(u64, let id = match eids.get(&e) { Some(id) => *id, None => { - let (Some(a), Some(b)) = (vids.get(ed.v[0]), vids.get(ed.v[1])) else { continue }; + let (Some(a), Some(b)) = (vertex(o, ed.v[0]), vertex(o, ed.v[1])) else { continue }; let id = o.add(format!("EDGE_CURVE('',#{a},#{b},#{},{})", ed.curve, if ed.rev { ".F." } else { ".T." })); eids.insert(e, id); id @@ -1335,7 +1338,7 @@ fn sew_surfaces( styles: &mut Vec<(u64, [f32; 3])>, faces: &mut Vec, sw: &mut Sewer, -) -> R> { +) -> R> { faces.clear(); sw.verts.clear(); sw.grid.clear(); @@ -1358,17 +1361,60 @@ fn sew_surfaces( faces.push(FaceB { surface: d.surface, sense: true, loops, color: d.color }); } if faces.is_empty() { - return Ok(None); + return Ok(Vec::new()); } orient(faces); - let (shell, closed) = write_shell(&mut t.o, sw, faces, styles); + // Faces that share no edge, directly or through others, are separate bodies: one shell of + // two lumps is closed edge by edge but not a solid. + let pieces = connected(faces); let name = name.replace('\'', "''"); - Ok(Some(if closed { - t.o.add(format!("MANIFOLD_SOLID_BREP('{name}',#{shell})")) - } else { - t.warn("the surfaces do not close into a solid: imported as an open body"); - t.o.add(format!("SHELL_BASED_SURFACE_MODEL('{name}',(#{shell}))")) - })) + let mut items = Vec::with_capacity(pieces.len()); + for (k, piece) in pieces.into_iter().enumerate() { + let (shell, closed) = write_shell(&mut t.o, sw, &piece, styles); + let name = if k == 0 { name.clone() } else { format!("{name} {}", k + 1) }; + items.push(if closed { + t.o.add(format!("MANIFOLD_SOLID_BREP('{name}',#{shell})")) + } else { + t.warn("the surfaces do not close into a solid: imported as an open body"); + t.o.add(format!("SHELL_BASED_SURFACE_MODEL('{name}',(#{shell}))")) + }); + } + Ok(items) +} + +/// The faces in groups that share edges, taken out of `faces`. +fn connected(faces: &mut Vec) -> Vec> { + let mut parent: Vec = (0..faces.len()).collect(); + let root = |parent: &[usize], mut i: usize| { + while let Some(&p) = parent.get(i).filter(|p| **p != i) { + i = p; + } + i + }; + let mut first: HashMap = HashMap::new(); + for (fi, f) in faces.iter().enumerate() { + for &(e, _) in f.loops.iter().flatten() { + let other = *first.entry(e).or_insert(fi); + let (a, b) = (root(&parent, fi), root(&parent, other)); + if let Some(x) = parent.get_mut(a) { + *x = b; + } + } + } + // In file order: a group comes where its first face does. + let mut slot: HashMap = HashMap::new(); + let mut out: Vec> = Vec::new(); + let roots: Vec = (0..faces.len()).map(|i| root(&parent, i)).collect(); + for (f, r) in faces.drain(..).zip(roots) { + let k = *slot.entry(r).or_insert_with(|| { + out.push(Vec::new()); + out.len() - 1 + }); + if let Some(g) = out.get_mut(k) { + g.push(f); + } + } + out } /// A face read from a trimmed or bounded surface, its loops not yet sewn. diff --git a/crates/kernel/src/iges_in/assembly.rs b/crates/kernel/src/iges_in/assembly.rs index 9c77c9bcd..2a3894f34 100644 --- a/crates/kernel/src/iges_in/assembly.rs +++ b/crates/kernel/src/iges_in/assembly.rs @@ -180,9 +180,7 @@ impl Assembly { .copied() .filter(|s| seq != 0 || !self.referenced.contains(s)) .filter(|s| f.des.get(s).is_some_and(|d| matches!(d.typ, 143 | 144) || (d.typ == 128 && !self.surface_references.contains(s)))); - if let Some(item) = sew_surfaces(t, surfaces, if seq == 0 { "Body1" } else { name }, styles, &mut faces, &mut sewer)? { - items.push(item); - } + items.extend(sew_surfaces(t, surfaces, if seq == 0 { "Body1" } else { name }, styles, &mut faces, &mut sewer)?); made += items.len(); list.clear(); let _ = write!(list, "#{origin}"); diff --git a/crates/kernel/src/iges_in/tests.rs b/crates/kernel/src/iges_in/tests.rs index c05022c86..b7922b5de 100644 --- a/crates/kernel/src/iges_in/tests.rs +++ b/crates/kernel/src/iges_in/tests.rs @@ -299,6 +299,25 @@ fn trimmed_surfaces_sew_into_a_solid() { assert!(rel(m.volume, 6000.0) < 1e-6 && rel(m.area, 2200.0) < 1e-6, "{} {}", m.volume, m.area); } +/// One part whose surfaces make two separate boxes: two solids, not one shell of two lumps +/// (closed edge by edge, but not connected, so it was read as an open body). +#[test] +fn separate_lumps_of_one_part_are_separate_solids() { + let mut ents = Vec::new(); + let mut faces = trimmed_box(&mut ents, 0.0); + faces.extend(trimmed_box(&mut ents, 100.0)); + let members = faces.iter().map(|s| s.to_string()).collect::>().join(","); + ents.push((308, 0, format!("0,5HFrame,{},{members}", faces.len()))); + let imp = iges_import(&iges_file(&ents)).unwrap(); + assert!(imp.warnings.is_empty(), "{:?}", imp.warnings); + assert_eq!(imp.bodies.len(), 2); + for (body, x) in imp.bodies.iter().zip([0.0, 100.0]) { + let m = measure(&body.body).unwrap(); + assert!(body.closed && rel(m.volume, 6000.0) < 1e-6, "{} {}", body.name, m.volume); + assert!(m.bbox.min.dist(Vec3::new(x, 0.0, 0.0)) < 1e-6, "{} at {:?}", body.name, m.bbox.min); + } +} + /// Trim pieces whose ends miss each other by a hundredth of a millimetre, far past the file's /// stated resolution: the loop is closed and the box sews into a solid. A gap of half a /// millimetre is no corner written loosely, and stays open. From 2daf22923cb3cadfbd4c149f252614d10f8ca7d0 Mon Sep 17 00:00:00 2001 From: raykholo Date: Wed, 21 Oct 2026 22:37:31 +0000 Subject: [PATCH 16/25] Extrude preview: a cut from an empty root is no longer refused (#3085) (#3363) * claim: #3085 * Extrude preview: a cut from an empty root is not refused (#3085) A cut or intersect sketched where the active component has no body of its own (the root of an assembly, or of a design whose part was imported into a component) takes part in every body (#1234): the command makes the cut. The Extrude preview checked the targets itself, looked only in the active component, and showed "there is no body to cut or intersect" beside a tool going through the part. Pressing OK still cut, so the dialog said one thing and the model another. The rule now lives in one place, Session::cut_takes_every_body, which both the command and the preview ask, so they cannot disagree again. --------- Co-authored-by: bherbruck Co-authored-by: Claude Sonnet 5.5 --- crates/engine/src/cmd/features.rs | 16 ++++++++++++---- crates/ui-egui/src/preview.rs | 28 +++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index d441131b6..2bd92b1ee 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -182,6 +182,16 @@ pub fn auto_operation(s: &Session, p: &Value) -> Option<&'static str> { auto_operation_in(s, p, true) } +impl Session { + /// Whether a cut or intersect that names no bodies takes part in every body of `st`: the + /// active component has no body of its own while the model has some (a sketch in the + /// assembly's root cutting through its parts, #1234). The command and its preview both ask + /// this, so the preview never refuses a cut the command makes (#3085). + pub fn cut_takes_every_body(&self, st: &solidcraft_doc::ModelState) -> bool { + !st.bodies.is_empty() && !st.bodies.iter().any(|b| self.doc.model_body_component(b) == self.active_component) + } +} + fn auto_operation_in(s: &Session, p: &Value, world_faces: bool) -> Option<&'static str> { let symmetric = p.get("to").is_none() && str_(p, "direction").is_some_and(|d| d.eq_ignore_ascii_case("symmetric")); // Imported face groups can belong to a child of an empty active component. @@ -503,10 +513,8 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> && !primitive && (matches!(str_(p, "operation").and_then(Operation::parse), Some(Operation::Cut | Operation::Intersect)) || matches!(&kind, FeatureKind::Extrude { operation: Operation::Cut | Operation::Intersect, .. })) - && { - let st = s.model.state(); - !st.bodies.is_empty() && !st.bodies.iter().any(|b| s.doc.model_body_component(b) == s.active_component) - } { + && s.cut_takes_every_body(&s.model.state()) + { vec!["*".to_string()] } else { participants diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index 7b0161da2..b1bfee4b7 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -484,8 +484,13 @@ pub(crate) fn extrusion_target_error(s: &Session, cmds: &[(String, Value)], befo } } } else { + // A cut or intersect from a component with no body of its own takes part in every + // body: the command decides that (#1234), and the preview asks it the same (#3085). found = params.get("faces").and_then(|_| params.get("face_body")).and_then(Value::as_str).map_or_else( - || before.bodies.iter().any(|body| s.doc.model_body_component(body) == s.active_component), + || { + before.bodies.iter().any(|body| s.doc.model_body_component(body) == s.active_component) + || (matches!(op, "cut" | "intersect") && s.cut_takes_every_body(before)) + }, |name| s.world_state().body(name).is_some(), ); } @@ -1192,6 +1197,27 @@ mod tests { assert_eq!(whole.scene.xray.len(), tool.scene.xray.len()); } + /// #3085: a cut sketched in the root, where every body lives in a component, cuts every body + /// it meets (#1234). The preview said "there is no body to cut or intersect" all the same, + /// while the cut itself went through. + #[test] + fn a_cut_from_an_empty_root_is_not_refused_by_its_preview() { + let mut s = session_of(&[ + ("component.create", json!({"name": "Part"})), + ("solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Block"})), + ("component.activate", json!({"component": "root"})), + ("sketch.create", json!({"plane": "XY"})), + ("sketch.rectangle.two_point", json!({"p0": [3, 3], "p1": [7, 7]})), + ("sketch.finish", json!({})), + ]); + let params = json!({"distance": 20, "operation": "cut"}); + let cmds = vec![("solid.extrude".to_string(), params.clone())]; + assert_eq!(extrusion_target_error(&s, &cmds, &s.model.state()), None); + s.execute("solid.extrude", ¶ms).unwrap(); + let volume = s.model.state().body("Block").map(|b| solidcraft_engine::kernel::measure(&b.body).unwrap().volume).unwrap_or(0.0); + assert!((volume - (1000.0 - 160.0)).abs() < 1e-6, "{volume}"); + } + /// While an arrow is dragged the inputs change faster than a tool is built: a tool built /// for inputs since changed is shown anyway (then the latest computed), an error only for /// the inputs it belongs to. From b289dc2421a8c3a172afa4754f731072eea7f6ef Mon Sep 17 00:00:00 2001 From: Daniel Date: Wed, 21 Oct 2026 22:57:22 +0000 Subject: [PATCH 17/25] Sketch Dimension: `name = value` defines a user parameter (#2916) (#3638) * Sketch Dimension: `name = value` defines a user parameter (#2916) In a dimension's value (the D tool's box, and `sketch.dimension`'s `value` from scripts, the CLI, MCP and the control channel), `name = expression` adds the user parameter `name` with that expression and dimensions with `name`: typing `width = 40` on a line gives a 40 mm user parameter `width` and a dimension whose expression is `width`. A bare number is read in the design's unit, as a bare dimension value is; an angle's parameter is in degrees. The expression may be anything the parameter editor takes. It is one command: one undo removes the parameter and the dimension together, and a dimension the sketch refuses leaves no parameter behind. A taken name is refused with a hint (type the name to use it, or change it in Parameters), a reserved name with the parameter editor's message, and a left side that is not a name (`2 = 3`) still fails to parse as before. A driven dimension defines nothing. The reply carries `defined`, and the status line names the parameter. The splitter lives in the doc crate (`expr::definition`) so other value inputs can take the same form later; editing an existing dimension, the inline shape boxes and feature dialogs are follow-ups. Co-Authored-By: Claude Fable 5.1 * Sketch Dimension: say why a name is refused, in the command's own words (#2916) The dimension editor showed a refused definition raw, in the box and the status line: "invalid parameters for `sketch.dimension`: value: `mm` is a unit, constant or function name". It now reads "Sketch Dimension: `mm` is a unit name, so it cannot be a parameter name": the editor passes the command's errors through `friendly_error` like every other command, and drops the `value:` field tag, since the box is the value. The taken-name hint reads the same way: "Sketch Dimension: there is already a parameter `w`: type `w` to use it, or change it in Parameters". A reserved name says what kind of word it is and what that means (`param_name_problem`, shared with the Parameters dialog): a unit name, a function name, or a constant, "so it cannot be a parameter name"; `expr::reserved_kind` tells them apart. `friendly_error` translates the command label with the interface language (the engine's sentence stays English), so the prefix reads "Wymiar szkicu:" in Polish. Co-Authored-By: Claude Fable 5.1 * Sketch Dimension test: keep the third line off the ribbon (#2916) On current `main` the ribbon floats over the top of the canvas, and the test's third line at sketch y = 50 projected under it: the click opened Parameters instead of picking the line. The line now goes below the first one. Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: bherbruck --- crates/doc/src/document.rs | 7 +- crates/doc/src/expr.rs | 79 ++++++++- crates/engine/src/cmd/sketch.rs | 34 +++- .../src/cmd/sketch_constraints_tests.rs | 153 ++++++++++++++++++ crates/engine/src/tests.rs | 6 + crates/ui-egui/src/dim_view.rs | 95 +++++++++-- crates/ui-egui/src/lib.rs | 15 +- docs/book/src/guide/parameters.md | 4 +- docs/book/src/guide/sketching.md | 3 +- 9 files changed, 377 insertions(+), 19 deletions(-) diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index ef77f1f52..9a52d36a1 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -3227,10 +3227,11 @@ impl Document { if name.len() > 64 { return Some("parameter names are at most 64 characters".into()); } - if expr::is_reserved(name) { - return Some(format!("`{name}` is a unit, constant or function name")); + match expr::reserved_kind(name) { + Some("constant") => Some(format!("`{name}` is a constant, so it cannot be a parameter name")), + Some(kind) => Some(format!("`{name}` is a {kind} name, so it cannot be a parameter name")), + None => None, } - None } /// Add or change a parameter. Fails if the result would not evaluate. A new parameter diff --git a/crates/doc/src/expr.rs b/crates/doc/src/expr.rs index 694cbe72a..d8419b129 100644 --- a/crates/doc/src/expr.rs +++ b/crates/doc/src/expr.rs @@ -304,9 +304,23 @@ fn is_constant(id: &str) -> bool { CONSTANTS.contains(&id) } +/// What kind of word the expression language reserves `name` as: `unit`, `constant` or +/// `function` (None: free for a parameter). +pub fn reserved_kind(name: &str) -> Option<&'static str> { + if unit(name).is_some() { + Some("unit") + } else if is_constant(name) { + Some("constant") + } else if FUNCTIONS.iter().any(|(f, _)| *f == name) { + Some("function") + } else { + None + } +} + /// Is this a name the expression language reserves (unit, constant or function)? pub fn is_reserved(name: &str) -> bool { - unit(name).is_some() || is_constant(name) || FUNCTIONS.iter().any(|(f, _)| *f == name) + reserved_kind(name).is_some() } #[derive(Clone, Debug, PartialEq)] @@ -535,6 +549,24 @@ pub fn is_bare_number(s: &str) -> bool { is_literal(s) && s.trim().trim_start_matches(['-', '+']).trim().parse::().is_ok() } +/// Is `s` shaped like a parameter name: a letter or `_`, then letters, digits and `_`? The shape +/// only; whether the name is free or reserved is `Document::param_name_problem`'s business. +fn is_name_shaped(s: &str) -> bool { + let mut cs = s.chars(); + matches!(cs.next(), Some(c) if c.is_alphabetic() || c == '_') && cs.all(|c| c.is_alphanumeric() || c == '_') +} + +/// A value typed as a definition, `name = expression`: the name and the text after the first +/// `=`, both trimmed (the text may be empty). `None` for anything else, including text whose +/// left side is not shaped like a name (`2 = 3`), which stays an ordinary expression and fails +/// to parse as before. The dimension input defines a user parameter this way (#2916); other +/// value inputs can take the same form later. +pub fn definition(s: &str) -> Option<(&str, &str)> { + let (name, rhs) = s.split_once('=')?; + let name = name.trim(); + is_name_shaped(name).then(|| (name, rhs.trim())) +} + /// The length unit of a design with these units: `mm` unless they name another length unit. pub fn length_unit_or_mm(units: &str) -> &str { let u = units.trim(); @@ -1204,4 +1236,49 @@ mod tests { assert!(is_bare_number(" -1.5 ") && is_bare_number("+2") && !is_bare_number("20 mm") && !is_bare_number("(2)")); assert_eq!((length_unit_or_mm(" in "), length_unit_or_mm("deg"), length_unit_or_mm("")), ("in", "mm", "mm")); } + + /// `name = expression` splits at the first `=` when the left side is shaped like a name; the + /// right side is any text, checked by whoever evaluates it. + #[test] + fn definitions_split_on_a_name_and_an_equals_sign() { + let splits = [ + ("w = 20", "w", "20"), + ("w=20", "w", "20"), + (" w = 20 mm ", "w", "20 mm"), + ("w = (a + b) / 2", "w", "(a + b) / 2"), + ("w = 2 * (3 + sin(45 deg))", "w", "2 * (3 + sin(45 deg))"), + ("w = 1 in - 5.4 mm", "w", "1 in - 5.4 mm"), + ("_w1 = 1", "_w1", "1"), + ("szerokość = 20", "szerokość", "20"), + // Reserved names split too: the parameter check names the reason. + ("mm = 5", "mm", "5"), + // A second `=` stays in the expression, which then fails to evaluate. + ("w == 3", "w", "= 3"), + ("w = a = 3", "w", "a = 3"), + // An empty expression is the caller's error to report. + ("w =", "w", ""), + ("w = ", "w", ""), + ]; + for (text, name, rhs) in splits { + assert_eq!(definition(text), Some((name, rhs)), "{text:?}"); + } + for text in ["20", "20 mm", "width / 2", "= 20", "=", "", "2w = 3", "a b = 3", "a-b = 3", "w.x = 3", "(w) = 3", "-w = 3"] { + assert_eq!(definition(text), None, "{text:?}"); + } + } + + /// A reserved name is refused by saying what kind of word it is. + #[test] + fn a_reserved_name_is_refused_by_its_kind() { + assert_eq!( + (reserved_kind("mm"), reserved_kind("deg"), reserved_kind("pi"), reserved_kind("sin"), reserved_kind("width")), + (Some("unit"), Some("unit"), Some("constant"), Some("function"), None) + ); + let problem = |n: &str| crate::Document::param_name_problem(n).unwrap_or_default(); + assert_eq!(problem("mm"), "`mm` is a unit name, so it cannot be a parameter name"); + assert_eq!(problem("sin"), "`sin` is a function name, so it cannot be a parameter name"); + assert_eq!(problem("pi"), "`pi` is a constant, so it cannot be a parameter name"); + assert_eq!(crate::Document::param_name_problem("width"), None); + assert!(problem("2w").contains("not a valid parameter name")); + } } diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 6dbbc2218..ec1ff880d 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -115,7 +115,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .params(concat!("p0, p1: overall ends, width", connect_doc!(), created_doc!())), CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them), id?", connect_doc!(), created_doc!())), CommandSpec::new("sketch.dimension", "Sketch Dimension", dimension).at("SKETCH", "CREATE").icon("dimension").key("D").enabled(in_sketch).params( - "entities: [refs], type?: auto|distance|horizontal|vertical|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them is the distance between them, above or below them horizontal, beside them vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled", + "entities: [refs], type?: auto|distance|horizontal|vertical|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override), or `name = expression` (e.g. \"width = 40\"), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them is the distance between them, above or below them horizontal, beside them vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled", ), CommandSpec::new("sketch.constraint.horizontal_vertical", "Horizontal/Vertical", c_horizontal_vertical) .at("SKETCH", "CONSTRAINTS") @@ -2095,6 +2095,19 @@ fn dimension(s: &mut Session, p: &Value) -> Result { let value = expr(p, "value"); let text_at = p.get("text_at").and_then(vec2); let driven = bool_(p, "driven").unwrap_or(false); + // `name = expression` defines the user parameter `name` and dimensions with it (#2916). + let (defines, value) = match value.as_ref().and_then(|v| solidcraft_doc::expr::definition(v.as_str())) { + Some((name, rhs)) => { + if rhs.is_empty() { + return Err(bad(cmd, format!("value: `{name} =` needs a value after the `=`"))); + } + if driven { + return Err(bad(cmd, format!("value: a driven dimension has no value, so it cannot define `{name}`"))); + } + (Some((name.to_string(), rhs.to_string())), Some(solidcraft_doc::expr::Expr::new(name))) + } + None => (None, value), + }; let scale_sketch = bool_(p, "scale_sketch").unwrap_or(false); let mut scaled = None; let mut before = None; @@ -2260,7 +2273,21 @@ fn dimension(s: &mut Session, p: &Value) -> Result { } let (unit, default_expr) = if is_angle { ("deg", format!("{} deg", round6(cur.to_degrees()))) } else { ("mm", format!("{} mm", round6(cur))) }; - let e = value.as_ref().map(|e| doc.with_design_unit(e, if is_angle { Kind::Angle } else { Kind::Length })).unwrap_or(default_expr); + let kind = if is_angle { Kind::Angle } else { Kind::Length }; + if let Some((name, rhs)) = &defines { + // The new user parameter reads a bare number as the dimension would (the design's + // unit for a length, degrees for an angle), and carries that unit. + if let Some(problem) = solidcraft_doc::Document::param_name_problem(name) { + return Err(bad(cmd, format!("value: {problem}"))); + } + if doc.param(name).is_some() { + return Err(bad(cmd, format!("value: there is already a parameter `{name}`: type `{name}` to use it, or change it in Parameters"))); + } + let rhs = doc.with_design_unit(rhs, kind); + let unit = if is_angle { "deg".to_string() } else { solidcraft_doc::expr::length_unit_or_mm(&doc.units).to_string() }; + doc.add_user_param(name, &rhs, Some(&unit), None).map_err(|e| bad(cmd, format!("value: {e}")))?; + } + let e = value.as_ref().map(|e| doc.with_design_unit(e, kind)).unwrap_or(default_expr); let pname = doc.new_model_param(&e, unit); // The value must evaluate. let (vals, errs) = doc.param_values(); @@ -2326,6 +2353,9 @@ fn dimension(s: &mut Session, p: &Value) -> Result { if let Some(factor) = scaled { out["scaled"] = json!(round6(factor)); } + if let Some((name, _)) = defines { + out["defined"] = json!(name); + } Ok(out) } diff --git a/crates/engine/src/cmd/sketch_constraints_tests.rs b/crates/engine/src/cmd/sketch_constraints_tests.rs index 1e4c08746..ace5abcaf 100644 --- a/crates/engine/src/cmd/sketch_constraints_tests.rs +++ b/crates/engine/src/cmd/sketch_constraints_tests.rs @@ -735,3 +735,156 @@ fn midpoint_rejects_wrong_picks_without_changing_the_sketch() { assert_eq!(s.undo.len(), undo, "{params}"); } } + +/// A parameter's row in `parameters.list` (Null when there is none). +fn param_row(s: &mut Session, name: &str) -> Value { + let l = run(s, "parameters.list", json!({})); + l["parameters"].as_array().and_then(|a| a.iter().find(|p| p["name"] == name)).cloned().unwrap_or(Value::Null) +} + +/// The distance between a line's ends on the solved sketch. +fn line_length(s: &Session, line: &str) -> f64 { + let sk = sketch(s); + let at = |r: &str| sk.point(sk.resolve_point(r).unwrap()).unwrap(); + at(&format!("{line}.start")).dist(at(&format!("{line}.end"))) +} + +/// A session with the user parameter `len = 60 mm` and a sketch holding one 30 mm line `la` +/// whose start is on the origin. +fn sketch_with_len() -> Session { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "len", "expression": "60 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [30, 0]], "ids": ["la"], "infer": false})); + run(&mut s, "sketch.constraint.coincident", json!({"a": "la.start", "b": "origin"})); + s +} + +/// `name = expression` in a dimension's value adds the user parameter and dimensions with it +/// (#2916): the expression may be anything the parameter editor takes (arithmetic, units, +/// parentheses, functions, other parameters), and is stored as typed on the new parameter. +#[test] +fn a_dimension_value_can_define_a_user_parameter() { + let cases = [ + ("w = 20", "20"), + ("w=40/2", "40/2"), + (" w = (10 + 30) / 2 ", "(10 + 30) / 2"), + ("w = 1 in - 5.4 mm", "1 in - 5.4 mm"), + ("w = len / 3", "len / 3"), + ("w = sqrt(400)", "sqrt(400)"), + ("w = 2 * (len / 6)", "2 * (len / 6)"), + ("w = min(len, 20 mm)", "min(len, 20 mm)"), + ]; + for (value, stored) in cases { + let mut s = sketch_with_len(); + let d = run(&mut s, "sketch.dimension", json!({"entities": ["la"], "value": value})); + assert_eq!(d["defined"], "w", "{value}: {d}"); + assert_eq!(d["expression"], "w", "{value}: the dimension refers to the parameter: {d}"); + assert!((d["measured"].as_f64().unwrap() - 20.0).abs() < 1e-6, "{value}: {d}"); + assert!((line_length(&s, "la") - 20.0).abs() < 1e-6, "{value}"); + let w = param_row(&mut s, "w"); + assert_eq!(w["source"], "user", "{value}: {w}"); + assert_eq!(w["expression"], stored, "{value}: {w}"); + assert_eq!(w["unit"], "mm", "{value}: {w}"); + assert!((w["value"].as_f64().unwrap() - 20.0).abs() < 1e-9, "{value}: {w}"); + // The dimension follows the parameter from now on. + run(&mut s, "parameters.change", json!({"name": "w", "expression": "30 mm"})); + assert!((line_length(&s, "la") - 30.0).abs() < 1e-6, "{value}"); + } +} + +/// A bare right-hand side is in the design's unit, like a bare dimension value, and the new +/// parameter carries that unit; an angle's parameter is in degrees. +#[test] +fn a_defined_parameter_takes_the_design_unit_or_degrees() { + let mut s = Session::default(); + run(&mut s, "document.units", json!({"units": "in"})); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [30, 0]], "ids": ["la"], "infer": false})); + let d = run(&mut s, "sketch.dimension", json!({"entities": ["la"], "value": "w = 2"})); + assert_eq!(d["defined"], "w", "{d}"); + assert!((d["measured"].as_f64().unwrap() - 50.8).abs() < 1e-6, "{d}"); + // Stored with the design's unit spelled out, as a bare dimension value is. + let w = param_row(&mut s, "w"); + assert_eq!((w["unit"].as_str(), w["expression"].as_str()), (Some("in"), Some("2 in")), "{w}"); + assert!((line_length(&s, "la") - 50.8).abs() < 1e-6); + // A unit in the expression wins over the design's. + run(&mut s, "sketch.line", json!({"points": [[0, 50], [30, 50]], "ids": ["lb"], "infer": false})); + let d = run(&mut s, "sketch.dimension", json!({"entities": ["lb"], "value": "h = 20 mm"})); + assert!((d["measured"].as_f64().unwrap() - 20.0).abs() < 1e-6, "{d}"); + assert_eq!((param_row(&mut s, "h")["unit"].as_str(), param_row(&mut s, "h")["expression"].as_str()), (Some("in"), Some("20 mm"))); + + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0]], "ids": ["a"], "infer": false})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 10]], "ids": ["b"], "infer": false})); + let d = run(&mut s, "sketch.dimension", json!({"entities": ["a", "b"], "type": "angle", "value": "ang = 60"})); + assert_eq!((d["defined"].as_str(), d["unit"].as_str()), (Some("ang"), Some("deg")), "{d}"); + assert!((d["measured"].as_f64().unwrap() - 60.0).abs() < 1e-6, "{d}"); + let ang = param_row(&mut s, "ang"); + assert_eq!((ang["unit"].as_str(), ang["expression"].as_str()), (Some("deg"), Some("60")), "{ang}"); + assert!((line_angle(&s, "a", "b") - 60.0).abs() < 1e-6); +} + +/// A definition that cannot be made is refused with the reason, and leaves no parameter behind: +/// a taken or reserved name, no expression, a driven dimension, a left side that is not a name +/// (which stays the old parse error), and a dimension the sketch refuses. +#[test] +fn a_definition_that_cannot_be_made_is_refused_and_leaves_nothing() { + let refused = [ + ("w = 20", json!({"name": "w", "expression": "5 mm"}), "there is already a parameter `w`: type `w` to use it"), + ("len = 20", Value::Null, "there is already a parameter `len`"), + ("mm = 5", Value::Null, "`mm` is a unit name, so it cannot be a parameter name"), + ("sin = 5", Value::Null, "`sin` is a function name, so it cannot be a parameter name"), + ("pi = 5", Value::Null, "`pi` is a constant, so it cannot be a parameter name"), + ("w =", Value::Null, "`w =` needs a value after the `=`"), + ("w = ", Value::Null, "needs a value"), + ("2 = 3", Value::Null, "unexpected `=`"), + ("w == 3", Value::Null, "unexpected `=`"), + ("w = nope", Value::Null, "nope"), + ("w = 1 deg", Value::Null, ""), + ("w = w", Value::Null, ""), + ]; + for (value, add, message) in refused { + let mut s = sketch_with_len(); + if !add.is_null() { + run(&mut s, "parameters.add", add); + } + let before = run(&mut s, "parameters.list", json!({}))["count"].clone(); + let e = s.execute("sketch.dimension", &json!({"entities": ["la"], "value": value})).unwrap_err().to_string(); + assert!(e.contains(message), "{value}: {e}"); + assert_eq!(run(&mut s, "parameters.list", json!({}))["count"], before, "{value}: a refused definition added a parameter"); + assert_eq!(sketch(&s).constraints.iter().filter(|c| c.param.is_some()).count(), 0, "{value}: a refused definition added a dimension"); + } + // A driven (reference) dimension has no value, so it defines nothing. + let mut s = sketch_with_len(); + let e = s.execute("sketch.dimension", &json!({"entities": ["la"], "value": "w = 20", "driven": true})).unwrap_err().to_string(); + assert!(e.contains("driven"), "{e}"); + assert!(param_row(&mut s, "w").is_null()); + // A dimension the sketch already determines is refused as before, and its parameter with it. + let mut s = sketch_with_len(); + run(&mut s, "sketch.dimension", json!({"entities": ["la"], "value": 30})); + let e = s.execute("sketch.dimension", &json!({"entities": ["la.start", "la.end"], "value": "w = 30"})).unwrap_err().to_string(); + assert!(e.contains("already determined"), "{e}"); + assert!(param_row(&mut s, "w").is_null(), "the parameter of a refused dimension was kept"); + // Placed as driven instead (`if_redundant`), it has no value and defines nothing. + let d = run(&mut s, "sketch.dimension", json!({"entities": ["la.start", "la.end"], "value": "w = 30", "if_redundant": "driven"})); + assert_eq!((d["driven"].as_bool(), d.get("defined")), (Some(true), None), "{d}"); + assert!(param_row(&mut s, "w").is_null(), "a driven dimension kept the parameter"); +} + +/// The parameter and the dimension are one command, so one undo removes both and one redo +/// brings both back. +#[test] +fn undoing_a_defining_dimension_removes_the_parameter_too() { + let mut s = sketch_with_len(); + let params = run(&mut s, "parameters.list", json!({}))["count"].as_u64().unwrap(); + run(&mut s, "sketch.dimension", json!({"entities": ["la"], "value": "w = 20"})); + assert_eq!(run(&mut s, "parameters.list", json!({}))["count"].as_u64().unwrap(), params + 2, "the user parameter and the dimension's own"); + run(&mut s, "edit.undo", json!({})); + assert!(param_row(&mut s, "w").is_null()); + assert_eq!(run(&mut s, "parameters.list", json!({}))["count"].as_u64().unwrap(), params); + assert!((line_length(&s, "la") - 30.0).abs() < 1e-6); + run(&mut s, "edit.redo", json!({})); + assert_eq!(param_row(&mut s, "w")["expression"], "20"); + assert!((line_length(&s, "la") - 20.0).abs() < 1e-6); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e9a6685d4..b92c4d83e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -682,6 +682,12 @@ pub(crate) fn hostile_values() -> Vec { json!("nope"), json!("1/0"), json!("((((((((((1"), + json!("w = 20"), + json!("w ="), + json!("= 20"), + json!("mm = 5"), + json!("w = w"), + json!("w == 1/0"), json!([]), json!([1e308, -1e308]), json!([0, 0, 0]), diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rs index 1fa26a315..e0af566cc 100644 --- a/crates/ui-egui/src/dim_view.rs +++ b/crates/ui-egui/src/dim_view.rs @@ -103,7 +103,7 @@ impl DimensionDraft { } fn evaluate(&self, app: &SolveApp, expr: &str) -> Result { let mut scratch = app.session.scratch(); - let result = scratch.execute("sketch.dimension", &self.params(expr)).map_err(|e| e.to_string())?; + let result = scratch.execute("sketch.dimension", &self.params(expr)).map_err(|e| shown_error("sketch.dimension", &e.to_string()))?; let param = result.get("param").and_then(serde_json::Value::as_str).ok_or("The dimension value is unavailable")?; let state = scratch.world_state(); let solved = state.sketch(self.sketch).ok_or("The dimension sketch is unavailable")?; @@ -120,6 +120,14 @@ impl DimensionDraft { } } +/// A command's error as the value box and the status line show it: the command's label instead +/// of its id, and without the `value:` field tag, since the box is the value +/// ("Sketch Dimension: `mm` is a unit name, so it cannot be a parameter name"). +fn shown_error(id: &str, e: &str) -> String { + let label = crate::i18n::tr_label(crate::command_label(id)); + crate::friendly_error(id, e).replacen(&format!("{label}: value: "), &format!("{label}: "), 1) +} + pub fn cancel() { EDIT.with(|edit| *edit.borrow_mut() = None); PLACEMENT.with(|preview| *preview.borrow_mut() = None); @@ -764,7 +772,9 @@ fn edit_box(app: &mut SolveApp, ctx: &egui::Context) { Some(true) => { let result = if let Some(draft) = &e.draft { if draft.valid(app) { - draft.evaluate(app, &e.expr).and_then(|_| app.run("sketch.dimension", draft.params(&e.expr))) + draft + .evaluate(app, &e.expr) + .and_then(|_| app.run("sketch.dimension", draft.params(&e.expr)).map_err(|err| shown_error("sketch.dimension", &err))) } else { Err("The sketch changed; place the dimension again".into()) } @@ -777,14 +787,20 @@ fn edit_box(app: &mut SolveApp, ctx: &egui::Context) { .map(|(k, _)| k) .unwrap_or(solidcraft_engine::doc::expr::Kind::Unitless); let expression = app.session.doc.with_design_unit(&e.expr, kind); - app.run("parameters.change", json!({"name": e.param, "expression": expression})) + app.run("parameters.change", json!({"name": e.param, "expression": expression})).map_err(|err| shown_error("parameters.change", &err)) }; - if let Err(err) = result { - app.set_status(err, true); - EDIT.with(|x| *x.borrow_mut() = Some(Edit { fresh: FRESH, ..e })); - } else { - clear_picks(app); - app.set_status("Dimension applied", false); + match result { + Err(err) => { + app.set_status(err, true); + EDIT.with(|x| *x.borrow_mut() = Some(Edit { fresh: FRESH, ..e })); + } + Ok(reply) => { + clear_picks(app); + match reply.get("defined").and_then(serde_json::Value::as_str) { + Some(name) => app.set_status(format!("Dimension applied; parameter `{name}` defined"), false), + None => app.set_status("Dimension applied", false), + } + } } } Some(false) if escaped => clear_picks(app), @@ -872,6 +888,67 @@ mod tests { cancel(); } + /// Typing `w = 20` into a new dimension's value defines the user parameter `w` and + /// dimensions with it, in one undo step, and the status line says so (#2916). A taken name + /// is refused and the editor stays open with the text to correct. + #[test] + fn typing_a_definition_adds_the_parameter_and_dimensions_with_it() { + cancel(); + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[10,10],[40,10]],"infer":false})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + let undo = h.app.session.undo.len(); + h.step(&json!({"start":"sketch.dimension"})).unwrap(); + h.step(&json!({"click":{"sketch":[25,10]}})).unwrap(); + assert!(editing()); + h.step(&json!({"text":"w = 20"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + assert!(!editing(), "{:?}", h.app.status); + let w = h.app.session.doc.param("w").expect("the user parameter was added"); + assert!(!w.model && w.expr.as_str() == "20" && w.unit == "mm", "{w:?}"); + let sk = h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap(); + let dim = sk.constraints.iter().find_map(|c| c.param.as_deref()).expect("the dimension was added"); + assert_eq!(h.app.session.doc.param(dim).map(|p| p.expr.as_str()), Some("w")); + assert_eq!(h.app.session.undo.len(), undo + 1, "one undo step"); + assert!(h.app.status.as_ref().is_some_and(|s| !s.2 && s.0.contains("`w`")), "{:?}", h.app.status); + // The same name again is refused; the editor keeps the text. + h.app.run("sketch.line", json!({"points":[[10,30],[40,30]],"infer":false})).unwrap(); + let undo = h.app.session.undo.len(); + h.step(&json!({"start":"sketch.dimension"})).unwrap(); + h.step(&json!({"click":{"sketch":[25,30]}})).unwrap(); + h.step(&json!({"text":"w = 25"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + assert!(editing(), "{:?}", h.app.status); + // The refusal reads as the command's own words, in the status line and in the box. + let taken = "Sketch Dimension: there is already a parameter `w`: type `w` to use it, or change it in Parameters"; + assert_eq!(h.app.status.as_ref().map(|s| (s.0.as_str(), s.2)), Some((taken, true))); + assert_eq!(box_error(), Some(taken.to_string())); + assert_eq!(EDIT.with(|e| e.borrow().as_ref().map(|e| e.expr.clone())), Some("w = 25".to_string())); + assert_eq!(h.app.session.undo.len(), undo, "a refused definition changed nothing"); + h.step(&json!({"key":"Escape"})).unwrap(); + h.step(&json!({"key":"Escape"})).unwrap(); + // A reserved name says what kind of word it is. The line goes below the first one: the + // ribbon floats over the top of the canvas, and a click at sketch y = 50 would land on it. + h.app.run("sketch.line", json!({"points":[[10,-10],[40,-10]],"infer":false})).unwrap(); + h.step(&json!({"start":"sketch.dimension"})).unwrap(); + h.step(&json!({"click":{"sketch":[25,-10]}})).unwrap(); + h.step(&json!({"text":"mm = 5"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + assert!(editing(), "{:?}", h.app.status); + let reserved = "Sketch Dimension: `mm` is a unit name, so it cannot be a parameter name"; + assert_eq!(h.app.status.as_ref().map(|s| (s.0.as_str(), s.2)), Some((reserved, true))); + assert_eq!(box_error(), Some(reserved.to_string())); + h.step(&json!({"key":"Escape"})).unwrap(); + h.step(&json!({"key":"Escape"})).unwrap(); + cancel(); + } + + /// The error shown inside the open value box. + fn box_error() -> Option { + EDIT.with(|e| e.borrow().as_ref().and_then(|e| e.draft.as_ref()).and_then(|d| d.error.clone())) + } + /// Placing a dimension the sketch can't take previews it as driven: in the draft it is a /// driven constraint with no parameter, labelled in parentheses (#320). #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7c73ef1be..3a058a049 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -114,6 +114,16 @@ mod status_tests { "Shell: offset: must be positive" ); assert_eq!(super::friendly_error("edit.undo", "nothing to undo"), "Undo: nothing to undo"); + { + // The label follows the interface language; the engine's words stay English. + let _polish = crate::i18n::scope("pl"); + assert_eq!(super::friendly_error("edit.undo", "nothing to undo"), "Cofnij: nothing to undo"); + assert_eq!( + super::friendly_error("sketch.dimension", "invalid parameters for `sketch.dimension`: value: `mm` is a unit name"), + "Wymiar szkicu: value: `mm` is a unit name" + ); + } + assert_eq!(super::friendly_error("edit.undo", "nothing to undo"), "Undo: nothing to undo"); let mut app = super::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); app.run("solid.box", serde_json::json!({"length": 5, "width": 5, "height": 5})).unwrap(); assert_eq!(app.session.log.last().map(String::as_str), Some("Box done")); @@ -1829,9 +1839,10 @@ pub fn command_label(id: &str) -> &str { solidcraft_engine::find_command(id).map_or(id, |c| c.label) } -/// An engine error with the command's label instead of its id: "Shell: offset must be …". +/// An engine error with the command's label instead of its id: "Shell: offset must be …". The +/// label follows the interface language; the engine's sentence stays as the engine wrote it. pub fn friendly_error(id: &str, e: &str) -> String { - let label = command_label(id); + let label = i18n::tr_label(command_label(id)); let msg = e.replace(&format!("invalid parameters for `{id}`: "), "").replace(&format!("{id}: "), "").replace(&format!("`{id}`"), label); if msg.starts_with(label) { msg } else { format!("{label}: {msg}") } } diff --git a/docs/book/src/guide/parameters.md b/docs/book/src/guide/parameters.md index e0cc5892b..802b27763 100644 --- a/docs/book/src/guide/parameters.md +++ b/docs/book/src/guide/parameters.md @@ -10,7 +10,9 @@ name (`d1`, `d2`, …). Click another driving dimension to use its name: when th just a number (such as `10` or `10 mm`) the name replaces it; otherwise it goes in at the cursor, replacing selected text and keeping what you typed, so typing `10 + ` and clicking `d1` gives `10 + d1`. Add arithmetic such as `/ 2` to build a dependent dimension. Press **Enter** to apply -the expression or **Escape** to cancel the edit. +the expression or **Escape** to cancel the edit. When placing a new dimension, `width = 40` adds +the user parameter `width` with that value (a bare number is in the design's units) and +dimensions with it; a name that is already taken is refused. Add and edit user parameters through the existing **Change Parameters** command. In the MANAGE tab's PARAMETERS section, click **Parameters** to open the user and model diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md index 090de552c..2b8b488c1 100644 --- a/docs/book/src/guide/sketching.md +++ b/docs/book/src/guide/sketching.md @@ -202,7 +202,8 @@ Press D, click what you want to measure and type the value: as soon as the click dimension (one line, circle or arc, or the second point or line of a distance or angle), its value box takes the keyboard with the measured value selected, so typing replaces it. Numbers, units (`1 in`), expressions (`2*width`) and parameter names all work; letters go into the box, -not to tool shortcuts. While you type, the dimension text follows the cursor, and Enter places +not to tool shortcuts. `width = 40` defines the user parameter `width` and dimensions with it, +in one step. While you type, the dimension text follows the cursor, and Enter places it there (or in its default place if you haven't moved the cursor) as one undo step. Esc cancels the dimension. From ba4f7864fffce89f37d0bd7bf66aabaa9de907be Mon Sep 17 00:00:00 2001 From: raykholo Date: Wed, 21 Oct 2026 23:09:57 +0000 Subject: [PATCH 18/25] Export Current View as DXF includes shown sketches (#3708) (#3780) * claim: #3708 * Export Current View as DXF includes shown sketches (#3708) The view export refused a design with only a sketch and left shown sketches out when bodies were present. It now draws the sketches the viewport shows (profile curves only: no construction geometry, points, dimensions or constraints) on a SKETCH layer, one entity per curve. Finished sketches are hidden behind bodies through the body-edge occlusion; the active sketch is drawn on top, as in the viewport. Sketch points use the same projection, budgets and cancellation. The export is refused only when there is neither a visible body nor a shown sketch curve; the dialog and the command share that check (cmd::view_dxf_exportable). --------- Co-authored-by: bherbruck Co-authored-by: Claude Sonnet 5.5 --- ROADMAP.md | 2 +- assets/locales/cs.json | 4 +- assets/locales/da.json | 4 +- assets/locales/de.json | 4 +- assets/locales/en.json | 4 +- assets/locales/es.json | 4 +- assets/locales/fr.json | 4 +- assets/locales/gl.json | 4 +- assets/locales/hu.json | 1 - assets/locales/id.json | 1 - assets/locales/it.json | 4 +- assets/locales/ja.json | 4 +- assets/locales/ko.json | 4 +- assets/locales/ms.json | 4 +- assets/locales/nl.json | 1 - assets/locales/pl.json | 4 +- assets/locales/pt-BR.json | 2 +- assets/locales/ro.json | 1 - assets/locales/ru.json | 1 - assets/locales/sv.json | 1 - assets/locales/tr.json | 1 - assets/locales/uk.json | 4 +- assets/locales/vi.json | 4 +- assets/locales/zh-TW.json | 1 - assets/locales/zh.json | 4 +- crates/engine/src/cmd/mod.rs | 1 + crates/engine/src/cmd/view_dxf.rs | 38 +++++++-- crates/engine/src/cmd/view_dxf_meshes.rs | 3 - crates/engine/src/cmd/view_dxf_projection.rs | 13 ++- crates/engine/src/cmd/view_dxf_scene.rs | 77 +++++++++++++++-- crates/engine/src/cmd/view_dxf_sketch.rs | 89 ++++++++++++++++++++ crates/engine/src/cmd/view_dxf_tests.rs | 61 ++++++++++++++ crates/ui-egui/src/dialogs_view_dxf.rs | 4 +- docs/view-dxf.md | 17 +++- 34 files changed, 313 insertions(+), 62 deletions(-) create mode 100644 crates/engine/src/cmd/view_dxf_sketch.rs diff --git a/ROADMAP.md b/ROADMAP.md index 592b07a55..6d0f80da5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -70,7 +70,7 @@ pointer movement orbits without a mouse button, and vertical scrolling zooms. Ot retain their saved two-finger scroll preference; camera motion is available through `view.navigate` and modifier-aware `ui.move` automation. -M11 precursor: File → Export Current View as DXF exports shown placed bodies from the current +M11 precursor: File → Export Current View as DXF exports shown placed bodies and sketches from the current camera as a 2D millimetre drawing, with hidden edges omitted or dashed. Vector occlusion splits partly hidden edges and includes curved silhouettes. Repeated part meshes and triangle hierarchies are shared; bounded desktop preparation and occlusion use up to eight workers. diff --git a/assets/locales/cs.json b/assets/locales/cs.json index bbd15354e..ad5a50c04 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -233,7 +233,7 @@ "No crash reports.": "Žádná hlášení o pádech.", "No matching appearance presets.": "Žádné odpovídající předvolby vzhledu.", "No matching appearances": "Žádné odpovídající vzhledy", - "No visible bodies to export.": "Žádná viditelná tělesa k exportu.", + "No visible bodies or sketches to export.": "Žádná viditelná tělesa ani náčrty k exportu.", "None": "Žádné", "Not available yet": "Zatím není k dispozici", "Notch": "Zářez", @@ -832,7 +832,7 @@ "dxf.progress.projection": "Promítání geometrie (3/5)", "dxf.progress.write": "Zápis DXF (5/5)", "dxf.tolerance": "Tolerance křivek", - "dxf.tolerance_help": "Pouze viditelná tělesa. Křivky jsou nahrazeny úsečkami. Menší tolerance dává jemnější křivky, ale zabere více času a paměti.", + "dxf.tolerance_help": "Pouze viditelná tělesa a zobrazené náčrty. Křivky jsou nahrazeny úsečkami. Menší tolerance dává jemnější křivky, ale zabere více času a paměti.", "file_load.built": "Dosud sestaveno: {built} z {total} prvků.", "file_load.converting": "Převod tělesa {done} z {total}", "file_load.inserting": "Vkládání geometrie", diff --git a/assets/locales/da.json b/assets/locales/da.json index 74781809a..9f15c4899 100644 --- a/assets/locales/da.json +++ b/assets/locales/da.json @@ -233,7 +233,7 @@ "No crash reports.": "Ingen nedbrudsrapporter.", "No matching appearance presets.": "Ingen matchende udseendeforudindstillinger.", "No matching appearances": "Ingen matchende udseender", - "No visible bodies to export.": "Der er ingen synlige emner at eksportere.", + "No visible bodies or sketches to export.": "Der er ingen synlige emner eller skitser at eksportere.", "None": "Ingen", "Not available yet": "Endnu ikke tilgængelig", "Notch": "Udskæring", @@ -832,7 +832,7 @@ "dxf.progress.projection": "Projicerer geometri (3/5)", "dxf.progress.write": "Skriver DXF (5/5)", "dxf.tolerance": "Kurvetolerance", - "dxf.tolerance_help": "Kun synlige emner. Kurver består af rette linjestykker. En mindre tolerance giver finere kurver og kræver mere tid og hukommelse.", + "dxf.tolerance_help": "Kun synlige emner og viste skitser. Kurver består af rette linjestykker. En mindre tolerance giver finere kurver og kræver mere tid og hukommelse.", "file_load.built": "Bygget indtil videre: {built} af {total} features.", "file_load.converting": "Konverterer solid {done} af {total}", "file_load.inserting": "Indsætter geometri", diff --git a/assets/locales/de.json b/assets/locales/de.json index b242a26d9..64375c539 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -233,7 +233,7 @@ "No crash reports.": "Keine Absturzberichte.", "No matching appearance presets.": "Keine passenden Erscheinungsbildvorlagen.", "No matching appearances": "Keine passenden Erscheinungsbilder", - "No visible bodies to export.": "Keine sichtbaren Körper zum Exportieren.", + "No visible bodies or sketches to export.": "Keine sichtbaren Körper oder Skizzen zum Exportieren.", "None": "Keine", "Not available yet": "Noch nicht verfügbar", "Notch": "Ausklinkung", @@ -832,7 +832,7 @@ "dxf.progress.projection": "Geometrie projizieren (3/5)", "dxf.progress.write": "DXF schreiben (5/5)", "dxf.tolerance": "Kurventoleranz", - "dxf.tolerance_help": "Nur sichtbare Körper. Kurven werden durch gerade Segmente angenähert. Eine kleinere Toleranz liefert feinere Kurven und benötigt mehr Zeit und Speicher.", + "dxf.tolerance_help": "Nur sichtbare Körper und angezeigte Skizzen. Kurven werden durch gerade Segmente angenähert. Eine kleinere Toleranz liefert feinere Kurven und benötigt mehr Zeit und Speicher.", "file_load.built": "Bisher erstellt: {built} von {total} Merkmalen.", "file_load.converting": "Volumenkörper {done} von {total} wird konvertiert", "file_load.inserting": "Geometrie wird eingefügt", diff --git a/assets/locales/en.json b/assets/locales/en.json index 8124c4930..719566cbf 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -240,7 +240,7 @@ "No crash reports.": "No crash reports.", "No matching appearance presets.": "No matching appearance presets.", "No matching appearances": "No matching appearances", - "No visible bodies to export.": "No visible bodies to export.", + "No visible bodies or sketches to export.": "No visible bodies or sketches to export.", "Nominal diameter": "Nominal diameter", "None": "None", "Not available yet": "Not available yet", @@ -856,7 +856,7 @@ "dxf.progress.projection": "Projecting geometry (3/5)", "dxf.progress.write": "Writing DXF (5/5)", "dxf.tolerance": "Curve tolerance", - "dxf.tolerance_help": "Visible bodies only. Curves use straight segments. Smaller tolerance gives finer curves and uses more time and memory.", + "dxf.tolerance_help": "Visible bodies and shown sketches only. Curves use straight segments. Smaller tolerance gives finer curves and uses more time and memory.", "file_load.built": "Built so far: {built} of {total} features.", "file_load.converting": "Converting solid {done} of {total}", "file_load.inserting": "Inserting geometry", diff --git a/assets/locales/es.json b/assets/locales/es.json index 77c44315d..938aa72f6 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -233,7 +233,7 @@ "No crash reports.": "No hay informes de fallos.", "No matching appearance presets.": "No hay preajustes de apariencia coincidentes.", "No matching appearances": "No hay apariencias coincidentes", - "No visible bodies to export.": "No hay cuerpos visibles para exportar.", + "No visible bodies or sketches to export.": "No hay cuerpos ni bocetos visibles para exportar.", "None": "Ninguno", "Not available yet": "Todavía no disponible", "Notch": "Muesca", @@ -832,7 +832,7 @@ "dxf.progress.projection": "Proyectando geometría (3/5)", "dxf.progress.write": "Escribiendo DXF (5/5)", "dxf.tolerance": "Tolerancia de curva", - "dxf.tolerance_help": "Solo cuerpos visibles. Las curvas usan segmentos rectos. Una tolerancia menor da curvas más finas y consume más tiempo y memoria.", + "dxf.tolerance_help": "Solo cuerpos visibles y bocetos mostrados. Las curvas usan segmentos rectos. Una tolerancia menor da curvas más finas y consume más tiempo y memoria.", "file_load.built": "Construido hasta ahora: {built} de {total} operaciones.", "file_load.converting": "Convirtiendo sólido {done} de {total}", "file_load.inserting": "Insertando geometría", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 9f54fcfbe..27318a26c 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -233,7 +233,7 @@ "No crash reports.": "Aucun rapport de plantage.", "No matching appearance presets.": "Aucun préréglage d’apparence correspondant.", "No matching appearances": "Aucune apparence correspondante", - "No visible bodies to export.": "Aucun corps visible à exporter.", + "No visible bodies or sketches to export.": "Aucun corps ni esquisse visible à exporter.", "None": "Aucun", "Not available yet": "Pas encore disponible", "Notch": "Encoche", @@ -832,7 +832,7 @@ "dxf.progress.projection": "Projection de la géométrie (3/5)", "dxf.progress.write": "Écriture du DXF (5/5)", "dxf.tolerance": "Tolérance des courbes", - "dxf.tolerance_help": "Corps visibles uniquement. Les courbes sont approchées par des segments de droite. Une tolérance plus faible donne des courbes plus fines, au prix de plus de temps et de mémoire.", + "dxf.tolerance_help": "Corps visibles et esquisses affichées uniquement. Les courbes sont approchées par des segments de droite. Une tolérance plus faible donne des courbes plus fines, au prix de plus de temps et de mémoire.", "file_load.built": "Construit jusqu’ici : {built} entités sur {total}.", "file_load.converting": "Conversion du solide {done} sur {total}", "file_load.inserting": "Insertion de la géométrie", diff --git a/assets/locales/gl.json b/assets/locales/gl.json index a4a3d36d3..3af7f3cd2 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -233,7 +233,7 @@ "No crash reports.": "Non hai informes de fallos.", "No matching appearance presets.": "Non hai preaxustes de aparencia coincidentes.", "No matching appearances": "Non hai aparencias coincidentes", - "No visible bodies to export.": "Non hai corpos visibles para exportar.", + "No visible bodies or sketches to export.": "Non hai corpos nin bosquexos visibles para exportar.", "None": "Ningún", "Not available yet": "Aínda non dispoñible", "Notch": "Entalle", @@ -832,7 +832,7 @@ "dxf.progress.projection": "Proxectando a xeometría (3/5)", "dxf.progress.write": "Escribindo o DXF (5/5)", "dxf.tolerance": "Tolerancia da curva", - "dxf.tolerance_help": "Só os corpos visibles. As curvas usan segmentos rectos. Unha tolerancia menor dá curvas máis finas e usa máis tempo e memoria.", + "dxf.tolerance_help": "Só os corpos visibles e os bosquexos amosados. As curvas usan segmentos rectos. Unha tolerancia menor dá curvas máis finas e usa máis tempo e memoria.", "file_load.built": "Construído ata agora: {built} de {total} operacións.", "file_load.converting": "Convertendo o sólido {done} de {total}", "file_load.inserting": "Inserindo a xeometría", diff --git a/assets/locales/hu.json b/assets/locales/hu.json index f7ac25b92..bd712ad81 100644 --- a/assets/locales/hu.json +++ b/assets/locales/hu.json @@ -233,7 +233,6 @@ "No crash reports.": "Nincsenek összeomlási jelentések.", "No matching appearance presets.": "Nincs egyező megjelenés-előbeállítás.", "No matching appearances": "Nincs egyező megjelenés", - "No visible bodies to export.": "Nincs exportálható látható test.", "None": "Nincs", "Not available yet": "Még nem érhető el", "Notch": "Bevágás", diff --git a/assets/locales/id.json b/assets/locales/id.json index 7b8c2d9cc..46e1ca73e 100644 --- a/assets/locales/id.json +++ b/assets/locales/id.json @@ -233,7 +233,6 @@ "No crash reports.": "Tidak ada laporan crash.", "No matching appearance presets.": "Tidak ada preset tampilan yang cocok.", "No matching appearances": "Tidak ada tampilan yang cocok", - "No visible bodies to export.": "Tidak ada bodi terlihat untuk diekspor.", "None": "Tidak ada", "Not available yet": "Belum tersedia", "Notch": "Takik", diff --git a/assets/locales/it.json b/assets/locales/it.json index 360991eb3..854570f34 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -234,7 +234,7 @@ "No crash reports.": "Nessun rapporto di arresto anomalo.", "No matching appearance presets.": "Nessun predefinito di aspetto corrispondente.", "No matching appearances": "Nessun aspetto corrispondente", - "No visible bodies to export.": "Nessun corpo visibile da esportare.", + "No visible bodies or sketches to export.": "Nessun corpo o schizzo visibile da esportare.", "Nominal diameter": "Diametro nominale", "None": "Nessuno", "Not available yet": "Non ancora disponibile", @@ -835,7 +835,7 @@ "dxf.progress.projection": "Proiezione della geometria (3/5)", "dxf.progress.write": "Scrittura DXF (5/5)", "dxf.tolerance": "Tolleranza delle curve", - "dxf.tolerance_help": "Solo corpi visibili. Le curve usano segmenti rettilinei. Una tolleranza minore produce curve più precise e richiede più tempo e memoria.", + "dxf.tolerance_help": "Solo corpi visibili e schizzi mostrati. Le curve usano segmenti rettilinei. Una tolleranza minore produce curve più precise e richiede più tempo e memoria.", "file_load.built": "Costruite finora: {built} di {total} feature.", "file_load.converting": "Conversione del solido {done} di {total}", "file_load.inserting": "Inserimento della geometria", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 18ee80029..cfd220b2b 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -240,7 +240,7 @@ "No crash reports.": "クラッシュレポートはありません。", "No matching appearance presets.": "一致する外観プリセットはありません。", "No matching appearances": "一致する外観がありません", - "No visible bodies to export.": "出力する表示中のボディがありません。", + "No visible bodies or sketches to export.": "出力する表示中のボディまたはスケッチがありません。", "Nominal diameter": "呼び径", "None": "なし", "Not available yet": "まだ利用できません", @@ -856,7 +856,7 @@ "dxf.progress.projection": "形状を投影中 (3/5)", "dxf.progress.write": "DXFを書き込み中 (5/5)", "dxf.tolerance": "曲線の許容誤差", - "dxf.tolerance_help": "表示中のボディを出力し、曲線は線分で近似します。許容誤差を小さくすると曲線が滑らかになりますが、処理時間とメモリ使用量が増えます。", + "dxf.tolerance_help": "表示中のボディとスケッチを出力し、曲線は線分で近似します。許容誤差を小さくすると曲線が滑らかになりますが、処理時間とメモリ使用量が増えます。", "file_load.built": "構築済み: 全{total}フィーチャー中{built}件。", "file_load.converting": "ソリッドを変換中: {done}/{total}", "file_load.inserting": "ジオメトリを挿入中", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 9f5d16bb7..8530af89b 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -233,7 +233,7 @@ "No crash reports.": "충돌 보고서가 없습니다.", "No matching appearance presets.": "일치하는 외관 프리셋이 없습니다.", "No matching appearances": "일치하는 외관 없음", - "No visible bodies to export.": "표시된 바디가 없어 내보낼 수 없습니다.", + "No visible bodies or sketches to export.": "표시된 바디나 스케치가 없어 내보낼 수 없습니다.", "None": "없음", "Not available yet": "아직 사용할 수 없음", "Notch": "노치", @@ -832,7 +832,7 @@ "dxf.progress.projection": "형상 투영 중 (3/5)", "dxf.progress.write": "DXF 쓰는 중 (5/5)", "dxf.tolerance": "곡선 허용 오차", - "dxf.tolerance_help": "표시된 바디만 내보내며 곡선은 직선 구간으로 근사합니다. 허용 오차가 작을수록 곡선이 매끄러워지지만 처리 시간과 메모리 사용량이 늘어납니다.", + "dxf.tolerance_help": "표시된 바디와 스케치만 내보내며 곡선은 직선 구간으로 근사합니다. 허용 오차가 작을수록 곡선이 매끄러워지지만 처리 시간과 메모리 사용량이 늘어납니다.", "file_load.built": "지금까지 빌드됨: 피처 {total}개 중 {built}개.", "file_load.converting": "솔리드 변환 중 {done}/{total}", "file_load.inserting": "기하 삽입 중", diff --git a/assets/locales/ms.json b/assets/locales/ms.json index e94a45751..a299a44a8 100644 --- a/assets/locales/ms.json +++ b/assets/locales/ms.json @@ -233,7 +233,7 @@ "No crash reports.": "Tiada laporan ranap.", "No matching appearance presets.": "Tiada pratetap penampilan yang sepadan.", "No matching appearances": "Tiada penampilan yang sepadan", - "No visible bodies to export.": "Tiada jasad kelihatan untuk dieksport.", + "No visible bodies or sketches to export.": "Tiada jasad atau lakaran kelihatan untuk dieksport.", "None": "Tiada", "Not available yet": "Belum tersedia", "Notch": "Takuk", @@ -832,7 +832,7 @@ "dxf.progress.projection": "Mengunjurkan geometri (3/5)", "dxf.progress.write": "Menulis DXF (5/5)", "dxf.tolerance": "Toleransi lengkung", - "dxf.tolerance_help": "Jasad kelihatan sahaja. Lengkung guna segmen lurus. Toleransi kecil lebih halus tetapi guna lebih masa dan memori.", + "dxf.tolerance_help": "Jasad kelihatan dan lakaran yang ditunjukkan sahaja. Lengkung guna segmen lurus. Toleransi kecil lebih halus tetapi guna lebih masa dan memori.", "file_load.built": "Dibina setakat ini: {built} daripada {total} ciri.", "file_load.converting": "Menukar pepejal {done} daripada {total}", "file_load.inserting": "Menyisip geometri", diff --git a/assets/locales/nl.json b/assets/locales/nl.json index 4ad7d7000..cbb087dbb 100644 --- a/assets/locales/nl.json +++ b/assets/locales/nl.json @@ -233,7 +233,6 @@ "No crash reports.": "Geen crashrapporten.", "No matching appearance presets.": "Geen overeenkomende uiterlijkvoorinstellingen.", "No matching appearances": "Geen overeenkomende uiterlijken", - "No visible bodies to export.": "Geen zichtbare lichamen om te exporteren.", "None": "Geen", "Not available yet": "Nog niet beschikbaar", "Notch": "Inkeping", diff --git a/assets/locales/pl.json b/assets/locales/pl.json index 2acada1e9..ce10bfb73 100644 --- a/assets/locales/pl.json +++ b/assets/locales/pl.json @@ -233,7 +233,7 @@ "No crash reports.": "Brak raportów o awariach.", "No matching appearance presets.": "Brak pasujących ustawień wyglądu.", "No matching appearances": "Brak pasujących wyglądów", - "No visible bodies to export.": "Brak widocznych brył do wyeksportowania.", + "No visible bodies or sketches to export.": "Brak widocznych brył lub szkiców do wyeksportowania.", "None": "Brak", "Not available yet": "Jeszcze niedostępne", "Notch": "Wycięcie", @@ -832,7 +832,7 @@ "dxf.progress.projection": "Rzutowanie geometrii (3/5)", "dxf.progress.write": "Zapisywanie DXF (5/5)", "dxf.tolerance": "Tolerancja krzywych", - "dxf.tolerance_help": "Tylko widoczne bryły. Krzywe są przybliżane odcinkami. Mniejsza tolerancja daje dokładniejsze krzywe, ale zajmuje więcej czasu i pamięci.", + "dxf.tolerance_help": "Tylko widoczne bryły i pokazane szkice. Krzywe są przybliżane odcinkami. Mniejsza tolerancja daje dokładniejsze krzywe, ale zajmuje więcej czasu i pamięci.", "file_load.built": "Dotąd zbudowano: {built} z {total} elementów.", "file_load.converting": "Konwertowanie bryły {done} z {total}", "file_load.inserting": "Wstawianie geometrii", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index 964727458..a50d42098 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -233,7 +233,7 @@ "No crash reports.": "Nenhum relatório de falha.", "No matching appearance presets.": "Nenhuma predefinição de aparência correspondente.", "No matching appearances": "Nenhuma aparência correspondente", - "No visible bodies to export.": "Nenhum corpo visível para exportar.", + "No visible bodies or sketches to export.": "Nenhum corpo ou esboço visível para exportar.", "None": "Nenhum", "Not available yet": "Ainda não disponível", "Notch": "Entalhe", diff --git a/assets/locales/ro.json b/assets/locales/ro.json index 4c535f3b4..654e79cca 100644 --- a/assets/locales/ro.json +++ b/assets/locales/ro.json @@ -233,7 +233,6 @@ "No crash reports.": "Niciun raport de blocare.", "No matching appearance presets.": "Niciun preset de aspect corespunzător.", "No matching appearances": "Niciun aspect corespunzător", - "No visible bodies to export.": "Niciun corp vizibil de exportat.", "None": "Niciunul", "Not available yet": "Indisponibil deocamdată", "Notch": "Crestătură", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index d2156fa15..eed32d1cd 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -233,7 +233,6 @@ "No crash reports.": "Нет отчётов о сбоях.", "No matching appearance presets.": "Нет подходящих наборов внешнего вида.", "No matching appearances": "Нет подходящих внешних видов", - "No visible bodies to export.": "Нет видимых тел для экспорта.", "None": "Нет", "Not available yet": "Пока недоступно", "Notch": "Вырез", diff --git a/assets/locales/sv.json b/assets/locales/sv.json index e6b07be92..ad7f24add 100644 --- a/assets/locales/sv.json +++ b/assets/locales/sv.json @@ -233,7 +233,6 @@ "No crash reports.": "Inga kraschrapporter.", "No matching appearance presets.": "Inga matchande utseendeförinställningar.", "No matching appearances": "Inga matchande utseenden", - "No visible bodies to export.": "Inga synliga kroppar att exportera.", "None": "Ingen", "Not available yet": "Inte tillgänglig ännu", "Notch": "Urtag", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index 2b41a5d58..2879a141f 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -233,7 +233,6 @@ "No crash reports.": "Çökme raporu yok.", "No matching appearance presets.": "Eşleşen görünüm ön ayarı yok.", "No matching appearances": "Eşleşen görünüm yok", - "No visible bodies to export.": "Dışa aktarılacak görünür gövde yok.", "None": "Hiçbiri", "Not available yet": "Henüz kullanılamıyor", "Notch": "Çentik", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 1879b9de1..d7f2dacdd 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -233,7 +233,7 @@ "No crash reports.": "Немає звітів про збої.", "No matching appearance presets.": "Немає відповідних наборів вигляду.", "No matching appearances": "Немає відповідних виглядів", - "No visible bodies to export.": "Немає видимих тіл для експорту.", + "No visible bodies or sketches to export.": "Немає видимих тіл або ескізів для експорту.", "None": "Немає", "Not available yet": "Ще недоступно", "Notch": "Виріз", @@ -832,7 +832,7 @@ "dxf.progress.projection": "Проєктування геометрії (3/5)", "dxf.progress.write": "Запис DXF (5/5)", "dxf.tolerance": "Допуск кривої", - "dxf.tolerance_help": "Лише видимі тіла. Криві подаються відрізками. Менший допуск дає точніші криві, але потребує більше часу й пам'яті.", + "dxf.tolerance_help": "Лише видимі тіла та показані ескізи. Криві подаються відрізками. Менший допуск дає точніші криві, але потребує більше часу й пам'яті.", "file_load.built": "Побудовано: {built} із {total} елементів.", "file_load.converting": "Перетворення тіла {done} із {total}", "file_load.inserting": "Вставлення геометрії", diff --git a/assets/locales/vi.json b/assets/locales/vi.json index 74b71bba4..b85d4d3e0 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -233,7 +233,7 @@ "No crash reports.": "Không có báo cáo sự cố.", "No matching appearance presets.": "Không có cài đặt sẵn vật liệu bề mặt phù hợp.", "No matching appearances": "Không có màu sắc/vật liệu phù hợp", - "No visible bodies to export.": "Không có thân khối hiển thị nào để xuất.", + "No visible bodies or sketches to export.": "Không có thân khối hoặc phác thảo hiển thị nào để xuất.", "None": "Không có", "Not available yet": "Chưa khả dụng", "Notch": "Rãnh khía chữ V", @@ -832,7 +832,7 @@ "dxf.progress.projection": "Đang chiếu hình học (3/5)", "dxf.progress.write": "Đang ghi tệp DXF (5/5)", "dxf.tolerance": "Dung sai đường cong", - "dxf.tolerance_help": "Chỉ áp dụng cho các thân khối hiển thị. Đường cong sử dụng các đoạn thẳng. Dung sai nhỏ hơn cho đường cong mịn hơn nhưng tốn nhiều thời gian và bộ nhớ hơn.", + "dxf.tolerance_help": "Chỉ áp dụng cho các thân khối và phác thảo hiển thị. Đường cong sử dụng các đoạn thẳng. Dung sai nhỏ hơn cho đường cong mịn hơn nhưng tốn nhiều thời gian và bộ nhớ hơn.", "file_load.built": "Đã dựng được: {built} trên {total} tính năng.", "file_load.converting": "Đang chuyển đổi khối đặc {done} trên {total}", "file_load.inserting": "Đang chèn hình học", diff --git a/assets/locales/zh-TW.json b/assets/locales/zh-TW.json index 13d847e07..2528f3417 100644 --- a/assets/locales/zh-TW.json +++ b/assets/locales/zh-TW.json @@ -233,7 +233,6 @@ "No crash reports.": "沒有當機報告。", "No matching appearance presets.": "沒有符合的外觀預設。", "No matching appearances": "沒有符合的外觀", - "No visible bodies to export.": "沒有可匯出的可見實體。", "None": "無", "Not available yet": "暫不可用", "Notch": "缺口", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index a44b405ce..2fe7801b3 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -240,7 +240,7 @@ "No crash reports.": "没有崩溃报告。", "No matching appearance presets.": "没有匹配的外观预设。", "No matching appearances": "没有匹配的外观", - "No visible bodies to export.": "没有可导出的可见实体。", + "No visible bodies or sketches to export.": "没有可导出的可见实体或草图。", "Nominal diameter": "公称直径", "None": "无", "Not available yet": "暂不可用", @@ -856,7 +856,7 @@ "dxf.progress.projection": "正在投影几何体 (3/5)", "dxf.progress.write": "正在写入 DXF (5/5)", "dxf.tolerance": "曲线公差", - "dxf.tolerance_help": "仅导出可见实体。曲线使用直线段近似。公差越小,曲线越精细,但需要更多时间和内存。", + "dxf.tolerance_help": "仅导出可见实体和显示的草图。曲线使用直线段近似。公差越小,曲线越精细,但需要更多时间和内存。", "file_load.built": "已构建:{built}/{total} 个特征。", "file_load.converting": "正在转换实体 {done}/{total}", "file_load.inserting": "正在插入几何体", diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 1b692d75c..68a519c5b 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -40,6 +40,7 @@ pub(crate) use features::profiles as feature_profiles; pub(crate) use features::{EdgeRefForm, edge_ref_form, sketch_key}; pub use features::{auto_operation, extrude_reach}; pub use sketch_modify::trim_piece; +pub use view_dxf::sketch::exportable as view_dxf_exportable; mod component_link; mod config; mod file; diff --git a/crates/engine/src/cmd/view_dxf.rs b/crates/engine/src/cmd/view_dxf.rs index c62488411..2047a2833 100644 --- a/crates/engine/src/cmd/view_dxf.rs +++ b/crates/engine/src/cmd/view_dxf.rs @@ -1,5 +1,5 @@ -//! A drawing of the visible bodies from a supplied viewport camera. No screen pixels, grid, -//! selection highlights or tessellation diagonals are exported. +//! A drawing of the visible bodies and shown sketches from a supplied viewport camera. No +//! screen pixels, grid, selection highlights or tessellation diagonals are exported. #[path = "view_dxf_meshes.rs"] mod meshes; @@ -7,8 +7,11 @@ mod meshes; mod progress; #[path = "view_dxf_projection.rs"] mod projection; +#[path = "view_dxf_sketch.rs"] +pub(super) mod sketch; use serde_json::{Value, json}; +use solidcraft_geom::Vec2; use solidcraft_io::{DxfEntity, DxfLayer, DxfLinetype, DxfShape}; use solidcraft_render::Camera; @@ -20,7 +23,7 @@ const CMD: &str = "file.export_view_dxf"; pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Export Current View as DXF", export) .icon("export") .noundo() - .params("camera: Camera (current view); hidden?: omit|dashed (default omit); tolerance?: 0.0001..1 mm (curve chord tolerance, default 0.01); path?: .dxf file (else returns dxf text). Visible placed bodies only; 2D LINE/LWPOLYLINE entities on VISIBLE/HIDDEN layers, mm; perspective projected onto the camera target plane; no viewport crop or overlays.")]; + .params("camera: Camera (current view); hidden?: omit|dashed (default omit); tolerance?: 0.0001..1 mm (curve chord tolerance, default 0.01); path?: .dxf file (else returns dxf text). Visible placed bodies and shown sketches' profile curves (no construction geometry, points, dimensions or constraints); 2D LINE/LWPOLYLINE entities on VISIBLE/HIDDEN layers (sketch curves on SKETCH), mm; finished sketches are hidden behind bodies, the active sketch is drawn on top; perspective projected onto the camera target plane; no viewport crop or overlays.")]; fn export(s: &mut Session, p: &Value) -> Result { let cam: Camera = @@ -39,6 +42,9 @@ fn export(s: &mut Session, p: &Value) -> Result { Some(Value::String(v)) if v == "dashed" => true, _ => return Err(bad(CMD, "hidden must be omit or dashed")), }; + if !sketch::exportable(s) { + return Err(bad(CMD, "no visible bodies or sketches to export")); + } let tolerance = match p.get("tolerance") { None => 0.01, Some(v) => v.as_f64().filter(|t| (0.0001..=1.0).contains(t)).ok_or_else(|| bad(CMD, "tolerance must be 0.0001..1 mm"))?, @@ -54,7 +60,7 @@ fn export(s: &mut Session, p: &Value) -> Result { progress::Stage::new("dxf_meshes", 1).check().map_err(|e| bad(CMD, e))?; let meshes = meshes::prepare(s, tolerance)?; let prepare_ms = started.elapsed().as_secs_f64() * 1000.; - let drawing = projection::drawing(&meshes, &cam).map_err(|e| bad(CMD, e))?; + let drawing = projection::drawing(&meshes, &sketch::parts(s, tolerance).map_err(|e| bad(CMD, e))?, &cam).map_err(|e| bad(CMD, e))?; let writing = progress::Stage::new("dxf_write", 1); writing.check().map_err(|e| bad(CMD, e))?; let mut visible = 0; @@ -73,14 +79,18 @@ fn export(s: &mut Session, p: &Value) -> Result { }; entities.push(DxfEntity { layer: layer.into(), shape: DxfShape::Line(line.a, line.b) }); } - let entities = projection::connect(entities); + let mut entities = projection::connect(entities); + let sketch = sketch_entities(drawing.sketch, dashed, &mut entities); let mut layers = vec![DxfLayer::new("VISIBLE", 7)]; if dashed { layers.push(DxfLayer { linetype: DxfLinetype::Hidden, ..DxfLayer::new("HIDDEN", 8) }); } + if sketch > 0 { + layers.push(DxfLayer::new("SKETCH", 5)); + } let text = solidcraft_io::write_dxf_drawing(&layers, &entities); writing.check().map_err(|e| bad(CMD, e))?; - let mut result = json!({"visible":visible,"hidden":hidden,"units":"mm","tolerance":tolerance,"projection":if cam.fov > 0.0 {"perspective"} else {"orthographic"}}); + let mut result = json!({"visible":visible,"hidden":hidden,"sketch":sketch,"units":"mm","tolerance":tolerance,"projection":if cam.fov > 0.0 {"perspective"} else {"orthographic"}}); result["stats"] = json!({"bodies":meshes.placements.len(),"shared_meshes":meshes.meshes.len(),"triangles":meshes.triangles, "mesh_bytes":meshes.bytes,"worker_limit":meshes::WORKERS,"segments":drawing.segments,"occlusion_work":drawing.work, "prepare_ms":prepare_ms,"projection_ms":drawing.projection_ms,"occlusion_ms":drawing.occlusion_ms}); @@ -94,6 +104,22 @@ fn export(s: &mut Session, p: &Value) -> Result { Ok(result) } +/// Sketch runs as entities: visible ones on SKETCH, hidden ones dashed on HIDDEN or omitted. +/// Returns the number of SKETCH entities. +fn sketch_entities(paths: Vec, dashed: bool, entities: &mut Vec) -> usize { + let mut count = 0; + for path in paths.into_iter().filter(|p| dashed || !p.hidden) { + let layer = if path.hidden { "HIDDEN" } else { "SKETCH" }; + count += usize::from(!path.hidden); + let shape = match <[Vec2; 2]>::try_from(path.points) { + Ok([a, b]) => DxfShape::Line(a, b), + Err(points) => DxfShape::Polyline { points }, + }; + entities.push(DxfEntity { layer: layer.into(), shape }); + } + count +} + #[cfg(test)] #[path = "view_dxf_tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/view_dxf_meshes.rs b/crates/engine/src/cmd/view_dxf_meshes.rs index ec3f0e4d9..48cbfe6a8 100644 --- a/crates/engine/src/cmd/view_dxf_meshes.rs +++ b/crates/engine/src/cmd/view_dxf_meshes.rs @@ -123,9 +123,6 @@ pub(super) fn prepare(s: &Session, tolerance: f64) -> Result { let keep = groups.get(group).is_some_and(|g| g.first == index); items.push(Item { body, group, keep, transform }); } - if items.is_empty() { - return Err(bad(CMD, "no visible bodies to export")); - } let progress = Stage::new("dxf_meshes", items.len()); let bytes = AtomicUsize::new(0); let results = map_with_local_pools(&items, WORKERS, |item| { diff --git a/crates/engine/src/cmd/view_dxf_projection.rs b/crates/engine/src/cmd/view_dxf_projection.rs index bfb08025b..d4e0b7157 100644 --- a/crates/engine/src/cmd/view_dxf_projection.rs +++ b/crates/engine/src/cmd/view_dxf_projection.rs @@ -16,10 +16,19 @@ pub(super) struct Drawing { pub segments: usize, pub projection_ms: f64, pub occlusion_ms: f64, + /// Shown sketch curves: one path per visible or hidden run of each curve. + pub sketch: Vec, } -pub(super) fn drawing(meshes: &super::meshes::Scene, cam: &Camera) -> Result { - scene::drawing(meshes, cam) +/// A connected run of a projected sketch curve. +#[derive(Clone, Debug)] +pub(super) struct Path { + pub points: Vec, + pub hidden: bool, +} + +pub(super) fn drawing(meshes: &super::meshes::Scene, sketch: &[super::sketch::Part], cam: &Camera) -> Result { + scene::drawing(meshes, sketch, cam) } /// Keep the hidden curves connected: restarting a dash on every short chord would make a diff --git a/crates/engine/src/cmd/view_dxf_scene.rs b/crates/engine/src/cmd/view_dxf_scene.rs index 849dcb568..37f4afea9 100644 --- a/crates/engine/src/cmd/view_dxf_scene.rs +++ b/crates/engine/src/cmd/view_dxf_scene.rs @@ -12,7 +12,8 @@ use solidcraft_render::Camera; use super::super::meshes::{Placement, Scene, WORKERS, claim, transformed_bounds}; use super::super::progress::Stage; -use super::{Drawing, Line, bounds, clip, key, merge_lines, occluded, overlap, xy}; +use super::super::sketch::Part; +use super::{Drawing, Line, Path, bounds, clip, key, merge_lines, occluded, overlap, xy}; const TOO_COMPLEX: &str = "view exceeds export work budget; hide bodies or increase tolerance"; const MAX_LINES: usize = 1_000_000; @@ -405,12 +406,13 @@ impl Query<'_, '_> { } } -pub(super) fn drawing(scene: &Scene, cam: &Camera) -> Result { +pub(super) fn drawing(scene: &Scene, sketch: &[Part], cam: &Camera) -> Result { let start = Instant::now(); let scale = scene .placements .iter() .filter_map(|p| scene.meshes.get(p.mesh).map(|m| transformed_bounds(m, &p.transform))) + .chain(sketch.iter().map(|p| bounds(p.points.iter().copied()))) .fold(Aabb3::EMPTY, |b, p| b.union(&p)) .diagonal() .max(1.); @@ -510,7 +512,72 @@ pub(super) fn drawing(scene: &Scene, cam: &Camera) -> Result