From 9e78e86b92a199c2d77877de2bbf0b79487814b7 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 12:18:40 -0400 Subject: [PATCH 01/42] perf: renaming a body evaluates nothing (#3044) (#3095) A body rename changes names only, but committing it went through the general "design changed" path: the whole timeline was evaluated again. On an imported assembly that means reading the STEP file again and meshing every body (about 100 s on the Prusa Core One, and the same again for undo). When the only change from the previous design is one body rename (the features' stored body names and the body-keyed maps the rename updates), the model now renames the body in its results instead: every body keeps its geometry and meshes, and the fingerprints are set to the renamed design's so the next evaluation reuses everything. Undo and redo of the rename take the same path. A rename the model can't follow that way (the body is changed or named by a later feature, sheet metal, threads) still evaluates the design as before. `bench-open --ops script.json` times commands and their undo on an opened design, with the view work each leaves. Co-authored-by: Claude Opus 5.5 --- apps/solidcraft-cli/src/main.rs | 40 +++++++++++++++- crates/doc/src/document.rs | 81 ++++++++++++++++++++++++++++++++ crates/doc/src/eval.rs | 52 ++++++++++++++++++++ crates/doc/src/naming.rs | 11 +++++ crates/engine/src/cmd/browser.rs | 80 +++++++++++++++---------------- crates/engine/src/lib.rs | 56 +++++++++++++++++++++- crates/engine/src/tests.rs | 34 ++++++++++++++ 7 files changed, 310 insertions(+), 44 deletions(-) diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index 9030066b9..04bc9766c 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -4,7 +4,7 @@ //! solidcraft-cli run [--in design|part.step|mesh.3mf] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--json-out FILE] [--allow-errors] //! solidcraft-cli eval [--json-out FILE] (alias: inspect) measurements as JSON //! solidcraft-cli script [--out script.json] the design's history as a command script -//! solidcraft-cli bench-open [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]] loading timings as JSON lines +//! solidcraft-cli bench-open [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]] [--ops script.json] loading timings as JSON lines //! solidcraft-cli bench-agent [--scale F] [--save F] [--script-out F] a ~1,300-body design built command by command, timed //! solidcraft-cli snapshot [--in design|part.step] --out shot.png [--width W] [--height H] [--view iso|front|top|…|NAME | --camera JSON] [--no-grid] [--no-axes] //! [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27] @@ -50,7 +50,9 @@ const USAGE: &str = "usage: as plain UTF-8: a shell's > can re-encode it, e.g. Windows PowerShell adds a byte-order mark) solidcraft-cli script [--out script.json] (the design's history as a command script that eval and run replay) - solidcraft-cli bench-open [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]] + solidcraft-cli bench-open [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]] [--ops script.json] + (--ops: after opening, run each command of the script and undo it, timing the command, the + evaluations it caused and the view it leaves: placing and meshing what changed) solidcraft-cli bench-agent [--scale F] [--save design.solidcraft] [--script-out script.json] solidcraft-cli snapshot [--in design.solidcraft|part.step] --out shot.png [--width W] [--height H] [--view NAME | --camera JSON] [--no-grid] [--no-axes] [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27] @@ -642,6 +644,36 @@ fn cmd_bench_edit(args: &[String]) -> Result<(), String> { Ok(()) } +/// `bench-open --ops`: each command of `script` (a JSON array of `{command, params}`), then its +/// undo, each timed as the command and the view it leaves (the placed model, its meshes warmed +/// as the desktop does after a change). +fn bench_ops(mut s: Session, script: &str) -> Result { + let text = std::fs::read_to_string(script).map_err(|e| format!("{script}: {e}"))?; + let ops: Value = serde_json::from_str(&text).map_err(|e| format!("{script}: {e}"))?; + let ops = ops.as_array().ok_or("--ops: a JSON array of {command, params}")?; + let time = |s: &mut Session, id: &str, p: &Value| -> Result { + let t = std::time::Instant::now(); + let r = s.execute(id, p).map_err(|e| format!("{id}: {e}"))?; + let ms = t.elapsed().as_secs_f64() * 1000.0; + let t = std::time::Instant::now(); + s.world_state().warm_meshes(|| true); + let view_ms = t.elapsed().as_secs_f64() * 1000.0; + println!("{}", json!({"step": "op", "command": id, "ms": ms, "view_ms": view_ms})); + Ok(r) + }; + for op in ops { + let id = op.get("command").and_then(Value::as_str).ok_or("--ops: each step needs a `command`")?; + let p = op.get("params").cloned().unwrap_or(Value::Null); + let steps = s.undo.len(); + time(&mut s, id, &p)?; + // Commands that are no undo step (showing and hiding) have nothing to undo. + if op.get("undo").and_then(Value::as_bool) != Some(false) && s.undo.len() > steps { + time(&mut s, "edit.undo", &json!({}))?; + } + } + Ok(s) +} + /// Separate file reading, JSON decoding/repair, timeline evaluation and display meshing. pub(crate) fn cmd_bench_open(args: &[String]) -> Result<(), String> { let path = args.first().ok_or("usage: solidcraft-cli bench-open [--parse-only]")?; @@ -727,6 +759,10 @@ pub(crate) fn cmd_bench_open(args: &[String]) -> Result<(), String> { // `--display LEVEL`: the display plans the viewport draws at that display quality, made as // the GPU viewport makes them; `--edit NAME EXPR` then changes a parameter and times the // evaluation and the plans of the bodies it changed. + let s = match flag("--ops").and_then(|i| args.get(i + 1)) { + Some(ops) => bench_ops(s, ops)?, + None => s, + }; let Some(level) = flag("--display").and_then(|i| args.get(i + 1)) else { return Ok(()) }; let q = solidcraft_engine::doc::display_quality::DisplayQuality::parse(level).ok_or("--display: coarse, normal, fine or ultra")?; let plans = |st: &solidcraft_engine::doc::ModelState| { diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 02afec755..8b5ed6eed 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -2637,6 +2637,87 @@ impl Document { } } + /// Rename body `old` to `new` where the design keeps things by body name outside its + /// features: materials, appearances, configuration columns, offsets, components and the + /// browser's groups and order. (The features are the rename command's to change.) + pub fn rename_body_keys(&mut self, old: &str, new: &str) { + if let Some(m) = self.materials.remove(old) { + self.materials.insert(new.to_string(), m); + } + if let Some(c) = self.appearances.bodies.remove(old) { + self.appearances.bodies.insert(new.to_string(), c); + } + for f in self.appearances.faces.iter_mut().filter(|f| f.body == old) { + f.body = new.to_string(); + } + for column in &mut self.configs.columns { + match column { + crate::config::Column::Material(body) | crate::config::Column::Appearance(body) if *body == old => { + *body = new.to_string(); + } + crate::config::Column::FaceAppearance(target) if target.body == old => { + target.body = new.to_string(); + } + _ => {} + } + } + if let Some(o) = self.body_offsets.remove(old) { + self.body_offsets.insert(new.to_string(), o); + } + if let Some(c) = self.body_components.remove(old) { + self.body_components.insert(new.to_string(), c); + } + for g in self.browser_groups.iter_mut().filter(|g| g.folder == "bodies") { + for k in g.items.iter_mut().filter(|k| *k == old) { + *k = new.to_string(); + } + } + for (_, v) in self.browser_order.iter_mut().filter(|(k, _)| k.ends_with("/bodies")) { + for k in v.iter_mut().filter(|k| *k == old) { + *k = new.to_string(); + } + } + } + + /// The single body rename (old name, new name) that turns `previous` into this design, + /// when that is all that changed: the features' stored body names (`made` gives the names + /// each feature's bodies have now, by feature id) and what [`Document::rename_body_keys`] + /// renames. `None` for any other change. + pub fn body_rename_from(&self, previous: &Document, made: impl Fn(u64) -> Vec) -> Option<(String, String)> { + if self.features.len() != previous.features.len() { + return None; + } + let mut rename: Option<(String, String)> = None; + for (a, b) in previous.features.iter().zip(&self.features) { + if a.id != b.id { + return None; + } + if a.body_names == b.body_names { + continue; + } + let now = made(a.id); + for (k, name) in b.body_names.iter().enumerate() { + let current = now.get(k); + // Slots the rename left alone, and the ones it set to the names they have now. + if a.body_names.get(k) == Some(name) || name.trim().is_empty() || current == Some(name) { + continue; + } + let pair = (current?.clone(), name.clone()); + match &rename { + Some(r) if *r != pair => return None, + _ => rename = Some(pair), + } + } + } + let (old, new) = rename?; + let mut expected = previous.clone(); + for (f, g) in expected.features.iter_mut().zip(&self.features) { + f.body_names.clone_from(&g.body_names); + } + expected.rename_body_keys(&old, &new); + (expected == *self).then_some((old, new)) + } + /// A complete structural proof: no non-render field is allowed to differ. Keeping this /// comparison based on the whole Document also includes fields added in future versions. /// The clone/comparison is only needed when render intent actually differs. diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 82dd4c7db..c4ced0c4b 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1494,6 +1494,58 @@ impl Model { } } +impl Model { + /// Follow a rename of body `old` to `new` without evaluating anything (#3044): `doc` is the + /// design after the rename, which changed nothing but names, so every result keeps its + /// geometry and meshes and only the body's name (and the names worked out from it) changes. + /// False, leaving the model as it was, when the rename can't be followed that way and the + /// design must be evaluated: the model isn't the design's, the body is changed by a later + /// feature, or is sheet metal, threaded, or named in a later feature's face references. + pub fn rename_body(&mut self, doc: &Document, old: &str, new: &str) -> bool { + if self.results.len() != doc.features.len() || self.results.iter().zip(&doc.features).any(|(r, f)| r.id != f.id || r.stale) { + return false; + } + let Some(at) = self.results.iter().position(|r| r.state.body(old).is_some()) else { return false }; + let Some(made) = self.results.get(at).and_then(|r| r.state.body(old)).map(|b| Arc::as_ptr(&b.mesh)) else { return false }; + // Untouched from the feature that made it to the end, and nothing else holds its name. + let untouched = self.results.iter().skip(at).all(|r| r.state.body(old).is_some_and(|b| Arc::as_ptr(&b.mesh) == made)); + let named_elsewhere = self + .results + .iter() + .any(|r| r.state.body(new).is_some() || r.state.sheets.iter().any(|x| x.body == old) || r.state.threads.iter().any(|t| t.body == old)); + let faces_named = doc.features.iter().skip(at + 1).any(|f| f.face_names.iter().any(|n| n.contains(old))); + if !untouched || named_elsewhere || faces_named { + return false; + } + // States shared between results stay shared. + let mut renamed: std::collections::HashMap<*const ModelState, Arc> = std::collections::HashMap::new(); + for r in self.results.iter_mut().skip(at) { + let state = renamed + .entry(Arc::as_ptr(&r.state)) + .or_insert_with(|| { + let mut st = (*r.state).clone(); + for b in st.bodies.iter_mut().filter(|b| b.name == old) { + b.name = new.to_string(); + b.names = b.names.renamed(); + } + Arc::new(st) + }) + .clone(); + r.state = state; + } + // The fingerprints of the renamed design, so the next evaluation reuses every result. + let (vals, _) = evaluation_values(doc); + let marker = doc.marker.unwrap_or(usize::MAX); + self.step_digests = StepDigests::of(doc, &self.step_digests); + let mut prev = 0; + for (i, (r, f)) in self.results.iter_mut().zip(&doc.features).enumerate() { + prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &self.step_digests); + r.fingerprint = prev; + } + true + } +} + /// Key of the design's length unit (mm per unit) among the values (no parameter can be named /// so). pub(crate) const DESIGN_LEN: &str = "\u{1}design_len"; diff --git a/crates/doc/src/naming.rs b/crates/doc/src/naming.rs index 71d32e6ee..1801fca6f 100644 --- a/crates/doc/src/naming.rs +++ b/crates/doc/src/naming.rs @@ -85,6 +85,17 @@ impl NameCell { pub(crate) fn id(&self) -> usize { Arc::as_ptr(&self.names) as usize } + /// The same origin, lineage and depth with nothing worked out yet: for a body given a new + /// name, whose faces' names may be made from it. + pub(crate) fn renamed(&self) -> Self { + NameCell { + origin: self.origin.clone(), + lineage: self.lineage.clone(), + copy_of: self.copy_of.clone(), + saved_depth: self.saved_depth, + ..NameCell::default() + } + } fn shared(names: Arc) -> Self { let cell = OnceLock::new(); let _ = cell.set(names); diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rs index 1de6dd786..824808a98 100644 --- a/crates/engine/src/cmd/browser.rs +++ b/crates/engine/src/cmd/browser.rs @@ -508,20 +508,6 @@ fn view_list(s: &mut Session, _p: &Value) -> Result { Ok(json!({ "views": s.doc.named_views })) } -/// Rename an item key in the browser's groups and orders of a folder. -fn rename_key(d: &mut solidcraft_doc::Document, folder: &str, old: &str, new: &str) { - for g in d.browser_groups.iter_mut().filter(|g| g.folder == folder) { - for k in g.items.iter_mut().filter(|k| *k == old) { - *k = new.to_string(); - } - } - for (_, v) in d.browser_order.iter_mut().filter(|(k, _)| k.ends_with(&format!("/{folder}"))) { - for k in v.iter_mut().filter(|k| *k == old) { - *k = new.to_string(); - } - } -} - /// The keys whose strings name bodies, alone or in a list (`body`, `targets`…), at any depth of a /// feature: its own fields and the face, edge and link references inside it. const BODY_KEYS: [&str; 5] = ["body", "bodies", "target", "targets", "tools"]; @@ -638,33 +624,7 @@ fn rename_body(s: &mut Session, p: &Value) -> Result { if let Some(e) = failed { return Err(bad(cmd, e)); } - if let Some(m) = d.materials.remove(&old) { - d.materials.insert(name.to_string(), m); - } - if let Some(c) = d.appearances.bodies.remove(&old) { - d.appearances.bodies.insert(name.to_string(), c); - } - for f in d.appearances.faces.iter_mut().filter(|f| f.body == old) { - f.body = name.to_string(); - } - for column in &mut d.configs.columns { - match column { - solidcraft_doc::config::Column::Material(body) | solidcraft_doc::config::Column::Appearance(body) if *body == old => { - *body = name.to_string(); - } - solidcraft_doc::config::Column::FaceAppearance(target) if target.body == old => { - target.body = name.to_string(); - } - _ => {} - } - } - if let Some(o) = d.body_offsets.remove(&old) { - d.body_offsets.insert(name.to_string(), o); - } - if let Some(c) = d.body_components.remove(&old) { - d.body_components.insert(name.to_string(), c); - } - rename_key(d, "bodies", &old, name); + d.rename_body_keys(&old, name); for b in s.visibility.hidden_bodies.iter_mut().filter(|b| **b == old) { *b = name.to_string(); } @@ -864,6 +824,44 @@ mod tests { assert!(names(&s).contains(&"Body2".to_string()) && names(&s).contains(&"Body4".to_string()), "{:?}", names(&s)); } + /// #3044: a rename changes names only, so it, its undo and its redo evaluate nothing: every + /// body keeps its geometry and display mesh, and the model is the one evaluating the renamed + /// design gives. + #[test] + fn renaming_a_body_evaluates_nothing() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A"})); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "center": [20, 0, 2.5], "operation": "new", "body_name": "B"})); + run(&mut s, "appearance.assign", json!({"bodies": ["A"], "appearance": "Aluminum - Satin"})); + let meshes = |s: &Session| s.model.state().bodies.iter().map(|b| std::sync::Arc::as_ptr(&b.mesh())).collect::>(); + let shown = meshes(&s); + s.evaluations = 0; + run(&mut s, "body.rename", json!({"body": "A", "name": "Plate"})); + assert_eq!(s.evaluations, 0, "a rename evaluates nothing"); + assert_eq!(names(&s), vec!["Plate".to_string(), "B".to_string()]); + assert_eq!(meshes(&s), shown, "the bodies keep their meshes"); + assert!(s.doc.appearances.bodies.contains_key("Plate")); + // The same model as evaluating the renamed design. + let mut fresh = Session::new((*s.doc).clone()); + fresh.refresh(); + assert_eq!(names(&fresh), names(&s)); + s.refresh(); + assert_eq!(s.model.last_recomputed, 0, "the next evaluation reuses every result"); + s.evaluations = 0; + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&s), vec!["A".to_string(), "B".to_string()]); + run(&mut s, "edit.redo", json!({})); + assert_eq!(names(&s), vec!["Plate".to_string(), "B".to_string()]); + assert_eq!(s.evaluations, 0, "undo and redo of a rename evaluate nothing"); + assert_eq!(meshes(&s), shown); + // A body a later feature uses is renamed in that feature too: that is evaluated. + run(&mut s, "solid.combine", json!({"target": "Plate", "tools": ["B"], "operation": "join", "keep_tools": true})); + s.evaluations = 0; + run(&mut s, "body.rename", json!({"body": "B", "name": "Tool"})); + assert!(s.evaluations > 0); + assert!(names(&s).contains(&"Tool".to_string())); + } + #[test] fn renaming_a_body_leaves_other_text_with_its_name_alone() { let mut s = Session::default(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e34aeb615..29516295b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -149,6 +149,14 @@ pub enum Sel { }, } +/// A body rename between two designs (see `Session::body_renames`). +struct BodyRename { + before: std::sync::Weak, + after: std::sync::Weak, + old: String, + new: String, +} + /// One undo step. #[derive(Clone, Debug)] pub struct Snapshot { @@ -246,6 +254,9 @@ pub struct Session { /// Pairs `inspect.clearance` measured, by the bodies' geometry where they stood (shared with /// scratch copies): a body that did not change or move is not measured again. clearance_cache: std::sync::Arc>, + /// Recent body renames: the design before and after each, and the names, so undo and redo + /// follow them without evaluating either. + body_renames: Vec, /// Features copied with `timeline.copy` (pasted by `timeline.paste`). pub clipboard: Vec, /// Sketch geometry copied with `sketch.copy` (pasted by `sketch.paste`). @@ -399,6 +410,7 @@ impl Session { occurrence_visibility_cache: Default::default(), removed_later_cache: Default::default(), clearance_cache: Default::default(), + body_renames: Vec::new(), clipboard: Vec::new(), sketch_clipboard: None, section: None, @@ -620,6 +632,47 @@ impl Session { } } + /// [`Session::refresh`] after the design changed from `previous`; a change that only renamed + /// a body (or undid or redid such a rename) renames it in the model instead, which keeps + /// every result and mesh (#3044). + fn refresh_from(&mut self, previous: &Arc) { + if let Some((old, new)) = self.body_rename(previous) + && self.model.rename_body(&self.doc, &old, &new) + { + self.revision += 1; + if !self.doc.assembly.joints.is_empty() { + cmd::joints::resolve(self); + } + return; + } + self.refresh(); + } + + /// The body rename that turned `previous` into the design (old name, new name), if that is + /// the whole change: one this session made (either way round), else one the designs show. + fn body_rename(&mut self, previous: &Arc) -> Option<(String, String)> { + let holds = |w: &std::sync::Weak, d: &Arc| w.upgrade().is_some_and(|x| Arc::ptr_eq(&x, d)); + self.body_renames.retain(|r| r.before.strong_count() > 0 && r.after.strong_count() > 0); + for r in &self.body_renames { + if holds(&r.before, previous) && holds(&r.after, &self.doc) { + return Some((r.old.clone(), r.new.clone())); + } + if holds(&r.after, previous) && holds(&r.before, &self.doc) { + return Some((r.new.clone(), r.old.clone())); + } + } + let model = &self.model; + let made = |id: u64| -> Vec { + model.result(id).map(|r| r.state.bodies.iter().filter(|b| b.feature == id).map(|b| b.name.clone()).collect()).unwrap_or_default() + }; + let (old, new) = self.doc.body_rename_from(previous, made)?; + self.body_renames.push(BodyRename { before: Arc::downgrade(previous), after: Arc::downgrade(&self.doc), old: old.clone(), new: new.clone() }); + if self.body_renames.len() > MAX_UNDO { + self.body_renames.remove(0); + } + Some((old, new)) + } + /// Only persistent render intent, or only part properties, changed. Never evaluate or clear /// a stale model here. fn render_only_change(&self, before: &Snapshot) -> bool { @@ -766,7 +819,7 @@ impl Session { match live_edit { Some(edit) => self.refresh_live(edit), None if render_only => self.refresh_render(&previous_doc), - None => self.refresh(), + None => self.refresh_from(&previous_doc), } } Ok(v) @@ -874,6 +927,7 @@ impl Session { occurrence_visibility_cache: Default::default(), removed_later_cache: Default::default(), clearance_cache: self.clearance_cache.clone(), + body_renames: Vec::new(), clipboard: self.clipboard.clone(), sketch_clipboard: self.sketch_clipboard.clone(), section: None, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d7aafdc3d..3ede07560 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3791,3 +3791,37 @@ fn a_tapered_side_drawn_in_two_collinear_pieces_is_one_face() { let m = run(&mut s, "inspect.measure", json!({})); assert_eq!(m["bodies"][0]["kernel"]["faces"], 6, "{m}"); } + +/// #3044: renaming a body of an imported assembly (a part placed twice, so the file has more +/// solids than the part has bodies) evaluates nothing, not even the file again, and leaves the +/// model evaluating the renamed design gives; undo does the same. +#[test] +fn renaming_an_imported_assembly_body_reads_nothing_again() { + let dir = std::env::temp_dir().join(format!("solidcraft-step-rename-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut a = Session::default(); + run(&mut a, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Cube"})); + run(&mut a, "solid.box", json!({"length": 4, "width": 4, "height": 4, "center": [30, 0, 2], "operation": "new", "body_name": "Pin"})); + run(&mut a, "component.from_bodies", json!({"bodies": ["Cube"]})); + run(&mut a, "occurrence.copy", json!({"component": "Cube", "translate": [0, 40, 0]})); + let p = dir.join("Assembly.step"); + run(&mut a, "file.export", json!({"path": p.to_string_lossy()})); + let mut s = Session::default(); + run(&mut s, "doc.open", json!({"path": p.to_string_lossy()})); + let names = |s: &Session| s.model.state().bodies.iter().map(|b| b.name.clone()).collect::>(); + let before = names(&s); + let body = before.first().cloned().unwrap(); + s.evaluations = 0; + run(&mut s, "body.rename", json!({"body": body, "name": "Renamed"})); + assert_eq!(s.evaluations, 0, "a rename evaluates nothing"); + let after = names(&s); + assert_eq!(after.first().map(String::as_str), Some("Renamed")); + assert_eq!(after.len(), before.len()); + let mut fresh = Session::new((*s.doc).clone()); + fresh.refresh(); + assert_eq!(names(&fresh), after, "the same names as evaluating the renamed design"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&s), before); + assert_eq!(s.evaluations, 0, "nor does its undo"); + let _ = std::fs::remove_dir_all(&dir); +} From 2f5f65d6e32da842c3384d8175f369bfc93f2aaa Mon Sep 17 00:00:00 2001 From: Jakobonly <149584042+DundreDE@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:51:06 +0000 Subject: [PATCH 02/42] Sketch: an angle dimension between two lines from one point measures the angle between them (#2724) (#3439) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * claim: #2724 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0158is7fBbAVh538YmVF3MpZ * Sketch: an angle between two lines from one point measures the angle between them (#2724) An angle dimension on two lines that share an end (two radii of a circle, the two sides of a corner) took the acute reading of the lines' directions, so radii 120° apart measured 60° and 150° apart 30°. With no text position given, the angle is now measured from the shared end towards the lines' other ends, the reading anyone would mean; the supplement stays the alternative reading. Lines that share no end, and dimensions placed with a text position, are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0158is7fBbAVh538YmVF3MpZ * ci: re-run the checks; the run on the last push was cancelled Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0158is7fBbAVh538YmVF3MpZ --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/sketch.rs | 45 +++++++++++++++++-- .../src/cmd/sketch_constraints_tests.rs | 41 +++++++++++++++++ 2 files changed, 83 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 96d9bc5b0..5d9170243 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -2075,9 +2075,15 @@ fn dimension(s: &mut Session, p: &Value) -> Result { (ConstraintKind::PointLineDistance { p: bq, l: a, value: d }, d) } } else { - match text_at { - Some(t) => angle_by_sector(a, b, (a0, a1), (b0, b1), t).ok_or_else(|| bad(cmd, "cannot place that angle"))?, - None => { + match (text_at, angle_from_shared_end(a, b, (a0, a1), (b0, b1))) { + (Some(t), _) => angle_by_sector(a, b, (a0, a1), (b0, b1), t).ok_or_else(|| bad(cmd, "cannot place that angle"))?, + // Two lines from one point (two radii, a corner) measure the angle + // between them, from that point towards their other ends (#2724). + (None, Some((between, supplement))) => { + alt = Some(supplement); + between + } + (None, None) => { let mut ang = da.cross(db).atan2(da.dot(db)); let (mut ka, mut kb) = (a, b); if ang < 0.0 { @@ -2295,6 +2301,39 @@ fn angle_by_sector(a: usize, b: usize, (a0, a1): (Vec2, Vec2), (b0, b1): (Vec2, None } +/// The angle dimension between two lines that run from one shared end, measured from that end +/// towards their other ends (#2724), and its supplement; None when they share no end or are +/// collinear. +fn angle_from_shared_end( + a: usize, + b: usize, + (a0, a1): (Vec2, Vec2), + (b0, b1): (Vec2, Vec2), +) -> Option<((ConstraintKind, f64), (ConstraintKind, f64))> { + let tol = 1e-9 * a0.dist(a1).max(b0.dist(b1)).max(1.0); + // The sign that turns each line's direction into its ray away from the shared end. + let (sa, sb) = [(a0, b0, 1.0, 1.0), (a0, b1, 1.0, -1.0), (a1, b0, -1.0, 1.0), (a1, b1, -1.0, -1.0)] + .into_iter() + .find(|(p, q, ..)| p.dist(*q) <= tol) + .map(|(_, _, sa, sb)| (sa, sb))?; + let (ra, rb) = ((a1 - a0) * sa, (b1 - b0) * sb); + let mut ang = ra.cross(rb).atan2(ra.dot(rb)); + let (mut first, mut second) = ((a, sa), (b, sb)); + if ang < 0.0 { + ang = -ang; + std::mem::swap(&mut first, &mut second); + } + if !(ang > 1e-9 && ang < std::f64::consts::PI - 1e-9) { + return None; + } + // The constraint turns the first line's direction onto the second's, negated when the + // two rays run against their lines' directions differently. + let flip = first.1 * second.1 < 0.0; + let between = (ConstraintKind::Angle { a: first.0, b: second.0, value: ang, flip }, ang); + let supplement = (ConstraintKind::Angle { a: second.0, b: first.0, value: std::f64::consts::PI - ang, flip: !flip }, std::f64::consts::PI - ang); + Some((between, supplement)) +} + pub(super) fn round6(x: f64) -> f64 { (x * 1e6).round() / 1e6 } diff --git a/crates/engine/src/cmd/sketch_constraints_tests.rs b/crates/engine/src/cmd/sketch_constraints_tests.rs index 56063ccdc..de5e2e114 100644 --- a/crates/engine/src/cmd/sketch_constraints_tests.rs +++ b/crates/engine/src/cmd/sketch_constraints_tests.rs @@ -313,6 +313,47 @@ fn an_angle_between_lines_takes_the_reading_nearest_its_value_and_reports_degree assert_eq!(d["unit"], "mm", "{d}"); } +#[test] +fn an_angle_between_two_lines_from_one_point_measures_the_angle_between_them() { + // #2724: two radii of a circle 120° apart measured 60°, and 150° apart 30°. + for deg in [30.0_f64, 60.0, 90.0, 120.0, 150.0] { + let far = [20.0 * deg.to_radians().cos(), 20.0 * deg.to_radians().sin()]; + // Both drawn out from the centre, the second drawn in towards it, or a corner. + let shapes = [ + vec![json!([[0, 0], [20, 0]]), json!([[0, 0], far])], + vec![json!([[0, 0], [20, 0]]), json!([far, [0, 0]])], + vec![json!([[20, 0], [0, 0], far])], + ]; + for (i, lines) in shapes.iter().enumerate() { + let mut s = new_sketch(); + for pts in lines { + run(&mut s, "sketch.line", json!({"points": pts, "connect": false})); + } + let d = run(&mut s, "sketch.dimension", json!({"entities": ["l1", "l2"]})); + assert!((d["measured"].as_f64().unwrap() - deg).abs() < 1e-4, "{deg}° shape {i}: {d}"); + } + // A value turns the corner's sides to it, keeping them on the same side of each other. + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[20, 0], [0, 0], far], "connect": false})); + let want = deg + 10.0; + let d = run(&mut s, "sketch.dimension", json!({"entities": ["l1", "l2"], "value": format!("{want} deg")})); + assert!((d["measured"].as_f64().unwrap() - want).abs() < 1e-6, "{deg}°: {d}"); + let sk = sketch(&s); + let line = |l: &str| crate::cmd::sketch::line_pts(&sk, sk.curve_index(l).unwrap()).unwrap(); + let ((a0, a1), (b0, b1)) = (line("l1"), line("l2")); + assert!(a1.dist(b0) < 1e-9, "the corner stays joined"); + let (ra, rb) = (a0 - a1, b1 - b0); + let between = ra.cross(rb).abs().atan2(ra.dot(rb)).to_degrees(); + assert!((between - want).abs() < 1e-6, "{deg}°: the sides are {between}° apart"); + } + // Lines that share no end keep the acute reading. + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [20, 0]], "connect": false})); + run(&mut s, "sketch.line", json!({"points": [[30, 10], [40, 27.3205]], "connect": false})); + let d = run(&mut s, "sketch.dimension", json!({"entities": ["l1", "l2"]})); + assert!((d["measured"].as_f64().unwrap() - 60.0).abs() < 1e-3, "{d}"); +} + #[test] fn symmetry_moves_a_free_line_between_two_fixed_lines() { // #1796: with both mirrored lines fixed, the symmetry line between them (a free construction From 7bda28e78640faf7a96fa66db587d4ac59cc8588 Mon Sep 17 00:00:00 2001 From: Dahak Builds Date: Tue, 20 Oct 2026 15:21:17 +0000 Subject: [PATCH 03/42] Contact: a check finds bodies crossing face to face, not only a corner inside (#3323) (#3388) * claim: #3323 * Contact: a check finds bodies crossing face to face, not only a corner inside (#3323) The collision probe sampled each tessellation's points (vertices, edge midpoints, triangle centres) against the other body, so plates crossing face to face - where the crossing strip is smaller than a face triangle - put no sample point inside and went unreported while inspect.interference found the overlap. Where an edge of one body passes through the other's surface, the middle of the chord it cuts lies inside; its distance from that surface is the depth. Touching and grazing are unchanged. The sweep's collision work model pays for the added edge pass. --------- Co-authored-by: DahakBuilds --- crates/engine/src/cmd/contact_sweep.rs | 9 +++-- crates/engine/src/cmd/motion.rs | 50 +++++++++++++++++++++++++ crates/engine/src/cmd/motion_tests.rs | 51 ++++++++++++++++++++++++++ 3 files changed, 106 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/contact_sweep.rs b/crates/engine/src/cmd/contact_sweep.rs index 7004e9a7e..e253aea34 100644 --- a/crates/engine/src/cmd/contact_sweep.rs +++ b/crates/engine/src/cmd/contact_sweep.rs @@ -302,9 +302,10 @@ impl ContactGeometry { let cost = ma .positions .len() - .saturating_add(ma.triangles.len().saturating_mul(4)) + // 4 sample points and 3 edges to probe per triangle of `a` against each triangle of `b` (#3323), and the other way round. + .saturating_add(ma.triangles.len().saturating_mul(7)) .saturating_mul(mb.triangles.len()) - .saturating_add(mb.positions.len().saturating_add(mb.triangles.len().saturating_mul(4)).saturating_mul(ma.triangles.len())); + .saturating_add(mb.positions.len().saturating_add(mb.triangles.len().saturating_mul(7)).saturating_mul(ma.triangles.len())); *work = work.saturating_add(cost); if *work > budget { return Err(limit("motion exceeds contact sweep collision budget; simplify the contact set or use smaller increments")); @@ -522,8 +523,8 @@ fn tri_distance(a: &[Vec3; 3], b: &[Vec3; 3]) -> (f64, Vec3, Vec3) { best } -/// Where segment pq passes through triangle t (None: it misses, or lies in its plane). -fn segment_hits_triangle(p: Vec3, q: Vec3, t: &[Vec3; 3]) -> Option { +/// Where the segment `p`→`q` hits triangle `t` (endpoints count), if it crosses its plane. +pub(super) fn segment_hits_triangle(p: Vec3, q: Vec3, t: &[Vec3; 3]) -> Option { let d = q - p; let (e1, e2) = (t[1] - t[0], t[2] - t[0]); let h = d.cross(e2); diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rs index d83094a84..e49e97334 100644 --- a/crates/engine/src/cmd/motion.rs +++ b/crates/engine/src/cmd/motion.rs @@ -179,6 +179,8 @@ pub fn collisions(s: &Session) -> Vec<(String, String, f64)> { /// How deep one body reaches into the other, when more than a touch (`None`: apart or /// touching). Points of each tessellation (vertices, edge midpoints, triangle centres) are /// tested against the other closed mesh: inside by ray parity, and deeper than the tolerance. +/// Edges are tested for crossing the other's surface too: plates crossing face to face have +/// no sample point inside (#3323). fn overlap(a: &Body, b: &Body) -> Option { let (ma, mb) = (a.tessellate((a.size() * 1e-3).max(1e-3)).ok()?, b.tessellate((b.size() * 1e-3).max(1e-3)).ok()?); mesh_overlap(&ma, &mb, 1e-4 * a.size().max(b.size()).max(1.0)) @@ -208,8 +210,10 @@ fn deepest(a: &solidcraft_geom::Mesh, b: &solidcraft_geom::Mesh, tol: f64) -> f6 let tb = tris(b); let bx = b.bounds(); let mut pts: Vec = a.positions.clone(); + let mut edges: Vec<(Vec3, Vec3)> = Vec::new(); for [p, q, r] in tris(a) { pts.extend([(p + q) * 0.5, (q + r) * 0.5, (r + p) * 0.5, (p + q + r) * (1.0 / 3.0)]); + edges.extend([(p, q), (q, r), (r, p)]); } let mut best = 0.0f64; for p in pts.into_iter().take(200_000) { @@ -227,6 +231,52 @@ fn deepest(a: &solidcraft_geom::Mesh, b: &solidcraft_geom::Mesh, tol: f64) -> f6 best = d; } } + for (p, q) in edges.into_iter().take(200_000) { + best = best.max(crossing(p, q, &tb, bx, tol)); + } + best +} + +/// Where the edge `p`→`q` of one mesh reaches through the surface `tb` of the other: the +/// depth, or 0 when it misses, only touches, or grazes (the middle of the chord it cuts must +/// lie inside, deeper than `tol`, as elsewhere in the check). Two plates crossing each other's +/// faces put no vertex, mid-edge or triangle centre of either inside the other — the chord an +/// edge cuts is how that crossing is seen (#3323). +fn crossing(p: Vec3, q: Vec3, tb: &[[Vec3; 3]], bx: Aabb3, tol: f64) -> f64 { + if p.x.max(q.x) < bx.min.x - tol + || p.x.min(q.x) > bx.max.x + tol + || p.y.max(q.y) < bx.min.y - tol + || p.y.min(q.y) > bx.max.y + tol + || p.z.max(q.z) < bx.min.z - tol + || p.z.min(q.z) > bx.max.z + tol + { + return 0.0; + } + let d = q - p; + let len2 = d.dot(d); + if len2 <= 0.0 { + return 0.0; + } + // Where the edge crosses the surface, along the edge. A crossing at a vertex or along an + // edge shared by two triangles is found twice (or more); merges of neighbours leave the + // entry and exit of each chord as one pair each. + let mut hits: Vec = tb.iter().filter_map(|t| contact_sweep::segment_hits_triangle(p, q, t)).map(|h| (h - p).dot(d) / len2).collect(); + if hits.len() < 2 { + return 0.0; + } + hits.sort_by(|x, y| x.total_cmp(y)); + hits.dedup_by(|x, y| (*x - *y).abs() < 1e-6); + let mut best = 0.0; + for pair in hits.chunks(2) { + if pair.len() < 2 { + break; + } + let m = p + d * ((pair[0] + pair[1]) * 0.5); + let deep = tb.iter().map(|[a, b, c]| closest(m, *a, *b, *c).dist(m)).fold(f64::MAX, f64::min); + if deep > tol.max(best) && inside(m, tb) { + best = deep; + } + } best } diff --git a/crates/engine/src/cmd/motion_tests.rs b/crates/engine/src/cmd/motion_tests.rs index 44974d82b..5d7594f7c 100644 --- a/crates/engine/src/cmd/motion_tests.rs +++ b/crates/engine/src/cmd/motion_tests.rs @@ -71,6 +71,57 @@ fn contact_sets_stop_a_driven_joint_at_touching() { assert!(s.execute("contact.create", &json!({"occurrences": ["A"]})).is_err()); } +/// A base plate and a lid plate (both 40 × 40 × 3) hinged along their shared edge, driven +/// past flat by `angle` degrees. +fn hinged_plates(angle: f64) -> Session { + let mut s = Session::default(); + run( + &mut s, + "solid.box", + json!({"length": 40.0, "width": 40.0, "height": 3.0, "corner": [-20.0, -40.0, 0.0], "operation": "new", "body_name": "BasePlate"}), + ); + run( + &mut s, + "solid.box", + json!({"length": 40.0, "width": 40.0, "height": 3.0, "corner": [-20.0, 0.0, 0.0], "operation": "new", "body_name": "LidPlate"}), + ); + run(&mut s, "component.create", json!({"name": "Base", "parent": "root", "activate": false})); + run(&mut s, "component.move_bodies", json!({"bodies": ["BasePlate"], "component": "Base"})); + run(&mut s, "component.create", json!({"name": "Lid", "parent": "root", "activate": false})); + run(&mut s, "component.move_bodies", json!({"bodies": ["LidPlate"], "component": "Lid"})); + run(&mut s, "occurrence.ground", json!({"occurrence": "Base:1", "grounded": true})); + run( + &mut s, + "joint.create", + json!({"type": "revolute", "name": "Hinge", "flip": true, "limits": [[0.0, 270.0]], + "a": {"occurrence": "Base", "point": [0.0, 0.0, 3.0], "z": [1.0, 0.0, 0.0]}, + "b": {"occurrence": "Lid", "point": [0.0, 0.0, 3.0], "z": [1.0, 0.0, 0.0]}}), + ); + run(&mut s, "joint.drive", json!({"joint": "Hinge", "value": angle, "quiet": true})); + run(&mut s, "contact.create", json!({"occurrences": ["Base:1", "Lid:1"]})); + s +} + +/// Regression (#3323): past the angles where a corner lies inside the other plate, no vertex, +/// mid-edge or triangle centre of either plate is inside it, and `contact.check` reported no +/// collision while `inspect.interference` found the overlap. The faces crossing is the +/// collision; the check must see it. +#[test] +fn contact_check_finds_plates_crossing_face_to_face() { + // Flat against the base: touching is not crossing. + let mut s = hinged_plates(180.0); + assert_eq!(run(&mut s, "contact.check", json!({}))["collisions"].as_array().map(Vec::len), Some(0), "flat"); + for angle in [210.0, 240.0, 270.0] { + let mut s = hinged_plates(angle); + let collisions = run(&mut s, "contact.check", json!({}))["collisions"].clone(); + let c = collisions.as_array().unwrap(); + assert_eq!(c.len(), 1, "{angle}°: {c:?}"); + assert_eq!(c[0]["a"], "Base:1"); + assert_eq!(c[0]["b"], "Lid:1"); + assert!(c[0]["depth_mm"].as_f64().unwrap() > 0.5, "{angle}°: {c:?}"); + } +} + #[test] fn contact_uses_preserved_body_placements_after_component_reassignment() { let mut s = Session::default(); From 83790139b1d633fdbdae9b09ec802015576e59c1 Mon Sep 17 00:00:00 2001 From: phanoob Date: Tue, 20 Oct 2026 15:28:52 +0000 Subject: [PATCH 04/42] Editing a sketch past the history marker rolls the marker to it (#2716) (#3339) * claim: #2716 Co-Authored-By: Claude Opus 5.5 * Editing a sketch past the history marker rolls the marker to it (#2716) Edit Sketch rolled the timeline back to just after the sketch only when the marker was later. With the marker before the sketch it stayed there: the sketch wasn't built, so it opened with no palette and couldn't be edited. The marker now moves to just after the sketch either way, and Finish Sketch puts it back as before. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Phanoob Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 8 ++++---- crates/ui-egui/src/sketch_edit_tests.rs | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8e68c929b..514331e98 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -991,9 +991,9 @@ impl SolveApp { } } - /// Edit a sketch: roll the timeline back to just after it (so later - /// features don't hide it), turn the camera to face it, and remember both so Finish Sketch - /// puts them back. Editing the sketch that is already open does nothing; editing another one + /// Edit a sketch: roll the timeline to just after it (back, so later features don't hide + /// it, or forward from before it, where it isn't built yet: #2716), turn the camera to face + /// it, and remember both so Finish Sketch puts them back. Editing the sketch that is already open does nothing; editing another one /// finishes the current sketch first, so edit sessions never nest. pub fn edit_sketch(&mut self, id: u64) { if let solidcraft_engine::doc::FaceAttachmentStatus::Lost { message, .. } = @@ -1013,7 +1013,7 @@ impl SolveApp { self.dialog = None; let Some(idx) = self.session.doc.feature_index(id) else { return }; let marker = self.session.doc.marker; - let rolled = marker.is_none_or(|m| m > idx + 1) && self.run("timeline.roll_to", json!({ "position": idx + 1 })).is_ok(); + let rolled = marker != Some(idx + 1) && self.run("timeline.roll_to", json!({ "position": idx + 1 })).is_ok(); let before = self.cam; if self.run("sketch.edit", json!({ "sketch": id })).is_err() { if rolled { diff --git a/crates/ui-egui/src/sketch_edit_tests.rs b/crates/ui-egui/src/sketch_edit_tests.rs index 2430b5c7c..bbb9b6d1b 100644 --- a/crates/ui-egui/src/sketch_edit_tests.rs +++ b/crates/ui-egui/src/sketch_edit_tests.rs @@ -28,6 +28,25 @@ fn edit_sketch_rolls_back_and_finish_restores() { assert_eq!(app.session.doc.marker, marker, "marker restored"); } +/// #2716: with the history marker before a sketch, editing it rolls the marker forward to it +/// (it is built, its palette shows), and Finish puts the marker back. +#[test] +fn edit_sketch_rolls_forward_from_before_it_and_finish_restores() { + let mut app = sample_app(); + let id = first_sketch(&app); + let idx = app.session.doc.feature_index(id).unwrap(); + app.run("timeline.roll_to", serde_json::json!({ "position": idx })).unwrap(); + let marker = app.session.doc.marker; + assert!(app.session.model.state().sketch(id).is_none(), "the sketch is past the marker"); + app.edit_sketch(id); + assert_eq!(app.session.active_sketch, Some(id)); + assert_eq!(app.session.doc.marker, Some(idx + 1), "rolled forward to just after the sketch"); + assert!(app.session.model.state().sketch(id).is_some(), "the sketch is built"); + app.finish_sketch(); + assert_eq!(app.session.active_sketch, None); + assert_eq!(app.session.doc.marker, marker, "marker restored"); +} + #[test] fn editing_twice_does_not_nest() { let mut app = sample_app(); From 76b17f2663fa740692f2a0df2d03242aa2c453a6 Mon Sep 17 00:00:00 2001 From: SS-EN <84559909+SS-EN@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:32:07 +0000 Subject: [PATCH 05/42] sketch(feat): a click on another dimension inserts its name into the value being edited (#3186) While editing a dimension's value, a single click on another driving dimension now inserts its parameter name (a double-click no longer needed, and its second click does not insert it twice). A lone value such as `10` or `10 mm` is replaced by the name; an expression in progress keeps what was typed and gets the name at the cursor (replacing selected text), so `10 + ` becomes `10 + d10`. The cursor ends after the name and the field keeps the keyboard. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/dim_view.rs | 84 ++++++++++++++----- .../ui-egui/src/dimension_create_ui_tests.rs | 78 +++++++++++++++-- docs/book/src/guide/parameters.md | 9 +- 3 files changed, 143 insertions(+), 28 deletions(-) diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rs index ca2ebd093..7910a37e5 100644 --- a/crates/ui-egui/src/dim_view.rs +++ b/crates/ui-egui/src/dim_view.rs @@ -50,6 +50,9 @@ struct Edit { /// dimension, and its text follows the pointer until a click pins it or Enter places it. live: Option, selection: Option, + /// The last dimension a click referenced, and when: the second click of a double-click on + /// it must not insert its name again. + picked: Option<(String, f64)>, } #[derive(Clone, Copy, Debug)] @@ -134,7 +137,8 @@ pub fn begin_dimension(app: &mut SolveApp, entities: Vec, at: Vec2) -> R return Ok(()); } EDIT.with(|edit| { - *edit.borrow_mut() = Some(Edit { param, expr, at: None, fresh: FRESH, wait: 10, draft: Some(draft), live: None, selection: None }) + *edit.borrow_mut() = + Some(Edit { param, expr, at: None, fresh: FRESH, wait: 10, draft: Some(draft), live: None, selection: None, picked: None }) }); PLACEMENT.with(|preview| *preview.borrow_mut() = None); Ok(()) @@ -150,7 +154,9 @@ pub fn begin_live(app: &mut SolveApp, entities: Vec, pointer: Option bool { }; let expr = app.session.doc.param(¶m).map(|p| p.expr.clone()).unwrap_or_default(); EDIT.with(|e| { - *e.borrow_mut() = Some(Edit { param, expr, at: Some(d.text.center()), fresh: FRESH, wait: 0, draft: None, live: None, selection: None }) + *e.borrow_mut() = + Some(Edit { param, expr, at: Some(d.text.center()), fresh: FRESH, wait: 0, draft: None, live: None, selection: None, picked: None }) }); true } @@ -583,24 +590,45 @@ fn pos2_mid_top(r: Rect) -> Pos2 { pub fn edit_param(app: &SolveApp, param: &str) { let expr = app.session.doc.param(param).map(|p| p.expr.clone()).unwrap_or_default(); EDIT.with(|e| { - *e.borrow_mut() = Some(Edit { param: param.to_string(), expr, at: None, fresh: FRESH, wait: 10, draft: None, live: None, selection: None }) + *e.borrow_mut() = + Some(Edit { param: param.to_string(), expr, at: None, fresh: FRESH, wait: 10, draft: None, live: None, selection: None, picked: None }) }); } -/// Insert a reference at the expression's selection, using character offsets (not bytes). +/// A lone value such as `10`, `-3`, `12.5`, `2,5`, `10 mm` or `45 deg`: a number, optionally +/// followed by a unit, with no operator or name. +fn is_plain_value(text: &str) -> bool { + let t = text.trim(); + let t = t.strip_prefix(['-', '+']).unwrap_or(t); + let digits = t.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == ',')).unwrap_or(t.len()); + let (number, unit) = t.split_at(digits); + number.chars().any(|c| c.is_ascii_digit()) && unit.trim().chars().all(|c| c.is_alphabetic() || matches!(c, '°' | '"' | '\'')) +} + +/// Insert a reference into the expression, using character offsets (not bytes). The rule: +/// - the field holds a lone value (a number, optionally with a unit: `10`, `10 mm`): the name +/// replaces the whole text, so `10` becomes `d10`; +/// - otherwise (an expression in progress such as `10 + ` or `2 * (`): the name goes in at the +/// cursor, replacing selected text, so `10 + ` becomes `10 + d10`; with no cursor it is +/// appended. Nothing else (spaces, operators) is added. +/// +/// The cursor ends just after the name and the field keeps the keyboard. fn insert_reference(ctx: &egui::Context, edit: &mut Edit, name: &str) { let id = egui::Id::new("sc_dim_edit"); let mut state = egui::TextEdit::load_state(ctx, id).unwrap_or_default(); let len = edit.expr.chars().count(); - let (start, end) = edit - .selection - .or_else(|| state.cursor.char_range()) - .map(|r| { - let a = r.primary.index.0.min(len); - let b = r.secondary.index.0.min(len); - (a.min(b), a.max(b)) - }) - .unwrap_or((len, len)); + let (start, end) = if is_plain_value(&edit.expr) { + (0, len) + } else { + edit.selection + .or_else(|| state.cursor.char_range()) + .map(|r| { + let a = r.primary.index.0.min(len); + let b = r.secondary.index.0.min(len); + (a.min(b), a.max(b)) + }) + .unwrap_or((len, len)) + }; let before: String = edit.expr.chars().take(start).collect(); let after: String = edit.expr.chars().skip(end).collect(); edit.expr = format!("{before}{name}{after}"); @@ -614,17 +642,25 @@ fn insert_reference(ctx: &egui::Context, edit: &mut Edit, name: &str) { } } -/// Consume dimension clicks while editing; only a double-click inserts a reference. +/// Consume dimension clicks while editing: a click on another driving dimension inserts its +/// name at the cursor (replacing selected text), keeping what was typed. The second click of a +/// double-click on the same dimension does not insert it again. pub fn pick_reference(ctx: &egui::Context, pos: Pos2, double: bool) -> bool { EDIT.with(|editor| { let mut editor = editor.borrow_mut(); let Some(edit) = editor.as_mut() else { return false }; let Some(id) = hit(pos) else { return false }; let param = DRAWN.with(|d| d.borrow().iter().find(|d| d.id == id).and_then(|d| d.param.clone())); - if double && let Some(param) = param.filter(|p| p != &edit.param) { - insert_reference(ctx, edit, ¶m); - } // Self references and driven dimensions cannot supply a reference. + if let Some(param) = param.filter(|p| p != &edit.param) { + let now = ctx.input(|i| i.time); + let delay = ctx.options(|o| o.input_options.max_double_click_delay); + let repeat = double && edit.picked.as_ref().is_some_and(|(p, at)| *p == param && now - *at <= delay); + if !repeat { + insert_reference(ctx, edit, ¶m); + edit.picked = Some((param, now)); + } + } edit.fresh = FRESH - 1; true }) @@ -663,7 +699,7 @@ fn edit_box(app: &mut SolveApp, ctx: &egui::Context) { egui::Frame::popup(ui.style()).inner_margin(egui::Margin::symmetric(3, 1)).show(ui, |ui| { ui.set_max_width(popup_width); ui.label(egui::RichText::new(format!("Dimension: {}", e.param)).strong()) - .on_hover_text("Double-click another driving dimension to insert its name"); + .on_hover_text("Click another driving dimension to insert its name"); let r = ui.add(egui::TextEdit::singleline(&mut e.expr).id(id).desired_width(popup_width)); if r.has_focus() { e.selection = egui::TextEdit::load_state(ctx, id).and_then(|s| s.cursor.char_range()); @@ -758,6 +794,16 @@ pub fn drawn() -> Vec<(String, Pos2)> { mod tests { use super::*; + #[test] + fn plain_values_are_numbers_with_an_optional_unit() { + for t in ["10", " 10 mm ", "12.5", "2,5", "-3", "+4", "45 deg", "45°", "1in"] { + assert!(is_plain_value(t), "{t:?}"); + } + for t in ["", "10 + ", "2 * (", "Width - ", "width", "d1", "10 mm + d2", "(10)", "mm", "-"] { + assert!(!is_plain_value(t), "{t:?}"); + } + } + #[test] fn placement_previews_radial_and_angular_dimensions_and_invalidates_on_document_change() { cancel(); diff --git a/crates/ui-egui/src/dimension_create_ui_tests.rs b/crates/ui-egui/src/dimension_create_ui_tests.rs index 6ee556f7c..8ddf53203 100644 --- a/crates/ui-egui/src/dimension_create_ui_tests.rs +++ b/crates/ui-egui/src/dimension_create_ui_tests.rs @@ -66,8 +66,8 @@ fn dimension_editor_names_and_reference_picks_drive_new_and_existing_dimensions( crate::dim_view::cancel(); } -#[test] -fn single_clicking_another_dimension_does_not_change_the_expression() { +/// Two dimensioned lines, editing `d2` with `typed` in its value field. +fn editing_d2(typed: &str) -> Harness { let mut h = line([20., 0.]); h.app.run("sketch.dimension", json!({"entities":["l1"],"value":20,"text_at":[10,8]})).unwrap(); h.app.run("sketch.line", json!({"points":[[0,-10],[12,-10]],"infer":false})).unwrap(); @@ -75,11 +75,79 @@ fn single_clicking_another_dimension_does_not_change_the_expression() { h.settle(); crate::dim_view::edit_param(&h.app, "d2"); h.frames(5); - type_value(&mut h, "8"); + type_value(&mut h, typed); + h +} + +/// Click `d1`, check the editor stays focused, then apply and return d2's expression. +fn click_d1_and_apply(h: &mut Harness) -> String { h.step(&json!({"click":{"dimension":"d1"}})).unwrap(); - assert!(crate::dim_view::editing()); + assert!(crate::dim_view::editing(), "a reference click keeps the editor open"); + h.frames(2); + assert_eq!(h.ctx.memory(|m| m.focused()), Some(egui::Id::new("sc_dim_edit")), "the value field keeps the keyboard"); h.step(&json!({"key":"Enter"})).unwrap(); - assert_eq!(h.app.session.doc.param("d2").unwrap().expr, "8"); + assert!(!crate::dim_view::editing(), "{}", h.call("ui.inspect", json!({}))); + let expr = h.app.session.doc.param("d2").unwrap().expr.clone(); + crate::dim_view::cancel(); + expr +} + +#[test] +fn clicking_another_dimension_appends_its_name_to_the_typed_text() { + for (typed, expected) in [("2 * ", "2 * d1"), ("10 + ", "10 + d1")] { + let mut h = editing_d2(typed); + assert_eq!(click_d1_and_apply(&mut h), expected, "typed {typed:?}"); + } +} + +#[test] +fn clicking_another_dimension_replaces_a_lone_value() { + for typed in ["10", "10 mm", "-3.5"] { + let mut h = editing_d2(typed); + assert_eq!(click_d1_and_apply(&mut h), "d1", "typed {typed:?}"); + } + // The cursor inside the number does not matter: the whole value goes. + let mut h = editing_d2("125"); + h.step(&json!({"key":"Home"})).unwrap(); + h.step(&json!({"key":"ArrowRight"})).unwrap(); + assert_eq!(click_d1_and_apply(&mut h), "d1"); +} + +#[test] +fn clicking_another_dimension_lets_typing_continue_after_its_name() { + let mut h = editing_d2("2 * "); + h.step(&json!({"click":{"dimension":"d1"}})).unwrap(); + h.frames(2); + h.step(&json!({"text":" + 1"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + assert_eq!(h.app.session.doc.param("d2").unwrap().expr, "2 * d1 + 1"); + crate::dim_view::cancel(); +} + +#[test] +fn clicking_another_dimension_inserts_its_name_at_the_cursor() { + let mut h = editing_d2("( ) / 2"); + h.step(&json!({"key":"Home"})).unwrap(); + h.step(&json!({"key":"ArrowRight"})).unwrap(); + h.step(&json!({"key":"ArrowRight"})).unwrap(); + assert_eq!(click_d1_and_apply(&mut h), "( d1) / 2"); +} + +#[test] +fn clicking_another_dimension_replaces_the_selected_text() { + let mut h = editing_d2("5 + 7"); + h.step(&json!({"key":"ArrowLeft","shift":true})).unwrap(); + assert_eq!(click_d1_and_apply(&mut h), "5 + d1"); +} + +#[test] +fn double_clicking_another_dimension_inserts_its_name_once() { + let mut h = editing_d2("3 * "); + // Synthetic input feeds one pointer event per frame, so this is a click and, a frame + // later, a second click that egui reads as a double-click. + h.step(&json!({"click":{"dimension":"d1"},"double":true})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + assert_eq!(h.app.session.doc.param("d2").unwrap().expr, "3 * d1"); crate::dim_view::cancel(); } diff --git a/docs/book/src/guide/parameters.md b/docs/book/src/guide/parameters.md index 369ca6330..6ed4fcc01 100644 --- a/docs/book/src/guide/parameters.md +++ b/docs/book/src/guide/parameters.md @@ -6,10 +6,11 @@ are ones you add yourself, with a unit, an expression and an optional comment. C uses them. When creating or editing a sketch dimension, its value editor shows its model parameter -name (`d1`, `d2`, …). Double-click another driving dimension to insert its name at the cursor, -replacing selected text; add arithmetic such as `/ 2` to build a dependent dimension. -Single clicks on dimensions leave the expression unchanged. Press **Enter** to apply the -expression or **Escape** to cancel the edit. +name (`d1`, `d2`, …). Click another driving dimension to use its name: when the value is +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. Add and edit user parameters through the existing **Change Parameters** command. In the SOLID toolbar's CONFIGURE panel, click **Parameters** to open the user and model From 23b012075982c35672594cef3753324627d6b6e6 Mon Sep 17 00:00:00 2001 From: Jakobonly <149584042+DundreDE@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:40:26 +0000 Subject: [PATCH 06/42] Sketch: a radius dimension past an arc's end extends the arc to its arrow (#3393) (#3408) * claim: #3393 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0158is7fBbAVh538YmVF3MpZ * Sketch: a radius dimension past an arc's end extends the arc to its arrow (#3393) A radius or diameter dimension on an arc whose leader is dragged past the arc's ends had its arrow pointing at empty space. The radial frame now keeps the arc's span, and an arrow outside it gets the arc continued from the nearer end round to the arrow tip and a little past it, as dimension drawings do. Full circles, ellipses and arrows on the arc are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0158is7fBbAVh538YmVF3MpZ --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/sketch_ux_tests.rs | 2 +- crates/sketch/src/dims.rs | 85 +++++++++++++++++++++--- 2 files changed, 75 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/sketch_ux_tests.rs b/crates/engine/src/cmd/sketch_ux_tests.rs index b3d2c040b..da750c193 100644 --- a/crates/engine/src/cmd/sketch_ux_tests.rs +++ b/crates/engine/src/cmd/sketch_ux_tests.rs @@ -60,7 +60,7 @@ fn every_dimension_kind_has_a_drawable_frame() { } for f in [ DimFrame::Linear { p0: Default::default(), p1: Default::default(), dir: Default::default() }, - DimFrame::Radial { center: Default::default(), radius: 1.0, diameter: true }, + DimFrame::Radial { center: Default::default(), radius: 1.0, diameter: true, arc: None }, DimFrame::Angular { vertex: Default::default(), d0: Default::default(), sweep: 1.0 }, DimFrame::ArcLength { center: Default::default(), radius: 1.0, start: 0.0, sweep: 1.0 }, ] { diff --git a/crates/sketch/src/dims.rs b/crates/sketch/src/dims.rs index 7d4acb808..403510d7e 100644 --- a/crates/sketch/src/dims.rs +++ b/crates/sketch/src/dims.rs @@ -19,8 +19,9 @@ pub enum DimFrame { /// The distance from `p0` to `p1` along the unit direction `dir` (aligned, horizontal or /// vertical). Linear { p0: Vec2, p1: Vec2, dir: Vec2 }, - /// Radius or diameter of a circle or arc. - Radial { center: Vec2, radius: f64, diameter: bool }, + /// Radius or diameter of a circle or arc. `arc` is the arc's (start angle, counter-clockwise + /// sweep), None for a full circle: an arrow past the arc's ends gets an extension of the arc. + Radial { center: Vec2, radius: f64, diameter: bool, arc: Option<(f64, f64)> }, /// The angle at `vertex` from the unit ray `d0`, counter-clockwise by `sweep` radians. Angular { vertex: Vec2, d0: Vec2, sweep: f64 }, /// Length along an arc around `center` from angle `start` by `sweep`. @@ -104,11 +105,15 @@ pub fn dim_frame(sk: &Sketch, k: &ConstraintKind) -> Option { DimFrame::Linear { p0, p1, dir: unit(p1 - p0, normal) } } Radius { c, .. } | Diameter { c, .. } => { - let radius = match sk.curves.get(c)?.kind { - CurveKind::Ellipse { r, .. } => r, - _ => sk.radius(c)?, + let (radius, arc) = match sk.curves.get(c)?.kind { + CurveKind::Ellipse { r, .. } => (r, None), + CurveKind::Arc { .. } => match sk.segs(c).first()? { + solidcraft_geom::Seg2::Arc { radius, start, sweep, .. } => (*radius, Some((*start, *sweep))), + _ => return None, + }, + _ => (sk.radius(c)?, None), }; - DimFrame::Radial { center: sk.center(c)?, radius, diameter: matches!(k, Diameter { .. }) } + DimFrame::Radial { center: sk.center(c)?, radius, diameter: matches!(k, Diameter { .. }), arc } } ArcLength { c, .. } => match sk.segs(c).first()? { solidcraft_geom::Seg2::Arc { center, radius, start, sweep } => { @@ -189,6 +194,21 @@ fn arc_pts(c: Vec2, r: f64, a0: f64, sweep: f64) -> Vec { (0..=n).map(|i| c + Vec2::from_angle(a0 + sweep * i as f64 / n as f64) * r).collect() } +/// The arc around `c` from the nearer end of the arc (`start`, counter-clockwise by `sweep`) to +/// angle `at`, and `over` past it; None when `at` lies on the arc. +fn arc_extension(c: Vec2, r: f64, start: f64, sweep: f64, at: f64, over: f64) -> Option> { + if !(r > 0.0 && r.is_finite() && sweep.is_finite() && at.is_finite()) { + return None; + } + let ta = (at - start).rem_euclid(std::f64::consts::TAU); + if ta <= sweep + 1e-9 { + return None; + } + let past = over / r; + let (after_end, before_start) = (ta - sweep, std::f64::consts::TAU - ta); + Some(if after_end <= before_start { arc_pts(c, r, start + sweep, after_end + past) } else { arc_pts(c, r, at - past, before_start + past) }) +} + /// The lines a linear dimension's two extension lines may start from (#1361), for its `p0` and /// `p1` sides: a dimension to a line reaches the nearest part of that line, not the foot of the /// measured point, and a dimension between two parallel lines reaches the nearest part of the @@ -285,12 +305,21 @@ pub fn dim_layout_reaching(f: &DimFrame, text: Option, px: f64, half: Vec2 } } } - DimFrame::Radial { center, radius, diameter } => { + DimFrame::Radial { center, radius, diameter, arc } => { let t = text.unwrap_or_else(|| Vec2::new(1.0, 1.0) * ((radius + 18.0 * px) * std::f64::consts::FRAC_1_SQRT_2)); let u = t.normalized().unwrap_or(Vec2::new(1.0, 1.0) * std::f64::consts::FRAC_1_SQRT_2); let d = t.len(); let at = center + u * radius; out.text = center + t; + // An arrow past the ends of an arc points at the arc's extension (#3393). + if let Some((start, sweep)) = arc { + let tips: &[Vec2] = if diameter { &[u, -u] } else { &[u] }; + for tip in tips { + if let Some(ext) = arc_extension(center, radius, start, sweep, tip.angle(), over) { + out.lines.push(ext); + } + } + } let rim = half.x * u.x.abs() + half.y * u.y.abs() + gap; let from = if diameter { center - u * radius } else { center }; if d > radius { @@ -402,20 +431,54 @@ mod tests { let at = Vec2::new(7.0, 30.0); let enc = encode_text(&f, at); assert!(close(dim_layout(&f, Some(enc), 0.1, Vec2::ZERO).text, at)); - let r = DimFrame::Radial { center: Vec2::new(5.0, 5.0), radius: 3.0, diameter: true }; + let r = DimFrame::Radial { center: Vec2::new(5.0, 5.0), radius: 3.0, diameter: true, arc: None }; assert!(close(dim_layout(&r, Some(encode_text(&r, at)), 0.1, Vec2::ZERO).text, at)); } #[test] fn diameter_has_arrows_on_both_sides() { - let r = DimFrame::Radial { center: Vec2::ZERO, radius: 10.0, diameter: true }; + let r = DimFrame::Radial { center: Vec2::ZERO, radius: 10.0, diameter: true, arc: None }; let l = dim_layout(&r, Some(Vec2::new(20.0, 0.0)), 0.1, Vec2::new(2.0, 1.0)); assert_eq!(l.arrows.len(), 2); assert!(close(l.arrows[0].0, Vec2::new(10.0, 0.0)) && close(l.arrows[1].0, Vec2::new(-10.0, 0.0))); - let r = DimFrame::Radial { center: Vec2::ZERO, radius: 10.0, diameter: false }; + let r = DimFrame::Radial { center: Vec2::ZERO, radius: 10.0, diameter: false, arc: None }; assert_eq!(dim_layout(&r, None, 0.1, Vec2::ZERO).arrows.len(), 1); } + #[test] + fn an_arrow_past_the_end_of_an_arc_points_at_its_extension() { + // #3393: a quarter arc from 0° to 90°; a radius dimension dragged to 135° gets the arc + // continued from its 90° end round to the arrow, and a little past it. + let mut sk = Sketch::new(); + let c = sk.add_arc(Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(0.0, 10.0), [None, None, None], None).unwrap_or(0); + let f = + dim_frame(&sk, &ConstraintKind::Radius { c, value: 10.0 }).unwrap_or(DimFrame::Linear { p0: Vec2::ZERO, p1: Vec2::ZERO, dir: Vec2::X }); + let DimFrame::Radial { arc: Some((start, sweep)), .. } = f else { panic!("an arc's frame keeps its span: {f:?}") }; + assert!(start.abs() < 1e-9 && (sweep - std::f64::consts::FRAC_PI_2).abs() < 1e-9); + let on_circle = |line: &Vec| line.len() > 2 && line.iter().all(|p| (p.len() - 10.0).abs() < 1e-9); + let lay = dim_layout(&f, Some(Vec2::from_angle(0.75 * std::f64::consts::PI) * 20.0), 0.1, Vec2::new(2.0, 1.0)); + let ext: Vec<_> = lay.lines.iter().filter(|l| on_circle(l)).collect(); + assert_eq!(ext.len(), 1, "{:?}", lay.lines); + let (first, last) = (ext[0][0], ext[0][ext[0].len() - 1]); + assert!(first.dist(Vec2::new(0.0, 10.0)) < 1e-9, "starts at the arc's end: {first:?}"); + assert!((last.angle() - (0.75 * std::f64::consts::PI + 0.4 / 10.0)).abs() < 1e-9, "ends just past the arrow: {last:?}"); + // Dragged before the start (at -45°) the extension runs from the arrow to the start. + let lay = dim_layout(&f, Some(Vec2::from_angle(-0.25 * std::f64::consts::PI) * 20.0), 0.1, Vec2::new(2.0, 1.0)); + let ext: Vec<_> = lay.lines.iter().filter(|l| on_circle(l)).collect(); + assert_eq!(ext.len(), 1); + assert!(ext[0][ext[0].len() - 1].dist(Vec2::new(10.0, 0.0)) < 1e-9); + // On the arc, or on a full circle, nothing is added. + let on_arc = dim_layout(&f, Some(Vec2::from_angle(0.25 * std::f64::consts::PI) * 20.0), 0.1, Vec2::new(2.0, 1.0)); + assert!(!on_arc.lines.iter().any(on_circle)); + let circle = DimFrame::Radial { center: Vec2::ZERO, radius: 10.0, diameter: false, arc: None }; + assert!(!dim_layout(&circle, Some(Vec2::new(-20.0, 0.0)), 0.1, Vec2::ZERO).lines.iter().any(on_circle)); + // A diameter of the arc extends towards both arrows. + let DimFrame::Radial { center, radius, arc, .. } = f else { return }; + let dia = DimFrame::Radial { center, radius, diameter: true, arc }; + let lay = dim_layout(&dia, Some(Vec2::from_angle(0.75 * std::f64::consts::PI) * 20.0), 0.1, Vec2::new(2.0, 1.0)); + assert_eq!(lay.lines.iter().filter(|l| on_circle(l)).count(), 2); + } + #[test] fn angle_frame_uses_the_rays_toward_the_lines() { let mut sk = Sketch::new(); @@ -440,7 +503,7 @@ mod tests { let m = sk.add_line(Vec2::new(30.0, -80.0), Vec2::new(30.0, 90.0), None, None, None).unwrap_or(0); let p = sk.curves[m].kind.point_ids()[0]; let k = ConstraintKind::PointLineDistance { p, l, value: 30.0 }; - let f = dim_frame(&sk, &k).unwrap_or(DimFrame::Radial { center: Vec2::ZERO, radius: 1.0, diameter: false }); + let f = dim_frame(&sk, &k).unwrap_or(DimFrame::Radial { center: Vec2::ZERO, radius: 1.0, diameter: false, arc: None }); let reach = dim_reach(&sk, &k); assert!(reach[0].is_some() && reach[1].is_some()); let extension_ys = |at: Vec2| -> Vec<(f64, f64)> { From e29a57dc3a3d3a0c577739cda4f65deeb3b6000d Mon Sep 17 00:00:00 2001 From: rlartot <94693724+rlartot@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:42:39 +0000 Subject: [PATCH 07/42] inspect.interference/clearance: list mesh bodies as unchecked (#3249) (#3258) * claim: #3249 Co-Authored-By: Claude Sonnet 5.5 * inspect.interference/clearance: list mesh bodies as unchecked Mesh bodies (STL, 3MF and OBJ imports) were filtered out before any pair was formed, so two overlapping STL imports reported count 0 and an empty unchecked list, which reads as "no collision". Each mesh body is now listed in `unchecked` as {a: name, b: null, reason: "mesh body: not checked"} by both commands. inspect.clearance also stops refusing a mesh body named in `bodies` or `against` as "no solid body"; it is listed instead. The parameter docs and the assemblies guide say so. Fixes #3249 Co-Authored-By: Claude Sonnet 5.5 * docs: separate the mesh-body note from the paragraph above Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- crates/engine/src/cmd/clearance.rs | 25 ++++++++-- crates/engine/src/cmd/clearance_tests.rs | 51 +++++++++++++++++++++ crates/engine/src/cmd/interference.rs | 10 ++-- crates/engine/src/cmd/interference_tests.rs | 48 +++++++++++++++++++ crates/engine/src/cmd/joints.rs | 2 +- docs/book/src/guide/assemblies.md | 4 ++ 6 files changed, 131 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/clearance.rs b/crates/engine/src/cmd/clearance.rs index 2ef36228f..902005f53 100644 --- a/crates/engine/src/cmd/clearance.rs +++ b/crates/engine/src/cmd/clearance.rs @@ -19,13 +19,13 @@ use crate::params::{bad, num, str_, string_list}; use crate::{Result, Session}; pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.clearance", "Clearance", clearance).icon("interference").noundo().params( - "bodies?: [names] (default: every solid body, in world placement, but those in `against`); against?: [names] (only pairs with one body in `bodies` and the other here); \ + "bodies?: [names] (default: every solid body, in world placement, but those in `against`; mesh bodies are not measured); against?: [names] (only pairs with one body in `bodies` and the other here); \ min_volume?: mm³ (default 0.01: smaller overlaps count as contact); clearance?: mm (default 0: report pairs closer than this); \ nearest?: n (each body of `bodies` gets its n nearest others); skip_within?: \"occurrence\" (pairs of bodies of one occurrence) | \ \"component\" (pairs of bodies inside one placed component, its subcomponents included) | null; tolerance?: mm (default 1e-6: a gap \ below it is contact, 0) → overlaps: [{a, b, volume_mm3, area_mm2, bbox, center}]; near: [{a, b, distance_mm, from, to, overlap_mm3?: \ a contact's shared volume below min_volume, exact?: false when measured on the meshes}], nearest by body (the same for pairs that overlap: 0); \ - nearest: {body: [{body, distance_mm}]}; unchecked: [{a, b, reason}] (pairs whose overlap could not be worked out); pairs_checked; \ + nearest: {body: [{body, distance_mm}]}; unchecked: [{a, b, reason}] (pairs whose overlap could not be worked out; each mesh body, STL/3MF/OBJ import, is not measured and is listed as {a: name, b: null, reason: \"mesh body: not checked\"}, also when named in `bodies` or `against`; the result's `bodies` counts the solid bodies only); pairs_checked; \ pairs_reused (of those, measured by an earlier call: neither body changed or moved since); pairs_pruned (ruled out by their boxes); ms. Distances are measured on the exact faces and edges, the meshes only rule pairs out", )]; @@ -92,12 +92,19 @@ fn clearance(s: &mut Session, p: &Value) -> Result { }; let st = s.world_state(); - let solid: Vec<&solidcraft_doc::ModelBody> = st.bodies.iter().filter(|b| !b.body.is_mesh()).collect(); + let (mesh_bodies, solid): (Vec<&solidcraft_doc::ModelBody>, Vec<&solidcraft_doc::ModelBody>) = st.bodies.iter().partition(|b| b.body.is_mesh()); + // Mesh bodies are not measured. A mesh body named in `bodies` or `against` is left out of the + // pairs and listed as unchecked, rather than refused as "no solid body". let named = |key: &str| -> Result> { let names = string_list(p, key); let mut out = Vec::new(); for n in &names { - let i = solid.iter().position(|b| &b.name == n).ok_or_else(|| bad(cmd, format!("no solid body `{n}`")))?; + let Some(i) = solid.iter().position(|b| &b.name == n) else { + if mesh_bodies.iter().any(|b| &b.name == n) { + continue; + } + return Err(bad(cmd, format!("no solid body `{n}`"))); + }; if !out.contains(&i) { out.push(i); } @@ -249,7 +256,15 @@ fn clearance(s: &mut Session, p: &Value) -> Result { let results = results.into_iter().map(|r| r.unwrap_or_else(|| Ok(PairResult::default()))); let mut known: HashMap<(usize, usize), f64> = HashMap::new(); - let (mut overlaps, mut near, mut unchecked) = (Vec::new(), Vec::new(), Vec::new()); + let (mut overlaps, mut near) = (Vec::new(), Vec::new()); + // The mesh bodies the call was about (every one without `bodies`, else those named in + // `bodies` or `against`) come first, so "nothing found" is not read as "no overlap". + let asked: Vec = ["bodies", "against"].iter().flat_map(|k| string_list(p, k)).collect(); + let mut unchecked: Vec = mesh_bodies + .iter() + .filter(|b| p.get("bodies").is_none_or(Value::is_null) || asked.contains(&b.name)) + .map(|b| json!({"a": b.name, "b": null, "reason": super::interference::MESH_NOT_CHECKED})) + .collect(); let name = |i: usize| solid.get(i).map_or("", |b| b.name.as_str()); for (&(i, j), r) in close.iter().zip(results) { let r = match r { diff --git a/crates/engine/src/cmd/clearance_tests.rs b/crates/engine/src/cmd/clearance_tests.rs index 16bc3fda7..5cfa44b66 100644 --- a/crates/engine/src/cmd/clearance_tests.rs +++ b/crates/engine/src/cmd/clearance_tests.rs @@ -474,6 +474,57 @@ fn a_roller_pressed_into_a_large_plate_is_reported() { assert!((f(&overlaps[0]["volume_mm3"]) - want).abs() < 0.01 * want, "{want} {res}"); } +/// Two STL copies of a cube inserted into a design. Returns the names of the two mesh bodies. +fn insert_two_mesh_cubes(s: &mut Session, tag: &str) -> Vec { + let dir = std::env::temp_dir().join(format!("solidcraft-mesh-unchecked-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let stl = dir.join("cube.stl"); + let mut cube = Session::default(); + run(&mut cube, "solid.box", json!({"length": 20, "width": 20, "height": 20, "corner": [0, 0, 0], "body_name": "Cube"})); + run(&mut cube, "file.export", json!({"path": stl.to_string_lossy()})); + for _ in 0..2 { + run(s, "file.insert_mesh", json!({"path": stl.to_string_lossy()})); + } + let _ = std::fs::remove_dir_all(&dir); + s.world_state().bodies.iter().filter(|b| b.body.is_mesh()).map(|b| b.name.clone()).collect() +} + +/// #3249: mesh bodies are not measured, and used to vanish from the answer (`bodies: 0`, nothing +/// unchecked). They are listed in `unchecked` with a reason, and naming one in `bodies` or +/// `against` is not "no solid body". +#[test] +fn mesh_bodies_are_listed_as_unchecked_and_can_be_named() { + let mut s = Session::default(); + let meshes = insert_two_mesh_cubes(&mut s, "clearance"); + assert_eq!(meshes.len(), 2, "{meshes:?}"); + let r = run(&mut s, "inspect.clearance", json!({"clearance": 1})); + assert_eq!((r["bodies"].as_u64(), r["pairs_checked"].as_u64()), (Some(0), Some(0)), "{r}"); + let unchecked = r["unchecked"].as_array().cloned().unwrap_or_default(); + assert_eq!(unchecked.len(), 2, "{r}"); + for (u, name) in unchecked.iter().zip(&meshes) { + assert_eq!(u["a"].as_str(), Some(name.as_str()), "{r}"); + assert!(u["b"].is_null(), "{r}"); + assert_eq!(u["reason"], "mesh body: not checked", "{r}"); + } + // Beside solid bodies: those are measured, the meshes are still listed. + cube(&mut s, "A", 10.0, [100.0, 0.0, 0.0]); + cube(&mut s, "B", 10.0, [105.0, 0.0, 0.0]); + let r = run(&mut s, "inspect.clearance", json!({})); + assert_eq!(r["bodies"], 2, "{r}"); + assert_eq!(r["overlaps"].as_array().map(Vec::len), Some(1), "{r}"); + assert_eq!(r["unchecked"].as_array().map(Vec::len), Some(2), "{r}"); + // A mesh body named in `bodies` or `against` is listed, not refused; an unknown name still is. + for params in [json!({"bodies": ["A", meshes[0]]}), json!({"bodies": ["A"], "against": [meshes[0]]})] { + let r = run(&mut s, "inspect.clearance", params.clone()); + let unchecked = r["unchecked"].as_array().cloned().unwrap_or_default(); + assert_eq!(unchecked.len(), 1, "{params}: {r}"); + assert_eq!(unchecked[0]["a"].as_str(), Some(meshes[0].as_str()), "{params}: {r}"); + } + let e = s.execute("inspect.clearance", &json!({"bodies": ["Nope"]})).unwrap_err().to_string(); + assert!(e.contains("`Nope`"), "{e}"); +} + /// A pin turned from a profile (its wall in three faces) in the bore of a tube of its own size /// (in two faces), its end inside the bore, a hair off the axis, and a slit tube with the pin /// through it: touching, not overlapping. Their facets cross where one body's faces end on the diff --git a/crates/engine/src/cmd/interference.rs b/crates/engine/src/cmd/interference.rs index 06c5c1bfc..43781bb66 100644 --- a/crates/engine/src/cmd/interference.rs +++ b/crates/engine/src/cmd/interference.rs @@ -31,6 +31,8 @@ const MAX_BUDGET_S: f64 = 86_400.0; /// How many chord tolerances apart (of both meshes together) two meshes must be to clear a pair /// without intersecting it: twice what the tolerances allow, for meshers that sag a little more. const MESH_MARGIN: f64 = 4.0; +/// Why a mesh body is listed under `unchecked` (here and in `inspect.clearance`). +pub(super) const MESH_NOT_CHECKED: &str = "mesh body: not checked"; /// Most pairs listed under `slowest`. const SLOWEST: usize = 8; @@ -73,8 +75,8 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result { let budget = std::time::Duration::from_secs_f64(budget_s); let want = string_list(p, "bodies"); let st = s.world_state(); - let bodies: Vec<&solidcraft_doc::ModelBody> = - st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).filter(|b| !b.body.is_mesh()).collect(); + let (meshes_left, bodies): (Vec<&solidcraft_doc::ModelBody>, Vec<&solidcraft_doc::ModelBody>) = + st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).partition(|b| b.body.is_mesh()); // The bodies' display meshes, made once (in parallel) and kept on the bodies: a design open // in the app has them already. @@ -152,7 +154,9 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result { let (done, threads) = run_jobs(jobs, left); let waited_ms = waited.elapsed().as_secs_f64() * 1000.0; - let (mut hits, mut unchecked, mut timed) = (Vec::new(), Vec::new(), Vec::new()); + // Mesh bodies are not intersected: say so, rather than let `count: 0` read as "no overlap". + let mut unchecked: Vec = meshes_left.iter().map(|b| json!({"a": b.name, "b": null, "reason": MESH_NOT_CHECKED})).collect(); + let (mut hits, mut timed) = (Vec::new(), Vec::new()); let (mut not_checked, mut boolean_ms, mut tessellate_ms) = (0usize, 0.0, 0.0); for ((a, b), d) in done { let Some(d) = d else { diff --git a/crates/engine/src/cmd/interference_tests.rs b/crates/engine/src/cmd/interference_tests.rs index 9d65ee89a..2be9c0383 100644 --- a/crates/engine/src/cmd/interference_tests.rs +++ b/crates/engine/src/cmd/interference_tests.rs @@ -108,3 +108,51 @@ fn pairs_left_when_the_budget_runs_out_are_listed_not_checked() { assert!(s.execute("inspect.interference", &json!({"budget_s": bad})).is_err(), "{bad}"); } } + +/// Two STL copies of a cube inserted into a design. Returns the names of the two mesh bodies. +pub(super) fn insert_two_mesh_cubes(s: &mut Session, tag: &str) -> Vec { + let dir = std::env::temp_dir().join(format!("solidcraft-mesh-unchecked-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let stl = dir.join("cube.stl"); + let mut cube = Session::default(); + run(&mut cube, "solid.box", json!({"length": 20, "width": 20, "height": 20, "corner": [0, 0, 0], "body_name": "Cube"})); + run(&mut cube, "file.export", json!({"path": stl.to_string_lossy()})); + for _ in 0..2 { + run(s, "file.insert_mesh", json!({"path": stl.to_string_lossy()})); + } + let _ = std::fs::remove_dir_all(&dir); + s.world_state().bodies.iter().filter(|b| b.body.is_mesh()).map(|b| b.name.clone()).collect() +} + +/// #3249: mesh bodies (STL, 3MF, OBJ imports) are not intersected, but they used to vanish from +/// the answer: `count: 0, unchecked: []` read as "no collision". Each is now listed in `unchecked` +/// with a reason, and the solid bodies are checked as before. +#[test] +fn mesh_bodies_are_listed_as_unchecked_not_dropped() { + let mut s = Session::default(); + let meshes = insert_two_mesh_cubes(&mut s, "interference"); + assert_eq!(meshes.len(), 2, "{meshes:?}"); + // Only meshes: nothing is checked, and both are said to be left out. + let i = run(&mut s, "inspect.interference", json!({})); + assert_eq!((i["count"].as_u64(), i["checked"].as_u64()), (Some(0), Some(0)), "{i}"); + let unchecked = i["unchecked"].as_array().cloned().unwrap_or_default(); + assert_eq!(unchecked.len(), 2, "{i}"); + for (u, name) in unchecked.iter().zip(&meshes) { + assert_eq!(u["a"].as_str(), Some(name.as_str()), "{i}"); + assert!(u["b"].is_null(), "{i}"); + assert_eq!(u["reason"], "mesh body: not checked", "{i}"); + } + // With solid bodies beside them: those are checked, the meshes are still listed. + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [100, 0, 0], "operation": "new", "body_name": "A"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [105, 0, 0], "operation": "new", "body_name": "B"})); + let i = run(&mut s, "inspect.interference", json!({})); + assert_eq!((i["count"].as_u64(), i["checked"].as_u64()), (Some(1), Some(2)), "{i}"); + assert_eq!(i["unchecked"].as_array().map(Vec::len), Some(2), "{i}"); + // Naming only solid bodies lists no mesh; naming a mesh body lists just that one. + let i = run(&mut s, "inspect.interference", json!({"bodies": ["A", "B"]})); + assert_eq!(i["unchecked"].as_array().map(Vec::len), Some(0), "{i}"); + let i = run(&mut s, "inspect.interference", json!({"bodies": ["A", meshes[0]]})); + assert_eq!(i["checked"], 1, "{i}"); + assert_eq!(i["unchecked"][0]["a"].as_str(), Some(meshes[0].as_str()), "{i}"); +} diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index bac77a780..9917c5dd2 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -94,7 +94,7 @@ pub static COMMANDS: &[CommandSpec] = &[ ), CommandSpec::new("joint.solve", "Solve Joints", solve_cmd).icon("compute").params("re-place the occurrences from the joints → conflicts, errors, dof"), CommandSpec::new("inspect.interference", "Interference", super::interference::interference).at("SOLID", "INSPECT").icon("interference").noundo().params( - "bodies?: [names] (default: all, in world placement); budget_s?: seconds (default 240, at most 86400: pairs not finished by then are listed in unchecked as \"not checked: the time budget … ran out\" and the call returns) → interferences: pairs that overlap with the overlap volume, area, bounding box and centre (a pin a hair off the axis of a hole of its size also has near_coaxial: {offset_mm, length_mm}, its volume the crescent the walls share); unchecked: pairs that could not be checked, with the reason. Bodies are pruned by bounding box first, then by their display meshes (pairs whose meshes stay apart by more than their chord tolerances, neither inside the other, are clear without a boolean), so any number of bodies is fine; the pairs left are intersected exactly, in parallel on desktop, the slowest first; at most 20000 pairs whose boxes overlap are intersected per call (truncated: true and skipped_pairs: n say when more were left out). Also: pairs_candidate (boxes overlap), pairs_cleared (by the meshes), pairs_intersected, pairs_not_checked, budget_exceeded, threads (worker threads; 0: on the calling thread), boolean_ms and tessellate_ms (kernel time summed over the pairs), slowest: [{a, b, ms, boolean_ms, tessellate_ms}] and ms", + "bodies?: [names] (default: all, in world placement); budget_s?: seconds (default 240, at most 86400: pairs not finished by then are listed in unchecked as \"not checked: the time budget … ran out\" and the call returns) → interferences: pairs that overlap with the overlap volume, area, bounding box and centre (a pin a hair off the axis of a hole of its size also has near_coaxial: {offset_mm, length_mm}, its volume the crescent the walls share); unchecked: [{a, b, reason}], the pairs that could not be checked, with the reason, and each mesh body (STL, 3MF or OBJ import: not intersected) as {a: name, b: null, reason: \"mesh body: not checked\"}, so count: 0 is not read as no overlap (checked counts the solid bodies). Bodies are pruned by bounding box first, then by their display meshes (pairs whose meshes stay apart by more than their chord tolerances, neither inside the other, are clear without a boolean), so any number of bodies is fine; the pairs left are intersected exactly, in parallel on desktop, the slowest first; at most 20000 pairs whose boxes overlap are intersected per call (truncated: true and skipped_pairs: n say when more were left out). Also: pairs_candidate (boxes overlap), pairs_cleared (by the meshes), pairs_intersected, pairs_not_checked, budget_exceeded, threads (worker threads; 0: on the calling thread), boolean_ms and tessellate_ms (kernel time summed over the pairs), slowest: [{a, b, ms, boolean_ms, tessellate_ms}] and ms", ), ]; diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index e7888b56d..f7a5a0452 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -89,6 +89,10 @@ pairs whose meshes stay apart without intersecting them, intersects the rest in returns after `budget_s` seconds (default 240) at most, listing the pairs it had no time for as not checked. +Mesh bodies (STL, 3MF and OBJ imports) are not checked by either command: each is listed in +`unchecked` as `{a: name, b: null, reason: "mesh body: not checked"}`, so `count: 0` or an empty +`overlaps` is not mistaken for "no overlap" when a mesh body was in the design. + **Gear**, **Rack and Pinion** and **Screw** (on the **ASSEMBLE** panel) are motion links whose ratio comes from the parts rather than a typed number: From 26685180792180d20b672dc8204236e821823567 Mon Sep 17 00:00:00 2001 From: kaltenbrunnermarkus <153593707+kaltenbrunnermarkus@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:54:04 +0000 Subject: [PATCH 08/42] Section Analysis: dragging the cut stays smooth on large parts (#3616) On an imported part with 2.5 million triangles, every frame of a Section Analysis drag looked up the picked face's plane several times (each lookup tessellates the whole body, about 0.1 s) and cut every triangle again for the outline (38 ms). - planar_face keeps its last answers for the model state they were found in. - The outline cuts through a SectionIndex: the mesh's triangles sorted into slabs along the cut's normal, kept per mesh while the normal stays, so a cut looks at one slab (0.06 ms on that part) and finds the same segments. Co-authored-by: Claude Opus 5.5 --- crates/engine/src/tests.rs | 25 ++++++++ crates/engine/src/view.rs | 105 +++++++++++++++++++++++++++++---- crates/ui-egui/src/dialogs.rs | 69 ++++++++++++++++++++-- crates/ui-egui/src/viewport.rs | 16 ++++- 4 files changed, 196 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3ede07560..7c5e24363 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1543,6 +1543,31 @@ fn section_analysis() { assert_eq!(s.undo.len(), undo); } +/// A section index finds the same cut segments, in the same order, as cutting every triangle: +/// tilted and axis normals, cuts through vertices, at the ends and beyond the part. +#[test] +fn section_index_cuts_like_every_triangle() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 12, "height": 30})); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 8, "operation": "join"})); + let st = s.model.state(); + let m = st.bodies.first().unwrap().mesh(); + assert!(m.triangles.len() > 64, "enough triangles for several slabs: {}", m.triangles.len()); + for n in [Vec3::Z, -Vec3::Y, Vec3::new(1.0, 2.0, 3.0).normalized().unwrap(), Vec3::new(-0.3, 0.1, 0.9).normalized().unwrap()] { + let index = view::SectionIndex::new(&m, n); + let heights: Vec = m.positions.iter().map(|p| n.dot(*p)).collect(); + let (lo, hi) = heights.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), h| (a.min(*h), b.max(*h))); + let mut cuts: Vec = (0..=40).map(|k| lo - 1.0 + (hi - lo + 2.0) * k as f64 / 40.0).collect(); + cuts.extend(heights.iter().step_by(7).copied()); + cuts.extend([lo, hi]); + for at in cuts { + let o = n * at; + let segments = view::section_segments(&m, o, n); + assert_eq!(index.segments(&m, o), segments, "{n:?} at {at}"); + } + } +} + /// Press Pull: positive pulls a face out, negative pushes it in (a cut), edges get a fillet. #[test] fn press_pull() { diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 4ce7ec792..64863cc01 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -544,25 +544,104 @@ fn build_scene( /// Where the plane through `o` with normal `n` cuts a mesh: one segment per crossed triangle, /// nudged a hair to the kept side (so the clip leaves them drawn). pub fn section_segments(m: &solidcraft_geom::Mesh, o: Vec3, n: Vec3) -> Vec<(Vec3, Vec3)> { - let eps = 1e-4 * (1.0 + m.bounds().diagonal()); + let eps = section_nudge(m); let mut out = Vec::new(); for t in &m.triangles { - let Some(p) = m.tri(t) else { continue }; - let d = p.map(|q| n.dot(q - o)); - let mut pts = Vec::with_capacity(2); - for (i, j) in [(0, 1), (1, 2), (2, 0)] { - if (d[i] < 0.0) != (d[j] < 0.0) { - let s = d[i] / (d[i] - d[j]); - pts.push(p[i] + (p[j] - p[i]) * s - n * eps); - } - } - if let [a, b] = pts[..] { - out.push((a, b)); - } + cut_triangle(m, t, o, n, eps, &mut out); } out } +/// How far [`section_segments`] nudges the cut to the kept side. +fn section_nudge(m: &solidcraft_geom::Mesh) -> f64 { + 1e-4 * (1.0 + m.bounds().diagonal()) +} + +/// The segment where the plane through `o` with normal `n` crosses triangle `t`, if it does. +fn cut_triangle(m: &solidcraft_geom::Mesh, t: &[u32; 3], o: Vec3, n: Vec3, eps: f64, out: &mut Vec<(Vec3, Vec3)>) { + let Some(p) = m.tri(t) else { return }; + let d = p.map(|q| n.dot(q - o)); + let mut pts = Vec::with_capacity(2); + for (i, j) in [(0, 1), (1, 2), (2, 0)] { + if (d[i] < 0.0) != (d[j] < 0.0) { + let s = d[i] / (d[i] - d[j]); + pts.push(p[i] + (p[j] - p[i]) * s - n * eps); + } + } + if let [a, b] = pts[..] { + out.push((a, b)); + } +} + +/// A mesh's triangles sorted into slabs along one normal, so cuts with that normal at any +/// height look only at the triangles of one slab: dragging a Section Analysis keeps the normal +/// and moves the cut, and an imported part can have millions of triangles. The same segments +/// as [`section_segments`]. +pub struct SectionIndex { + normal: Vec3, + /// The lowest height (`normal · p`) of the mesh, and the slab thickness. + start: f64, + step: f64, + /// Per slab, the triangles whose heights reach into it. + slabs: Vec>, + eps: f64, +} + +/// Slabs a [`SectionIndex`] makes, at most. +const SECTION_SLABS: usize = 4096; + +impl SectionIndex { + pub fn new(m: &solidcraft_geom::Mesh, normal: Vec3) -> SectionIndex { + let heights: Vec> = m + .triangles + .iter() + .map(|t| { + let d = m.tri(t)?.map(|q| normal.dot(q)); + Some((d[0].min(d[1]).min(d[2]), d[0].max(d[1]).max(d[2]))) + }) + .collect(); + let (lo, hi) = heights.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), (l, h)| (a.min(*l), b.max(*h))); + let count = if lo.is_finite() && hi.is_finite() { (m.triangles.len() / 64).clamp(1, SECTION_SLABS) } else { 0 }; + let step = if count > 0 && hi > lo { (hi - lo) / count as f64 } else { 1.0 }; + let mut index = SectionIndex { normal, start: lo, step, slabs: vec![Vec::new(); count], eps: section_nudge(m) }; + for (i, h) in heights.iter().enumerate() { + let (Some((l, h)), Ok(i)) = (h, u32::try_from(i)) else { continue }; + for k in index.slab(*l)..=index.slab(*h) { + if let Some(slab) = index.slabs.get_mut(k) { + slab.push(i); + } + } + } + index + } + + /// The normal this index was made for. + pub fn normal(&self) -> Vec3 { + self.normal + } + + fn slab(&self, height: f64) -> usize { + let k = ((height - self.start) / self.step).floor(); + if k.is_finite() { (k.max(0.0) as usize).min(self.slabs.len().saturating_sub(1)) } else { 0 } + } + + /// [`section_segments`] of `m` (the mesh this index was made from) at the plane through + /// `o` with this index's normal. + pub fn segments(&self, m: &solidcraft_geom::Mesh, o: Vec3) -> Vec<(Vec3, Vec3)> { + let mut out = Vec::new(); + let at = self.normal.dot(o); + if self.slabs.is_empty() || !at.is_finite() || at < self.start { + return out; + } + for i in self.slabs.get(self.slab(at)).into_iter().flatten() { + if let Some(t) = m.triangles.get(*i as usize) { + cut_triangle(m, t, o, self.normal, self.eps, &mut out); + } + } + out + } +} + /// Is a sketch drawn? The active one is; others unless hidden. Finished sketches are hidden /// once a feature uses them, by default, unless shown one by one. pub fn sketch_shown(s: &Session, id: u64) -> bool { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 5e874f3de..911dbea68 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1391,6 +1391,36 @@ pub(crate) fn take_snap_work() -> (usize, usize) { mod face_snap_tests { use super::*; + /// A planar face's plane is found once per model state: an open Section Analysis on a face + /// asks for it several times a frame, and each lookup tessellates the body. + #[test] + fn a_planar_face_is_looked_up_once_per_model_state() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":40,"width":30,"height":20})).unwrap(); + let top = |s: &Session| { + let st = s.world_state(); + let b = st.bodies.first().unwrap(); + let faces = b.body.faces(1e-3).unwrap(); + let f = faces.iter().max_by(|a, b| a.centroid.z.total_cmp(&b.centroid.z)).unwrap(); + (b.name.clone(), f.index) + }; + let (body, face) = top(&s); + take_snap_work(); + let first = planar_face(&s, &body, face).expect("the top face is planar"); + for _ in 0..5 { + assert_eq!(planar_face(&s, &body, face), Some(first)); + } + assert_eq!(take_snap_work().0, 1, "the same model state looks the face up once"); + assert!((first.0.z - 20.0).abs() < 1e-9 && (first.1 - Vec3::Z).len() < 1e-9, "{first:?}"); + + // A changed model is looked at again. + s.execute("solid.box", &json!({"length":10,"width":10,"height":50,"operation":"join"})).unwrap(); + let (body, face) = top(&s); + let again = planar_face(&s, &body, face).expect("the new top face is planar"); + assert_eq!(take_snap_work().0, 1); + assert!((again.0.z - 50.0).abs() < 1e-9, "{again:?}"); + } + #[test] fn a_point_more_than_a_micrometre_off_a_sliver_is_off_the_face() { // A triangle with half-micrometre legs. Points 2 µm below its lower side and 1.6 µm past @@ -1443,13 +1473,42 @@ fn profiles_used(s: &Session, sketch: u64) -> bool { /// The plane of a planar body face: (point on it, unit normal). pub fn planar_face(s: &Session, body: &str, face: usize) -> Option<(Vec3, Vec3)> { + let st = s.world_state(); + let known = FACE_PLANES.with(|c| { + let c = c.borrow(); + c.0.as_ref().filter(|k| std::sync::Arc::ptr_eq(k, &st)).and_then(|_| c.1.iter().find(|(b, f, _)| b == body && *f == face).map(|x| x.2)) + }); + if let Some(found) = known { + return found; + } #[cfg(test)] SNAP_WORK.with(|w| w.set((w.get().0 + 1, w.get().1))); - let st = s.world_state(); - let b = st.body(body)?; - let tol = (b.body.size() * 1e-3).max(1e-3); - let f = b.body.faces(tol).ok()?.into_iter().find(|f| f.index == face)?; - Some((f.centroid, f.plane_normal?)) + let found = st.body(body).and_then(|b| { + let tol = (b.body.size() * 1e-3).max(1e-3); + let f = b.body.faces(tol).ok()?.into_iter().find(|f| f.index == face)?; + Some((f.centroid, f.plane_normal?)) + }); + FACE_PLANES.with(|c| { + let mut c = c.borrow_mut(); + if !c.0.as_ref().is_some_and(|k| std::sync::Arc::ptr_eq(k, &st)) { + *c = (Some(st.clone()), Vec::new()); + } + if c.1.len() >= 8 { + c.1.remove(0); + } + c.1.push((body.to_string(), face, found)); + }); + found +} + +thread_local! { + /// The planar faces looked up last, with the model state they were found in (kept, so the + /// pointer stays its own). Each lookup tessellates the whole body, about 0.1 s for an + /// imported part of a few million triangles, and an open Section Analysis on a face asks + /// for its plane several times a frame. + #[allow(clippy::type_complexity)] + static FACE_PLANES: std::cell::RefCell<(Option>, Vec<(String, usize, Option<(Vec3, Vec3)>)>)> = + const { std::cell::RefCell::new((None, Vec::new())) }; } fn polyline_mid(pts: &[Vec3]) -> Vec3 { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 61d18726f..1a8942798 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -62,6 +62,9 @@ pub struct ViewportState { lod_view: u64, /// Each body mesh's box (the mesh held, so its address stays its own), from the last state. mesh_bounds: std::sync::Mutex, solidcraft_engine::geom::Aabb3)>>, + /// Each shown body mesh's section index for the cut's normal (the mesh held, so its address + /// stays its own): a Section Analysis dragged along its normal cuts through it. + section_index: std::sync::Mutex, std::sync::Arc)>>, /// Each body mesh's picking index (made the first time a pick reaches the body), kept while /// the mesh is part of the world state. pub(crate) pick_index: crate::pick_index::PickIndexes, @@ -711,10 +714,21 @@ fn build_scene(app: &SolveApp) -> GpuScene { // Section: the outline of each body where the plane cuts it. if let Some((o, n)) = section_plane(app) { let col = c4(tk.text.gamma_multiply(0.9)); + let mut kept = app.viewport.section_index.lock().map(|mut k| std::mem::take(&mut *k)).unwrap_or_default(); + let mut made = Vec::new(); for b in st.bodies.iter().filter(|b| app.session.body_visible(&b.name)) { - for (a, c) in solidcraft_engine::view::section_segments(&b.mesh(), o, n) { + let mesh = b.mesh(); + let index = match kept.iter().position(|(m, i)| std::sync::Arc::ptr_eq(m, &mesh) && i.normal() == n) { + Some(k) => kept.swap_remove(k).1, + None => std::sync::Arc::new(solidcraft_engine::view::SectionIndex::new(&mesh, n)), + }; + for (a, c) in index.segments(&mesh, o) { sc.line(a.to_f32(), c.to_f32(), col, 1.8, false); } + made.push((mesh, index)); + } + if let Ok(mut k) = app.viewport.section_index.lock() { + *k = made; } } // Continuity analysis: each seam `inspect.continuity` measured, drawn over the model in the From 59cd55f53135470875d5359f7307f7a4909ddf05 Mon Sep 17 00:00:00 2001 From: Colin Faulkingham Date: Tue, 20 Oct 2026 15:55:58 +0000 Subject: [PATCH 09/42] Sketch: keep three-point arcs attached to the through point (#2166) (#3610) * claim: #2166 * Fix three-point arc through-point attachments (#2166) --- crates/engine/src/cmd/sketch.rs | 14 +++-- crates/engine/src/cmd/sketch_modify_tests.rs | 54 ++++++++++++++++++++ crates/ui-egui/src/sketch_corner_ui_tests.rs | 26 ++++++++++ crates/ui-egui/src/tools.rs | 2 +- 4 files changed, 90 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 5d9170243..77c1b4f7f 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -78,7 +78,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("circle3") .enabled(in_sketch) .params(concat!("p0, p1, p2", connect_doc!(), created_doc!())), - CommandSpec::new("sketch.arc.three_point", "3-Point Arc", arc_three).at("SKETCH", "CREATE").icon("arc3").enabled(in_sketch).params(concat!("start, end, through", connect_doc!(), created_doc!())), + CommandSpec::new("sketch.arc.three_point", "3-Point Arc", arc_three).at("SKETCH", "CREATE").icon("arc3").enabled(in_sketch).params(concat!("start, end, through: [x,y] or point ref (a referenced through point stays on the arc)", connect_doc!(), created_doc!())), CommandSpec::new("sketch.arc.center_point", "Center Point Arc", arc_center) .at("SKETCH", "CREATE") .icon("arc_center") @@ -1193,18 +1193,22 @@ fn arc_three(s: &mut Session, p: &Value) -> Result { let id = str_(p, "id").map(str::to_string); let (out, info) = draw(s, p, cmd, |sk, doc| { let (a, b) = (req_parg(sk, doc, p, "start", cmd)?, req_parg(sk, doc, p, "end", cmd)?); - let t = req_vec2(cmd, p, "through")?; - let (o, _) = circumcircle(a.pos(), t, b.pos()).ok_or_else(|| bad(cmd, "the points are collinear"))?; + let t = req_parg(sk, doc, p, "through", cmd)?; + let (o, _) = circumcircle(a.pos(), t.pos(), b.pos()).ok_or_else(|| bad(cmd, "the points are collinear"))?; // Counter-clockwise from start to end must pass the through point; otherwise swap. let ang = |q: Vec2| (q - o).angle(); let ccw_span = |from: f64, to: f64| (to - from).rem_euclid(std::f64::consts::TAU); - let ccw = ccw_span(ang(a.pos()), ang(t)) < ccw_span(ang(a.pos()), ang(b.pos())); + let ccw = ccw_span(ang(a.pos()), ang(t.pos())) < ccw_span(ang(a.pos()), ang(b.pos())); let (s0, e0) = if ccw { (a, b) } else { (b, a) }; let ci = sk.add_arc(o, s0.pos(), e0.pos(), [None, s0.idx(), e0.idx()], id.as_deref())?; if let Some(c) = sk.curves.get_mut(ci) { c.reversed = !ccw; } - Ok((ids_of(sk, &[ci]), Vec::new())) + let mut cons = Vec::new(); + if let Some(point) = t.idx() { + cons.push(add_c(sk, ConstraintKind::PointOnCurve { p: point, 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 b8a1f21b3..a65fbf258 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -337,6 +337,60 @@ fn a_tangent_arc_starts_from_a_trimmed_end() { ); } +#[test] +fn three_point_arc_keeps_referenced_through_points_when_dimensions_change() { + for (through, scale) in [(json!("height.end"), 1.0), (json!({"ref":"height.end"}), 1.0), (json!("mid:height"), 2.0)] { + for reverse in [false, true] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[-20,0],[20,0]],"ids":["base"]})); + run(&mut s, "sketch.constraint.fix", json!({"entity":"base"})); + run(&mut s, "sketch.line", json!({"points":["origin",[0,10.0 * scale]],"ids":["height"],"infer":true})); + let dim = run(&mut s, "sketch.dimension", json!({"entities":["height"],"value":10.0 * scale})); + let before = s.doc.to_json(); + let (start, end) = if reverse { ("base.end", "base.start") } else { ("base.start", "base.end") }; + let out = run(&mut s, "sketch.arc.three_point", json!({"start":start,"end":end,"through":through,"id":"arc"})); + let sk = sketch(&s); + let arc = sk.curve_index("arc").unwrap(); + let constraint = sk.constraints.iter().find(|k| matches!(k.kind, ConstraintKind::PointOnCurve { c, .. } if c == arc)).unwrap(); + assert!(ids(&out["created"]["constraints"]).contains(&constraint.id), "{out}"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before, "the arc and its attachment are one undo step"); + run(&mut s, "edit.redo", json!({})); + run(&mut s, "parameters.change", json!({"name":dim["param"],"expression":format!("{} mm", 15.0 * scale)})); + + let sid = s.active_sketch.unwrap(); + // Saving and reopening preserves the ordinary point-on-curve constraint too. + let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + for session in [&s, &reopened] { + let state = session.model.state(); + let ss = state.sketch(sid).unwrap(); + let sk = &ss.sketch; + let arc = sk.curve_index("arc").unwrap(); + assert!(ss.report.ok(), "{:?}", ss.report); + assert!(close(sk.radius(arc).unwrap(), 125.0 / 6.0), "{:?}", sk.radius(arc)); + let shape = sk.shape(arc).unwrap(); + for point in [Vec2::new(-20.0, 0.0), Vec2::new(20.0, 0.0), Vec2::new(0.0, 15.0)] { + assert!(shape.dist(point) < 1e-6, "{through}, reverse={reverse}: {point:?}"); + } + } + } + } +} + +#[test] +fn three_point_arc_coordinates_stay_free_and_invalid_references_are_atomic() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":["origin",[0,10]],"ids":["height"]})); + let out = run(&mut s, "sketch.arc.three_point", json!({"start":[-20,0],"end":[20,0],"through":[0,10],"id":"arc","connect":false})); + assert!(ids(&out["created"]["constraints"]).is_empty(), "coordinates must not fix the arc or attach it to a nearby point"); + let before = s.doc.to_json(); + for through in [json!("missing.end"), json!({"ref":"missing.end"}), json!([null, 10]), json!("origin"), json!("mid:height")] { + // The midpoint snap creates a point before the collinear arc is refused. + assert!(s.execute("sketch.arc.three_point", &json!({"start":[0,-10],"end":[0,20],"through":through})).is_err(), "{through}"); + assert_eq!(s.doc.to_json(), before, "failed through point {through} changed the sketch"); + } +} + #[test] fn new_creation_tools() { let mut s = new_sketch(); diff --git a/crates/ui-egui/src/sketch_corner_ui_tests.rs b/crates/ui-egui/src/sketch_corner_ui_tests.rs index 25cac7d37..0df701c34 100644 --- a/crates/ui-egui/src/sketch_corner_ui_tests.rs +++ b/crates/ui-egui/src/sketch_corner_ui_tests.rs @@ -1,6 +1,32 @@ use super::*; use solidcraft_engine::sketch::CurveKind; +#[test] +fn three_point_arc_follows_its_snapped_through_point_after_dimension_change() { + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[-20,0],[20,0]],"ids":["base"]})).unwrap(); + h.app.run("sketch.constraint.fix", json!({"entity":"base"})).unwrap(); + h.app.run("sketch.line", json!({"points":["origin",[0,10]],"ids":["height"],"infer":true})).unwrap(); + let dim = h.app.run("sketch.dimension", json!({"entities":["height"],"value":10})).unwrap(); + h.settle(); + h.step(&json!({"start":"sketch.arc.three_point"})).unwrap(); + for point in [[-20, 0, 0], [20, 0, 0], [0, 10, 0]] { + h.step(&json!({"click":{"world":point}})).unwrap(); + } + h.app.run("parameters.change", json!({"name":dim["param"],"expression":"15 mm"})).unwrap(); + let sid = h.app.session.active_sketch.unwrap(); + let state = h.app.session.model.state(); + let ss = state.sketch(sid).unwrap(); + let sk = &ss.sketch; + let arc = sk.curves.iter().position(|c| matches!(c.kind, CurveKind::Arc { .. })).unwrap(); + let through = sk.point(sk.resolve_point("height.end").unwrap()).unwrap(); + assert!(ss.report.ok()); + assert!(through.dist(Vec2::new(0.0, 15.0)) < 1e-6, "{through:?}"); + let distance = sk.shape(arc).unwrap().dist(through); + assert!(distance < 1e-6, "the arc misses its snapped through point by {distance} mm"); +} + #[test] fn clicked_periodic_fit_closes_at_start_and_right_click_keeps_natural() { let mut h = crate::scenario::Harness::new(); diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 773e9d074..c434a46df 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -398,7 +398,7 @@ fn run_shape(app: &mut SolveApp, t: &Tool) -> Result, String> { "sketch.circle.center" => json!({"center": arg(&p[0]), "radius": d(0, 1)}), "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": xy(&p[2])}), + "sketch.arc.three_point" => json!({"start": arg(&p[0]), "end": arg(&p[1]), "through": arg(&p[2])}), "sketch.arc.center_point" => match crate::sketch_dims::locked_value(app, t, "Sweep") { Some(sweep) => json!({"center": arg(&p[0]), "start": arg(&p[1]), "sweep": sweep.to_degrees()}), None => json!({"center": arg(&p[0]), "start": arg(&p[1]), "end": xy(&p[2])}), From 5305d7c82daa9980d6f538b06188dc2a55ef0f4e Mon Sep 17 00:00:00 2001 From: Victor Santos Oliveira <56417388+Vittuu@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:05:55 +0000 Subject: [PATCH 10/42] Clarify delayed detection in unclean-exit reports (#3640) --- assets/locales/en.json | 3 ++ assets/locales/ja.json | 3 ++ assets/locales/pt-BR.json | 3 ++ assets/locales/zh.json | 3 ++ crates/engine/src/crash.rs | 3 +- crates/ui-egui/src/crash_ui.rs | 63 +++++++++++++++++++++++++++--- crates/ui-egui/src/issue_report.rs | 46 ++++++++++++++++++++-- docs/crash-reports.md | 5 ++- 8 files changed, 117 insertions(+), 12 deletions(-) diff --git a/assets/locales/en.json b/assets/locales/en.json index 7ca850eec..aa55768ac 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -682,6 +682,9 @@ "coupling.rack": "Rack", "coupling.radius_1": "Radius 1", "coupling.radius_2": "Radius 2", + "crash.detected_time": "Detected {time} UTC", + "crash.previous_session": "An earlier SolidCraft session ended unexpectedly or hit an internal error. Reports from unclean exits are detected at startup. See Help > Crash Reports… for details.", + "crash.unclean_explanation": "Detected on a later launch; the exact exit time was not recorded. A system shutdown or forced stop can also cause an unclean exit.", "dialog.bodies_count": "{count} bodies", "dialog.clearance_invalid": "the clearance must be a length of 0 or more", "dialog.compute": "Compute", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index f75b515ed..3404d86a7 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -682,6 +682,9 @@ "coupling.rack": "ラック", "coupling.radius_1": "半径 1", "coupling.radius_2": "半径 2", + "crash.detected_time": "検出日時: {time} UTC", + "crash.previous_session": "以前の SolidCraft セッションが予期せず終了したか、内部エラーが発生しました。正常終了が記録されていないセッションは起動時に検出されます。詳細は ヘルプ > クラッシュレポート… を参照してください。", + "crash.unclean_explanation": "次回以降の起動時に検出されました。正確な終了時刻は記録されていません。システムのシャットダウンや強制停止によっても、正常終了が記録されない場合があります。", "dialog.bodies_count": "{count} ボディ", "dialog.clearance_invalid": "クリアランスは 0 以上の長さにしてください", "dialog.compute": "計算", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index eef1e243b..caef4b8fa 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -635,6 +635,9 @@ "coupling.rack": "Cremalheira", "coupling.radius_1": "Raio 1", "coupling.radius_2": "Raio 2", + "crash.detected_time": "Detectado em {time} UTC", + "crash.previous_session": "Uma sessão anterior do SolidCraft terminou inesperadamente ou teve um erro interno. Encerramentos sem confirmação são detectados ao iniciar o aplicativo. Consulte Ajuda > Relatórios de falha… para ver os detalhes.", + "crash.unclean_explanation": "Detectado em uma inicialização posterior; o horário exato do encerramento não foi registrado. Um desligamento do sistema ou uma parada forçada também pode causar um encerramento sem confirmação.", "dialog.computing": "Calculando… {seconds} s", "dialog.custom_axis": "↖ Eixo personalizado", "dialog.edit_title": "EDITAR {title}", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index d7b941bac..f7854b458 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -682,6 +682,9 @@ "coupling.rack": "齿条", "coupling.radius_1": "半径 1", "coupling.radius_2": "半径 2", + "crash.detected_time": "检测时间:{time} UTC", + "crash.previous_session": "较早的 SolidCraft 会话意外结束或发生了内部错误。未正常结束的会话会在启动时被检测到。详情请参阅 帮助 > 崩溃报告…。", + "crash.unclean_explanation": "在后续启动时检测到;未记录确切的退出时间。系统关机或强制停止也可能导致会话未正常结束。", "dialog.bodies_count": "{count} 个实体", "dialog.clearance_invalid": "间隙必须是 0 或更大的长度", "dialog.compute": "计算", diff --git a/crates/engine/src/crash.rs b/crates/engine/src/crash.rs index 6342e048a..c7cfee7bb 100644 --- a/crates/engine/src/crash.rs +++ b/crates/engine/src/crash.rs @@ -76,7 +76,8 @@ pub struct Summary { pub id: String, /// `command_panic`, `panic`, `kernel_panic_recovered` or `unclean_exit`. pub kind: String, - /// When it first happened (UTC). + /// When the report was first recorded (UTC). Unclean exits are recorded at a later launch, + /// which may be days after the session ended, rather than at the exact exit time. pub time: String, pub message: String, /// The command running when it happened, if one was. diff --git a/crates/ui-egui/src/crash_ui.rs b/crates/ui-egui/src/crash_ui.rs index c95bb5f9d..b1194c35b 100644 --- a/crates/ui-egui/src/crash_ui.rs +++ b/crates/ui-egui/src/crash_ui.rs @@ -41,6 +41,14 @@ fn kind_label(kind: &str) -> &'static str { } } +fn report_heading(r: &Summary) -> String { + let time = r.time.replace('T', " "); + let time = time.trim_end_matches('Z'); + let time = if r.kind == "unclean_exit" { crate::i18n::format("crash.detected_time", &[("time", time)]) } else { format!("{time} UTC") }; + let times = if r.count > 1 { format!(" ×{}", r.count) } else { String::new() }; + format!("{time} {}{times}", kind_label(&r.kind)) +} + /// The host found these new reports at startup: tell the user about real crashes (recovered /// kernel errors stay quiet; they are listed in the window). pub fn announce(app: &mut SolveApp, fresh: &[Summary]) { @@ -50,7 +58,8 @@ pub fn announce(app: &mut SolveApp, fresh: &[Summary]) { } app.crashes.open = true; app.crashes.refresh(); - app.set_status("SolidCraft closed unexpectedly or hit an internal error last time. A crash report was saved (Help > Crash Reports…).", true); + let locale = crate::i18n::Locale::for_language(&app.preferences.language); + app.set_status(locale.text("crash.previous_session"), true); } pub fn show(app: &mut SolveApp, ctx: &egui::Context) { @@ -89,15 +98,15 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { for r in &app.crashes.reports { ui.horizontal(|ui| { - let times = if r.count > 1 { format!(" ×{}", r.count) } else { String::new() }; - ui.label( - RichText::new(format!("{} {}{times}", r.time.replace('T', " ").trim_end_matches('Z'), kind_label(&r.kind))).strong(), - ); + ui.label(RichText::new(report_heading(r)).strong()); if let Some(c) = &r.command { ui.label(RichText::new(c).monospace().size(11.0).color(t.text_dim)); } }); ui.label(RichText::new(&r.message).size(12.0)); + if r.kind == "unclean_exit" { + ui.label(RichText::new(crate::i18n::tr("crash.unclean_explanation")).size(12.0).color(t.text_dim)); + } ui.horizontal(|ui| { if ui.small_button("Report…").clicked() { report = Some(r.id.clone()); @@ -171,6 +180,48 @@ mod tests { d } + #[test] + fn an_old_unclean_exit_is_shown_as_detected_on_a_later_launch() { + let d = folder("old-session"); + let mut h = crate::scenario::Harness::new(); + h.app.preferences.language = "en".into(); + h.app.crashes.folder = Some(d.clone()); + let id = "20261012-162341-bb60791ed6692f1d"; + let path = d.join(id).join("report.json"); + let mut report: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + report["message"] = json!("SolidCraft 0.3.2 (started 2026-10-01T10:00:00Z) ended without a clean exit between commands"); + report["command"] = serde_json::Value::Null; + std::fs::write(&path, report.to_string()).unwrap(); + super::announce(&mut h.app, &solidcraft_engine::crash::list(&d)); + h.frames(6); + assert!(h.app.crashes.open, "unclean exits still alert the user"); + let status = &h.app.status.as_ref().unwrap().0; + assert!(status.contains("earlier SolidCraft session"), "{status}"); + assert!(status.contains("detected at startup"), "{status}"); + assert!(h.widget("Detected 2026-10-12 16:23:41 UTC Closed unexpectedly ×2").is_some()); + assert!(h.widget(report["message"].as_str().unwrap()).is_some(), "keep the original session start visible"); + assert!(h.widget(crate::i18n::tr("crash.unclean_explanation")).is_some()); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn a_panic_keeps_its_event_time_without_the_unclean_exit_explanation() { + let d = folder("panic-time"); + let mut h = crate::scenario::Harness::new(); + h.app.preferences.language = "en".into(); + h.app.crashes.folder = Some(d.clone()); + let path = d.join("20261012-162341-bb60791ed6692f1d").join("report.json"); + let mut report: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + report["kind"] = json!("command_panic"); + std::fs::write(&path, report.to_string()).unwrap(); + super::announce(&mut h.app, &solidcraft_engine::crash::list(&d)); + h.frames(6); + assert!(h.app.crashes.open); + assert!(h.widget("2026-10-12 16:23:41 UTC Internal error in a command ×2").is_some()); + assert!(h.widget(crate::i18n::tr("crash.unclean_explanation")).is_none()); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn a_crash_report_opens_a_reviewed_issue_draft_and_can_be_deleted() { let d = folder("draft"); @@ -192,7 +243,7 @@ mod tests { "solid.box", "solidcraft-cli crashes replay 20261012-162341-bb60791ed6692f1d", "Renderer: test", - "Happened 2 time(s)", + "Recorded 2 time(s)", ] { assert!(draft.body.contains(want), "missing {want:?} in {}", draft.body); } diff --git a/crates/ui-egui/src/issue_report.rs b/crates/ui-egui/src/issue_report.rs index 29307854e..e0fc8c4a1 100644 --- a/crates/ui-egui/src/issue_report.rs +++ b/crates/ui-egui/src/issue_report.rs @@ -295,12 +295,18 @@ pub fn draft_for(app: &SolveApp, dialog: Option<&dialogs::Dialog>, error: Option /// and how to replay it. The design stays on this computer; the draft says how to share it. pub fn crash_draft(report: &serde_json::Value) -> Draft { let s = |k: &str| report.get(k).and_then(serde_json::Value::as_str).unwrap_or("?").to_string(); - let what = match report.get("kind").and_then(serde_json::Value::as_str) { + let kind = report.get("kind").and_then(serde_json::Value::as_str); + let what = match kind { Some("command_panic") => "An internal error stopped a command (the design was left unchanged)", Some("kernel_panic_recovered") => "The geometry kernel hit an internal error (caught; the operation failed)", - Some("unclean_exit") => "SolidCraft closed unexpectedly (abort, stack overflow, a crash in a graphics driver or the process was killed)", + Some("unclean_exit") => "An earlier SolidCraft session ended without recording a clean exit", _ => "SolidCraft hit an internal error", }; + let detection = if kind == Some("unclean_exit") { + "\n\nDetected on a later launch; the exact exit time was not recorded. A system shutdown or forced stop can also cause an unclean exit." + } else { + "" + }; let command = report.get("command").and_then(|c| c.get("command")).and_then(serde_json::Value::as_str); let frames: Vec<&str> = report.get("backtrace").and_then(serde_json::Value::as_array).into_iter().flatten().filter_map(serde_json::Value::as_str).take(25).collect(); @@ -318,7 +324,7 @@ pub fn crash_draft(report: &serde_json::Value) -> Draft { let field = |o: Option<&serde_json::Value>, k: &str| o.and_then(|o| o.get(k)).and_then(serde_json::Value::as_str).unwrap_or("?").to_string(); let system = report.get("system"); let mut body = format!( - "## What happened\n{what}{}.\n\nMessage: {}\nLocation: {}\nThread: {}\nHappened {} time(s), first {}\n\n## Backtrace\n{}\n## Command\n{}\n## Recent commands\n{}\n\n## Reproduction\nCrash report `{}` on the reporter's computer holds {}. Replay it with `solidcraft-cli crashes replay {}`.\nOnly attach the design if it can be shared publicly.\n\n## Environment\n{}\n", + "## What happened\n{what}{}.{detection}\n\nMessage: {}\nLocation: {}\nThread: {}\nRecorded {} time(s), first recorded {}\n\n## Backtrace\n{}\n## Command\n{}\n## Recent commands\n{}\n\n## Reproduction\nCrash report `{}` on the reporter's computer holds {}. Replay it with `solidcraft-cli crashes replay {}`.\nOnly attach the design if it can be shared publicly.\n\n## Environment\n{}\n", command.map(|c| format!(" while running `{c}`")).unwrap_or_default(), limited(&s("message"), 2000), s("location"), @@ -674,6 +680,40 @@ mod tests { dialog.inputs.get_mut(1).unwrap().items = vec![Sel::Body { name: "Cutter".into() }]; } + #[test] + fn crash_draft_marks_later_detection_without_losing_native_evidence() { + let message = + "SolidCraft 0.3.2 (started 2026-10-01T10:00:00Z) crashed with ACCESS_VIOLATION (0xc0000005) in driver.dll+0x1234 between commands"; + let frame = "0xc0000005 ACCESS_VIOLATION at driver.dll+0x1234"; + let report = json!({ + "kind": "unclean_exit", "count": 2, "first_seen": "2026-10-12T16:23:41Z", + "message": message, "location": "native exception in driver.dll+0x1234", + "backtrace": [frame], "native": {"code": "0xc0000005", "module": "driver.dll", "offset": "0x1234"}, + }); + let draft = crash_draft(&report); + for expected in [ + "Recorded 2 time(s), first recorded 2026-10-12T16:23:41Z", + "Detected on a later launch; the exact exit time was not recorded.", + "A system shutdown or forced stop can also cause an unclean exit.", + message, + frame, + ] { + assert!(draft.body.contains(expected), "missing {expected}: {}", draft.body); + } + assert!(!draft.body.contains("Happened 2 time(s)")); + } + + #[test] + fn crash_draft_only_explains_later_detection_for_unclean_exits() { + for kind in ["command_panic", "panic", "kernel_panic_recovered"] { + let report = json!({"kind": kind, "count": 1, "first_seen": "2026-10-12T16:23:41Z"}); + let draft = crash_draft(&report); + assert!(draft.body.contains("Recorded 1 time(s), first recorded 2026-10-12T16:23:41Z"), "{kind}: {}", draft.body); + assert!(!draft.body.contains("Detected on a later launch"), "{kind}: {}", draft.body); + assert!(!draft.body.contains("exact exit time was not recorded"), "{kind}: {}", draft.body); + } + } + #[test] fn issue_report_actual_pending_boolean_settings_and_failure_are_read_only() { let mut app = app(); diff --git a/docs/crash-reports.md b/docs/crash-reports.md index 911090e80..e910a7bbb 100644 --- a/docs/crash-reports.md +++ b/docs/crash-reports.md @@ -58,14 +58,15 @@ A folder `crashes/-/`: - `command_panic`: a command hit an internal error; it was caught and the design was left unchanged - `kernel_panic_recovered`: the third-party geometry kernel panicked and was caught. This is harmless on the desktop, but it would crash the web build. - `panic`: an internal error outside any command - - `unclean_exit`: the app ended without a hook seeing it (an abort, a stack overflow, a segfault, a crash inside a graphics driver, or the process being killed). It is found at the next start. When the app died while starting up, the message and `location` name the startup step (see below). On Windows, a crash in native code also says the exception, the module it happened in and the offset into it. + - `unclean_exit`: a previous session ended without recording a clean exit. It is detected at the next start, which may be days later. Possible causes include an abort, a stack overflow, a segfault, a crash inside a graphics driver, a system shutdown, or the process being forcibly stopped. This kind alone does not identify the cause. When the app died while starting up, the message and `location` name the startup step (see below). On Windows, a captured native exception also says the exception, the module it happened in and the offset into it. - `message`, `location` (file:line), `thread` - `backtrace`: frames `symbol (file:line)`, without the panic machinery, std internals or the user's home folder - `app` (version, commit, build date), `system` (OS, architecture, renderer and GPU), `session.uptime_s` - `command`: the command that crashed, with its parameters - `recent_commands`: up to 32, with ok or error - `base`: what the replay starts from (the design before the command, an autosave, a saved file or a new design) - - `count`, `first_seen`, `last_seen`: the same crash repeats only increase `count` + - `count`: how many matching reports have been recorded; repeats update the existing report. + - `first_seen`, `last_seen`: UTC timestamps when the report was first and most recently recorded. For `unclean_exit`, these are detection times at a later launch, not the exact times the sessions ended. The session start in `message` may be much earlier; the report does not imply a failure in the currently open design. - `notes`: what is missing and why, for example a design too large to copy - `startup_phase`: `{step, ms}` when the app died before it drew its first frame: the step it was in (`window`, `graphics instance`, `window surface`, `adapter request`, `adapter chosen`, From fb87cde6a1b96ce66990796d0ac94148f9f46d4e Mon Sep 17 00:00:00 2001 From: fkirill Date: Tue, 20 Oct 2026 16:26:19 +0000 Subject: [PATCH 11/42] Sketch: persist Shift-picked midpoints with ordinary constraints (#2087) (#2378) --- ROADMAP.md | 2 +- crates/engine/src/cmd/sketch.rs | 62 +++++- .../src/cmd/sketch_constraints_tests.rs | 199 ++++++++++++++++++ crates/ui-egui/src/sketch_tools.rs | 1 + crates/ui-egui/src/tools.rs | 81 +++++-- crates/ui-egui/src/viewport.rs | 20 +- crates/ui-egui/tests/point_alignment.rs | 168 ++++++++++++++- docs/book/src/guide/sketching.md | 17 +- 8 files changed, 512 insertions(+), 38 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c7b5de281..c269a33ec 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -50,7 +50,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | # | Milestone | Status | Hours left | |---|---|---|---| | M0 | Vertical slice | done | — | -| M1 | Sketch depth: command coverage implemented — projection/intersect/include as linked geometry (auto-project on faces, lost-reference warnings, break link), full SKETCH create/modify set (slots, polygons, tangent arcs/circles, ellipse, fit/control splines, conic, text, trim/extend/break, fillet/chamfer, offset, mirror, patterns, move/scale, blend curve, centerline), constraints incl. curvature and polygon with over-constraint refusal, driven/arc-length/linear-diameter dimensions, AutoConstrain, DXF/SVG insert, 3D sketch curves (Project To Surface, Intersection Curve, Isoparametric Curve, Spun Profile), exact free-form profiles (B-spline/NURBS edges, any spline degree, curves cut by crossings), sweeps and pipes along 3D sketch curves, canvases and decals, curvature combs. Exact free-form Extend and certified associative offsets now preserve geometry and IDs through edits, deletion and reopen. Occurrence-frame 3D wires now store explicit coordinate spaces and retain points and analytic fits through moves, refresh, undo and reopen. Constructive sketch solving (Owen 1991, Fudos & Hoffmann 1997) ahead of the numerical solver: points and rigid clusters are placed on the branch the sketch had, so dimension edits and drags keep their solution; edits that would turn a sketch over are refused; drags re-solve only the sketch per frame. Remaining workflow repairs: mixed offset junctions, legacy natural-spline seams, and damaged legacy wire links lacking frame provenance | in progress | 4 | +| M1 | Sketch depth: command coverage implemented — projection/intersect/include as linked geometry (auto-project on faces, lost-reference warnings, break link), full SKETCH create/modify set (slots, polygons, tangent arcs/circles, ellipse, fit/control splines, conic, text, trim/extend/break, fillet/chamfer, offset, mirror, patterns, move/scale, blend curve, centerline), constraints incl. curvature and polygon with over-constraint refusal, Shift-picked line midpoints in Horizontal/Vertical using persisted points and ordinary constraints (#2087), driven/arc-length/linear-diameter dimensions, AutoConstrain, DXF/SVG insert, 3D sketch curves (Project To Surface, Intersection Curve, Isoparametric Curve, Spun Profile), exact free-form profiles (B-spline/NURBS edges, any spline degree, curves cut by crossings), sweeps and pipes along 3D sketch curves, canvases and decals, curvature combs. Exact free-form Extend and certified associative offsets now preserve geometry and IDs through edits, deletion and reopen. Occurrence-frame 3D wires now store explicit coordinate spaces and retain points and analytic fits through moves, refresh, undo and reopen. Constructive sketch solving (Owen 1991, Fudos & Hoffmann 1997) ahead of the numerical solver: points and rigid clusters are placed on the branch the sketch had, so dimension edits and drags keep their solution; edits that would turn a sketch over are refused; drags re-solve only the sketch per frame. Remaining workflow repairs: mixed offset junctions, legacy natural-spline seams, and damaged legacy wire links lacking frame provenance | in progress | 4 | | M2 | Robust modelling: coplanar booleans in the kernel, holes (placed on faces and on sketch points), threads (cosmetic, then modelled), patterns, mirror, shell, draft, split, construction geometry | in progress | 16 | | 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 | diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 77c1b4f7f..63f827732 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -117,7 +117,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SKETCH", "CONSTRAINTS") .icon("c_hv") .enabled(in_sketch) - .params("line: id | points: [a, b]; mode?: horizontal|vertical"), + .params("line: id | points: [a, b] (point ids or {midpoint: line_id}; accepted midpoints reuse or create a point with a Midpoint constraint); mode?: horizontal|vertical"), CommandSpec::new("sketch.constraint.coincident", "Coincident", c_coincident) .at("SKETCH", "CONSTRAINTS") .icon("c_coincident") @@ -1625,14 +1625,68 @@ 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)) } +/// Temporary pick intent. Saved sketches use ordinary points and constraints only. +#[derive(Clone, Copy, PartialEq, Eq)] +enum AlignmentTarget { + Point(usize), + Midpoint(usize), +} + +impl AlignmentTarget { + fn materialize(self, sk: &mut Sketch) -> 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, + }) { + 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 })?; + Ok(p) + } + } + } +} + fn c_horizontal_vertical(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.constraint.horizontal_vertical"; let mode = str_(p, "mode").map(str::to_ascii_lowercase); constrain(s, p, cmd, |sk| { if let Some(pts) = p.get("points").and_then(Value::as_array) { - let a = point_ref(sk, pts.first(), cmd, "points[0]")?; - let b = point_ref(sk, pts.get(1), cmd, "points[1]")?; - let d = sk.point(b).unwrap_or_default() - sk.point(a).unwrap_or_default(); + if pts.len() != 2 { + return Err(bad(cmd, "`points` needs exactly two point references")); + } + let target = |v: &Value| -> Result { + if let Some(line) = v.get("midpoint") { + let l = curve_ref(sk, Some(line), cmd, "midpoint")?; + if !matches!(sk.curves.get(l).map(|c| &c.kind), Some(CurveKind::Line { .. })) { + return Err(bad(cmd, "a midpoint reference needs a line")); + } + Ok(AlignmentTarget::Midpoint(l)) + } else { + Ok(AlignmentTarget::Point(point_ref(sk, Some(v), cmd, "points")?)) + } + }; + // Validate both intents before materializing either. Hover and a pending first + // pick never change the sketch; this command accepts both in one undo step. + let a = target(pts.first().ok_or_else(|| bad(cmd, "missing first point"))?)?; + let b = target(pts.get(1).ok_or_else(|| bad(cmd, "missing second point"))?)?; + if a == b { + return Err(bad(cmd, "alignment needs two distinct point references")); + } + let a = a.materialize(sk)?; + let b = b.materialize(sk)?; + if a == b { + return Err(bad(cmd, "alignment needs two distinct points")); + } + let d = sk.point(b).ok_or_else(|| bad(cmd, "invalid second point"))? - sk.point(a).ok_or_else(|| bad(cmd, "invalid first point"))?; let horiz = match mode.as_deref() { Some("horizontal") => true, Some("vertical") => false, diff --git a/crates/engine/src/cmd/sketch_constraints_tests.rs b/crates/engine/src/cmd/sketch_constraints_tests.rs index de5e2e114..f835ded7e 100644 --- a/crates/engine/src/cmd/sketch_constraints_tests.rs +++ b/crates/engine/src/cmd/sketch_constraints_tests.rs @@ -373,3 +373,202 @@ fn symmetry_moves_a_free_line_between_two_fixed_lines() { assert!((at(end).x - x).abs() < 1e-9, "{end} moved to {:?}", at(end)); } } + +#[test] +fn midpoint_alignment_persists_undoes_and_survives_endpoint_edits() { + use solidcraft_sketch::ConstraintKind; + for mode in ["horizontal", "vertical"] { + for reverse in [false, true] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false})); + run(&mut s, "sketch.point", json!({"point":[24,40],"id":"target"})); + let before = s.doc.to_json(); + let undo = s.undo.len(); + let refs = if reverse { json!(["target",{"midpoint":"l1"}]) } else { json!([{"midpoint":"l1"},"target"]) }; + let result = run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points":refs,"mode":mode})); + assert_eq!(result["created"]["points"].as_array().unwrap().len(), 1); + assert_eq!(result["created"]["constraints"].as_array().unwrap().len(), 2); + assert_eq!(result["sketch"]["dof"], 5, "H/V removes one degree of freedom; the midpoint adds none"); + assert!(result["created"]["curves"].as_array().unwrap().is_empty()); + assert_eq!(s.undo.len(), undo + 1); + 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; + for end in [[50., -15.], [-20., 65.]] { + run(&mut reopened, "sketch.move_point", json!({"point":"l1.end","to":end})); + let sk = sketch(&reopened); + let point = sk.point(sk.resolve_point("target").unwrap()).unwrap(); + let mid = line_midpoint(&sk, "l1"); + assert!((if mode == "horizontal" { point.y - mid.y } else { point.x - mid.x }).abs() < 1e-6); + assert_eq!(sk.points.len(), 5); + } + let sk = sketch(&reopened); + assert!(sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { .. }))); + assert!(sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::HorizontalPoints { .. } | ConstraintKind::VerticalPoints { .. }))); + run(&mut reopened, "sketch.delete", json!({"entities":["l1"]})); + assert!(!sketch(&reopened).constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { .. }))); + assert!(sketch(&reopened).constraints.iter().any(|c| c.id == result["constraint"].as_str().unwrap())); + } + } +} + +#[test] +fn midpoint_alignment_rejects_invalid_or_conflicting_references_atomically() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false})); + run(&mut s, "sketch.circle.center", json!({"center":[40,50],"radius":3})); + run(&mut s, "sketch.constraint.fix", json!({"entities":["l1","c1"]})); + for points in [ + json!([{"midpoint":"l1"},"c1.center"]), + json!([{"midpoint":"c1"},"origin"]), + json!([{"midpoint":"missing"},"origin"]), + json!([{"midpoint":"l1"},{"midpoint":"l1"}]), + json!([{"midpoint":12},"origin"]), + json!([{"midpoint":"l1"}]), + json!([{"midpoint":"l1"},"origin","c1.center"]), + ] { + let before = s.doc.to_json(); + let undo = s.undo.len(); + assert!(s.execute("sketch.constraint.horizontal_vertical", &json!({"points":points,"mode":"vertical"})).is_err(), "{points}"); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.undo.len(), undo); + } +} + +fn line_midpoint(sk: &solidcraft_sketch::Sketch, id: &str) -> Vec2 { + // Read the curve's current endpoints: after a corner cut an original endpoint + // id can still name the retained construction side's corner. + 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()) * 0.5 +} + +#[test] +fn midpoint_alignment_reuses_associative_points_and_rejects_self_alignment() { + use solidcraft_sketch::ConstraintKind; + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false})); + // A drawing-time midpoint is an ordinary, reusable point too. + run(&mut s, "sketch.line", json!({"points":["mid:l1",[20,40]],"infer":false,"connect":false})); + run(&mut s, "sketch.point", json!({"point":[24,50],"id":"target"})); + let count = sketch(&s).points.len(); + let result = run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points":[{"midpoint":"l1"},"target"],"mode":"vertical"})); + assert!(result["created"]["points"].as_array().unwrap().is_empty()); + assert_eq!(result["created"]["constraints"].as_array().unwrap().len(), 1); + let sk = sketch(&s); + assert_eq!(sk.points.len(), count); + assert_eq!(sk.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).count(), 1); + for refs in [json!([{"midpoint":"l1"},"l2.start"]), json!(["l2.start",{"midpoint":"l1"}])] { + let before = s.doc.to_json(); + let undo = s.undo.len(); + assert!(s.execute("sketch.constraint.horizontal_vertical", &json!({"points":refs})).is_err()); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.undo.len(), undo); + } +} + +#[test] +fn midpoint_alignment_constraints_delete_independently_and_leave_the_point() { + use solidcraft_sketch::ConstraintKind; + for delete_midpoint in [false, true] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false})); + run(&mut s, "sketch.point", json!({"point":[24,40],"id":"target"})); + run(&mut s, "sketch.constraint.fix", json!({"entity":"l1"})); + let result = run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points":[{"midpoint":"l1"},"target"],"mode":"vertical"})); + let sk = sketch(&s); + let helper = result["created"]["points"][0].as_str().unwrap().to_string(); + let mid = sk.constraints.iter().find(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).unwrap().id.clone(); + let hv = result["constraint"].as_str().unwrap().to_string(); + let deleted = if delete_midpoint { &mid } else { &hv }; + let retained = if delete_midpoint { &hv } else { &mid }; + let before = s.doc.to_json(); + run(&mut s, "sketch.delete", json!({"entities":[deleted]})); + let sk = sketch(&s); + assert!(sk.resolve_point(&helper).is_some()); + assert!(sk.constraints.iter().any(|c| &c.id == retained)); + assert!(!sk.constraints.iter().any(|c| &c.id == deleted)); + assert_eq!(sk.points.len(), 5); + 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; + assert_eq!(sketch(&reopened).points.len(), 5); + if delete_midpoint { + // Once its defining relation is deleted it is an ordinary free point. + run(&mut reopened, "sketch.move_point", json!({"point":helper,"to":[55,65]})); + let sk = sketch(&reopened); + let helper = sk.point(sk.resolve_point(&helper).unwrap()).unwrap(); + let target = sk.point(sk.resolve_point("target").unwrap()).unwrap(); + assert!((helper.x - target.x).abs() < 1e-6); + assert!(helper.dist(line_midpoint(&sk, "l1")) > 1.0); + } else { + run(&mut reopened, "sketch.move_point", json!({"point":"target","to":[55,65]})); + let sk = sketch(&reopened); + let helper = sk.point(sk.resolve_point(&helper).unwrap()).unwrap(); + assert!(helper.dist(line_midpoint(&sk, "l1")) < 1e-6); + assert!((sk.point(sk.resolve_point("target").unwrap()).unwrap().x - helper.x).abs() > 1.0); + } + } +} + +#[test] +fn midpoint_alignment_keeps_original_side_after_fillet_and_chamfer() { + use solidcraft_sketch::ConstraintKind; + for (command, params) in + [("sketch.fillet", json!({"point":"l1.end","radius":3})), ("sketch.chamfer.equal_distance", json!({"point":"l1.end","distance":3}))] + { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[10,10],[50,10],[50,40]],"infer":true})); + run(&mut s, "sketch.point", json!({"point":[32,60],"id":"target"})); + let aligned = run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points":[{"midpoint":"l1"},"target"],"mode":"vertical"})); + let helper = aligned["created"]["points"][0].as_str().unwrap(); + let before = sketch(&s); + let original_mid = before.point(before.resolve_point(helper).unwrap()).unwrap(); + run(&mut s, command, params); + let after = s.doc.to_json(); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&after).unwrap()); + reopened.active_sketch = s.active_sketch; + let sk = sketch(&reopened); + let (point, line) = sk + .constraints + .iter() + .find_map(|c| match c.kind { + ConstraintKind::Midpoint { p, l } => Some((p, l)), + _ => None, + }) + .unwrap(); + assert!(sk.curves[line].construction); + let mid = sk.point(point).unwrap(); + assert!(mid.dist(original_mid) < 1e-5, "{command}: {mid:?} vs {original_mid:?}"); + assert!((sk.point(sk.resolve_point("target").unwrap()).unwrap().x - mid.x).abs() < 1e-6); + assert!(mid.dist(line_midpoint(&sk, "l1")) > 0.5, "midpoint belongs to original full side"); + assert!(mid.dist(line_midpoint(&sk, &sk.curves[line].id)) < 1e-6); + } +} + +#[test] +fn midpoint_alignment_remaps_after_unrelated_geometry_is_deleted() { + use solidcraft_sketch::ConstraintKind; + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[-30,-20],[-10,-10]],"infer":false,"connect":false})); + run(&mut s, "sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false})); + run(&mut s, "sketch.point", json!({"point":[24,40],"id":"target"})); + let result = run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points":[{"midpoint":"l2"},"target"],"mode":"vertical"})); + run(&mut s, "sketch.delete", json!({"entities":["l1"]})); + run(&mut s, "sketch.move_point", json!({"point":"l2.end","to":[60,-10]})); + let sk = sketch(&s); + let helper = sk.point(sk.resolve_point(result["created"]["points"][0].as_str().unwrap()).unwrap()).unwrap(); + assert!(helper.dist(line_midpoint(&sk, "l2")) < 1e-6); + assert!((sk.point(sk.resolve_point("target").unwrap()).unwrap().x - helper.x).abs() < 1e-6); + assert!(sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { l: 0, .. }))); + // Deleting the helper itself removes its H/V and Midpoint relationships. + run(&mut s, "sketch.delete", json!({"entities":[result["created"]["points"][0]]})); + assert!(sketch(&s).constraints.is_empty()); +} diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index 2e702599b..8ae0f8674 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -578,6 +578,7 @@ pub fn tool_for(id: &str) -> Option { pts: Vec::new(), hover: None, picks: Vec::new(), + point_picks: Vec::new(), dims: Vec::new(), dim_history: Vec::new(), dims_stage: usize::MAX, diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index c434a46df..31e413f26 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -78,6 +78,8 @@ pub struct Tool { pub hover: Option<(Vec2, Option)>, /// Picked entity ids. pub picks: Vec, + /// Horizontal/Vertical point references: point ids or `{midpoint: line_id}`. + pub point_picks: Vec, /// Inline dimension boxes for the shape being drawn, the point count they were made for, /// and whether the first box should take the keyboard. pub dims: Vec, @@ -126,6 +128,7 @@ impl Tool { pts: Vec::new(), hover: None, picks: Vec::new(), + point_picks: Vec::new(), dims: Vec::new(), dim_history: Vec::new(), dims_stage: usize::MAX, @@ -145,7 +148,7 @@ pub fn hint(id: &str) -> String { "sketch.arc.three_point" => "Arc: click start, end, then a point on the arc".into(), "sketch.arc.center_point" => "Arc: click centre and start, then click end or type a signed sweep".into(), "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 to align".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(), _ 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()), @@ -163,9 +166,32 @@ fn xy(p: &(Vec2, Option)) -> Value { json!([p.0.x, p.0.y]) } -pub fn on_hover(app: &mut SolveApp, proj: &Proj, pos: Pos2) { +/// Shift exposes a line midpoint as a point target, only in the alignment tool. +fn midpoint_at(app: &SolveApp, proj: &Proj, pos: Pos2, radius: f32) -> Option<(Vec2, String)> { + let sid = app.session.active_sketch?; + let state = app.session.world_state(); + let ss = state.sketch(sid)?; + pick(app, proj, pos).into_iter().find_map(|hit| { + let Hit::SketchCurve { sketch, id, straight: true, .. } = hit else { return None }; + if sketch != sid { + return None; + } + let l = ss.sketch.curve_index(&id)?; + let solidcraft_engine::sketch::Shape::Line { a, b } = ss.sketch.shape(l)? else { return None }; + let mid = (a + b) * 0.5; + let screen = proj.to_screen(ss.plane.to_world(mid))?; + (screen.distance(pos) <= radius).then_some((mid, id)) + }) +} + +pub fn on_hover(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) { crate::sketch3d::on_hover(app, proj, pos); - let h = if let Some(point) = app.tool.as_ref().and_then(|tool| crate::sketch_tools::periodic_start_snap(app, tool, proj, pos)) { + let midpoint = (shift && app.tool.as_ref().is_some_and(|t| t.kind == Kind::HorizontalVertical)) + .then(|| midpoint_at(app, proj, pos, f32::INFINITY)) + .flatten(); + let h = if let Some((point, _)) = midpoint { + Some((point, Some("Midpoint".into()))) + } else if let Some(point) = app.tool.as_ref().and_then(|tool| crate::sketch_tools::periodic_start_snap(app, tool, proj, pos)) { Some((point, Some("Close smooth loop".into()))) } else { sketch_point_at(app, proj, pos) @@ -175,7 +201,7 @@ pub fn on_hover(app: &mut SolveApp, proj: &Proj, pos: Pos2) { } } -pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2) { +pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) { // A click away dismisses the inline editor; it must not also pick the first entity of // the next dimension before that cancellation has been processed. The type-first value // of the Dimension tool takes clicks itself (a second pick, or where its text goes). @@ -206,25 +232,28 @@ pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2) { } Kind::HorizontalVertical => { let hits = pick(app, proj, pos); + let midpoint = shift.then(|| midpoint_at(app, proj, pos, 12.0)).flatten(); let hit = hits.iter().find(|hit| match hit { Hit::SketchPoint { sketch, .. } | Hit::SketchCurve { sketch, .. } => Some(*sketch) == app.session.active_sketch, _ => false, }); - match hit { - Some(Hit::SketchPoint { id, .. }) => { - if let Some(first) = tool.picks.first() { - if first != id { - let _ = app.run(tool.cmd, json!({"points": [first, id]})); - tool.picks.clear(); - } - } else { - tool.picks.push(id.clone()); + let point = midpoint.map(|(_, id)| json!({"midpoint": id})).or_else(|| match hit { + Some(Hit::SketchPoint { id, .. }) => Some(json!(id)), + _ => None, + }); + if let Some(point) = point { + if let Some(first) = tool.point_picks.first() { + if first != &point && app.run(tool.cmd, json!({"points": [first, point]})).is_ok() { + tool.point_picks.clear(); } + } else { + tool.point_picks.push(point); } - Some(Hit::SketchCurve { id, straight: true, .. }) if tool.picks.is_empty() => { - let _ = app.run(tool.cmd, json!({"line": id})); - } - _ => {} + } else if !shift + && tool.point_picks.is_empty() + && let Some(Hit::SketchCurve { id, straight: true, .. }) = hit + { + let _ = app.run(tool.cmd, json!({"line": id})); } } Kind::Pick(n) => { @@ -826,6 +855,9 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) { && let Some(sp) = to(*hp) { painter.circle_stroke(sp, if snap.is_some() { 6.0 } else { 3.0 }, stroke); + if snap.as_deref() == Some("Midpoint") && t.kind == Kind::HorizontalVertical { + painter.circle_stroke(sp, 8.0, Stroke::new(2.0, tk.accent)); + } painter.text( sp + egui::vec2(10.0, 10.0), egui::Align2::LEFT_TOP, @@ -834,6 +866,21 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) { tk.text_dim, ); } + if t.kind == Kind::HorizontalVertical { + for target in &t.point_picks { + let point = if let Some(id) = target.get("midpoint").and_then(Value::as_str) { + ss.sketch.curve_index(id).and_then(|l| match ss.sketch.shape(l)? { + solidcraft_engine::sketch::Shape::Line { a, b } => Some((a + b) * 0.5), + _ => None, + }) + } else { + target.as_str().and_then(|id| ss.sketch.resolve_point(id)).and_then(|p| ss.sketch.point(p)) + }; + if let Some(sp) = point.and_then(to) { + painter.circle_stroke(sp, 6.0, Stroke::new(2.0, tk.accent)); + } + } + } let Some(hover) = t.hover.as_ref() else { return }; let h = crate::sketch_dims::shown(app, t, hover); if let Some(corners) = polygon_outline(t, h, crate::sketch_dims::locked_value(app, t, "Sides").unwrap_or(6.0)) { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 1a8942798..aaae8c4a2 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -2520,8 +2520,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if let Some(p) = ui.input(|i| i.pointer.latest_pos()).filter(|p| rect.contains(*p)) && app.tool.is_some() { - crate::tools::on_hover(app, &proj, p); - crate::tools::on_click(app, &proj, p); + crate::tools::on_hover(app, &proj, p, mods.shift); + crate::tools::on_click(app, &proj, p, mods.shift); } } // A two-point shape being dragged out (#1630) follows the pointer and ends where it is let go, @@ -2542,11 +2542,11 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { t.pts.clear(); crate::sketch_dims::reset(t); } - crate::tools::on_hover(app, &proj, p); - crate::tools::on_click(app, &proj, p); + crate::tools::on_hover(app, &proj, p, mods.shift); + crate::tools::on_click(app, &proj, p, mods.shift); } } else if let Some(p) = at { - crate::tools::on_hover(app, &proj, p); + crate::tools::on_hover(app, &proj, p, mods.shift); } } // A Trim drag's path follows the pointer; letting go trims what it crossed. A path that @@ -2559,8 +2559,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { && let Some(p) = at && app.tool.is_some() { - crate::tools::on_hover(app, &proj, p); - crate::tools::on_click(app, &proj, p); + crate::tools::on_hover(app, &proj, p, mods.shift); + crate::tools::on_click(app, &proj, p, mods.shift); } } else if let Some(p) = at { crate::sketch_tools::trim_drag_to(app, &proj, p); @@ -2572,7 +2572,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { crate::sketch_text::set_one_letter(mods.shift); if let Some(p) = hover.filter(|_| inside) { if app.tool.is_some() { - crate::tools::on_hover(app, &proj, p); + crate::tools::on_hover(app, &proj, p, mods.shift); } // Trim also trims by press and drag across the pieces to remove (its own release handling, // so not a click that moved on the way below). @@ -2598,7 +2598,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { && resp.drag_started_by(egui::PointerButton::Primary) && let Some(a) = ui.input(|i| i.pointer.press_origin()) { - crate::tools::on_click(app, &proj, a); + crate::tools::on_click(app, &proj, a, mods.shift); app.viewport.draw_drag = app.tool.as_ref().is_some_and(|t| t.pts.len() == 1).then_some(a); } else if app.tool.is_some() && !app.viewport.trim_drag @@ -2617,7 +2617,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { && crate::dim_view::pick_reference(ui.ctx(), p, resp.double_clicked()); if resp.clicked() && !held && !reference_pick { if app.tool.is_some() { - crate::tools::on_click(app, &proj, p); + crate::tools::on_click(app, &proj, p, mods.shift); } else if app.dialog.as_ref().is_some_and(|d| d.wants_picks()) { if let Some((hit, Some(sel))) = cand { dialog_pick(app, &hit, sel); diff --git a/crates/ui-egui/tests/point_alignment.rs b/crates/ui-egui/tests/point_alignment.rs index a3fc4b151..5e526d868 100644 --- a/crates/ui-egui/tests/point_alignment.rs +++ b/crates/ui-egui/tests/point_alignment.rs @@ -4,6 +4,12 @@ use serde_json::json; use solidcraft_engine::sketch::ConstraintKind; use solidcraft_ui_egui::scenario::Harness; +fn line_midpoint(sk: &solidcraft_engine::sketch::Sketch, id: &str) -> solidcraft_engine::geom::Vec2 { + let a = sk.point(sk.resolve_point(&format!("{id}.start")).unwrap()).unwrap(); + let b = sk.point(sk.resolve_point(&format!("{id}.end")).unwrap()).unwrap(); + (a + b) * 0.5 +} + #[test] fn horizontal_vertical_uses_preselected_line_and_preserves_rejection() { for fixed in [false, true] { @@ -54,7 +60,7 @@ fn horizontal_vertical_leaves_ambiguous_preselection_to_pick_tool() { h.app.session.selection = selection.clone(); let undo = h.app.session.undo.len(); h.run(&json!([{"start":"sketch.constraint.horizontal_vertical"}])).unwrap(); - assert!(h.app.tool.as_ref().unwrap().picks.is_empty()); + assert!(h.app.tool.as_ref().unwrap().point_picks.is_empty()); assert_eq!(h.app.session.undo.len(), undo); assert_eq!(h.app.session.selection, selection); assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error)); @@ -110,7 +116,7 @@ fn horizontal_vertical_aligns_origin_and_circle_center() { let (first, second) = if origin_first { ([0.0, 0.0], center) } else { (center, [0.0, 0.0]) }; let undo = h.app.session.undo.len(); h.run(&json!([{"click":{"sketch":first}}, {"expect":{"errors":0}}])).unwrap(); - assert_eq!(h.app.tool.as_ref().unwrap().picks.len(), 1); + assert_eq!(h.app.tool.as_ref().unwrap().point_picks.len(), 1); assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error)); assert_eq!(h.app.session.undo.len(), undo); // Repeating the first point must not complete a self-constraint. @@ -128,7 +134,7 @@ fn horizontal_vertical_aligns_origin_and_circle_center() { matches!(c.kind, ConstraintKind::VerticalPoints { .. }) })); assert_eq!(h.app.session.undo.len(), undo + 1); - assert!(h.app.tool.as_ref().unwrap().picks.is_empty()); + assert!(h.app.tool.as_ref().unwrap().point_picks.is_empty()); h.run(&json!([{"call":"engine.execute","params":{"command":"edit.undo","params":{}}}])).unwrap(); assert!((aligned(&h) - 3.0).abs() < 1e-6); h.run(&json!([{"call":"engine.execute","params":{"command":"edit.redo","params":{}}}])).unwrap(); @@ -167,11 +173,11 @@ fn horizontal_vertical_ignores_curves_and_cancels_a_pending_point() { {"click":{"sketch":[25,3]}} ])) .unwrap(); - assert!(h.app.tool.as_ref().unwrap().picks.is_empty()); + assert!(h.app.tool.as_ref().unwrap().point_picks.is_empty()); assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error)); let undo = h.app.session.undo.len(); h.run(&json!([{"click":{"sketch":[0,0]}}, {"click":{"sketch":[25,3]}}])).unwrap(); - assert_eq!(h.app.tool.as_ref().unwrap().picks.len(), 1); + assert_eq!(h.app.tool.as_ref().unwrap().point_picks.len(), 1); h.run(&json!([{"key":"Escape"}])).unwrap(); assert!(h.app.tool.is_none()); assert_eq!(h.app.session.undo.len(), undo); @@ -179,3 +185,155 @@ fn horizontal_vertical_ignores_curves_and_cancels_a_pending_point() { let p = sk.point(sk.resolve_point("c1.center").unwrap()).unwrap(); assert!((p.y - 3.0).abs() < 1e-6); } + +#[test] +fn shift_picks_midpoint_in_either_order_and_persists_ordinary_constraints() { + for (target, horizontal) in [([50., 18.], true), ([23., 50.], false)] { + for midpoint_first in [true, false] { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false})).unwrap(); + h.app.run("sketch.circle.center", json!({"center":target,"radius":3})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + h.step(&json!({"start":"sketch.constraint.horizontal_vertical"})).unwrap(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.step(&json!({"move":{"sketch":[20,15]},"shift":true})).unwrap(); + assert_eq!(h.app.tool.as_ref().unwrap().hover.as_ref().unwrap().1.as_deref(), Some("Midpoint")); + let midpoint = json!({"click":{"sketch":[20,15]},"shift":true}); + let target = json!({"click":{"sketch":target}}); + let (first, second) = if midpoint_first { (&midpoint, &target) } else { (&target, &midpoint) }; + h.step(first).unwrap(); + h.step(first).unwrap(); + assert_eq!(h.app.tool.as_ref().unwrap().point_picks.len(), 1); + assert_eq!(h.app.session.undo.len(), undo); + h.step(second).unwrap(); + assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", h.app.status); + assert!(h.app.tool.as_ref().unwrap().point_picks.is_empty()); + assert_eq!(h.app.session.undo.len(), undo + 1); + let sk = &h.app.session.model.state().sketches[0].sketch; + assert_eq!(sk.points.len(), 5); + assert_eq!(sk.curves.len(), 2); + let p = sk.point(sk.resolve_point("c1.center").unwrap()).unwrap(); + let mid = line_midpoint(sk, "l1"); + assert!((if horizontal { p.y - mid.y } else { p.x - mid.x }).abs() < 1e-6); + assert!(sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { .. }))); + let constraint = sk + .constraints + .iter() + .find(|c| matches!(c.kind, ConstraintKind::HorizontalPoints { .. } | ConstraintKind::VerticalPoints { .. })) + .unwrap() + .id + .clone(); + h.step(&json!({"expect":{"glyphs":{constraint.clone():1}}})).unwrap(); + let after = h.app.session.doc.to_json(); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + h.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), after); + // The ordinary constraint glyph remains selectable and deletable. + h.step(&json!({"key":"Escape"})).unwrap(); + let glyph = solidcraft_ui_egui::sketch_tools::glyph_positions().into_iter().find(|(id, _)| id == &constraint).unwrap().1; + h.step(&json!({"click":[glyph.x,glyph.y]})).unwrap(); + h.step(&json!({"key":"Delete"})).unwrap(); + let sk = &h.app.session.model.state().sketches[0].sketch; + assert!(!sk.constraints.iter().any(|c| c.id == constraint)); + assert_eq!(sk.points.len(), 5); + let midpoint_constraint = sk.constraints.iter().find(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).unwrap().id.clone(); + // The defining Midpoint relationship is editable through the same glyph UI. + let glyph = solidcraft_ui_egui::sketch_tools::glyph_positions().into_iter().find(|(id, _)| id == &midpoint_constraint).unwrap().1; + h.step(&json!({"click":[glyph.x,glyph.y]})).unwrap(); + h.step(&json!({"key":"Delete"})).unwrap(); + let sk = &h.app.session.model.state().sketches[0].sketch; + assert!(!sk.constraints.iter().any(|c| c.id == midpoint_constraint)); + assert_eq!(sk.points.len(), 5); + } + } +} + +#[test] +fn shift_midpoint_pick_cancels_and_ignores_round_curves() { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false})).unwrap(); + h.app.run("sketch.circle.center", json!({"center":[40,40],"radius":3})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + h.step(&json!({"start":"sketch.constraint.horizontal_vertical"})).unwrap(); + let before = h.app.session.doc.to_json(); + h.step(&json!({"click":{"sketch":[43,40]},"shift":true})).unwrap(); + assert!(h.app.tool.as_ref().unwrap().point_picks.is_empty()); + h.step(&json!({"click":{"sketch":[20,15]},"shift":true})).unwrap(); + assert_eq!(h.app.tool.as_ref().unwrap().point_picks, vec![json!({"midpoint":"l1"})]); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(h.app.tool.is_none()); + assert_eq!(h.app.session.doc.to_json(), before); +} + +#[test] +fn shift_can_align_two_midpoints_and_reveal_one_from_anywhere_on_the_line() { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + for points in [json!([[10, 10], [30, 20]]), json!([[15, 40], [35, 50]])] { + h.app.run("sketch.line", json!({"points":points,"infer":false,"connect":false})).unwrap(); + } + h.call("ui.view", json!({"view":"top"})); + h.step(&json!({"start":"sketch.constraint.horizontal_vertical"})).unwrap(); + h.step(&json!({"move":{"sketch":[13,11.5]},"shift":true})).unwrap(); + let hover = h.app.tool.as_ref().unwrap().hover.as_ref().unwrap(); + assert_eq!([hover.0.x, hover.0.y], [20., 15.]); + assert_eq!(hover.1.as_deref(), Some("Midpoint")); + h.step(&json!({"click":{"sketch":[20,15]},"shift":true})).unwrap(); + h.step(&json!({"click":{"sketch":[25,45]},"shift":true})).unwrap(); + assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", h.app.status); + let sk = &h.app.session.model.state().sketches[0].sketch; + assert_eq!(sk.points.len(), 7); + assert_eq!(sk.curves.len(), 2); + let mid = |id| line_midpoint(sk, id); + assert!((mid("l1").x - mid("l2").x).abs() < 1e-6); +} + +#[test] +fn midpoint_aligns_to_the_fixed_origin_without_straightening_the_line() { + for midpoint_first in [true, false] { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[-10,15],[16,25]],"infer":false,"connect":false})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + h.step(&json!({"start":"sketch.constraint.horizontal_vertical"})).unwrap(); + let midpoint = json!({"click":{"sketch":[3,20]},"shift":true}); + let origin = json!({"click":{"sketch":[0,0]}}); + let (first, second) = if midpoint_first { (&midpoint, &origin) } else { (&origin, &midpoint) }; + h.step(first).unwrap(); + h.step(second).unwrap(); + assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", h.app.status); + let sk = &h.app.session.model.state().sketches[0].sketch; + assert_eq!(sk.points.len(), 4); + let a = sk.point(sk.resolve_point("l1.start").unwrap()).unwrap(); + let b = sk.point(sk.resolve_point("l1.end").unwrap()).unwrap(); + assert!(((a + b) * 0.5).x.abs() < 1e-6); + assert!((b.x - a.x).abs() > 1. && (b.y - a.y).abs() > 1., "only the midpoint is aligned"); + assert_eq!(sk.point(0).unwrap(), solidcraft_engine::geom::Vec2::ZERO); + } +} + +#[test] +fn conflicting_midpoint_pick_keeps_pending_preview_without_creating_geometry() { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[10,10],[30,20]],"infer":false,"connect":false})).unwrap(); + h.app.run("sketch.circle.center", json!({"center":[24,50],"radius":3})).unwrap(); + h.app.run("sketch.constraint.fix", json!({"entities":["l1","c1"]})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + h.step(&json!({"start":"sketch.constraint.horizontal_vertical"})).unwrap(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"sketch":[20,15]},"shift":true})).unwrap(); + h.step(&json!({"click":{"sketch":[24,50]}})).unwrap(); + assert!(h.app.status.as_ref().is_some_and(|(_, _, error)| *error)); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.tool.as_ref().unwrap().point_picks, vec![json!({"midpoint":"l1"})]); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(h.app.tool.is_none()); + assert_eq!(h.app.session.doc.to_json(), before); +} diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md index c74d2c301..08752de01 100644 --- a/docs/book/src/guide/sketching.md +++ b/docs/book/src/guide/sketching.md @@ -174,7 +174,22 @@ fresh link once the source is available; their stored point values are preserved **Horizontal/Vertical** accepts a click on a line or clicks on two distinct sketch points, including the origin, endpoints and circle centres. For two points, it chooses horizontal -or vertical alignment from their current positions. Esc cancels a pending first point. +or vertical alignment from their current positions. Hold **Shift** near a line's midpoint to +highlight and select it as either point. The midpoint follows both endpoints as the line moves, +resizes or rotates. Two line midpoints can also be aligned. Hovering and the first pick are +only previews; Esc cancels them without changing the sketch. Accepting the second pick reuses +or creates a sketch point with an ordinary Midpoint constraint, then adds the H/V constraint +in one undo step. Both constraints can be selected and deleted independently; deleting either +keeps the point. After a fillet or chamfer, its Midpoint constraint refers to the original full +side, retained as construction geometry, just like a manually constrained midpoint. + +Scripts use the same command, with a midpoint reference in the `points` array: + +```json +{"command":"sketch.constraint.horizontal_vertical","params":{"points":[{"midpoint":"l1"},"c1.center"],"mode":"vertical"}} +``` + +`mode` can be `horizontal` or `vertical`; omitting it chooses from the current positions. The solver is SolidCraft's own (damped Gauss–Newton with degree-of-freedom analysis). Constraints: coincident, horizontal/vertical, parallel, perpendicular, tangent, equal, concentric, collinear, From 932d8d6b4f7b633c45b1c80521355162563c8242 Mon Sep 17 00:00:00 2001 From: Irakli Kourtis Date: Tue, 20 Oct 2026 16:49:45 +0000 Subject: [PATCH 12/42] Tessellation: trimmed faces of display meshes stay on their surfaces (#1653) * Tessellation: trimmed faces of display meshes stay on their surfaces Display meshes triangulate a trimmed face in parameters scaled by the surface's speed along each, so a strip stretched along one parameter is not fanned across, and every boundary segment stays a constraint: one that crosses another is split where they meet. Boolean meshes keep truck's way. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * Tessellation: one boundary rule for every mesh; drop the #1648 retry A boundary segment that crosses one already added is split where they meet in Boolean meshes too, which keeps a pinched face (#1648) whole without the snap-and-retry. Faces whose segments all go in mesh as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * Robustness goldens: seeds 1, 23, 55, 64 and 86 re-recorded on current main for #1653 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT * Thread preview test: wait for the stale fit error to clear before the next preview After switching back from M6x1.3 to M8x1.3, wait_feature_preview stopped at the M6 error still on screen when the new preview started a few frames later (seen on Linux CI with #1653's meshing). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT * Robustness goldens: the slow seeds 14, 20 and 40 re-recorded for #1653 from the merge queue Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --------- Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/boolean_regression_tests.rs | 31 +++ crates/kernel/src/body.rs | 6 +- crates/kernel/src/edge_polyline_tests.rs | 2 +- crates/kernel/src/lib.rs | 3 + crates/kernel/src/thin_face_tests.rs | 2 +- crates/kernel/src/trimmed_face_mesh_tests.rs | 78 +++++++ crates/ui-egui/src/preselect_tests.rs | 8 + tests/robustness/goldens.json | 19 +- vendor/README.md | 29 ++- vendor/truck-meshalgo/src/tessellation/mod.rs | 15 +- .../src/tessellation/triangulation.rs | 191 +++++++++--------- 11 files changed, 257 insertions(+), 127 deletions(-) create mode 100644 crates/kernel/src/trimmed_face_mesh_tests.rs diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index 8cf79c6f1..2ed8cf4d5 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -1119,3 +1119,34 @@ fn cut_beside_a_sealed_void_keeps_the_body() { println!("rotated box beside a void: {got:.6} mm³, expected {want:.6}"); assert!((got - want).abs() < 1e-5 * want, "{got} vs {want}"); } + +/// The reference mesh of loft bodies joined into a bike frame covers each face once: within 1% +/// of the area of a mesh at a tenth of the tolerance. The trimmed loft sides were meshed with a +/// flat sheet through the down tube (Delaunay in raw parameters on a strip stretched twentyfold: +/// two and a half times the area), and the seat tube's side with slivers across it (a boundary +/// polyline hooking back past its vertex dropped a trimming curve's constraints). +#[test] +fn joined_loft_frames_reference_mesh_covers_each_face_once() { + for (script, name) in [ + (include_str!("../../../examples/regressions/loft_join_bracket_hull_triangle.json"), "DT2"), + (include_str!("../../../examples/regressions/front_triangle_hull_triangle.json"), "FrontTriangle"), + ] { + let s = replay(script); + let state = s.model.state(); + let body = &state.body(name).unwrap().body; + let per_face = |m: &solidcraft_geom::Mesh| { + let mut a = vec![0.0; body.face_count()]; + for (t, f) in m.triangles.iter().zip(&m.tri_face) { + let [p0, p1, p2] = t.map(|i| m.positions[i as usize]); + a[*f as usize] += (p1 - p0).cross(p2 - p0).len() / 2.0; + } + a + }; + let size = body.size(); + let mesh = per_face(&body.reference_display_mesh_angular(size * 3e-4, 12f64.to_radians()).unwrap()); + let fine = per_face(&body.reference_display_mesh_angular(size * 3e-5, 3f64.to_radians()).unwrap()); + for (fi, (m, f)) in mesh.iter().zip(&fine).enumerate() { + assert!((m - f).abs() <= 0.01 * f.max(1.0), "{name} face {fi}: mesh {m:.0} mm², finer mesh {f:.0} mm²"); + } + } +} diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index 5b082e649..b70d4ed6b 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -256,7 +256,7 @@ const MIN_DISPLAY_ANGLE: f64 = std::f64::consts::PI / 180.0; /// non-manifold shells an import can produce). Boundaries that lie on their surface only within /// tolerance (imports, boolean results) are projected onto it. fn mesh_shells(solid: &Solid, tol: f64) -> Vec { - mesh_shells_within(solid, Deflection { rulings: true, ..Deflection::chord(tol) }) + mesh_shells_within(solid, Deflection { display: true, ..Deflection::chord(tol) }) } /// [`mesh_shells`] divided by a chord tolerance and, when it has one, a bound on the angle a @@ -1242,9 +1242,9 @@ impl Body { } } let deflection = if angle.is_finite() && angle > 0.0 { - Deflection { chord: tol, angle: angle.max(MIN_DISPLAY_ANGLE), floor: tol * DISPLAY_ANGLE_FLOOR, rulings: true } + Deflection { chord: tol, angle: angle.max(MIN_DISPLAY_ANGLE), floor: tol * DISPLAY_ANGLE_FLOOR, display: true } } else { - Deflection { rulings: true, ..Deflection::chord(tol) } + Deflection { display: true, ..Deflection::chord(tol) } }; guard("tessellate", || { let meshed = mesh_shells_within(&self.solid, deflection); diff --git a/crates/kernel/src/edge_polyline_tests.rs b/crates/kernel/src/edge_polyline_tests.rs index 88d068e9d..a3d558573 100644 --- a/crates/kernel/src/edge_polyline_tests.rs +++ b/crates/kernel/src/edge_polyline_tests.rs @@ -121,7 +121,7 @@ fn same_division(curve: &Curve, d: Deflection) -> Vec { /// The chord tolerance alone (booleans), then with the display's facet angle. fn deflections(tol: f64) -> [Deflection; 2] { - [Deflection::chord(tol), Deflection { chord: tol, angle: DISPLAY_ANGLE, floor: tol * 0.05, rulings: true }] + [Deflection::chord(tol), Deflection { chord: tol, angle: DISPLAY_ANGLE, floor: tol * 0.05, display: true }] } #[test] diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 4d01043c1..239e719c1 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -272,3 +272,6 @@ pub fn guard(what: &str, f: impl FnOnce() -> Result) -> Result { #[cfg(test)] mod tests; + +#[cfg(test)] +mod trimmed_face_mesh_tests; diff --git a/crates/kernel/src/thin_face_tests.rs b/crates/kernel/src/thin_face_tests.rs index faef716b9..6107619a9 100644 --- a/crates/kernel/src/thin_face_tests.rs +++ b/crates/kernel/src/thin_face_tests.rs @@ -69,7 +69,7 @@ fn a_face_touching_its_own_edge_meshes() { let face = mt::Face::new(vec![wire], mt::Surface::Plane(plane)); let shell: mt::Shell = vec![face].into(); for tol in [0.3, 0.08, 0.02, 0.005] { - let meshed = shell.robust_triangulation_within(Deflection { rulings: true, ..Deflection::chord(tol) }); + let meshed = shell.robust_triangulation_within(Deflection { display: true, ..Deflection::chord(tol) }); let face = meshed.face_iter().next().unwrap(); let boundary: Vec = face.boundaries()[0].edge_iter().flat_map(|e| e.oriented_curve().0.into_iter().skip(1)).collect(); let mesh = face.surface().unwrap(); diff --git a/crates/kernel/src/trimmed_face_mesh_tests.rs b/crates/kernel/src/trimmed_face_mesh_tests.rs new file mode 100644 index 000000000..f1423f05c --- /dev/null +++ b/crates/kernel/src/trimmed_face_mesh_tests.rs @@ -0,0 +1,78 @@ +//! Tessellation of trimmed loft faces after a boolean: no triangle may leave the face. + +use std::f64::consts::FRAC_PI_2; + +use solidcraft_geom::{Loop2, Plane, Seg2, Vec2, Vec3}; +use truck_modeling::{self as mt, SearchNearestParameter}; + +use crate::*; + +/// Counter-clockwise rounded rectangle centred on the origin. +fn rounded(w: f64, h: f64, r: f64) -> Loop2 { + let (x, y) = (w / 2.0, h / 2.0); + let arc = |cx: f64, cy: f64, start: f64| Seg2::Arc { center: Vec2::new(cx, cy), radius: r, start, sweep: FRAC_PI_2 }; + Loop2 { + segs: vec![ + arc(x - r, -y + r, -FRAC_PI_2), + Seg2::Line { a: Vec2::new(x, -y + r), b: Vec2::new(x, y - r) }, + arc(x - r, y - r, 0.0), + Seg2::Line { a: Vec2::new(x - r, y), b: Vec2::new(-x + r, y) }, + arc(-x + r, y - r, FRAC_PI_2), + Seg2::Line { a: Vec2::new(-x, y - r), b: Vec2::new(-x, -y + r) }, + arc(-x + r, -y + r, 2.0 * FRAC_PI_2), + Seg2::Line { a: Vec2::new(-x + r, -y), b: Vec2::new(x - r, -y) }, + ], + } +} + +/// The down tube of a bicycle frame: rounded-rectangle sections lofted along a bend. +fn tube() -> Body { + let s = |o: [f64; 3], y: [f64; 3], w: f64, h: f64, r: f64| { + (Plane::new(Vec3::new(o[0], o[1], o[2]), Vec3::Y, Vec3::new(y[0], y[1], y[2])).unwrap(), rounded(w, h, r)) + }; + loft(&[ + s([8.0, 0.0, 3.0], [-0.178, 0.0, 0.984], 38.0, 36.0, 10.8), + s([80.0, 0.0, 16.0], [-0.211, 0.0, 0.977], 60.0, 52.0, 15.6), + s([175.0, 0.0, 40.0], [-0.596, 0.0, 0.803], 76.0, 66.0, 19.8), + s([314.248, 0.0, 271.657], [-0.857, 0.0, 0.515], 74.0, 66.0, 19.8), + s([422.553, 0.0, 451.835], [-0.857, 0.0, 0.515], 66.0, 60.0, 18.0), + s([484.441, 0.0, 554.793], [-0.857, 0.0, 0.515], 46.0, 44.0, 13.2), + ]) + .unwrap() +} + +/// Each face's mesh area, and how far its triangles' centroids lie off its surface at most. +fn per_face(body: &Body, mesh: &solidcraft_geom::Mesh) -> Vec<(f64, f64)> { + use mt::ParametricSurface; + let faces: Vec<&mt::Face> = body.solid.face_iter().collect(); + let mut out = vec![(0.0, 0.0f64); faces.len()]; + for (t, &f) in mesh.triangles.iter().zip(&mesh.tri_face) { + let ([a, b, c], Some(face), Some(slot)) = (mesh.tri(t).unwrap(), faces.get(f as usize), out.get_mut(f as usize)) else { continue }; + slot.0 += (b - a).cross(c - a).len() / 2.0; + let g = (a + b + c) / 3.0; + let surface = face.oriented_surface(); + let (u, v) = surface.search_nearest_parameter(mt::Point3::new(g.x, g.y, g.z), None, 50).unwrap(); + slot.1 = slot.1.max(crate::body::from_p3(surface.subs(u, v)).dist(g)); + } + out +} + +/// A lofted tube whose side faces are ruled across (straight section edges) and long along +/// the loft, joined to a cylinder that trims their ends: the display mesh of a trimmed side +/// fanned one trimming node to boundary nodes hundreds of millimetres away (Delaunay in raw +/// parameters on a strip stretched twentyfold), a flat sheet off the surface. +#[test] +fn trimmed_ruled_loft_faces_mesh_on_their_surfaces() { + let tube = tube(); + let shell = cylinder(Vec3::new(0.0, -36.5, 0.0), Vec3::Y, 23.0, 73.0).unwrap(); + let joined = boolean(&tube, &shell, BoolOp::Union).unwrap().unwrap(); + let tol = (joined.size() * 1e-3).max(1e-3); + let display = per_face(&joined, &joined.reference_display_mesh_angular(tol, DISPLAY_ANGLE).unwrap()); + let fine = per_face(&joined, &joined.tessellate(tol / 8.0).unwrap()); + for (fi, ((area, off), (fine_area, _))) in display.iter().zip(&fine).enumerate() { + // A centroid sags at most about the chord tolerance (the bad sheet was 7 mm off at 0.6). + assert!(*off < 2.0 * tol, "face {fi}: a triangle lies {off:.2} mm off the surface (tolerance {tol:.2})"); + // Covered once: the area of a much finer mesh (the bad face had two and a half times it). + assert!((area - fine_area).abs() < 0.02 * fine_area, "face {fi}: mesh area {area:.0} mm², finer mesh {fine_area:.0} mm²"); + } +} diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index 9afc5cf45..1ae3c3812 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -1362,6 +1362,14 @@ fn modelled_thread_preview_updates_reports_errors_and_cancels_without_changes() } assert!(h.app.preview.error.as_deref().is_some_and(|e| e.contains("does not fit")), "{:?}", h.app.preview.error); designation(&mut h, "M8x1.3"); + // The M6 error stays until the new preview starts; wait for it to go, or + // `wait_feature_preview` would stop at the stale error on a host that schedules the + // preview a few frames later. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); + while h.app.preview.error.is_some() && std::time::Instant::now() < deadline { + h.frames(2); + std::thread::sleep(std::time::Duration::from_millis(10)); + } wait_feature_preview(&mut h); assert!(h.app.preview.error.is_none()); assert_eq!(h.app.session.doc.to_json(), saved); diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.json index 1c882fbd0..bb62b4d58 100644 --- a/tests/robustness/goldens.json +++ b/tests/robustness/goldens.json @@ -2,7 +2,7 @@ "about": "What each robustness seed builds (crates/engine/src/tests/robustness_goldens.rs, docs/robustness.md). Record changes with ROBUSTNESS_GOLDENS_BLESS=\"why\".", "seeds": { "0": {"area":4807.582879,"bodies":1,"edges":72,"error":null,"faces":27,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","hole","circular pattern","circular pattern","cut sphere","join cylinder","cut cylinder","cut sphere"],"unsupported":0,"volume":13472.328916}, - "1": {"area":2642.476583,"bodies":1,"edges":37,"error":null,"faces":15,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut cylinder","join cylinder"],"unsupported":0,"volume":6991.559261}, + "1": {"area":2642.450646,"bodies":1,"edges":37,"error":null,"faces":15,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut cylinder","join cylinder"],"unsupported":0,"volume":6991.573271}, "2": {"area":2522.922626,"bodies":1,"edges":36,"error":"boolean Cut: the operation failed: no result","faces":14,"outcome":"failed","rejected":1,"shells":1,"steps":["box","cut cylinder","fillet","cut sphere","rectangular pattern"],"unsupported":2,"volume":5580.088497}, "3": {"area":6336.456143,"bodies":1,"edges":33,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut box","hole","fillet","hole"],"unsupported":0,"volume":28037.146888}, "4": {"area":5810.088602,"bodies":1,"edges":27,"error":null,"faces":11,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut cylinder","fillet"],"unsupported":0,"volume":28461.628006}, @@ -15,16 +15,16 @@ "11": {"area":7858.300481,"bodies":1,"edges":33,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","hole","rectangular pattern","fillet"],"unsupported":0,"volume":34605.048259}, "12": {"area":4668.773162,"bodies":1,"edges":59,"error":null,"faces":25,"outcome":"ok","rejected":0,"shells":2,"steps":["extruded profile","chamfer","join cylinder","join box","cut cylinder","circular pattern"],"unsupported":3,"volume":11874.973223}, "13": {"area":2112.846954,"bodies":1,"edges":99,"error":null,"faces":39,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","cut cylinder","join box","rectangular pattern","cut cylinder","cut box","fillet","hole"],"unsupported":0,"volume":2410.783741}, - "14": {"area":10553.267409,"bodies":1,"edges":43,"error":null,"faces":20,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","shell","fillet"],"unsupported":0,"volume":10369.008764}, + "14": {"area":10554.182993,"bodies":1,"edges":43,"error":null,"faces":20,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","shell","fillet"],"unsupported":0,"volume":10371.646072}, "15": {"area":2312.730168,"bodies":1,"edges":39,"error":null,"faces":15,"outcome":"ok","rejected":2,"shells":1,"steps":["revolved section","cut box","rectangular pattern","cut sphere","cut cylinder","cut sphere","join cylinder"],"unsupported":0,"volume":5728.661237}, "16": {"area":8872.878228,"bodies":1,"edges":49,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":3,"steps":["box","join cylinder","circular pattern","hole"],"unsupported":0,"volume":44953.407975}, "17": {"area":6022.921702,"bodies":1,"edges":48,"error":null,"faces":19,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut box","shell","cut cylinder"],"unsupported":0,"volume":2981.269959}, "18": {"area":5969.14407,"bodies":1,"edges":131,"error":null,"faces":53,"outcome":"ok","rejected":0,"shells":4,"steps":["extruded profile","join cylinder","circular pattern","cut cylinder","hole","cut cylinder","hole","circular pattern"],"unsupported":0,"volume":20696.295391}, "19": {"area":3440.869757,"bodies":1,"edges":42,"error":null,"faces":16,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","chamfer","cut sphere"],"unsupported":0,"volume":5909.174021}, - "20": {"area":5727.102692,"bodies":1,"edges":116,"error":null,"faces":45,"outcome":"ok","rejected":1,"shells":1,"steps":["extruded profile","fillet","cut box","cut cylinder","hole","circular pattern","cut box"],"unsupported":0,"volume":17142.747554}, + "20": {"area":5729.705185,"bodies":1,"edges":116,"error":null,"faces":45,"outcome":"ok","rejected":1,"shells":1,"steps":["extruded profile","fillet","cut box","cut cylinder","hole","circular pattern","cut box"],"unsupported":0,"volume":17157.584515}, "21": {"area":5814.791707,"bodies":1,"edges":56,"error":null,"faces":22,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","join box","hole","fillet","hole","cut box"],"unsupported":1,"volume":19153.734422}, "22": {"area":4634.445571,"bodies":1,"edges":138,"error":null,"faces":54,"outcome":"ok","rejected":0,"shells":2,"steps":["revolved section","join box","join box","join box","rectangular pattern","cut cylinder"],"unsupported":0,"volume":7855.557174}, - "23": {"area":1795.696192,"bodies":1,"edges":16,"error":null,"faces":7,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut sphere"],"unsupported":0,"volume":3198.694598}, + "23": {"area":1795.692727,"bodies":1,"edges":16,"error":null,"faces":7,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut sphere"],"unsupported":0,"volume":3198.694598}, "24": {"area":8910.288004,"bodies":1,"edges":64,"error":null,"faces":20,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","chamfer","hole","cut box","cut sphere","cut sphere","hole"],"unsupported":1,"volume":32456.126515}, "25": {"area":7142.717684,"bodies":1,"edges":48,"error":null,"faces":19,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","shell"],"unsupported":0,"volume":7012.754625}, "26": {"area":6461.702601,"bodies":1,"edges":56,"error":null,"faces":22,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","join box","cut cylinder","rectangular pattern","cut sphere"],"unsupported":0,"volume":21188.159601}, @@ -41,7 +41,7 @@ "37": {"area":11714.822253,"bodies":1,"edges":44,"error":null,"faces":18,"outcome":"ok","rejected":1,"shells":1,"steps":["box","cut cylinder","join cylinder","cut sphere","circular pattern","fillet","circular pattern","rectangular pattern"],"unsupported":2,"volume":75556.602064}, "38": {"area":11769.375811,"bodies":1,"edges":30,"error":"offset: a corner whose faces don't meet the same way after t","faces":12,"outcome":"failed","rejected":1,"shells":1,"steps":["box","hole","cut cylinder","shell"],"unsupported":0,"volume":78261.020975}, "39": {"area":1892.051593,"bodies":1,"edges":27,"error":null,"faces":11,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","chamfer","cut sphere","rectangular pattern"],"unsupported":1,"volume":4040.619835}, - "40": {"area":15548.516294,"bodies":1,"edges":49,"error":"offset: a corner whose faces don't meet the same way after t","faces":22,"outcome":"failed","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","shell","cut cylinder","join cylinder","shell"],"unsupported":0,"volume":16543.777532}, + "40": {"area":15549.121775,"bodies":1,"edges":49,"error":"offset: a corner whose faces don't meet the same way after t","faces":22,"outcome":"failed","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","shell","cut cylinder","join cylinder","shell"],"unsupported":0,"volume":16541.530092}, "41": {"area":7295.282884,"bodies":1,"edges":93,"error":null,"faces":32,"outcome":"ok","rejected":1,"shells":1,"steps":["box","cut sphere","shell","fillet","cut cylinder","rectangular pattern","fillet","cut sphere"],"unsupported":0,"volume":5185.221068}, "42": {"area":5486.877622,"bodies":1,"edges":51,"error":null,"faces":20,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut box","cut cylinder","rectangular pattern"],"unsupported":0,"volume":19095.106157}, "43": {"area":3492.988343,"bodies":1,"edges":72,"error":null,"faces":26,"outcome":"ok","rejected":2,"shells":1,"steps":["extruded profile","cut cylinder","rectangular pattern","fillet","hole","rectangular pattern","join cylinder"],"unsupported":1,"volume":7528.548742}, @@ -56,7 +56,7 @@ "52": {"area":8628.608654,"bodies":1,"edges":45,"error":null,"faces":18,"outcome":"ok","rejected":0,"shells":1,"steps":["box","shell","cut cylinder","chamfer","join cylinder"],"unsupported":1,"volume":9001.505742}, "53": {"area":17463.451761,"bodies":1,"edges":116,"error":null,"faces":48,"outcome":"ok","rejected":0,"shells":4,"steps":["extruded profile","cut cylinder","shell","fillet","join cylinder","circular pattern"],"unsupported":0,"volume":16954.551768}, "54": {"area":7075.531663,"bodies":1,"edges":81,"error":"offset: a corner whose faces don't meet the same way after t","faces":35,"outcome":"failed","rejected":0,"shells":4,"steps":["extruded profile","join box","circular pattern","cut cylinder","cut box","join cylinder","shell"],"unsupported":2,"volume":16028.147251}, - "55": {"area":6796.504547,"bodies":1,"edges":60,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":1,"steps":["box","fillet","cut sphere","circular pattern","rectangular pattern","cut sphere"],"unsupported":0,"volume":24744.182468}, + "55": {"area":6795.599353,"bodies":1,"edges":60,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":1,"steps":["box","fillet","cut sphere","circular pattern","rectangular pattern","cut sphere"],"unsupported":0,"volume":24743.737783}, "56": {"area":4453.31728,"bodies":1,"edges":33,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut box","chamfer"],"unsupported":0,"volume":11829.375}, "57": {"area":4671.095724,"bodies":1,"edges":66,"error":null,"faces":24,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut sphere","circular pattern","chamfer","cut sphere","cut sphere","cut cylinder"],"unsupported":2,"volume":16017.21038}, "58": {"area":4197.049258,"bodies":1,"edges":42,"error":null,"faces":16,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","fillet","cut sphere"],"unsupported":0,"volume":12543.173591}, @@ -65,7 +65,7 @@ "61": {"area":5020.413153,"bodies":1,"edges":36,"error":"boolean Cut: the operation failed: no result","faces":15,"outcome":"failed","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","shell","rectangular pattern"],"unsupported":0,"volume":4906.628538}, "62": {"area":8771.003732,"bodies":1,"edges":60,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","circular pattern","cut box","cut box","join cylinder"],"unsupported":2,"volume":40107.001728}, "63": {"area":4316.842909,"bodies":1,"edges":100,"error":null,"faces":38,"outcome":"ok","rejected":0,"shells":3,"steps":["revolved section","join box","cut cylinder","hole","cut cylinder","join box","rectangular pattern"],"unsupported":3,"volume":8229.233195}, - "64": {"area":4088.335645,"bodies":1,"edges":36,"error":null,"faces":14,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","fillet","join cylinder"],"unsupported":0,"volume":8495.220295}, + "64": {"area":4088.335645,"bodies":1,"edges":36,"error":null,"faces":14,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","fillet","join cylinder"],"unsupported":0,"volume":8495.235267}, "65": {"area":8436.255548,"bodies":1,"edges":37,"error":null,"faces":15,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut cylinder","fillet","rectangular pattern","circular pattern","circular pattern","fillet","cut box"],"unsupported":0,"volume":45143.475817}, "66": {"area":9222.76638,"bodies":1,"edges":99,"error":null,"faces":37,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","join box","join box","join box","cut sphere","cut box"],"unsupported":1,"volume":35217.203139}, "67": {"area":7940.064,"bodies":1,"edges":84,"error":null,"faces":35,"outcome":"ok","rejected":1,"shells":2,"steps":["extruded profile","cut cylinder","hole","join cylinder","join box","hole","chamfer","rectangular pattern"],"unsupported":1,"volume":27606.450855}, @@ -87,7 +87,7 @@ "83": {"area":8632.834978,"bodies":1,"edges":95,"error":null,"faces":35,"outcome":"ok","rejected":0,"shells":2,"steps":["box","join box","rectangular pattern","shell","cut sphere","join box","fillet"],"unsupported":2,"volume":6339.218896}, "84": {"area":4906.192237,"bodies":1,"edges":67,"error":null,"faces":25,"outcome":"ok","rejected":2,"shells":1,"steps":["extruded profile","fillet","hole","hole","cut cylinder","cut box","fillet"],"unsupported":0,"volume":14219.865875}, "85": {"area":3309.210936,"bodies":1,"edges":57,"error":null,"faces":24,"outcome":"ok","rejected":1,"shells":2,"steps":["revolved section","fillet","cut sphere","circular pattern","join cylinder","hole","join box"],"unsupported":0,"volume":6904.455565}, - "86": {"area":7570.844423,"bodies":1,"edges":66,"error":"offset: a corner whose faces don't meet the same way after t","faces":30,"outcome":"failed","rejected":0,"shells":3,"steps":["extruded profile","join cylinder","join cylinder","circular pattern","hole","rectangular pattern","shell"],"unsupported":1,"volume":20478.868768}, + "86": {"area":7580.468361,"bodies":1,"edges":66,"error":"offset: a corner whose faces don't meet the same way after t","faces":30,"outcome":"failed","rejected":0,"shells":3,"steps":["extruded profile","join cylinder","join cylinder","circular pattern","hole","rectangular pattern","shell"],"unsupported":1,"volume":20437.482684}, "87": {"area":4853.708989,"bodies":1,"edges":24,"error":null,"faces":10,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut box","rectangular pattern"],"unsupported":0,"volume":18568.611108}, "88": {"area":3947.799648,"bodies":1,"edges":18,"error":null,"faces":8,"outcome":"ok","rejected":0,"shells":1,"steps":["box","hole"],"unsupported":0,"volume":12788.04706}, "89": {"area":2512.5,"bodies":1,"edges":12,"error":null,"faces":6,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut box"],"unsupported":0,"volume":5906.25}, @@ -145,6 +145,7 @@ {"reason":"Rebase #2387 onto #2247: patterned pieces stay in one body. Seed 86 drills its hole, then reaches the same offset-corner shell refusal as main instead of shelling separate bodies. Completed steps still pass validity and volume-direction checks.","seeds":[86]}, {"reason":"A join whose coincident faces were pushed apart now trims the slab beyond the plane by editing faces when the boolean cut of it fails (a prism whose edge in the plane lies in the end face of a slab with rounded corners). Seed 70: the shell of a body in two lumps, refused before, now builds; its volume matches an independent offset of the profile (4120.90 vs 4120.67 mm3, the gap is the unshelled profile's own tessellation).","seeds":[70]}, {"reason":"#1648: a face whose boundary touches itself within the tolerance is triangulated through the touching point instead of across the face, so faces that meshed with triangles missing or outside them now mesh whole. Seeds 20 and 55 build the same designs (same steps, faces, edges and shells); only the measured area, and for seed 55 the volume, of their final bodies move. Seed 55: replaying it with the old and the new triangulation gives the same final body; two curved faces measured 442.14 and 325.42 mm2 with the old triangulation at a fine tolerance, 436.29 and 305.83 mm2 with the new one, which agrees with their coarser meshes, and its volume moves from 24740.93 to 24744.18 mm3, against 24743.58 mm3 from a mesh at 1e-4 mm. Seed 20, as main now builds it, moves only in area, from 5726.92956 to 5727.102692 mm2 (3e-5 relative). Recorded from the fork CI output (Linux).","seeds":[20,55]}, - {"reason":"A cut no longer comes out empty where a shell of one body meets nothing of the other (a sealed void, a body clear of the tool): truck placed such faces by their surfaces alone, which a turned body's reversed faces and a void's inward shell got wrong. Seeds 0, 45 and 77 each had a cut refused as empty that now takes what it should, and the generator builds different steps after it: seed 0 a sphere clear of the body (removes nothing), seed 45 a hole on the axis of a shelled turned body (widens its bore from r 2.5 to r 4 over 17.5 mm: 536.0 mm3), seed 77 a hole inside a turned body's bore (removes nothing; a later pattern copy drills r 1.5 through 27.5 mm: 194.4 mm3). Every step passes the validity and volume-direction checks.","seeds":[0,45,77]} + {"reason":"A cut no longer comes out empty where a shell of one body meets nothing of the other (a sealed void, a body clear of the tool): truck placed such faces by their surfaces alone, which a turned body's reversed faces and a void's inward shell got wrong. Seeds 0, 45 and 77 each had a cut refused as empty that now takes what it should, and the generator builds different steps after it: seed 0 a sphere clear of the body (removes nothing), seed 45 a hole on the axis of a shelled turned body (widens its bore from r 2.5 to r 4 over 17.5 mm: 536.0 mm3), seed 77 a hole inside a turned body's bore (removes nothing; a later pattern copy drills r 1.5 through 27.5 mm: 194.4 mm3). Every step passes the validity and volume-direction checks.","seeds":[0,45,77]}, + {"reason":"Trimmed faces of display meshes stay on their surfaces (#1653): seeds 1, 23, 55, 64 and 86 end with bodies whose trimmed faces were meshed off their surfaces; measured on the corrected meshes their area and volume move slightly (seed 86 most: area +9.6 mm2, volume -41.4 mm3, 0.2 %). Steps, outcome and counts are unchanged; recorded from Linux CI on main at the time of the rebase. The slow seeds 14, 20 and 40 (run only by the merge queue) move too: 14 area +0.92 mm2 / volume +2.64 mm3, 20 area +2.60 mm2 / volume +14.8 mm3, 40 area +0.61 mm2 / volume -2.25 mm3, from merge-group run 39450833424.","seeds":[1,14,20,23,40,55,64,86]} ] } diff --git a/vendor/README.md b/vendor/README.md index 726783874..1d974fa7e 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -180,6 +180,22 @@ Changes: old test is kept as `tessellation::include_test_hooks`, behind a `test-hooks` feature that only `solidcraft-kernel`'s tests turn on, and `crates/kernel/tests/tess_include_equivalence.rs` compares the two. +- `tessellation/triangulation.rs`: the constrained Delaunay triangulation of a trimmed face + works in (u, v) scaled by the surface's mean speed along each (a power of two, so exact both + ways). In raw parameters, a loft side ruled across (about 30 mm) and long along the loft + (about 600 mm) is a strip stretched twentyfold, and a trimming node was fanned to boundary + nodes hundreds of millimetres away: a flat sheet through a joined tube. +- `tessellation/triangulation.rs`: every segment of a face's boundary becomes a constraint; one + that crosses or overlaps a constraint already added (an intersection edge's polyline can hook + back a few micrometres past its vertex) is split where they meet. truck dropped such a + segment and joined its start to the first later node it could reach, which on a joined tube + left a trimming curve's 130 nodes behind one constraint across the face: slivers from it + sagged millimetres off the surface, and a face pinched to a point (#1648) got no triangles. + All meshes; faces whose segments all go in mesh as before. +- `tessellation/mod.rs`: `Deflection::rulings` is now `Deflection::display`: a mesh to display + or export (the kernel's `tessellate` and display meshes), which gets the ruling grid lines, + and the speed-scaled triangulation above. The meshes a Boolean operation intersects + (`Deflection::chord`) keep truck's (u, v) and insertion order. - `lib.rs`: compiler warnings no longer fail the build. Example, test and bench targets are dropped (their sources are not vendored). - `tessellation/triangulation.rs`: adaptive division also splits a cell that bows off its @@ -191,21 +207,12 @@ Changes: face's mesh puts each point at its parameters on the face's own surface, so a point of an edge that lies off a surface within tolerance (an intersection-curve sample whose projection did not converge, an imported edge) came out in a different place on each of the edge's faces, and the - exported mesh had a crack there. In display and export meshes (`Deflection::rulings`), a + exported mesh had a crack there. In display and export meshes (`Deflection::display`), a vertex at a point of a face's boundary loops that is farther than `TOLERANCE` from the nearest point of the face's edges now goes to that point, when it is within the chord tolerance (`onto_edges`). Points within `TOLERANCE` stay on the surface, so exact geometry meshes as before. The meshes Boolean operations intersect keep truck's points. -- `tessellation/triangulation.rs`: a face whose boundary touches itself or another of its loops - within `TOLERANCE` (pinched to a point where a body touches its edge, #1648) can cross there by - less than that. A segment that would cross one already added was left out of the triangulation, - and the fallback that joins the next point instead cut across the face: such a face came out - with no triangles, or without those at the pinch, depending on which segment went in first. - When a segment is left out, every boundary point within `TOLERANCE` of a segment, away from its - ends, is put into it (`pinched`: at most 8192 boundary points, and at most 8192 put in), and - the face is triangulated again. Faces whose segments all go in are triangulated as before. - -- `tessellation/triangulation.rs`: in display and export meshes (`Deflection::rulings`), a +- `tessellation/triangulation.rs`: in display and export meshes (`Deflection::display`), a direction left undivided along the rulings of a face ruled one way also gets a grid line through each point of the face's boundary that lies inside the face along it (`with_boundary_lines`), when there are at most 16 such points: corners standing into the diff --git a/vendor/truck-meshalgo/src/tessellation/mod.rs b/vendor/truck-meshalgo/src/tessellation/mod.rs index b51c098b0..0ec2f9011 100644 --- a/vendor/truck-meshalgo/src/tessellation/mod.rs +++ b/vendor/truck-meshalgo/src/tessellation/mod.rs @@ -122,10 +122,13 @@ pub struct Deflection { pub angle: f64, /// Sag below which `angle` no longer splits a facet. pub floor: f64, - /// SolidCraft: grid lines through the vertices that split a face's ruling edges (see - /// `with_ruling_vertices`). Meshes for display and export ask for them; the meshes Boolean - /// operations intersect do not, so a Boolean's result does not depend on them. - pub rulings: bool, + /// SolidCraft: a mesh to display or export, which must lie on its faces, rather than one a + /// Boolean operation intersects (whose results must not depend on what follows). Such a + /// mesh gets grid lines through the vertices that split a face's ruling edges (see + /// `with_ruling_vertices`), triangulates a trimmed face in speed-scaled parameters + /// (`UvScale`), keeps every boundary segment as a constraint (`PolyBoundary::insert_to`), + /// and puts its boundary points on the face's edges (`onto_edges`). + pub display: bool, } impl Deflection { @@ -145,7 +148,7 @@ impl Deflection { chord: tol, angle: f64::INFINITY, floor: 0.0, - rulings: false, + display: false, } } @@ -158,7 +161,7 @@ impl Deflection { let angle = self.angle * f64::from(1u32 << level.min(Self::MAX_RELAX)); match level == 0 || (level < Self::MAX_RELAX && angle < std::f64::consts::PI) { true => Self { angle, ..*self }, - false => Self { rulings: self.rulings, ..Self::chord(self.chord) }, + false => Self { display: self.display, ..Self::chord(self.chord) }, } } diff --git a/vendor/truck-meshalgo/src/tessellation/triangulation.rs b/vendor/truck-meshalgo/src/tessellation/triangulation.rs index 1428376c9..b9c36de41 100644 --- a/vendor/truck-meshalgo/src/tessellation/triangulation.rs +++ b/vendor/truck-meshalgo/src/tessellation/triangulation.rs @@ -12,6 +12,7 @@ use rayon::prelude::*; type SPoint2 = spade::Point2; type Cdt = ConstrainedDelaunayTriangulation; +type VertexId = handles::FixedVertexHandle; type MeshedShell = Shell>; type MeshedCShell = CompressedShell>; @@ -484,7 +485,7 @@ fn shell_create_polygon( let mut mesh = trimming_tessellation(surface, &boundary, tol, cap); // Display and export meshes only, as the ruling grid lines: the meshes Boolean // operations intersect keep truck's points. - if tol.rulings { + if tol.display { let points: Vec = wires.iter().flat_map(Wire::edge_iter).flat_map(|e| e.curve().0).collect(); onto_edges(&mut mesh, &boundary, &points, tol.chord); } @@ -881,21 +882,17 @@ impl PolyBoundary { .unwrap_or(false) } - /// Inserts points and adds constraint into triangulation. SolidCraft: whether every segment - /// went in. - fn insert_to(&self, triangulation: &mut Cdt) -> bool { - let poly2tri: Vec<_> = self - .0 - .iter() - .flatten() - .map(|pt| { - let p = [spade_round(pt.x), spade_round(pt.y)]; - triangulation.insert(SPoint2::from(p)).ok() - }) - .collect(); - let mut prev: Option = None; + /// Inserts the loops' points into the triangulation; [`Self::add_constraints`] then joins + /// them. + fn insert_points(&self, triangulation: &mut Cdt, scale: UvScale) -> Vec> { + self.0.iter().flatten().map(|pt| triangulation.insert(scale.to_cdt(*pt)).ok()).collect() + } + + /// Adds the loops' segments between the vertices [`Self::insert_points`] gave. SolidCraft: a + /// segment that crosses one already added is split where they meet (truck dropped it and + /// joined across the face; #1648). + fn add_constraints(&self, triangulation: &mut Cdt, poly2tri: &[Option]) { let mut counter = 0; - let mut complete = true; self.0 .iter() .map(Vec::len) @@ -905,73 +902,68 @@ impl PolyBoundary { range.circular_tuple_windows() }) .for_each(|(i, j)| { - let Some(vj) = poly2tri[j] else { return }; - if let Some(p) = prev { - let Some(v) = poly2tri[p] else { return }; - if triangulation.can_add_constraint(v, vj) { - triangulation.add_constraint(v, vj); - prev = None; - } + let (Some(vi), Some(vj)) = (poly2tri[i], poly2tri[j]) else { return }; + if vi == vj { + return; + } + if triangulation.can_add_constraint(vi, vj) { + triangulation.add_constraint(vi, vj); } else { - let Some(vi) = poly2tri[i] else { return }; - if triangulation.can_add_constraint(vi, vj) { - triangulation.add_constraint(vi, vj); - } else { - complete = false; - prev = Some(i); - } + triangulation.add_constraint_and_split(vi, vj, |p| p); } }); - complete } } -/// SolidCraft: most boundary points [`pinched`] compares with every segment, and most points it -/// puts into segments. -const MAX_PINCH_POINTS: usize = 8192; +/// SolidCraft: the (u, v) scale the triangulation works in, each parameter by the surface's mean +/// speed along it (a power of two, so exact both ways): Delaunay in raw parameters fans a +/// stretched strip (a long loft side) across the surface. +#[derive(Clone, Copy, Debug)] +struct UvScale([f64; 2]); -/// SolidCraft: `loops` with every point that lies within `TOLERANCE` of a segment, away from its -/// ends, put into that segment (in order along it): where a loop touches itself or another, -/// both pass through the same point. `None` when no point does, or the loops have more than -/// [`MAX_PINCH_POINTS`] points, or more than that would be put in. -fn pinched(loops: &[Vec]) -> Option>> { - if loops.iter().map(Vec::len).sum::() > MAX_PINCH_POINTS { - return None; - } - let mut extra: Vec>> = loops.iter().map(|l| vec![Vec::new(); l.len()]).collect(); - let mut found = 0; - for (l, extra) in loops.iter().zip(&mut extra) { - let n = l.len(); - for (i, extra) in extra.iter_mut().enumerate() { - let (q0, q1) = (l[i], l[(i + 1) % n]); - let d = q1 - q0; - let len2 = d.magnitude2(); - if len2 <= TOLERANCE2 { - continue; - } - for &p in loops.iter().flatten() { - if p.distance2(q0) <= TOLERANCE2 || p.distance2(q1) <= TOLERANCE2 { - continue; - } - let t = (p - q0).dot(d) / len2; - if t > 0.0 && t < 1.0 && p.distance2(q0 + d * t) <= TOLERANCE2 { - if found == MAX_PINCH_POINTS { - return None; - } - extra.push((t, p)); - found += 1; +impl UvScale { + const IDENTITY: UvScale = UvScale([1.0, 1.0]); + /// Most binary orders of magnitude between the two scales. + const MAX_EXPONENT: f64 = 30.0; + /// Samples per direction over the boundary's box. + const SAMPLES: usize = 5; + + fn of(surface: &impl PreMeshableSurface, polyline: &PolyBoundary) -> Self { + let bdb: BoundingBox = polyline.0.iter().flatten().collect(); + let (min, max) = (bdb.min(), bdb.max()); + if !(min.x.is_finite() && min.y.is_finite() && max.x.is_finite() && max.y.is_finite()) { + return Self::IDENTITY; + } + let n = Self::SAMPLES; + let (mut su, mut sv, mut count) = (0.0, 0.0, 0usize); + for i in 0..n { + for j in 0..n { + let (s, t) = (i as f64 / (n - 1) as f64, j as f64 / (n - 1) as f64); + let (u, v) = (min.x + (max.x - min.x) * s, min.y + (max.y - min.y) * t); + let (du, dv) = (surface.uder(u, v).magnitude(), surface.vder(u, v).magnitude()); + if du.is_finite() && dv.is_finite() { + su += du; + sv += dv; + count += 1; } } - extra.sort_by(|a, b| a.0.total_cmp(&b.0)); + } + // Speeds' ratio, as a power of two; none where either speed vanishes throughout. + let ratio = su / sv; + if count == 0 || !(ratio.is_finite() && ratio > 0.0) { + return Self::IDENTITY; + } + let e = ratio.log2().round().clamp(-Self::MAX_EXPONENT, Self::MAX_EXPONENT); + // The faster parameter keeps its values; the slower one is shrunk. + match e >= 0.0 { + true => UvScale([1.0, (-e).exp2()]), + false => UvScale([e.exp2(), 1.0]), } } - (found > 0).then(|| { - loops - .iter() - .zip(extra) - .map(|(l, extra)| l.iter().zip(extra).flat_map(|(p, e)| std::iter::once(*p).chain(e.into_iter().map(|(_, q)| q))).collect()) - .collect() - }) + + fn to_cdt(self, p: Point2) -> SPoint2 { SPoint2::new(spade_round(p.x * self.0[0]), spade_round(p.y * self.0[1])) } + + fn from_cdt(self, p: SPoint2) -> Point2 { Point2::new(p.x / self.0[0], p.y / self.0[1]) } } fn spade_round(x: f64) -> f64 { @@ -1015,23 +1007,25 @@ pub(super) fn preview_face(surface: &S, loops: &[Vec

(surface: &S, polyboundary: &PolyBoundary, tol: Deflection, cap: usize, steps: Option) -> PolygonMesh { let mut triangulation = Cdt::new(); - // SolidCraft: a loop that touches itself or another loop within `TOLERANCE` (a face pinched - // to a point where a body touches its edge, #1648) can cross there by less than that. A - // segment that would cross one already added is left out, the fallback in `insert_to` then - // joins the next point across the face, and the face came out with no triangles. Its - // segments are then taken through the points they pass, and it is triangulated again. - if !polyboundary.insert_to(&mut triangulation) { - if let Some(loops) = pinched(&polyboundary.0) { - triangulation = Cdt::new(); - PolyBoundary(loops, Vec::new(), Vec::new()).insert_to(&mut triangulation); - } + // Display meshes only (see `Deflection::display`). + let scale = if tol.display { UvScale::of(surface, polyboundary) } else { UvScale::IDENTITY }; + let poly2tri = polyboundary.insert_points(&mut triangulation, scale); + if tol.display { + // Every point before any constraint, so no grid point lands on a split's inexact crossing. + let grid = insert_surface(&mut triangulation, surface, polyboundary, tol, cap, steps, scale); + polyboundary.add_constraints(&mut triangulation, &poly2tri); + add_grid_constraints(&mut triangulation, &grid); + } else { + polyboundary.add_constraints(&mut triangulation, &poly2tri); + let grid = insert_surface(&mut triangulation, surface, polyboundary, tol, cap, steps, scale); + add_grid_constraints(&mut triangulation, &grid); } - insert_surface(&mut triangulation, surface, polyboundary, tol, cap, steps); let mut mesh = triangulation_into_polymesh( triangulation.vertices(), triangulation.inner_faces(), surface, polyboundary, + scale, ); // SolidCraft: a face that came out with no triangles at all, though its boundary encloses // an area in space (a lens thinner than the tolerance: its two edges are different curves, @@ -1157,7 +1151,7 @@ fn ear_clipping(points: &[[f64; 2]]) -> Option> { Some(triangles) } -/// Inserts parameter divisions into triangulation. +/// Inserts parameter divisions into triangulation; SolidCraft: returns their vertices, row by row, for [`add_grid_constraints`]. fn insert_surface( triangulation: &mut Cdt, surface: impl PreMeshableSurface, @@ -1165,11 +1159,12 @@ fn insert_surface( tol: Deflection, cap: usize, steps: Option, -) { + scale: UvScale, +) -> Vec>> { let bdb: BoundingBox = polyline.0.iter().flatten().collect(); let range = ((bdb.min()[0], bdb.max()[0]), (bdb.min()[1], bdb.max()[1])); if !(range.0 .0.is_finite() && range.0 .1.is_finite() && range.1 .0.is_finite() && range.1 .1.is_finite()) { - return; + return Vec::new(); } // SolidCraft: fixed preview grids skip both adaptive division and balancing. let (udiv, vdiv) = if let Some(n) = steps { @@ -1179,23 +1174,27 @@ fn insert_surface( let (u, v) = bounded_surface_division(&surface, range, tol, cap); let (u_ruled, v_ruled) = (u.len() <= 3, v.len() <= 3); let (u, v) = balanced_grid(&surface, u, v, cap); - let v = with_ruling_vertices(v, polyline, 1, tol.rulings && v_ruled, u.len(), cap); - let u = with_ruling_vertices(u, polyline, 0, tol.rulings && u_ruled, v.len(), cap); - let v = with_boundary_lines(v, polyline, 1, tol.rulings && v_ruled && !u_ruled, u.len(), cap); - let u = with_boundary_lines(u, polyline, 0, tol.rulings && u_ruled && !v_ruled, v.len(), cap); + let v = with_ruling_vertices(v, polyline, 1, tol.display && v_ruled, u.len(), cap); + let u = with_ruling_vertices(u, polyline, 0, tol.display && u_ruled, v.len(), cap); + let v = with_boundary_lines(v, polyline, 1, tol.display && v_ruled && !u_ruled, u.len(), cap); + let u = with_boundary_lines(u, polyline, 0, tol.display && u_ruled && !v_ruled, v.len(), cap); (u, v) }; - let insert_res: Vec>> = udiv - .into_iter() + udiv.into_iter() .map(|u| { vdiv.iter() .map(|v| match polyline.include(Point2::new(u, *v)) { - true => triangulation.insert(SPoint2::new(u, *v)).ok(), + true => triangulation.insert(scale.to_cdt(Point2::new(u, *v))).ok(), false => None, }) .collect() }) - .collect(); + .collect() +} + +/// SolidCraft: joins neighbouring grid points [`insert_surface`] inserted, where no constraint +/// is in the way (truck did this at the end of `insert_surface`). +fn add_grid_constraints(triangulation: &mut Cdt, insert_res: &[Vec>]) { insert_res.windows(2).for_each(|vec| { vec[0].windows(2).zip(&vec[1]).for_each(|(a, z)| { if let Some(x) = a[0] { @@ -1509,6 +1508,7 @@ fn triangulation_into_polymesh<'a>( triangles: InnerFaceIterator<'a, SPoint2, (), CdtEdge<()>, ()>, surface: &impl ParametricSurface3D, polyline: &PolyBoundary, + scale: UvScale, ) -> PolygonMesh { let mut positions = Vec::::new(); let mut uv_coords = Vec::::new(); @@ -1516,7 +1516,7 @@ fn triangulation_into_polymesh<'a>( let vmap: HashMap<_, _> = vertices .enumerate() .map(|(i, v)| { - let p = *v.as_ref(); + let p = scale.from_cdt(*v.as_ref()); let uv = Vector2::new(p.x, p.y); positions.push(surface.subs(uv[0], uv[1])); uv_coords.push(uv); @@ -1527,8 +1527,7 @@ fn triangulation_into_polymesh<'a>( let tri_faces: Vec<[StandardVertex; 3]> = triangles .map(|tri| tri.vertices()) .filter(|tri| { - fn sp2cg(p: SPoint2) -> Point2 { Point2::new(p.x, p.y) } - let tri = array![i => sp2cg(*tri[i].as_ref()); 3]; + let tri = array![i => scale.from_cdt(*tri[i].as_ref()); 3]; let (a, b) = (tri[1] - tri[0], tri[2] - tri[0]); let c = tri[0] + (a + b) / 3.0; let area = a.x * b.y - a.y * b.x; From 34afcf75c15dcd2d5da459ed41f43c6d085130f5 Mon Sep 17 00:00:00 2001 From: SS-EN <84559909+SS-EN@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:41:37 +0000 Subject: [PATCH 13/42] Joints: a loop that meets only to within nanometres still moves (#3475) A closed loop whose joints meet a few nanometres apart along their parallel axes (faces modelled that far apart) passes the conflict check, but the loop solver wanted 1e-7 mm before it moved anything. No value of a planar loop takes such a gap out, so every drive of it stopped at once (stopped_by_loop, fraction 0) and joint.reach called the loop open. The solver now closes such a loop as far as it comes and, when what is left is within the conflict check, keeps it that closed on the way. joint.drive, joint.reach and the nearby pose of the dof count share it. Co-authored-by: Claude Opus 5.5 --- crates/doc/src/joints.rs | 39 +++++++++-- crates/doc/src/joints_reach.rs | 24 ++++--- crates/engine/src/cmd/joints_tests.rs | 98 +++++++++++++++++++++++++++ 3 files changed, 145 insertions(+), 16 deletions(-) diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs index a099d7963..f929d1714 100644 --- a/crates/doc/src/joints.rs +++ b/crates/doc/src/joints.rs @@ -1235,6 +1235,29 @@ fn closure_gaps(tree: &Tree, closing: &[u64], vals: &Values, scale: f64, out: &m Some(()) } +/// How far a closing joint may be off before it is a conflict: its frames apart by more than +/// this many millimetres or turned by more than this many radians. +const CONFLICT_MM: f64 = 1e-6; +const CONFLICT_RAD: f64 = 1e-8; + +/// The largest gap (`closure_gaps`, for loops of size `scale`) that still passes the conflict +/// check, with room to spare. +fn loose_gap(scale: f64) -> f64 { + CONFLICT_MM.min(CONFLICT_RAD * scale) / 4.0 +} + +/// Close loops whose gaps `f` gives from `x`, and the tolerance to keep them closed to from here +/// on: `tol`, or, where they come no closer than that but within `loose`, a little more than they +/// do come. Faces modelled a few nanometres apart along parallel axes leave a gap no value of a +/// planar loop takes out; the loop still moves, as closed as it is. `None` when they can't close. +fn close_within(f: &mut dyn FnMut(&[f64]) -> Option>, x: &mut Vec, bounds: &[(f64, f64)], tol: f64, loose: f64) -> Option { + if least_squares(f, x, bounds, tol) { + return Some(tol); + } + let left = largest(&f(x)?); + (left <= loose).then(|| (4.0 * left).clamp(tol, loose.max(tol))) +} + /// Occurrences whose degrees of freedom are worked out through their loops, at most; the rest /// keep the tree's count. const MAX_DOF_OCCURRENCES: usize = 256; @@ -1287,7 +1310,7 @@ fn nearby_pose(tree: &Tree, groups: &[Group], asm: &Assembly, linked: &BTreeSet< closure_gaps(tree, closing, &work, scale, &mut out)?; out.iter().all(|v| v.is_finite()).then_some(out) }; - if least_squares(&mut gaps, &mut x, &bounds, (1e-10 * scale).min(1e-7)) + if close_within(&mut gaps, &mut x, &bounds, (1e-10 * scale).min(1e-7), loose_gap(scale)).is_some() && x.iter().zip(&x0).zip(&step).all(|((a, b), d)| (a - b).abs() <= 4.0 * d) && gaps(&x).is_some() { @@ -1525,11 +1548,15 @@ fn close_group( if moves.is_empty() && gaps(&x0, 1.0).is_some_and(|r| largest(&r) <= tol) { return Some(BTreeMap::new()); } - // A loop open at the start closes first. + // A loop open at the start closes first. One that comes only to within the conflict check + // (`close_within`) moves on as closed as it is; with nothing held moving, one that started + // that close is left as it is. let mut x = x0; - if largest(&gaps(&x, 0.0)?) > tol && !least_squares(&mut |x| gaps(x, 0.0), &mut x, &bounds, tol) { - return None; - } + let start = largest(&gaps(&x, 0.0)?); + let tol = match close_within(&mut |x| gaps(x, 0.0), &mut x, &bounds, tol, loose_gap(scale))? { + t if t > tol && moves.is_empty() && start <= t => return Some(BTreeMap::new()), + t => t, + }; let (mut t, mut dt) = (if moves.is_empty() { 1.0 } else { 0.0 }, first); let mut at = effective(&x, t); while t < 1.0 { @@ -1680,7 +1707,7 @@ pub fn solve_holding(doc: &Document, st: &ModelState, held: &Held) -> Solution { let (Some(want), Some((_, fb))) = (tree.step(*id, true, ta, &vals), tree.frames.get(id)) else { continue }; // Measured at the joint, where the loop solver closes it. let (dt, da) = mismatch(&mat_mul(&want, fb), &mat_mul(tb, fb)); - if dt > 1e-6 || da > 1e-8 { + if dt > CONFLICT_MM || da > CONFLICT_RAD { sol.conflicts.push(( j.id, j.name.clone(), diff --git a/crates/doc/src/joints_reach.rs b/crates/doc/src/joints_reach.rs index 07bd137f4..4a5f4fbf2 100644 --- a/crates/doc/src/joints_reach.rs +++ b/crates/doc/src/joints_reach.rs @@ -9,8 +9,8 @@ use solidcraft_geom::Vec3; use solidcraft_sketch::linalg; use super::{ - Assembly, Held, MAX_LOOP_VALUES, MAX_LOOP_WORK, MAX_LOOPS, Solution, Tree, Values, apply_links, build, closure_gaps, jacobian, joint_values, - largest, least_squares, limit_bounds, link_chains, loop_groups, loop_scale, unknowns, + Assembly, Held, MAX_LOOP_VALUES, MAX_LOOP_WORK, MAX_LOOPS, Solution, Tree, Values, apply_links, build, close_within, closure_gaps, jacobian, + joint_values, largest, least_squares, limit_bounds, link_chains, loop_groups, loop_scale, loose_gap, unknowns, }; use crate::{Document, ModelState, apply_point, apply_vector, mat_mul}; @@ -159,7 +159,7 @@ pub fn reach(doc: &Document, st: &ModelState, r: &Reach) -> Result().sqrt(); let before = f(&x0).map_or(f64::INFINITY, |r| miss(&r)); - let res = approach(&mut f, &|a, b| stride(asm, &vals, &vars, &paced, a, b), mt, &mut x, &bounds, &cap, tol) + let res = approach(&mut f, &|a, b| stride(asm, &vals, &vars, &paced, a, b), mt, &mut x, &bounds, &cap, tol, loose_gap(scale)) .ok_or("a closed loop on its chain is open and can't close (joint.list shows its conflict)")?; let mut out = Reached::default(); let point_miss = res.iter().take(3).map(|v| v * v).sum::().sqrt(); @@ -219,7 +219,7 @@ pub fn reach(doc: &Document, st: &ModelState, r: &Reach) -> Result Option>, stride: &dyn Fn(&[f64], &[f64]) -> f64, @@ -322,16 +322,20 @@ fn approach( bounds: &[(f64, f64)], cap: &[f64], tol: f64, + loose: f64, ) -> Option> { let n = x.len(); let miss = |r: &[f64]| r.iter().take(mt).map(|v| v * v).sum::(); - let close = |f: &mut dyn FnMut(&[f64]) -> Option>, x: &mut Vec| { - least_squares(&mut |y| f(y).map(|r| r.get(mt..).unwrap_or_default().to_vec()), x, bounds, tol * LOOP_WEIGHT) - }; + // The loops close first, to `tol` or as near as they come within `loose` (`close_within`), + // and stay that closed. let loops = f(x)?.len() > mt; - if loops && !close(f, x) { - return None; + let mut loop_tol = tol * LOOP_WEIGHT; + if loops { + loop_tol = close_within(&mut |y| f(y).map(|r| r.get(mt..).unwrap_or_default().to_vec()), x, bounds, loop_tol, loose * LOOP_WEIGHT)?; } + let close = |f: &mut dyn FnMut(&[f64]) -> Option>, x: &mut Vec| { + least_squares(&mut |y| f(y).map(|r| r.get(mt..).unwrap_or_default().to_vec()), x, bounds, loop_tol) + }; let mut r = f(x)?; let (mut lambda, mut kicked) = (1e-3, false); for _ in 0..MAX_REACH_STEPS { diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rs index af2590786..736757088 100644 --- a/crates/engine/src/cmd/joints_tests.rs +++ b/crates/engine/src/cmd/joints_tests.rs @@ -549,6 +549,104 @@ fn slider_crank_moves_the_piston() { } } +/// A slotted-arm drive: a clamp turns about the origin (Yaw) and carries a pin 26 from it; an arm +/// turns about a shaft 52 out on a motor fixed to the ground, and the pin slides in the arm's slot +/// (Slot: its frame at the shaft, x along the slot towards the pin). Every joint of the loop +/// moves when it does, the slot's included. The pin's face sits `gap` mm off the arm's along +/// the axes: a gap no value of the loop takes out, within the conflict check. +fn slotted_arm(yaw_first: bool, gap: f64) -> Session { + let mut s = Session::default(); + for (name, x) in [("Ground", 0.0), ("Clamp", 26.0), ("Motor", 52.0), ("Arm", 40.0)] { + part(&mut s, name, [x - 1.0, -1.0, -5.0]); + } + let g = occ(&s, "Ground"); + run(&mut s, "occurrence.ground", json!({"occurrence": g, "grounded": true})); + // The joint order sets the tree: with the yaw first, the arm hangs from the clamp through the + // slot and the arm's shaft closes the loop; with the motor first, the slot closes it. + if yaw_first { + pin(&mut s, "revolute", "Yaw", "Ground", "Clamp", Vec3::ZERO, Vec3::Z); + } + pin(&mut s, "rigid", "Mount", "Ground", "Motor", Vec3::new(52.0, 0.0, 0.0), Vec3::Z); + if !yaw_first { + pin(&mut s, "revolute", "Yaw", "Ground", "Clamp", Vec3::ZERO, Vec3::Z); + } + pin(&mut s, "revolute", "Shaft", "Arm", "Motor", Vec3::new(52.0, 0.0, 0.0), Vec3::Z); + let r = run( + &mut s, + "joint.create", + json!({"type": "pin_slot", "a": framed("Arm", [52.0, 0.0, 0.0], [0.0, 0.0, 1.0], [-1.0, 0.0, 0.0]), + "b": framed("Clamp", [26.0, 0.0, gap], [0.0, 0.0, 1.0], [-1.0, 0.0, 0.0]), "flip": true, "values": [0, 26], "name": "Slot"}), + ); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{r}"); + s +} + +/// A joint's stored values. +fn values_of(s: &Session, joint: &str) -> Vec { + s.doc.assembly.joints.iter().find(|j| j.name == joint).map(|j| j.values.clone()).unwrap_or_default() +} + +/// Driving either end of the slotted arm moves the other: the arm turns atan(26 sin θ / (52 − +/// 26 cos θ)) for a yaw θ, and the pin slides out from 26 to √(26² + 52² − 2·26·52 cos θ). +#[test] +fn slotted_arm_drives_both_ways() { + for (yaw_first, gap) in [(false, 0.0), (true, 0.0), (false, 3e-8), (true, 3e-8)] { + slotted_arm_drives(yaw_first, gap); + } +} + +fn slotted_arm_drives(yaw_first: bool, gap: f64) { + let mut s = slotted_arm(yaw_first, gap); + let (shaft, pin_at) = (Vec3::new(52.0, 0.0, 0.0), Vec3::new(26.0, 0.0, 0.0)); + let check = |s: &Session, what: &str| { + let th = values_of(s, "Yaw").first().copied().unwrap_or(f64::NAN); + let p = Vec3::new(26.0 * th.cos(), 26.0 * th.sin(), 0.0); + assert!(near(place(s, "Clamp", pin_at), p), "{what}: pin {:?} wants {p:?}", place(s, "Clamp", pin_at)); + let arm = values_of(s, "Shaft").first().copied().unwrap_or(f64::NAN); + let want = (26.0 * th.sin()).atan2(52.0 - 26.0 * th.cos()); + assert!((arm.abs() - want.abs()).abs() < 1e-6, "{what}: arm {arm} wants ±{want}"); + // The arm's slot points at the pin, which sits as far out as the slot says. + let tip = place(s, "Arm", Vec3::new(40.0, 0.0, 0.0)); + let along = (p - shaft) * (1.0 / (p - shaft).len()); + assert!(near(tip, shaft + along * 12.0), "{what}: arm tip {tip:?}"); + let slide = values_of(s, "Slot").get(1).copied().unwrap_or(f64::NAN); + assert!((slide.abs() - (p - shaft).len()).abs() < 1e-6, "{what}: slide {slide} wants {}", (p - shaft).len()); + }; + check(&s, &format!("yaw first {yaw_first}, gap {gap}, at rest")); + for v in [10.0, 40.0, -40.0, 0.0] { + let r = run(&mut s, "joint.drive", json!({"joint": "Yaw", "value": v})); + assert!( + r["stopped_by_loop"].is_null() && r["conflicts"].as_array().map(Vec::len) == Some(0), + "yaw first {yaw_first}, gap {gap}, yaw {v}°: {r}" + ); + assert!((values_of(&s, "Yaw").first().copied().unwrap_or(f64::NAN) - f64::to_radians(v)).abs() < 1e-9); + check(&s, &format!("yaw first {yaw_first}, gap {gap}, yaw {v}°")); + } + let slide = values_of(&s, "Slot").get(1).copied().unwrap_or(f64::NAN).abs(); + assert!((slide - 26.0).abs() < 1e-6, "{slide}"); + for v in [15.0, -27.0, 27.0] { + let r = run(&mut s, "joint.drive", json!({"joint": "Shaft", "value": v})); + assert!( + r["stopped_by_loop"].is_null() && r["conflicts"].as_array().map(Vec::len) == Some(0), + "yaw first {yaw_first}, gap {gap}, arm {v}°: {r}" + ); + assert!((values_of(&s, "Shaft").first().copied().unwrap_or(f64::NAN) - f64::to_radians(v)).abs() < 1e-9); + check(&s, &format!("yaw first {yaw_first}, gap {gap}, arm {v}°")); + } + // The clamp's pin reaches a point on its circle, the arm following. + let (th, at) = (20f64.to_radians(), place(&s, "Clamp", pin_at)); + let r = run(&mut s, "joint.reach", json!({"occurrence": "Clamp", "at": [at.x, at.y, at.z], "point": [26.0 * th.cos(), 26.0 * th.sin(), 0.0]})); + assert!(r["reached"] == json!(true) && r["stopped_by_loop"].is_null(), "yaw first {yaw_first}, gap {gap}, reach: {r}"); + check(&s, &format!("yaw first {yaw_first}, gap {gap}, reach")); + // A limit on the arm stops the yaw where the arm meets it. + run(&mut s, "joint.limits", json!({"joint": "Shaft", "min": -20, "max": 20})); + let r = run(&mut s, "joint.drive", json!({"joint": "Yaw", "value": 40})); + assert!(r["stopped_by_loop"].is_object() && r["conflicts"].as_array().map(Vec::len) == Some(0), "yaw first {yaw_first}, gap {gap}, limit: {r}"); + check(&s, &format!("yaw first {yaw_first}, gap {gap}, limit")); + let arm = values_of(&s, "Shaft").first().copied().unwrap_or(f64::NAN).abs().to_degrees(); + assert!(arm > 19.9 && arm <= 20.0 + 1e-9, "yaw first {yaw_first}, gap {gap}: the arm stopped at {arm}°"); +} + /// A joint frame on an occurrence, by origin and axes. fn framed(o: &str, origin: [f64; 3], z: [f64; 3], x: [f64; 3]) -> Value { json!({"occurrence": o, "frame": {"origin": origin, "z": z, "x": x}}) From b2168435baf7c076d303b3ca793677f28f8180ff Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 13:39:55 -0400 Subject: [PATCH 14/42] Web: save to and open from files on your computer (#104) (#3681) Save As and Open use the browser's file dialogs where the File System Access API exists; Save writes back to the same file, its handle kept in IndexedDB across reloads. File > Download design added. Other browsers keep storing designs in OPFS. --- apps/solidcraft-web/Cargo.toml | 1 + apps/solidcraft-web/src/disk.rs | 418 +++++++++++++++++++++++++++++++ apps/solidcraft-web/src/files.rs | 45 +++- apps/solidcraft-web/src/main.rs | 45 +++- apps/solidcraft/src/main.rs | 2 + crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/toolbar.rs | 48 ++++ docs/book/src/guide/files.md | 29 ++- 8 files changed, 568 insertions(+), 25 deletions(-) create mode 100644 apps/solidcraft-web/src/disk.rs diff --git a/apps/solidcraft-web/Cargo.toml b/apps/solidcraft-web/Cargo.toml index 668fe0860..6bfebbb56 100644 --- a/apps/solidcraft-web/Cargo.toml +++ b/apps/solidcraft-web/Cargo.toml @@ -29,5 +29,6 @@ web-sys = { version = "0.3", features = [ "Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "Location", "Navigator", "StorageManager", "FileSystemHandle", "FileSystemDirectoryHandle", "FileSystemFileHandle", "FileSystemGetFileOptions", "FileSystemWritableFileStream", "WritableStream", "File", "FileList", "Blob", "BlobPropertyBag", "Url", "HtmlAnchorElement", "HtmlInputElement", "Storage", + "IdbFactory", "IdbDatabase", "IdbObjectStore", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "BeforeUnloadEvent", "Event", "EventTarget", "Response", "MediaQueryList", "Gamepad", "Performance", ] } diff --git a/apps/solidcraft-web/src/disk.rs b/apps/solidcraft-web/src/disk.rs new file mode 100644 index 000000000..0b6b839ab --- /dev/null +++ b/apps/solidcraft-web/src/disk.rs @@ -0,0 +1,418 @@ +//! Designs on the computer's own disk, through the File System Access API (Chrome, Edge, Opera): +//! Save As and Open show the browser's file dialogs, and the chosen file's handle is kept (in +//! memory, and in IndexedDB so Save still reaches the file after a reload) so Save writes back to +//! it. To the engine such a design is the file `/disk//`: it saves there like anywhere, +//! and [`flush`](crate::files::flush) forwards what it wrote to the handle. Browsers without the +//! API (Firefox, Safari) keep designs in the origin private file system (`files.rs`). +//! +//! The path logic is plain Rust and tested natively; the browser calls are wasm-only. +#![cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + +/// Where a design on the computer's disk appears to the engine. +pub const PREFIX: &str = "/disk/"; + +/// The engine path of the design `name` kept under handle `id`. +pub fn path(id: &str, name: &str) -> String { + format!("{PREFIX}{id}/{name}") +} + +/// The handle id and file name of an engine path made by [`path`]. +pub fn parse(path: &str) -> Option<(&str, &str)> { + let (id, name) = path.strip_prefix(PREFIX)?.split_once('/')?; + (!id.is_empty() && !name.is_empty() && !name.contains('/')).then_some((id, name)) +} + +/// A handle id from the time and a random number. +pub fn make_id(ms: u64, random: u64) -> String { + format!("{ms:x}-{random:x}") +} + +/// Where a design saved with Save As goes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SaveTarget { + /// A file the user picks on their computer. + Disk, + /// The browser's private storage (OPFS): what browsers without the API have always done. + Browser, + /// Not a design (an export): handed over as a download. + Download, +} + +/// Choose where a Save As goes: designs to the disk when the browser can pick a file, else into +/// the browser's storage; anything else is a download. +pub fn save_target(api: bool, design: bool) -> SaveTarget { + match (design, api) { + (false, _) => SaveTarget::Download, + (true, true) => SaveTarget::Disk, + (true, false) => SaveTarget::Browser, + } +} + +/// Does a picker for `extensions` (what the command reads; `&[]`: anything) belong to a design? +/// Only those go through the disk dialog; inserting a STEP or mesh keeps using the file window. +pub fn opens_design(extensions: &[&str]) -> bool { + extensions.is_empty() || extensions.iter().any(|e| solidcraft_engine::io::DESIGN_EXTS.contains(e)) +} + +/// The file type a Save As dialog offers for `name`: (description, MIME type, extension). +pub fn save_type(name: &str) -> (&'static str, &'static str, &'static str) { + let json = std::path::Path::new(name).extension().is_some_and(|e| e.eq_ignore_ascii_case("json")); + if json { ("Plain JSON design", "application/json", ".json") } else { ("SolidCraft design", "application/octet-stream", ".solidcraft") } +} + +/// Is this a cancelled dialog (the browser's `AbortError`)? Not an error to show. +pub fn is_abort(error_name: &str) -> bool { + error_name == "AbortError" +} + +#[cfg(target_arch = "wasm32")] +pub use web::*; + +#[cfg(target_arch = "wasm32")] +mod web { + use std::cell::{Cell, RefCell}; + use std::collections::{HashMap, VecDeque}; + use std::rc::Rc; + + use js_sys::{Array, Function, Object, Promise, Reflect}; + use solidcraft_engine::io::vfs; + use wasm_bindgen::{JsCast as _, JsValue, closure::Closure}; + use wasm_bindgen_futures::{JsFuture, spawn_local}; + use web_sys::{FileSystemFileHandle, IdbDatabase, IdbObjectStore, IdbOpenDbRequest, IdbRequest, IdbTransactionMode}; + + use super::{is_abort, make_id, opens_design, parse, path, save_type}; + use crate::files::{Files, err, read_handle}; + + const DB: &str = "solidcraft-disk-handles"; + const STORE: &str = "handles"; + + thread_local! { + /// Handles picked or looked up in this session, by id. + static HANDLES: RefCell> = RefCell::new(HashMap::new()); + /// Writes waiting for their turn (a file takes one writer at a time), latest per id. + static QUEUE: RefCell)>> = const { RefCell::new(VecDeque::new()) }; + static BUSY: Cell = const { Cell::new(false) }; + } + + /// Why a dialog gave no file. + enum Pick { + Cancelled, + Failed(String), + } + + fn failed(e: JsValue) -> Pick { + let name = Reflect::get(&e, &"name".into()).ok().and_then(|n| n.as_string()).unwrap_or_default(); + if is_abort(&name) { Pick::Cancelled } else { Pick::Failed(err(e)) } + } + + /// Can this page show the browser's file dialogs and write to the files they pick? + pub fn supported() -> bool { + let Some(window) = web_sys::window() else { return false }; + let has = |name: &str| Reflect::get(&window, &name.into()).is_ok_and(|f| f.is_function()); + window.is_secure_context() && has("showSaveFilePicker") && has("showOpenFilePicker") + } + + /// Is `path` a design on the disk? + pub fn is_disk(path: &str) -> bool { + parse(path).is_some() + } + + fn types(description: &str, mime: &str, extension: &str) -> Array { + let accept = Object::new(); + let _ = Reflect::set(&accept, &mime.into(), &Array::of1(&extension.into())); + let entry = Object::new(); + let _ = Reflect::set(&entry, &"description".into(), &description.into()); + let _ = Reflect::set(&entry, &"accept".into(), &accept); + Array::of1(&entry) + } + + /// Start a dialog. This must run in the click that asked for it (the browser wants a user + /// gesture), so it is called before anything is awaited. + fn start_picker(function: &str, options: &Object) -> Result { + let window = web_sys::window().ok_or_else(|| Pick::Failed("no window".into()))?; + let f: Function = Reflect::get(&window, &function.into()) + .map_err(failed)? + .dyn_into() + .map_err(|_| Pick::Failed("this browser can't open file dialogs".into()))?; + f.call1(&window, options).map_err(failed)?.dyn_into().map_err(|_| Pick::Failed("no answer from the file dialog".into())) + } + + /// Remember a picked file: in memory now, in IndexedDB for the next session. + fn register(handle: &FileSystemFileHandle) -> String { + let id = make_id(js_sys::Date::now() as u64, (js_sys::Math::random() * 1e15) as u64); + HANDLES.with(|h| h.borrow_mut().insert(id.clone(), handle.clone())); + let (key, kept, name) = (id.clone(), handle.clone(), handle.name()); + spawn_local(async move { + if let Err(e) = remember(&key, &kept).await { + log::warn!("the file's handle isn't kept for the next session: {e}"); + } + }); + path(&id, &name) + } + + /// Save As, step one: show the browser's save dialog (call in the click). The answer is the + /// engine path the design is saved to, `None` when the dialog was closed. + pub fn pick_save(files: &Rc, name: &str) -> impl std::future::Future> + use<> { + let options = Object::new(); + let _ = Reflect::set(&options, &"suggestedName".into(), &name.into()); + let (description, mime, extension) = save_type(name); + let _ = Reflect::set(&options, &"types".into(), &types(description, mime, extension)); + let promise = start_picker("showSaveFilePicker", &options); + let files = files.clone(); + async move { + let handle = match promise { + Ok(p) => JsFuture::from(p) + .await + .map_err(failed) + .and_then(|h| h.dyn_into::().map_err(|_| Pick::Failed("not a file".into()))), + Err(e) => Err(e), + }; + match handle { + Ok(h) => Some(register(&h)), + Err(Pick::Cancelled) => None, + Err(Pick::Failed(e)) => { + files.say(format!("save: {e}"), true); + None + } + } + } + } + + /// Open, step one: show the browser's open dialog for a design (call in the click). The + /// answer is the engine path of the file, read into the engine's files; a design keeps its + /// handle, so Save writes back to the file. `None`: closed, or it could not be read. + pub fn pick_open(files: &Rc) -> impl std::future::Future> + use<> { + let promise = start_picker("showOpenFilePicker", &open_options()); + let files = files.clone(); + async move { + let r = async { + let p = promise?; + let handles: Array = JsFuture::from(p).await.map_err(failed)?.dyn_into().map_err(|_| Pick::Failed("no file".into()))?; + let h: FileSystemFileHandle = handles.get(0).dyn_into().map_err(|_| Pick::Cancelled)?; + let bytes = read_handle(&h).await.map_err(Pick::Failed)?; + Ok((h, bytes)) + }; + match r.await { + Ok((h, bytes)) => Some(arrive(&h, bytes)), + Err(Pick::Cancelled) => None, + Err(Pick::Failed(e)) => { + files.say(format!("open: {e}"), true); + None + } + } + } + } + + /// The options of the open dialog: a single file, designs and CAD files listed first. + pub fn open_options() -> Object { + let options = Object::new(); + let _ = Reflect::set(&options, &"multiple".into(), &JsValue::FALSE); + let extensions = Array::new(); + for e in [".solidcraft", ".solvecraft", ".json", ".step", ".stp", ".3mf", ".stl", ".obj", ".glb", ".gltf"] { + extensions.push(&e.into()); + } + let accept = Object::new(); + let _ = Reflect::set(&accept, &"application/octet-stream".into(), &extensions); + let entry = Object::new(); + let _ = Reflect::set(&entry, &"description".into(), &"Designs and CAD files".into()); + let _ = Reflect::set(&entry, &"accept".into(), &accept); + let _ = Reflect::set(&options, &"types".into(), &Array::of1(&entry)); + options + } + + /// A file read from a dialog's handle: a design lives at its disk path from now on (and + /// keeps the handle); anything else is an upload to open or insert. + pub fn arrive(handle: &FileSystemFileHandle, bytes: Vec) -> String { + let name = handle.name(); + let p = if solidcraft_engine::io::is_design_path(&name) { register(handle) } else { format!("{}{name}", crate::files::UPLOAD) }; + vfs::insert(&p, bytes); + p + } + + /// Does an Open for `extensions` use the browser's open dialog? + pub fn handles_open(extensions: &[&str]) -> bool { + supported() && opens_design(extensions) + } + + // ---- writing ------------------------------------------------------------------------ + + /// Queue what a command wrote to a disk path. Writes go one at a time; a newer write of the + /// same file replaces one still waiting. + pub fn enqueue(files: &Rc, path: &str, bytes: Vec) { + QUEUE.with(|q| { + let mut q = q.borrow_mut(); + q.retain(|(p, _)| p != path); + q.push_back((path.to_string(), bytes)); + }); + if BUSY.with(|b| b.replace(true)) { + return; + } + let files = files.clone(); + spawn_local(async move { + while let Some((path, bytes)) = QUEUE.with(|q| q.borrow_mut().pop_front()) { + if let Err(e) = write(&path, &bytes).await { + files.failed_disk(&path, &e); + } + } + BUSY.with(|b| b.set(false)); + }); + } + + async fn write(path: &str, bytes: &[u8]) -> Result<(), String> { + let (id, name) = parse(path).ok_or("not a file on the computer")?; + let handle = handle_for(id).await.map_err(|e| format!("{name}: {e}"))?; + ensure_readwrite(&handle).await.map_err(|e| format!("{name}: {e}"))?; + let w: web_sys::FileSystemWritableFileStream = + JsFuture::from(handle.create_writable()).await.map_err(err)?.dyn_into().map_err(|_| "no writable stream".to_string())?; + JsFuture::from(w.write_with_u8_array(bytes).map_err(err)?).await.map_err(err)?; + JsFuture::from(w.close()).await.map_err(err)?; + Ok(()) + } + + async fn handle_for(id: &str) -> Result { + if let Some(h) = HANDLES.with(|h| h.borrow().get(id).cloned()) { + return Ok(h); + } + let h: FileSystemFileHandle = recall(id) + .await? + .and_then(|v| v.dyn_into().ok()) + .ok_or("the browser no longer remembers where this design was saved: use Save As to choose the file again")?; + HANDLES.with(|m| m.borrow_mut().insert(id.to_string(), h.clone())); + Ok(h) + } + + /// Ask for write access if the browser doesn't hold it any more (after a reload): one prompt, + /// from the click that asked for the save. + async fn ensure_readwrite(handle: &FileSystemFileHandle) -> Result<(), String> { + let options = Object::new(); + let _ = Reflect::set(&options, &"mode".into(), &"readwrite".into()); + for method in ["queryPermission", "requestPermission"] { + let Some(f) = Reflect::get(handle, &method.into()).ok().and_then(|f| f.dyn_into::().ok()) else { + // A browser without the permission calls hands out writable handles as they are. + return Ok(()); + }; + let answer = f.call1(handle, &options).map_err(err)?; + let state = JsFuture::from(Promise::resolve(&answer)).await.map_err(err)?; + if state.as_string().as_deref() == Some("granted") { + return Ok(()); + } + } + Err("the browser wasn't given permission to write the file: use Save As to choose it again".into()) + } + + // ---- IndexedDB: the handles, by id -------------------------------------------------- + + /// The result of an IndexedDB request. + async fn result(req: &IdbRequest) -> Result { + let promise = Promise::new(&mut |resolve, reject| { + let r = req.clone(); + let ok = Closure::once_into_js(move || { + let _ = resolve.call1(&JsValue::NULL, &r.result().unwrap_or(JsValue::UNDEFINED)); + }); + let bad = Closure::once_into_js(move || { + let _ = reject.call1(&JsValue::NULL, &"IndexedDB failed".into()); + }); + req.set_onsuccess(Some(ok.unchecked_ref())); + req.set_onerror(Some(bad.unchecked_ref())); + }); + JsFuture::from(promise).await.map_err(err) + } + + async fn open_db() -> Result { + let factory = web_sys::window().ok_or("no window")?.indexed_db().map_err(err)?.ok_or("this browser has no IndexedDB")?; + let request: IdbOpenDbRequest = factory.open_with_u32(DB, 1).map_err(err)?; + let target = request.clone(); + let upgrade = Closure::once_into_js(move || { + if let Ok(db) = target.result().and_then(|r| r.dyn_into::()) { + let _ = db.create_object_store(STORE); + } + }); + request.set_onupgradeneeded(Some(upgrade.unchecked_ref())); + result(&request).await?.dyn_into().map_err(|_| "no database".to_string()) + } + + fn store(db: &IdbDatabase, mode: IdbTransactionMode) -> Result { + db.transaction_with_str_and_mode(STORE, mode).map_err(err)?.object_store(STORE).map_err(err) + } + + async fn remember(id: &str, handle: &FileSystemFileHandle) -> Result<(), String> { + let db = open_db().await?; + let req = store(&db, IdbTransactionMode::Readwrite)?.put_with_key(handle, &id.into()).map_err(err)?; + result(&req).await.map(|_| ()) + } + + async fn recall(id: &str) -> Result, String> { + let db = open_db().await?; + let req = store(&db, IdbTransactionMode::Readonly)?.get(&id.into()).map_err(err)?; + Ok(Some(result(&req).await?).filter(|v| !v.is_undefined())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_disk_path_round_trips_its_handle_id_and_name() { + let p = path("18f-2a", "Bracket v2.solidcraft"); + assert_eq!(p, "/disk/18f-2a/Bracket v2.solidcraft"); + assert_eq!(parse(&p), Some(("18f-2a", "Bracket v2.solidcraft"))); + } + + #[test] + fn only_disk_paths_parse() { + for not in [ + "/opfs/a.solidcraft", + "/downloads/a.step", + "/upload/a.step", + "/disk/", + "/disk/id", + "/disk/id/", + "/disk//a", + "/disk/id/x/y", + "a.solidcraft", + ] { + assert_eq!(parse(not), None, "{not}"); + } + } + + #[test] + fn handle_ids_differ_by_time_and_by_chance() { + assert_ne!(make_id(1, 5), make_id(2, 5)); + assert_ne!(make_id(1, 5), make_id(1, 6)); + assert!(!make_id(0, 0).contains('/')); + } + + /// Save As: a design goes to the disk where the browser can pick files and to the browser's + /// storage where it cannot (today's behaviour); an export is a download either way. + #[test] + fn save_as_chooses_between_the_disk_the_browsers_storage_and_a_download() { + assert_eq!(save_target(true, true), SaveTarget::Disk); + assert_eq!(save_target(false, true), SaveTarget::Browser); + assert_eq!(save_target(true, false), SaveTarget::Download); + assert_eq!(save_target(false, false), SaveTarget::Download); + } + + #[test] + fn only_design_opens_use_the_disk_dialog() { + assert!(opens_design(&[])); + assert!(opens_design(&["solidcraft"])); + assert!(opens_design(&["solvecraft"])); + assert!(!opens_design(&["step", "stp"])); + assert!(!opens_design(&["json"])); + } + + #[test] + fn the_save_dialog_offers_the_type_of_the_name() { + assert_eq!(save_type("Plate.solidcraft").2, ".solidcraft"); + assert_eq!(save_type("Plate.JSON").2, ".json"); + assert_eq!(save_type("Plate").2, ".solidcraft"); + } + + #[test] + fn closing_a_dialog_is_not_an_error() { + assert!(is_abort("AbortError")); + assert!(!is_abort("NotAllowedError")); + assert!(!is_abort("SecurityError")); + } +} diff --git a/apps/solidcraft-web/src/files.rs b/apps/solidcraft-web/src/files.rs index 126bede0c..42be96dee 100644 --- a/apps/solidcraft-web/src/files.rs +++ b/apps/solidcraft-web/src/files.rs @@ -2,14 +2,18 @@ //! the engine's in-memory files (`solidcraft_engine::io::vfs`) at start, written back whenever a //! command writes one. Files come in from the computer through a file picker (the File System //! Access API where the browser has it, an `` otherwise) or a drop on the page, -//! and go out as downloads (exports, and "Download design"). An autosave of unsaved work is kept -//! in OPFS too and offered again after a reload or a crash. +//! and go out as downloads (exports, and "Download design"). Where the File System Access API +//! exists a design also lives on the computer's disk, saved and opened through the browser's file +//! dialogs (`disk.rs`). An autosave of unsaved work is kept in OPFS and offered again after a +//! reload or a crash. use std::cell::{Cell, RefCell}; use std::rc::Rc; use js_sys::{Array, Function, Object, Reflect, Uint8Array}; use solidcraft_engine::io::vfs; + +use crate::disk; use wasm_bindgen::{JsCast as _, JsValue, closure::Closure}; use wasm_bindgen_futures::{JsFuture, spawn_local}; use web_sys::{FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemGetFileOptions, FileSystemWritableFileStream}; @@ -51,6 +55,10 @@ pub struct Files { pub entries: RefCell>, /// Files read from the computer: (name, bytes, what to do). pub incoming: RefCell, Intent)>>, + /// Designs opened from the computer's disk: their paths in the engine's files. + pub opened: RefCell>, + /// Disk designs whose last write failed: they are not saved. + pub unsaved: RefCell>, /// Messages for the status line (errors and confirmations). pub messages: RefCell>, /// The stored designs are loaded (the app may open them). @@ -64,11 +72,17 @@ pub struct Files { } impl Files { - fn say(&self, text: impl Into, error: bool) { + pub fn say(&self, text: impl Into, error: bool) { self.messages.borrow_mut().push((text.into(), error)); self.wake(); } + /// Writing the design at disk `path` failed: say so, and take its "saved" back. + pub fn failed_disk(&self, path: &str, error: &str) { + self.unsaved.borrow_mut().push(path.to_string()); + self.say(format!("Not saved to your computer: {error}"), true); + } + /// A file arrived from the computer. fn arrive(&self, name: String, bytes: Vec, intent: Intent) { self.incoming.borrow_mut().push((name, bytes, intent)); @@ -127,7 +141,7 @@ pub fn local_only() -> bool { LOCAL.with(Cell::get) } -fn err(e: JsValue) -> String { +pub(crate) fn err(e: JsValue) -> String { e.as_string().or_else(|| Reflect::get(&e, &"message".into()).ok().and_then(|m| m.as_string())).unwrap_or_else(|| format!("{e:?}")) } @@ -150,7 +164,7 @@ async fn root() -> Result { dir.dyn_into::().map_err(|_| "this browser has no private file storage (OPFS)".to_string()) } -async fn read_handle(h: &FileSystemFileHandle) -> Result, String> { +pub(crate) async fn read_handle(h: &FileSystemFileHandle) -> Result, String> { let file: web_sys::File = JsFuture::from(h.get_file()).await.map_err(err)?.dyn_into().map_err(|_| "not a file".to_string())?; blob_bytes(&file).await } @@ -311,6 +325,8 @@ pub fn flush(files: &Rc) { files.say(format!("{name}: {e}"), true); } }); + } else if crate::disk::is_disk(&path) { + disk::enqueue(files, &path, bytes); } else if let Some(name) = path.strip_prefix(DOWNLOADS) && let Err(e) = download(name, &bytes) { @@ -427,8 +443,15 @@ pub fn pick_from_disk(files: &Rc, intent: Intent) { let picker = Reflect::get(&window, &"showOpenFilePicker".into()).ok().and_then(|f| f.dyn_into::().ok()); match picker { Some(f) => { - let opts = Object::new(); - let _ = Reflect::set(&opts, &"multiple".into(), &JsValue::FALSE); + // A design from the computer's disk keeps its file, so Save writes back to it. + let on_disk = intent == Intent::Open && disk::supported(); + let opts = if on_disk { + disk::open_options() + } else { + let opts = Object::new(); + let _ = Reflect::set(&opts, &"multiple".into(), &JsValue::FALSE); + opts + }; let promise = f.call1(&window, &opts); let files = files.clone(); spawn_local(async move { @@ -438,7 +461,13 @@ pub fn pick_from_disk(files: &Rc, intent: Intent) { for h in handles.iter() { let h: FileSystemFileHandle = h.dyn_into().map_err(|_| "not a file".to_string())?; let bytes = read_handle(&h).await?; - files.arrive(h.name(), bytes, intent); + if on_disk && solidcraft_engine::io::is_design_path(&h.name()) { + let path = disk::arrive(&h, bytes); + files.opened.borrow_mut().push(path); + files.wake(); + } else { + files.arrive(h.name(), bytes, intent); + } } Ok::<(), String>(()) }; diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs index 4b4819f65..72de50bb3 100644 --- a/apps/solidcraft-web/src/main.rs +++ b/apps/solidcraft-web/src/main.rs @@ -8,6 +8,8 @@ #[cfg(target_arch = "wasm32")] mod api; +#[cfg(any(target_arch = "wasm32", test))] +mod disk; #[cfg(target_arch = "wasm32")] mod files; #[cfg(target_arch = "wasm32")] @@ -25,6 +27,7 @@ mod web { use wasm_bindgen::JsCast as _; use crate::api::Api; + use crate::disk::{self, SaveTarget}; use crate::files::{self, Files, Intent}; use crate::space_mouse::SpaceMouse; @@ -121,6 +124,18 @@ mod web { return; } files::flush(&self.files); + // A write to the computer's disk that failed: the design is not saved after all. + for path in self.files.unsaved.borrow_mut().drain(..) { + if self.app.session.path.as_deref() == Some(path.as_str()) { + self.app.session.mark_unsaved(); + } + } + // Designs opened from the computer's disk (the files window): open them. + let opened: Vec<_> = self.files.opened.borrow_mut().drain(..).collect(); + for path in opened { + self.app.open_path(&path); + self.files.panel.set(false); + } for (text, error) in self.files.messages.borrow_mut().drain(..) { self.app.set_status(text, error); } @@ -224,6 +239,9 @@ mod web { act = Some(("download_open", String::new())); } }); + if !disk::supported() { + ui.weak("This browser can't save to a folder: designs stay in this browser. Download design saves a file."); + } ui.separator(); if !self.files.ready.get() { ui.horizontal(|ui| { @@ -533,18 +551,33 @@ mod web { solidcraft_ui_egui::fonts::setup_fonts(&cc.egui_ctx); let files = Rc::new(Files::default()); files::start(&files); - let panel = files.clone(); + let (panel, opener, saver, shown) = (files.clone(), files.clone(), files.clone(), files.clone()); let services = Services { - // Open shows the browser's files (and the computer's, from there). - pick_open: Some(Box::new(move |_: &[&str]| { + // Open shows the browser's open dialog for a design where it has one + // (the file keeps its handle, so Save writes back to it); otherwise, + // and for inserting STEP or meshes, the browser's files window. + pick_open: Some(Box::new(move |exts: &[&str]| { + if disk::handles_open(exts) { + return Box::pin(disk::pick_open(&opener)); + } panel.panel.set(true); Box::pin(std::future::ready(None)) })), - // Designs are kept in the browser; everything else is downloaded. - pick_save: Some(Box::new(|name: &str, exts: &[&str]| { + // A design is saved to a file the user picks, or kept in the browser + // where the browser can't pick one; everything else is downloaded. + pick_save: Some(Box::new(move |name: &str, exts: &[&str]| { let design = exts.contains(&solidcraft_engine::io::DESIGN_EXT); - Box::pin(std::future::ready(Some(format!("{}{name}", if design { files::OPFS } else { files::DOWNLOADS })))) + match disk::save_target(disk::supported(), design) { + SaveTarget::Disk => Box::pin(disk::pick_save(&saver, name)), + SaveTarget::Browser => { + saver.say("This browser can't save to a folder: the design is kept in this browser. File > Download design saves a file.", false); + Box::pin(std::future::ready(Some(format!("{}{name}", files::OPFS)))) + } + SaveTarget::Download => Box::pin(std::future::ready(Some(format!("{}{name}", files::DOWNLOADS)))), + } })), + download_design: Some(Box::new(files::download)), + browser_files: Some(Box::new(move || shown.panel.set(true))), install_app: Some(crate::install::service(&cc.egui_ctx)), ..Default::default() }; diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index c4489c6fb..d80917d73 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -210,6 +210,8 @@ fn services(cc: &eframe::CreationContext<'_>) -> Services { http_download: Some(std::sync::Arc::new(http_download)), // Already an installed app: only the browser build offers to install. install_app: None, + download_design: None, + browser_files: None, agent_http: Some(std::sync::Arc::new(agent_http)), secrets: Some(std::sync::Arc::new(Keychain)), show_in_folder: Some(Box::new(|path| { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 514331e98..5d3be9ce3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -304,6 +304,11 @@ pub struct Services { pub http_download: Option, /// The browser's offer to install the web app (`install`); None: no Install button (desktop). pub install_app: Option, + /// Hand a design's bytes to the user as a downloaded file (name, bytes); the browser build's + /// File > Download design. None: the host saves real files, so there is nothing to offer. + pub download_design: Option Result<(), String>>>, + /// Show the designs the browser keeps for itself; None: the host has no such store. + pub browser_files: Option>, /// HTTP for the agent chat's API agents (OpenAI-compatible endpoints); None: no API agents. pub agent_http: Option, /// The system keychain, for API agents' keys; None: keys can't be stored. diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index e9650a944..be868569c 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -522,6 +522,17 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { save_as_with_extension(app, "json"); close = true; } + // The browser build: a copy as a downloaded file, whatever Save does. + if app.services.download_design.is_some() && item_if(ui, "Download design", "", shown) { + download_design(app); + close = true; + } + if app.services.browser_files.is_some() && item(ui, "Files in this browser…", "") { + if let Some(show) = &app.services.browser_files { + show(); + } + close = true; + } ui.separator(); if item_if(ui, "Save as mesh…", "", shown) { app.start("file.save_mesh"); @@ -619,6 +630,20 @@ fn save_as_with_extension(app: &mut SolveApp, extension: &str) { }); } +/// File > Download design (browser build): the open design as a `.solidcraft` file download. +fn download_design(app: &mut SolveApp) { + let name = format!("{}.{}", app.session.doc.name, solidcraft_engine::io::DESIGN_EXT); + let result = app + .session + .design_container(solidcraft_engine::io::DesignCompression::Fast, false, false) + .map_err(|e| e.to_string()) + .and_then(|bytes| app.services.download_design.as_ref().map_or(Ok(()), |download| download(&name, &bytes))); + match result { + Ok(()) => app.set_status(format!("Downloaded {name}"), false), + Err(e) => app.set_status(format!("Download design: {e}"), true), + } +} + fn export(app: &mut SolveApp, ext: &str) { export_as(app, ext, None); } @@ -1486,6 +1511,29 @@ mod header_report_tests { assert!(!solidcraft_engine::io::is_design_container(&std::fs::read(saved).unwrap()), "subsequent Save keeps a .json choice"); } + /// The browser build's File > Download design hands the open design to the host as a + /// `.solidcraft` container named after it; a host that saves real files shows no such item. + #[test] + fn file_menu_download_design_hands_the_container_to_the_host() { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length":2,"width":3,"height":4})).unwrap(); + h.app.session.doc_mut().name = "Plate".into(); + let got = std::rc::Rc::new(std::cell::RefCell::new(Vec::<(String, Vec)>::new())); + let sink = got.clone(); + h.app.services.download_design = Some(Box::new(move |name, bytes| { + sink.borrow_mut().push((name.to_string(), bytes.to_vec())); + Ok(()) + })); + h.frames(3); + h.step(&json!({"click":{"handle":"appbar:folder"}})).unwrap(); + h.step(&json!({"widget":"Download design"})).unwrap(); + let got = got.borrow(); + assert_eq!(got.len(), 1); + assert_eq!(got[0].0, "Plate.solidcraft"); + assert!(solidcraft_engine::io::is_design_container(&got[0].1)); + assert!(h.app.session.path.is_none(), "a download is no save: the design keeps no file"); + } + fn sizes(buttons: &[usize]) -> Vec { buttons.iter().map(|&b| PanelSize { buttons: b, labelled: false }).collect() } diff --git a/docs/book/src/guide/files.md b/docs/book/src/guide/files.md index ee253e6fa..7a05dd98c 100644 --- a/docs/book/src/guide/files.md +++ b/docs/book/src/guide/files.md @@ -164,18 +164,25 @@ copy its properties; Save As keeps them. A command script of the design ## Saving in the web app -In the web app, **Save** and **Save As** keep designs in this browser's private storage; -they do not open a dialog for choosing a folder on your computer. Clearing the site's data +In Chrome, Edge and Opera, **Save As** opens your browser's save dialog and writes the +`.solidcraft` file to the folder you choose, and **Open** opens the browser's open dialog. +**Save** then writes back to that same file. The browser remembers the file, so after you +reload the page the first **Save** asks once for permission to write to it, and carries on. +A design you open from your computer saves back to the file you opened. + +In Firefox and Safari, which can't write to a folder, **Save** and **Save As** keep designs in +this browser's private storage instead, and the app says so. Clearing the site's data can remove those designs. Download a copy to keep it outside the browser or move it to another device. -1. Open the File menu and choose **Open** to show **Files in this browser**. -2. Choose **Download open design** for the current design, including its unsaved changes, - or **Download** beside a stored file for its last saved contents. -3. Find the `.solidcraft` file in your browser's downloads. Whether a folder chooser appears - depends on your browser's download settings. +To get a copy as a download in any browser, choose **File → Download design**. It holds the +current design, including its unsaved changes. In **File → Files in this browser…** (and in +Firefox and Safari, **File → Open**), **Download open design** does the same, and **Download** +beside a stored file gives its last saved contents. Whether a folder chooser appears depends +on your browser's download settings. -Use **Open from computer…** in the same panel to reopen a downloaded design. The web app -works on a browser-stored copy; later saves do not update the original downloaded file. -Use **Rename** beside a stored file to change its name. Exports such as STEP and STL are -also downloaded. +Use **Open from computer…** in the same window to open a design from your computer; where the +browser can write to a folder it saves back to that file, otherwise it works on a copy kept +in the browser. Use **Rename** beside a stored file to change its name. Autosave and recovery +stay in the browser's private storage in every browser. Exports such as STEP and STL are +downloaded. From 76af4ee855f6ba4995fa27f9d57229c22eaac63b Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 13:51:01 -0400 Subject: [PATCH 15/42] =?UTF-8?q?Web:=20Save=20to=20computer=E2=80=A6=20fo?= =?UTF-8?q?r=20designs=20kept=20in=20the=20browser;=20OPFS=20writes=20rout?= =?UTF-8?q?e=20as=20before=20(#104)=20(#3687)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/solidcraft-web/src/disk.rs | 99 ++++++++++++++++++++++++++++---- apps/solidcraft-web/src/files.rs | 44 +++++++------- apps/solidcraft-web/src/main.rs | 11 ++++ 3 files changed, 124 insertions(+), 30 deletions(-) diff --git a/apps/solidcraft-web/src/disk.rs b/apps/solidcraft-web/src/disk.rs index 0b6b839ab..dc3396903 100644 --- a/apps/solidcraft-web/src/disk.rs +++ b/apps/solidcraft-web/src/disk.rs @@ -11,6 +11,38 @@ /// Where a design on the computer's disk appears to the engine. pub const PREFIX: &str = "/disk/"; +/// Where designs kept in the browser's private storage (OPFS) appear to the engine. +pub const OPFS_PREFIX: &str = "/opfs/"; +/// Paths written here are handed to the user as downloads. +pub const DOWNLOADS_PREFIX: &str = "/downloads/"; + +/// Where what a command wrote to an engine path goes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WriteTo { + /// The browser's private storage: the design (or recovery file) keeps its name there. + Opfs, + /// A file on the computer, through its handle. + Disk, + /// A download. + Download, + /// Kept only in memory (uploads). + Memory, +} + +/// Route a write by its path. OPFS paths always go to OPFS, whatever the browser can do: a design +/// opened from the browser's storage keeps saving there until the user picks Save As. +pub fn route(path: &str) -> WriteTo { + if path.starts_with(OPFS_PREFIX) { + WriteTo::Opfs + } else if parse(path).is_some() { + WriteTo::Disk + } else if path.starts_with(DOWNLOADS_PREFIX) { + WriteTo::Download + } else { + WriteTo::Memory + } +} + /// The engine path of the design `name` kept under handle `id`. pub fn path(id: &str, name: &str) -> String { format!("{PREFIX}{id}/{name}") @@ -112,11 +144,6 @@ mod web { window.is_secure_context() && has("showSaveFilePicker") && has("showOpenFilePicker") } - /// Is `path` a design on the disk? - pub fn is_disk(path: &str) -> bool { - parse(path).is_some() - } - fn types(description: &str, mime: &str, extension: &str) -> Array { let accept = Object::new(); let _ = Reflect::set(&accept, &mime.into(), &Array::of1(&extension.into())); @@ -150,14 +177,45 @@ mod web { path(&id, &name) } - /// Save As, step one: show the browser's save dialog (call in the click). The answer is the - /// engine path the design is saved to, `None` when the dialog was closed. - pub fn pick_save(files: &Rc, name: &str) -> impl std::future::Future> + use<> { + fn save_options(name: &str) -> Object { let options = Object::new(); let _ = Reflect::set(&options, &"suggestedName".into(), &name.into()); let (description, mime, extension) = save_type(name); let _ = Reflect::set(&options, &"types".into(), &types(description, mime, extension)); - let promise = start_picker("showSaveFilePicker", &options); + options + } + + /// "Save to computer…" for a design kept in the browser: write a copy of `bytes` to a file the + /// user picks (call in the click), or download it where the browser can't pick one. The design + /// itself stays where it is. + pub fn save_copy(files: &Rc, name: &str, bytes: Vec) { + if !supported() { + if let Err(e) = crate::files::download(name, &bytes) { + files.say(format!("{name}: {e}"), true); + } + return; + } + let promise = start_picker("showSaveFilePicker", &save_options(name)); + let files = files.clone(); + spawn_local(async move { + let r = async { + let h: FileSystemFileHandle = + JsFuture::from(promise?).await.map_err(failed)?.dyn_into().map_err(|_| Pick::Failed("not a file".into()))?; + write_handle(&h, &bytes).await.map_err(Pick::Failed)?; + Ok::(h.name()) + }; + match r.await { + Ok(saved) => files.say(format!("Saved a copy to {saved}"), false), + Err(Pick::Cancelled) => {} + Err(Pick::Failed(e)) => files.say(format!("save to computer: {e}"), true), + } + }); + } + + /// Save As, step one: show the browser's save dialog (call in the click). The answer is the + /// engine path the design is saved to, `None` when the dialog was closed. + pub fn pick_save(files: &Rc, name: &str) -> impl std::future::Future> + use<> { + let promise = start_picker("showSaveFilePicker", &save_options(name)); let files = files.clone(); async move { let handle = match promise { @@ -261,7 +319,11 @@ mod web { async fn write(path: &str, bytes: &[u8]) -> Result<(), String> { let (id, name) = parse(path).ok_or("not a file on the computer")?; let handle = handle_for(id).await.map_err(|e| format!("{name}: {e}"))?; - ensure_readwrite(&handle).await.map_err(|e| format!("{name}: {e}"))?; + write_handle(&handle, bytes).await.map_err(|e| format!("{name}: {e}")) + } + + async fn write_handle(handle: &FileSystemFileHandle, bytes: &[u8]) -> Result<(), String> { + ensure_readwrite(handle).await?; let w: web_sys::FileSystemWritableFileStream = JsFuture::from(handle.create_writable()).await.map_err(err)?.dyn_into().map_err(|_| "no writable stream".to_string())?; JsFuture::from(w.write_with_u8_array(bytes).map_err(err)?).await.map_err(err)?; @@ -376,6 +438,23 @@ mod tests { } } + /// Designs already stored in OPFS (and the recovery files) keep saving to OPFS under their own + /// names, whether or not the browser can write to the disk. + #[test] + fn writes_to_opfs_paths_still_go_to_opfs() { + for p in + ["/opfs/Bracket.solidcraft", "/opfs/Bracket (2).solidcraft", "/opfs/recovery.solidcraft", "/opfs/recovery.json", "/opfs/old.solvecraft"] + { + assert_eq!(route(p), WriteTo::Opfs, "{p}"); + } + // A design opened from OPFS saves to its own path; only a Save As can pick the disk. + assert_eq!(save_target(false, true), SaveTarget::Browser); + assert_eq!(route(&format!("{OPFS_PREFIX}Bracket.solidcraft")), WriteTo::Opfs); + assert_eq!(route("/disk/18f-2a/Bracket.solidcraft"), WriteTo::Disk); + assert_eq!(route("/downloads/part.step"), WriteTo::Download); + assert_eq!(route("/upload/part.step"), WriteTo::Memory); + } + #[test] fn handle_ids_differ_by_time_and_by_chance() { assert_ne!(make_id(1, 5), make_id(2, 5)); diff --git a/apps/solidcraft-web/src/files.rs b/apps/solidcraft-web/src/files.rs index 42be96dee..79341a976 100644 --- a/apps/solidcraft-web/src/files.rs +++ b/apps/solidcraft-web/src/files.rs @@ -19,9 +19,9 @@ use wasm_bindgen_futures::{JsFuture, spawn_local}; use web_sys::{FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemGetFileOptions, FileSystemWritableFileStream}; /// Where OPFS files appear to the engine. -pub const OPFS: &str = "/opfs/"; +pub const OPFS: &str = disk::OPFS_PREFIX; /// Paths written here are handed to the user as downloads. -pub const DOWNLOADS: &str = "/downloads/"; +pub const DOWNLOADS: &str = disk::DOWNLOADS_PREFIX; /// Files brought in from the computer. pub const UPLOAD: &str = "/upload/"; /// The autosave of unsaved work (in OPFS: `recovery.solidcraft` and `recovery.json`). @@ -309,28 +309,32 @@ pub fn start(files: &Rc) { /// Store what commands wrote: OPFS paths into OPFS, download paths as downloads. pub fn flush(files: &Rc) { for (path, bytes) in vfs::take_writes() { - if let Some(name) = path.strip_prefix(OPFS) { - let name = name.to_string(); - { - let mut e = files.entries.borrow_mut(); - e.retain(|x| x.name != name); - if name != RECOVERY && name != RECOVERY_META { - e.push(Entry { name: name.clone(), size: bytes.len() as u64, modified: js_sys::Date::now() }); - e.sort_by_key(|a| a.name.to_lowercase()); + match disk::route(&path) { + disk::WriteTo::Opfs => { + let name = path.strip_prefix(OPFS).unwrap_or(&path).to_string(); + { + let mut e = files.entries.borrow_mut(); + e.retain(|x| x.name != name); + if name != RECOVERY && name != RECOVERY_META { + e.push(Entry { name: name.clone(), size: bytes.len() as u64, modified: js_sys::Date::now() }); + e.sort_by_key(|a| a.name.to_lowercase()); + } } + let files = files.clone(); + spawn_local(async move { + if let Err(e) = write_file(&name, &bytes).await { + files.say(format!("{name}: {e}"), true); + } + }); } - let files = files.clone(); - spawn_local(async move { - if let Err(e) = write_file(&name, &bytes).await { + disk::WriteTo::Disk => disk::enqueue(files, &path, bytes), + disk::WriteTo::Download => { + let name = path.strip_prefix(DOWNLOADS).unwrap_or(&path); + if let Err(e) = download(name, &bytes) { files.say(format!("{name}: {e}"), true); } - }); - } else if crate::disk::is_disk(&path) { - disk::enqueue(files, &path, bytes); - } else if let Some(name) = path.strip_prefix(DOWNLOADS) - && let Err(e) = download(name, &bytes) - { - files.say(format!("{name}: {e}"), true); + } + disk::WriteTo::Memory => {} } } } diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs index 72de50bb3..feb74f40a 100644 --- a/apps/solidcraft-web/src/main.rs +++ b/apps/solidcraft-web/src/main.rs @@ -288,6 +288,13 @@ mod web { self.renaming = Some((e.name.clone(), e.name.clone())); self.rename_focus = true; } + if ui + .small_button("Save to computer…") + .on_hover_text("A copy in a file you choose; the stored design stays here") + .clicked() + { + act = Some(("save_copy", e.name.clone())); + } if ui.small_button("Download").clicked() { act = Some(("download", e.name.clone())); } @@ -323,6 +330,10 @@ mod web { } Err(e) => self.app.set_status(e.to_string(), true), }, + "save_copy" => match vfs::read(&path, solidcraft_engine::io::MAX_DESIGN_BYTES) { + Ok(b) => disk::save_copy(&self.files, &name, b), + Err(e) => self.app.set_status(e.to_string(), true), + }, "download_open" => { let d = &self.app.session.doc; let result = self From 5d9ebe991112b540302e783a30976bb5ac867b64 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 14:08:59 -0400 Subject: [PATCH 16/42] Renaming a feature no longer rebuilds the design (#3044) (#3097) * perf: renaming a feature evaluates nothing (#3044) A feature's name labels it and builds nothing, but a timeline rename evaluated the whole design again (about 70 s on the Prusa Core One assembly, and again for undo). When the only change is one feature's name, the model renames its result, sketch and construction geometry in place and takes the renamed design's fingerprints. A rename other features follow (a plane a sketch is on) or of a failed feature still evaluates the design. Co-Authored-By: Claude Opus 5.5 * Guard cheap commands on designs with thousands of bodies, plus a scaling bench (#3044) (#3121) Cheap commands stay cheap on designs with thousands of bodies, with a scaling bench. --------- Co-authored-by: Claude Opus 5.5 --- crates/doc/src/document.rs | 16 +++++ crates/doc/src/eval.rs | 53 +++++++++++++- crates/engine/src/cmd/edit_tests.rs | 61 ++++++++++++++++ crates/engine/src/lib.rs | 11 ++- crates/engine/src/tests.rs | 47 ++++++++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/scale_tests.rs | 107 ++++++++++++++++++++++++++++ crates/ui-egui/src/viewport.rs | 4 +- 8 files changed, 295 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/scale_tests.rs diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 8b5ed6eed..2a3ea293b 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -2718,6 +2718,22 @@ impl Document { (expected == *self).then_some((old, new)) } + /// The feature whose name alone turns `previous` into this design, when that is all that + /// changed. + pub fn feature_rename_from(&self, previous: &Document) -> Option { + if self.features.len() != previous.features.len() { + return None; + } + let mut renamed = previous.features.iter().zip(&self.features).filter(|(a, b)| a.id == b.id && a.name != b.name); + let (_, b) = renamed.next()?; + if renamed.next().is_some() { + return None; + } + let mut expected = previous.clone(); + expected.feature_mut(b.id)?.name.clone_from(&b.name); + (expected == *self).then_some(b.id) + } + /// A complete structural proof: no non-render field is allowed to differ. Keeping this /// comparison based on the whole Document also includes fields added in future versions. /// The clone/comparison is only needed when render intent actually differs. diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index c4ced0c4b..fecbe34d7 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1533,7 +1533,57 @@ impl Model { .clone(); r.state = state; } - // The fingerprints of the renamed design, so the next evaluation reuses every result. + self.refingerprint(doc); + true + } + + /// Follow a rename of feature `id` to `doc`'s name for it without evaluating anything: a + /// feature's name labels it (its result, its sketch, its construction geometry) but builds + /// nothing. False, leaving the model as it was, when the model isn't the design's, the + /// feature failed, or a later failed feature's error quotes its old name: evaluate then. + pub fn rename_feature(&mut self, doc: &Document, id: u64) -> bool { + if self.results.len() != doc.features.len() || self.results.iter().zip(&doc.features).any(|(r, f)| r.id != f.id || r.stale) { + return false; + } + let Some(name) = doc.feature(id).map(|f| f.name.clone()) else { return false }; + let Some(at) = self.results.iter().position(|r| r.id == id) else { return false }; + // An error may quote the old name: the feature's own, or a later one's that refers to it + // by id (a pattern of it: "{name} cannot be patterned or mirrored yet"). + let old = self.results.get(at).map(|r| r.name.clone()).unwrap_or_default(); + if self.results.iter().skip(at).any(|r| r.error.as_deref().is_some_and(|e| r.id == id || e.contains(&old))) { + return false; + } + if let Some(r) = self.results.get_mut(at) { + r.name.clone_from(&name); + } + let mut renamed: std::collections::HashMap<*const ModelState, Arc> = std::collections::HashMap::new(); + for r in self.results.iter_mut().skip(at) { + let labels = r.state.sketches.iter().any(|k| k.feature == id) || r.state.construct.iter().any(|c| c.feature == id); + if !labels { + continue; + } + let state = renamed + .entry(Arc::as_ptr(&r.state)) + .or_insert_with(|| { + let mut st = (*r.state).clone(); + for k in st.sketches.iter_mut().filter(|k| k.feature == id) { + Arc::make_mut(k).name.clone_from(&name); + } + for c in st.construct.iter_mut().filter(|c| c.feature == id) { + c.name.clone_from(&name); + } + Arc::new(st) + }) + .clone(); + r.state = state; + } + self.refingerprint(doc); + true + } + + /// Set every result's fingerprint to `doc`'s, so the next evaluation reuses every result + /// (after a change that builds nothing differently). + fn refingerprint(&mut self, doc: &Document) { let (vals, _) = evaluation_values(doc); let marker = doc.marker.unwrap_or(usize::MAX); self.step_digests = StepDigests::of(doc, &self.step_digests); @@ -1542,7 +1592,6 @@ impl Model { prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &self.step_digests); r.fingerprint = prev; } - true } } diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index e29aede83..bdc464f7b 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -746,3 +746,64 @@ fn edit_takes_dotted_keys_and_numbers_for_expressions() { } assert_eq!(*s.doc, before); } + +/// #3044: renaming a feature labels it and builds nothing, so it, its undo and its redo evaluate +/// nothing, and leave the model evaluating the renamed design gives (the result's, the sketch's +/// and the construction plane's names). A rename other features follow is evaluated. +#[test] +fn renaming_a_feature_evaluates_nothing() { + let mut s = Session::default(); + run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 5, "name": "Shelf"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Outline"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 6]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 4, "name": "Plate"})); + let labels = |s: &Session| { + let st = s.model.state(); + let results: Vec = s.model.results.iter().map(|r| r.name.clone()).collect(); + let sketches: Vec = st.sketches.iter().map(|k| k.name.clone()).collect(); + let planes: Vec = st.construct.iter().map(|c| c.name.clone()).collect(); + (results, sketches, planes) + }; + for (feature, name) in [("Outline", "Profile"), ("Plate", "Base plate")] { + s.evaluations = 0; + run(&mut s, "timeline.rename", json!({"feature": feature, "name": name})); + assert_eq!(s.evaluations, 0, "renaming {feature} evaluates nothing"); + let mut fresh = Session::new((*s.doc).clone()); + fresh.refresh(); + assert_eq!(labels(&s), labels(&fresh)); + s.refresh(); + assert_eq!(s.model.last_recomputed, 0, "the next evaluation reuses every result"); + } + let renamed = labels(&s); + s.evaluations = 0; + run(&mut s, "edit.undo", json!({})); + assert!(labels(&s).0.contains(&"Profile".to_string()) && labels(&s).0.contains(&"Plate".to_string())); + run(&mut s, "edit.redo", json!({})); + assert_eq!(labels(&s), renamed); + assert_eq!(s.evaluations, 0, "undo and redo of a rename evaluate nothing"); + // A sketch on the plane names it: renaming the plane renames it there too, which is evaluated. + run(&mut s, "sketch.create", json!({"plane": "Shelf", "name": "Top"})); + run(&mut s, "sketch.finish", json!({})); + s.evaluations = 0; + run(&mut s, "timeline.rename", json!({"feature": "Shelf", "name": "Ledge"})); + assert!(s.evaluations > 0); + assert!(labels(&s).2.contains(&"Ledge".to_string())); + // A failed pattern's error quotes its source's name: renaming the source is evaluated, so + // the error names it as an evaluation does. + run(&mut s, "solid.pattern.rectangular", json!({"features": ["Base plate"], "dir1": [0, 0, 1], "count1": 2, "spacing1": 10, "name": "Copies"})); + let copies = s.doc.find_feature("Copies").unwrap().id; + if let Some(solidcraft_doc::FeatureKind::Pattern { features, .. }) = s.doc_mut().feature_mut(copies).map(|f| &mut f.kind) { + *features = vec!["Top".into()]; + } + s.refresh(); + let failed = |s: &Session| s.model.results.iter().filter_map(|r| r.error.clone()).collect::>(); + assert!(failed(&s).iter().any(|e| e.contains("Top")), "{:?}", failed(&s)); + s.evaluations = 0; + run(&mut s, "timeline.rename", json!({"feature": "Top", "name": "Lid sketch"})); + assert!(s.evaluations > 0, "a later error quotes the old name"); + assert!(failed(&s).iter().any(|e| e.contains("Lid sketch")), "{:?}", failed(&s)); + let mut fresh = Session::new((*s.doc).clone()); + fresh.refresh(); + assert_eq!(failed(&s), failed(&fresh)); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 29516295b..3eae93671 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -633,8 +633,8 @@ impl Session { } /// [`Session::refresh`] after the design changed from `previous`; a change that only renamed - /// a body (or undid or redid such a rename) renames it in the model instead, which keeps - /// every result and mesh (#3044). + /// a body or a feature (or undid or redid such a rename) renames it in the model instead, + /// which keeps every result and mesh (#3044). fn refresh_from(&mut self, previous: &Arc) { if let Some((old, new)) = self.body_rename(previous) && self.model.rename_body(&self.doc, &old, &new) @@ -645,6 +645,13 @@ impl Session { } return; } + // A feature's name labels it and builds nothing. + if let Some(id) = self.doc.feature_rename_from(previous) + && self.model.rename_feature(&self.doc, id) + { + self.revision += 1; + return; + } self.refresh(); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7c5e24363..42d9f57fe 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3850,3 +3850,50 @@ fn renaming_an_imported_assembly_body_reads_nothing_again() { assert_eq!(s.evaluations, 0, "nor does its undo"); let _ = std::fs::remove_dir_all(&dir); } + +/// #3044: on a design with thousands of bodies the cheap commands stay cheap: showing, hiding, +/// selecting, colouring and renaming a body or a feature, and undoing them, recompute no feature +/// (renames don't even look over the timeline) and leave every body's display mesh as it was, so +/// nothing is meshed or uploaded again. +#[test] +fn cheap_commands_on_thousands_of_bodies_evaluate_nothing() { + let mut s = Session::default(); + for k in 0..2 { + run( + &mut s, + "solid.box", + json!({"length": 4, "width": 4, "height": 4, "center": [0, 6 * k, 2], "operation": "new", "name": format!("Seed{k}")}), + ); + run( + &mut s, + "solid.pattern.rectangular", + json!({"features": [format!("Seed{k}")], "dir1": [1, 0, 0], "count1": 1000, "spacing1": 6, "name": format!("Row{k}")}), + ); + } + let st = s.model.state(); + assert_eq!(st.bodies.len(), 2000); + let meshes = |s: &Session| s.model.state().bodies.iter().map(|b| std::sync::Arc::as_ptr(&b.mesh())).collect::>(); + let shown = meshes(&s); + s.refresh(); + for (command, params) in [ + ("select.set", json!({"items": [{"type": "body", "name": "Body7"}]})), + ("browser.visibility", json!({"visible": false, "items": ["Body7"]})), + ("browser.visibility", json!({"visible": true, "items": ["Body7"]})), + ("appearance.assign", json!({"bodies": ["Body7"], "appearance": "Aluminum - Satin"})), + ("body.rename", json!({"body": "Body7", "name": "Renamed"})), + ("timeline.rename", json!({"feature": "Row1", "name": "Second row"})), + ("edit.undo", json!({})), + ("edit.undo", json!({})), + ("edit.redo", json!({})), + ] { + s.evaluations = 0; + run(&mut s, command, params); + // Renames are followed in the model; the rest may look over the timeline, which then + // finds every result as it was. + assert_eq!(s.model.last_recomputed, 0, "{command} recomputed a feature"); + if command.ends_with("rename") { + assert_eq!(s.evaluations, 0, "{command} evaluated the design"); + } + } + assert_eq!(meshes(&s), shown, "every body keeps its mesh"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5d3be9ce3..44adfee3d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -86,6 +86,8 @@ pub mod messages; #[cfg(test)] mod pattern_arrow_tests; #[cfg(test)] +mod scale_tests; +#[cfg(test)] mod surface_clamp_tests; #[cfg(test)] mod surface_errors_tests; diff --git a/crates/ui-egui/src/scale_tests.rs b/crates/ui-egui/src/scale_tests.rs new file mode 100644 index 000000000..fcd56ba46 --- /dev/null +++ b/crates/ui-egui/src/scale_tests.rs @@ -0,0 +1,107 @@ +//! How the cost of a frame and of cheap commands grows with the number of bodies (#3044): a +//! design with many bodies must not make every frame or every click slower per body squared. + +use serde_json::json; + +use crate::scenario::Harness; + +/// A design of `n` boxes (ten patterns of a box each), in a headless app, settled. +fn grid(n: usize) -> Harness { + let mut h = Harness::new(); + let per = n.div_ceil(10).max(1); + for k in 0..n.div_ceil(per) { + let count = per.min(n - k * per); + h.app + .run("solid.box", json!({"length": 4, "width": 4, "height": 4, "center": [0, 6 * k, 2], "operation": "new", "name": format!("Seed{k}")})) + .unwrap(); + if count > 1 { + h.app + .run( + "solid.pattern.rectangular", + json!({"features": [format!("Seed{k}")], "dir1": [1, 0, 0], "count1": count, "spacing1": 6, "name": format!("Row{k}")}), + ) + .unwrap(); + } + } + assert_eq!(h.app.session.model.state().bodies.len(), n); + h.frames(3); + h +} + +fn ms(f: impl FnOnce()) -> f64 { + let t = std::time::Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1000.0 +} + +/// Times per body count; run with `--ignored --nocapture` (not a pass/fail check). +#[test] +#[ignore = "manual scaling measurement"] +fn frame_and_cheap_command_cost_by_body_count() { + for n in [50, 500, 5000] { + let mut h = grid(n); + h.app.session.world_state().warm_meshes(|| true); + let scene_cold = ms(|| drop(crate::viewport::build_scene(&h.app))); + let scene_again = ms(|| drop(crate::viewport::build_scene(&h.app))); + let idle = ms(|| h.frames(10)) / 10.0; + h.app.tree.expanded.insert("c0/bodies".into()); + h.frames(2); + let expanded = ms(|| h.frames(10)) / 10.0; + let rename = ms(|| { + h.app.run("body.rename", json!({"body": "Body7", "name": "Renamed"})).unwrap(); + h.frame(); + }); + let scene_renamed = ms(|| drop(crate::viewport::build_scene(&h.app))); + let select = ms(|| { + h.app.run("select.set", json!({"items": [{"type": "body", "name": "Renamed"}]})).unwrap(); + h.frame(); + }); + let highlight = ms(|| drop(crate::viewport::build_highlight(&h.app))); + let hide = ms(|| { + h.app.run("browser.visibility", json!({"visible": false, "items": ["Renamed"]})).unwrap(); + h.frame(); + }); + let undo = ms(|| { + h.app.run("edit.undo", json!({})).unwrap(); + h.frame(); + }); + println!( + "SCALE n={n} scene_cold_ms={scene_cold:.2} scene_again_ms={scene_again:.2} scene_renamed_ms={scene_renamed:.2} highlight_ms={highlight:.2} idle_frame_ms={idle:.2} expanded_frame_ms={expanded:.2} rename_ms={rename:.2} select_ms={select:.2} hide_ms={hide:.2} undo_ms={undo:.2}" + ); + } +} + +/// A design from a file (`SOLIDCRAFT_SCALE_DESIGN`), every browser folder open: the time of an +/// idle frame and of the cheap commands, as [`frame_and_cheap_command_cost_by_body_count`]. +#[test] +#[ignore = "manual measurement on a design file"] +fn frame_cost_of_a_design_file() { + let Some(path) = std::env::var_os("SOLIDCRAFT_SCALE_DESIGN") else { return }; + let bytes = std::fs::read(&path).unwrap(); + let doc = solidcraft_engine::io::read_design(&bytes).unwrap(); + let mut h = Harness::new(); + h.app.session = solidcraft_engine::Session::new(doc); + h.app.session.world_state().warm_meshes(|| true); + h.frames(3); + let idle = ms(|| h.frames(5)) / 5.0; + let keys: Vec = + h.app.session.doc.components.iter().flat_map(|c| ["bodies", "components", "occurrences"].map(|f| format!("c{}/{f}", c.id))).collect(); + h.app.tree.expanded.extend(keys); + h.frames(2); + let expanded = ms(|| h.frames(5)) / 5.0; + let scene = ms(|| drop(crate::viewport::build_scene(&h.app))); + let scene_again = ms(|| drop(crate::viewport::build_scene(&h.app))); + let bodies = h.app.session.world_state().bodies.len(); + let rename = ms(|| { + h.app.run("body.rename", json!({"body": "Body1", "name": "Renamed"})).unwrap(); + h.frame(); + }); + let scene_renamed = ms(|| drop(crate::viewport::build_scene(&h.app))); + println!( + "DESIGN bodies={bodies} idle_frame_ms={idle:.2} expanded_frame_ms={expanded:.2} scene_ms={scene:.2} scene_again_ms={scene_again:.2} rename_ms={rename:.2} scene_renamed_ms={scene_renamed:.2}" + ); + let t = std::time::Instant::now(); + while t.elapsed().as_secs() < std::env::var("SOLIDCRAFT_SCALE_LOOP").ok().and_then(|v| v.parse().ok()).unwrap_or(0) { + h.frame(); + } +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index aaae8c4a2..64d36b710 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -646,7 +646,7 @@ fn push_block( made.insert(key, block); } -fn build_scene(app: &SolveApp) -> GpuScene { +pub(crate) fn build_scene(app: &SolveApp) -> GpuScene { let tk = Tokens::get(); let mut sc = GpuScene::default(); let s = &app.session; @@ -1977,7 +1977,7 @@ struct HoverBlock { } /// The highlight scene: origin widget, construction planes, selection and hover. -fn build_highlight(app: &SolveApp) -> GpuScene { +pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { let t = Tokens::get(); let mut sc = GpuScene::default(); let st = crate::open_meshing::shown_world(app); From 20a0d3b2e4f7d9ebe14c06e85170b43fccc2759e Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 14:13:53 -0400 Subject: [PATCH 17/42] README: Trendshift badge (#3706) --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 4dcc5562e..25ad4b0f6 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,10 @@ Stars

+

+ tangency-labs%2Fsolidcraft | Trendshift +

+ ![SolidCraft 0.8: model a Raspberry Pi 4 case from an empty design: a sketch dimensioned with parameters, extrude, fillets and shell, a rim rounded in one pick, standoffs patterned on the board's mounting holes, port cut-outs, vent slots, "Pi 4" engraved in a font, a PETG material with its mass in Properties, and a height change in Parameters](docs/screenshots/demo-0.8.gif) *A Raspberry Pi 4 case from an empty design: a sketch dimensioned with the board's parameters, extrude, fillet, shell, the rim rounded in one pick, an M2.5 standoff patterned on the 58 × 49 mm hole rectangle, port cut-outs, vent slots, "Pi 4" engraved in DejaVu Sans Bold and a PETG material defined in the design, with its mass in Properties, then height 24 → 32 mm in Parameters and it all rebuilds. 9× playback. [Full video](https://github.com/tangency-labs/solidcraft/raw/refs/heads/main/docs/screenshots/demo-0.8.mp4), recorded with the [demo script](examples/demo/record_ui.sh).* From 3606d44ad919ad526a6930af332c6128c6e90901 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 14:20:13 -0400 Subject: [PATCH 18/42] README: Trendshift Rust badge next to the overall one (#3714) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 25ad4b0f6..1aecd1768 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@

tangency-labs%2Fsolidcraft | Trendshift + tangency-labs%2Fsolidcraft | Trendshift (Rust)

![SolidCraft 0.8: model a Raspberry Pi 4 case from an empty design: a sketch dimensioned with parameters, extrude, fillets and shell, a rim rounded in one pick, standoffs patterned on the board's mounting holes, port cut-outs, vent slots, "Pi 4" engraved in a font, a PETG material with its mass in Properties, and a height change in Parameters](docs/screenshots/demo-0.8.gif) From a0c1a672206efb82af495cbacbdde49209ea61db Mon Sep 17 00:00:00 2001 From: Nathan Dane Date: Tue, 20 Oct 2026 17:23:49 +0000 Subject: [PATCH 19/42] Application bar and ribbon redesign (step 1 of #2016) (#2176) * ui: spacing, radius and type tokens, per-tab accents, agent and on-accent tokens * ui: per-tab accent behaviour and a larger application bar with a Start page button * icons: silhouette master and flat assistant and agent link icons (open for review) * icons: apply review notes (sparkle assistant, refined plug, silhouette halo) * icons: wire the silhouette master to inspect.silhouette; record the accepted icons * ui: application bar to the design: separators, Save, house, assistant icon, readable hovers * ui: ribbon structure: Model to View tabs, contextual Sketch and Sheet Metal, migrated pins * ui: ribbon painting to the compact design * ui: smaller icon button highlight and assistant mark on the bubble corner * ui: short ribbon labels that wrap at spaces * ui: ribbon buttons fit their labels and Finish Sketch shows its full name * ui: constraint gallery, workspace menu, section list headings and richer tooltips * ui: lighter selected tab label, ribbon surface and dimmer bar separators match the dark design * ui: document tabs as rounded chips with a dimmer inactive label * ui: document tabs fit their names and show close only when active or hovered * icons: close and plus masters for the document tabs (open for review) * ui: centre the new-tab plus and overflow button on the bar * ui: a quiet rule under the ribbon tabs on non-contextual tabs * ui: the application bar mark separates its faces with the bar colour, not white * ui: open ribbon section label uses the selected tint and a chevron * ui: dim the tab close and plus icons until hovered * ui: every ribbon dropdown uses the chevron, the workspace card included * ui: the active document tab uses the design's surface colour * ui: the bug button's right padding mirrors its icon side * ui: square constraint cells and a rule before the grid * ui: constraint cells back to their earlier size, keeping the rule * ui: smaller constraint cells and icons, centred in the section * ui: constraint cells fit the height of the large buttons' icon and label * ui: sketch Create titles share the other labels' line * ui: format the application bar and ribbon changes * ui: active tab surface token and the colour and hover tests that follow the redesign * tests: the merged parameter and narrow toolbar tests follow the compact ribbon * i18n: the Malay Gap label has an English source and its Japanese and Chinese translations * apply_off_thread tests: the evaluation lingers in tests, so still computing never depends on machine speed --------- Co-authored-by: bherbruck --- ATTRIBUTION.md | 4 + assets/icons/ui/design/review.json | 2 + .../icons/ui/design/svg/flat/agent_link.svg | 6 + assets/icons/ui/design/svg/flat/assistant.svg | 11 + assets/icons/ui/design/svg/flat/close.svg | 4 + assets/icons/ui/design/svg/flat/plus.svg | 4 + assets/icons/ui/source/glyphs.rs | 8 +- assets/locales/cs.json | 27 + assets/locales/de.json | 27 + assets/locales/en.json | 83 +- assets/locales/es.json | 27 + assets/locales/fr.json | 27 + assets/locales/gl.json | 27 + assets/locales/ja.json | 83 +- assets/locales/ko.json | 27 + assets/locales/pt-BR.json | 27 + assets/locales/ru.json | 27 + assets/locales/tr.json | 27 + assets/locales/uk.json | 27 + assets/locales/zh.json | 79 + assets/styles/ui/palettes.rs | 50 +- crates/ui-egui/src/agent_chat/mod.rs | 60 +- crates/ui-egui/src/agent_chat/tests.rs | 44 +- crates/ui-egui/src/agent_cursor.rs | 3 +- crates/ui-egui/src/browser.rs | 16 +- crates/ui-egui/src/colour_tokens_tests.rs | 9 +- crates/ui-egui/src/colour_vision_tests.rs | 74 +- crates/ui-egui/src/context_menu.rs | 163 +- crates/ui-egui/src/control.rs | 3 +- crates/ui-egui/src/dialogs.rs | 7 +- crates/ui-egui/src/dialogs_sheet_tests.rs | 7 +- crates/ui-egui/src/dialogs_surface.rs | 1 + crates/ui-egui/src/dim_view.rs | 1 + crates/ui-egui/src/documents.rs | 103 +- crates/ui-egui/src/frame.rs | 10 +- crates/ui-egui/src/home.rs | 43 +- crates/ui-egui/src/i18n.rs | 4 + crates/ui-egui/src/i18n_ui_tests.rs | 14 +- crates/ui-egui/src/icons.rs | 43 +- crates/ui-egui/src/lib.rs | 16 +- crates/ui-egui/src/menu_tests.rs | 12 +- crates/ui-egui/src/prefs.rs | 2 +- crates/ui-egui/src/preview.rs | 39 +- crates/ui-egui/src/render_workspace.rs | 5 +- crates/ui-egui/src/shortcut_box.rs | 38 +- crates/ui-egui/src/sketch_dims.rs | 1 + crates/ui-egui/src/sketch_modify_ui_tests.rs | 2 +- crates/ui-egui/src/sketch_palette.rs | 2 +- crates/ui-egui/src/sketch_text.rs | 2 +- crates/ui-egui/src/sketch_tools.rs | 34 - crates/ui-egui/src/theme.rs | 129 +- crates/ui-egui/src/theme_files.rs | 11 +- crates/ui-egui/src/timeline.rs | 15 +- crates/ui-egui/src/timeline_left.rs | 8 +- crates/ui-egui/src/titlebar.rs | 59 +- crates/ui-egui/src/toolbar.rs | 1489 ++++++++++++----- crates/ui-egui/src/toolbar_custom.rs | 114 +- crates/ui-egui/src/update/tests.rs | 7 +- crates/ui-egui/src/viewport.rs | 33 +- crates/ui-egui/src/viewport_layout_tests.rs | 8 +- crates/ui-egui/src/workspace.rs | 832 +++++++-- crates/ui-egui/tests/parameter_enter.rs | 5 +- crates/ui-egui/tests/parameter_order.rs | 4 +- crates/ui-egui/tests/scenarios.rs | 13 +- .../tests/scenarios/ribbon_docked.json | 26 + .../scenarios/s09_step_roundtrip_hole.json | 10 +- .../scenarios/s13_plastic_enclosure.json | 2 +- .../scenarios/s14_appearance_export.json | 10 +- .../s15_start_page_sample_save_reopen.json | 4 +- .../s40_toolbar_customize_persists.json | 16 +- .../scenarios/s46_toolbar_dropdown_hover.json | 8 +- .../s47_toolbar_drag_from_dropdown.json | 6 +- .../scenarios/s48_toolbar_many_pins.json | 50 +- .../scenarios/s49_sketch_point_toolbar.json | 9 +- .../scenarios/s50_toolbar_panel_drops.json | 20 +- .../sketch_centerline_toolbar_icon.json | 5 +- crates/ui-egui/tests/ui_layout.rs | 75 + docs/agent-chat.md | 4 +- docs/book/src/guide/parameters.md | 4 +- docs/book/src/guide/plastic.md | 4 +- docs/book/src/guide/sheet-metal.md | 3 +- docs/book/src/guide/ui-tour.md | 6 +- docs/control-protocol.md | 2 +- docs/ribbon-layout.md | 149 ++ 84 files changed, 3592 insertions(+), 910 deletions(-) create mode 100644 assets/icons/ui/design/svg/flat/agent_link.svg create mode 100644 assets/icons/ui/design/svg/flat/assistant.svg create mode 100644 assets/icons/ui/design/svg/flat/close.svg create mode 100644 assets/icons/ui/design/svg/flat/plus.svg create mode 100644 crates/ui-egui/tests/scenarios/ribbon_docked.json create mode 100644 docs/ribbon-layout.md diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index d109bb129..a9a38d33d 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -137,6 +137,7 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/icons/ui/design/palette.toml | SolidCraft contributors | icon colour roles (light and dark) and accents, original SolidCraft data | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/bug_report.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/chevron.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/close.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/fit.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/folder.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/help.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | @@ -145,6 +146,7 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/icons/ui/design/svg/flat/moon.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/nav_settings.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/orbit.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/plus.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/pan.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/perspective.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/flat/redo.svg | SolidCraft contributors | single-colour application/navigation icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | @@ -281,6 +283,8 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/icons/ui/design/svg/model/perforate.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/pipe.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/silhouette.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/assistant.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/agent_link.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/placeholder.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/plane.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/plane_angle.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | diff --git a/assets/icons/ui/design/review.json b/assets/icons/ui/design/review.json index e8381d42c..d3583be57 100644 --- a/assets/icons/ui/design/review.json +++ b/assets/icons/ui/design/review.json @@ -4,6 +4,7 @@ "accessibility": "012aa26ece9ffa8bd6a850b7a19279c3675164b12438f5fbfe560e575c8fe2eb", "activate": "9d28c47dcb0b733095eadc840a30fa898a19f9cf9eee203496386546666cb1f8", "agent_chat": "4a9ae0e7e2c360b4858b3175674c93d096705c92318fecd481e849f3ae650bf4", + "agent_link": "2f20d89a0e3e9b28744910dddf7f282a1099ccd91aa160c9841c5b1d9ea9ed0f", "align": "05615db7dd9e4be56ae898e59a68c548b8a8447794442a9a394940651204bc4f", "appearance": "b3162edd92291a5ef402e8499cd52be05beb2fa7eda641163c3f6e98325de2bf", "arc3": "fdca3d501fd557ac989376a12e9c4fa8231fde2b455c20724d1079a466153e9c", @@ -12,6 +13,7 @@ "arc_slot_center": "ba93e773e06e948fcf3c6dab28df341c07d35c6a3afa33a840b261bb82bcf32b", "arc_tangent": "d6910c8d42878cc34617b96e26c3018f4a6e4e793443ac81f2c294f88d70fa28", "as_built": "0f481932deca5586a8a8ea3d707efca0747f5c59559d53830b694d3458531013", + "assistant": "8fac392b16b4f13c6a399c59962b97c1912282e0ec909976496959472f1d642d", "auto_constrain": "012e5da4ff83449f6a3a92ee2d9924998cbeea545281bdf97873710b7436183d", "axis": "66ebabe43a7b1b73b59a3a03b7bd92ab54d899947d0cc2d93ad6e6aac4d76501", "axis_edge": "5a65898bc38bdaaaf5b04f2c2f7556915b5b7b1fdc4de9708fcc30f64aa1ab18", diff --git a/assets/icons/ui/design/svg/flat/agent_link.svg b/assets/icons/ui/design/svg/flat/agent_link.svg new file mode 100644 index 000000000..ff496e985 --- /dev/null +++ b/assets/icons/ui/design/svg/flat/agent_link.svg @@ -0,0 +1,6 @@ + + Connected agent + + + + diff --git a/assets/icons/ui/design/svg/flat/assistant.svg b/assets/icons/ui/design/svg/flat/assistant.svg new file mode 100644 index 000000000..ccbfcd03f --- /dev/null +++ b/assets/icons/ui/design/svg/flat/assistant.svg @@ -0,0 +1,11 @@ + + Assistant + + + + + + + + + diff --git a/assets/icons/ui/design/svg/flat/close.svg b/assets/icons/ui/design/svg/flat/close.svg new file mode 100644 index 000000000..b2278302f --- /dev/null +++ b/assets/icons/ui/design/svg/flat/close.svg @@ -0,0 +1,4 @@ + + Close + + diff --git a/assets/icons/ui/design/svg/flat/plus.svg b/assets/icons/ui/design/svg/flat/plus.svg new file mode 100644 index 000000000..ff70459a2 --- /dev/null +++ b/assets/icons/ui/design/svg/flat/plus.svg @@ -0,0 +1,4 @@ + + Plus + + diff --git a/assets/icons/ui/source/glyphs.rs b/assets/icons/ui/source/glyphs.rs index 75edc8fe1..6650a38c0 100644 --- a/assets/icons/ui/source/glyphs.rs +++ b/assets/icons/ui/source/glyphs.rs @@ -98,10 +98,6 @@ pub(crate) fn breadcrumb(p: &egui::Painter, c: egui::Pos2, col: Color32) { p.line_segment([pos2(c.x + 1.5, c.y), pos2(c.x - 1.5, c.y + 3.0)], s); } -pub(crate) fn caret(p: &egui::Painter, c: egui::Pos2, col: Color32) { - p.add(egui::Shape::convex_polygon(vec![pos2(c.x - 3.5, c.y - 2.0), pos2(c.x + 3.5, c.y - 2.0), pos2(c.x, c.y + 2.5)], col, Stroke::NONE)); -} - pub(crate) fn brand_mark(p: &egui::Painter, c: Pos2) { let s = 20.0 / 412.217; let m = |pts: &[(f32, f32)]| -> Vec { pts.iter().map(|&(x, y)| pos2(c.x + (x - 178.5) * s, c.y + (y - 206.1) * s)).collect() }; @@ -109,7 +105,9 @@ pub(crate) fn brand_mark(p: &egui::Painter, c: Pos2) { let face = |col: Color32, pts: &[(f32, f32)]| { p.add(egui::Shape::convex_polygon(m(pts), col, Stroke::NONE)); }; - let [light, mid, dark, edge_col] = crate::theme::Tokens::get().logo; + // The faces are separated by gaps that show the application bar, not by white lines. + let [light, mid, dark, _] = crate::theme::Tokens::get().logo; + let edge_col = crate::theme::Tokens::get().app_bar; face(light, &[(3.5, 105.9), (177.0, 5.8), (263.4, 55.6), (263.8, 156.0), (177.0, 406.4)]); face(light, &[(177.0, 206.1), (263.8, 156.0), (350.5, 206.2), (350.5, 306.3), (177.0, 406.4)]); face(mid, &[(3.5, 105.9), (177.0, 206.1), (177.0, 406.4)]); diff --git a/assets/locales/cs.json b/assets/locales/cs.json index 8c4d47f64..786444d52 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -3,9 +3,11 @@ "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Otevřete níže koncept na GitHubu a vložte hlášení zkopírované do schránky.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Otevřete níže koncept na GitHubu. Název a hlášení se vyplní automaticky.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Přiložte snímek obrazovky: zkopírujte a vložte jej, nebo uložte a nahrajte PNG.", + "2D": "2D", "3. Click Submit new issue on GitHub to send your report.": "3. Hlášení odešlete na GitHubu tlačítkem Submit new issue.", "A new configuration, a copy of the active one": "Nová konfigurace, kopie aktivní", "AI": "AI", + "ARRANGE": "USPOŘÁDAT", "About SolidCraft": "O aplikaci SolidCraft", "Active": "Aktivní", "Active rule": "Aktivní pravidlo", @@ -36,6 +38,12 @@ "Body": "Těleso", "Boundary": "Hranice", "Bounding box": "Ohraničující kvádr", + "CHECK": "KONTROLA", + "COMPONENTS": "KOMPONENTY", + "CONFIGURATIONS": "KONFIGURACE", + "CONSTRAIN": "VAZBY", + "CONTACT": "KONTAKT", + "CONVERT": "PŘEVÉST", "CSV or JSON: updates existing parameters, adds new ones": "CSV nebo JSON: aktualizuje existující parametry, přidá nové", "Capture All Positions": "Zachytit všechny polohy", "Catch Direction": "Směr záchytu", @@ -101,6 +109,8 @@ "Export hidden edges as dashed lines": "Exportovat skryté hrany čárkovaně", "Extend to meet": "Prodloužit k protnutí", "Extents": "Rozsahy", + "FILES": "SOUBORY", + "FLAT": "ROZVIN", "Face": "Plocha", "Face attachment lost": "Připojení k ploše ztraceno", "Faces": "Plochy", @@ -117,21 +127,26 @@ "From edges": "Výchozí hrany", "Full Length": "Celá délka", "Grid": "Mřížka", + "HISTORY": "HISTORIE", "Height": "Výška", "Hidden edges": "Skryté hrany", "Holes": "Otvory", "Holes (edges on them)": "Otvory (jejich hrany)", "Home view": "Výchozí pohled", + "IMAGES": "OBRÁZKY", "In This Design": "V tomto návrhu", "In place (surfaces)": "Na místě (plochy)", "In plane": "V rovině", "Inside": "Uvnitř", "Interferes": "Koliduje", "Issue title": "Název hlášení", + "JOINTS": "SPOJE", "Joint Origin1": "Počátek kloubu1", "Keep (points on it)": "Ponechat (body na ní)", "Keep Tools": "Ponechat nástroje", "Keep of the other surface": "Ponechat z druhé plochy", + "LIBRARY": "KNIHOVNA", + "LINKS": "ODKAZY", "Later": "Později", "Leave it": "Nechat být", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Starší typ připojení k ploše. Novým navázáním na ověřenou plochu vznikne přesné připojení.", @@ -141,6 +156,10 @@ "Library": "Knihovna", "Line Spacing": "Řádkování", "Loop": "Smyčka", + "MANAGE": "SPRÁVA", + "MATERIALS": "MATERIÁLY", + "MODEL": "MODEL", + "MOTION": "POHYB", "Margin": "Okraj", "Mass": "Hmotnost", "Material": "Materiál", @@ -163,6 +182,7 @@ "Normal to sketch": "Kolmo ke skice", "Not available yet": "Zatím není k dispozici", "Notch": "Zářez", + "OUTPUT": "VÝSTUP", "Opacity": "Neprůhlednost", "Open GitHub draft": "Otevřít koncept na GitHubu", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Open-source parametrický 3D CAD v jazyce Rust. Licence MIT OR Apache-2.0.", @@ -187,7 +207,9 @@ "Profiles/Curves": "Profily/křivky", "Projection": "Promítání", "RECENT": "NEDÁVNÉ", + "REFERENCE": "REFERENCE", "RULED SURFACE": "PŘÍMKOVÁ PLOCHA", + "RULES": "PRAVIDLA", "Radius Fit": "Proložení poloměrem", "Ratio": "Poměr", "Reattach selected face": "Znovu připojit k vybrané ploše", @@ -219,6 +241,8 @@ "Roll History Marker Here": "Přesunout značku historie sem", "Round": "Zaoblený", "Rule": "Pravidlo", + "SECTION": "ŘEZ", + "SURFACE QUALITY": "KVALITA POVRCHU", "Save Rule": "Uložit pravidlo", "Save the study as an animated GIF, seen as the viewport shows it": "Uložit studii jako animovaný GIF tak, jak ji zobrazuje pohled", "Saved preview. Geometry is being checked before editing.": "Uložený náhled. Geometrie se před úpravou kontroluje.", @@ -285,6 +309,7 @@ "Use saved fixed plane": "Použít uloženou pevnou rovinu", "Use selected face as fixed plane": "Použít vybranou plochu jako pevnou rovinu", "VIEW": "POHLED", + "VIEWS": "POHLEDY", "Value": "Hodnota", "Vertices": "Vrcholy", "View navigator": "Navigátor pohledu", @@ -1351,6 +1376,8 @@ "ui.restore_defaults": "Obnovit výchozí", "ui.reverse_zoom_direction": "Obrátit směr přiblížení", "ui.revolve": "Rotace", + "ui.ribbon_exit": "Ukončit", + "ui.ribbon_workspace": "Pracovní prostředí", "ui.right": "Zprava", "ui.save": "Uložit", "ui.save_as": "Uložit jako", diff --git a/assets/locales/de.json b/assets/locales/de.json index 8be6072b1..a44087874 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -2,8 +2,10 @@ "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Unten den GitHub-Entwurf öffnen und den kopierten Bericht aus der Zwischenablage einfügen.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Unten den GitHub-Entwurf öffnen. Titel und Bericht werden vorausgefüllt.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Screenshot anhängen: kopieren und einfügen oder als PNG speichern und hochladen.", + "2D": "2D", "3. Click Submit new issue on GitHub to send your report.": "3. Auf GitHub auf Submit new issue klicken, um den Bericht zu senden.", "AI": "KI", + "ARRANGE": "ANORDNEN", "Acceleration": "Beschleunigung", "Against": "Gegen", "Alignment": "Ausrichtung", @@ -13,6 +15,12 @@ "BROWSER": "BROWSER", "Bends": "Biegungen", "Boundary": "Begrenzung", + "CHECK": "PRÜFEN", + "COMPONENTS": "KOMPONENTEN", + "CONFIGURATIONS": "KONFIGURATIONEN", + "CONSTRAIN": "ABHÄNGIGKEITEN", + "CONTACT": "KONTAKT", + "CONVERT": "KONVERTIEREN", "Centre to centre": "Mitte zu Mitte", "Check collisions": "Kollisionen prüfen", "Circumference": "Umfang", @@ -41,20 +49,31 @@ "Export DXF…": "DXF exportieren…", "Export hidden edges as dashed lines": "Verdeckte Kanten gestrichelt exportieren", "Extend to meet": "Verlängern, bis sie sich treffen", + "FILES": "DATEIEN", + "FLAT": "ABWICKLUNG", "Face": "Fläche", "Faces": "Flächen", "Find in Browser": "Im Browser suchen", "Flat": "Flach", "From edges": "Ausgangskanten", + "HISTORY": "VERLAUF", "Hidden edges": "Verdeckte Kanten", "Holes": "Löcher", "Holes (edges on them)": "Löcher (ihre Kanten)", + "IMAGES": "BILDER", "In place (surfaces)": "An Ort und Stelle (Flächen)", "In plane": "In der Ebene", "Inside": "Innen", + "JOINTS": "GELENKE", "Keep (points on it)": "Behalten (Punkte darauf)", "Keep of the other surface": "Vom anderen Flächenkörper behalten", + "LIBRARY": "BIBLIOTHEK", + "LINKS": "VERKNÜPFUNGEN", "Length": "Länge", + "MANAGE": "VERWALTEN", + "MATERIALS": "MATERIALIEN", + "MODEL": "MODELL", + "MOTION": "BEWEGUNG", "Max": "Max", "Min": "Min", "Mitre": "Gehrung", @@ -63,6 +82,7 @@ "None": "Keine", "Normal to sketch": "Normal zur Skizze", "Notch": "Ausklinkung", + "OUTPUT": "AUSGABE", "Other surface (mutual trim)": "Anderer Flächenkörper (gegenseitig trimmen)", "Outside": "Außen", "Overall length": "Gesamtlänge", @@ -75,7 +95,9 @@ "Profiles/Curves": "Profile/Kurven", "Projection": "Projektion", "Quantity": "Größe", + "REFERENCE": "REFERENZ", "RULED SURFACE": "REGELFLÄCHE", + "RULES": "REGELN", "Rectangular": "Rechteckig", "Reference face": "Referenzfläche", "Report a bug — review a screenshot and open a GitHub draft": "Fehler melden — Screenshot prüfen und einen GitHub-Entwurf öffnen", @@ -83,6 +105,8 @@ "Restore outer boundary": "Äußere Begrenzung wiederherstellen", "Revert Position": "Position zurücksetzen", "Round": "Rund", + "SECTION": "SCHNITT", + "SURFACE QUALITY": "OBERFLÄCHENQUALITÄT", "Save the study as an animated GIF, seen as the viewport shows it": "Die Studie als animiertes GIF speichern, so wie der Ansichtsbereich sie zeigt", "Select bodies (a face picks its body)": "Körper auswählen (eine Fläche wählt ihren Körper)", "Selection filter": "Auswahlfilter", @@ -108,6 +132,7 @@ "Turn off section analysis before exporting the view.": "Deaktivieren Sie die Schnittanalyse, bevor Sie die Ansicht exportieren.", "Type": "Typ", "UNTRIM": "TRIMMEN AUFHEBEN", + "VIEWS": "ANSICHTEN", "Velocity": "Geschwindigkeit", "Vertices": "Scheitelpunkte", "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Nur sichtbare Körper. Kurven werden durch Liniensegmente angenähert (Toleranz: 0,01 mm).", @@ -1133,6 +1158,8 @@ "ui.restore_defaults": "Standardeinstellungen wiederherstellen", "ui.reverse_zoom_direction": "Zoomrichtung umkehren", "ui.revolve": "Drehen", + "ui.ribbon_exit": "Beenden", + "ui.ribbon_workspace": "Arbeitsbereich", "ui.right": "Rechts", "ui.save": "Speichern", "ui.save_as": "Speichern unter", diff --git a/assets/locales/en.json b/assets/locales/en.json index aa55768ac..c04b52ad3 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -3,11 +3,14 @@ "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Open GitHub draft below, then paste the report copied to your clipboard.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Open GitHub draft below. Your title and report will be filled in.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Attach your screenshot: copy and paste it, or save and upload the PNG.", + "2D": "2D", "3. Click Submit new issue on GitHub to send your report.": "3. Click Submit new issue on GitHub to send your report.", "A new configuration, a copy of the active one": "A new configuration, a copy of the active one", "AI": "AI", + "ARRANGE": "ARRANGE", "About SolidCraft": "About SolidCraft", "Acceleration": "Acceleration", + "Access": "Access", "Active": "Active", "Active rule": "Active rule", "Add": "Add", @@ -30,6 +33,8 @@ "Apply to selection": "Apply to selection", "Arc length": "Arc length", "Area": "Area", + "As-Built": "As-Built", + "Assign Rule": "Assign Rule", "Attachment": "Attachment", "BLEND SURFACE": "BLEND SURFACE", "BOUNDARY SURFACE": "BOUNDARY SURFACE", @@ -37,12 +42,21 @@ "Bend Line Position": "Bend Line Position", "Bend Position": "Bend Position", "Bend Radius": "Bend Radius", + "Bend Table": "Bend Table", "Bends": "Bends", + "Bodies": "Bodies", "Body": "Body", "Boundary": "Boundary", "Bounding box": "Bounding box", + "CHECK": "CHECK", + "COMPONENTS": "COMPONENTS", + "CONFIGURATIONS": "CONFIGURATIONS", + "CONSTRAIN": "CONSTRAIN", + "CONTACT": "CONTACT", + "CONVERT": "CONVERT", "CSV or JSON: updates existing parameters, adds new ones": "CSV or JSON: updates existing parameters, adds new ones", "Capture All Positions": "Capture All Positions", + "Capture Pos.": "Capture Pos.", "Catch Direction": "Catch Direction", "Cells": "Cells", "Center X": "Center X", @@ -53,15 +67,18 @@ "Check collisions": "Check collisions", "Checked": "Checked", "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.", + "Circular": "Circular", "Circumference": "Circumference", "Close draft": "Close draft", "Collisions": "Collisions", "Colour": "Colour", "Component1": "Component1", + "Config Table": "Config Table", "Configuration": "Configuration", "Configuration rules": "Configuration rules", "Construction": "Construction", "Contact": "Contact", + "Contact Sets": "Contact Sets", "Contact sets": "Contact sets", "Continuity": "Continuity", "Copy Error Message": "Copy Error Message", @@ -79,6 +96,7 @@ "Cube": "Cube", "Current orthographic view (1:1 mm)": "Current orthographic view (1:1 mm)", "Current perspective view": "Current perspective view", + "Curv. Comb": "Curv. Comb", "Curvature (G2)": "Curvature (G2)", "Curvature change (G3)": "Curvature change (G3)", "Customize Toolbar": "Customize Toolbar", @@ -88,6 +106,7 @@ "Delete the set": "Delete the set", "Delete this parameter": "Delete this parameter", "Density": "Density", + "Dependents": "Dependents", "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", @@ -109,41 +128,56 @@ "Export Animation…": "Export Animation…", "Export Current View as DXF": "Export Current View as DXF", "Export Current View as DXF…": "Export Current View as DXF…", + "Export DXF": "Export DXF", "Export DXF…": "Export DXF…", "Export hidden edges as dashed lines": "Export hidden edges as dashed lines", "Extend to meet": "Extend to meet", "Extents": "Extents", + "FILES": "FILES", + "FLAT": "FLAT", "Face": "Face", "Face attachment lost": "Face attachment lost", "Faces": "Faces", "Faces / edges / vertices": "Faces / edges / vertices", + "Fastener": "Fastener", "Favourite": "Favourite", "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Files from many CAD programs have Y up, so they open lying on their back here (Z up).", "Filter": "Filter", "Find in Browser": "Find in Browser", + "Finish": "Finish", "Flat": "Flat", + "Flat Pattern": "Flat Pattern", "Flat size": "Flat size", "Follow camera (Look At sketches)": "Follow camera (Look At sketches)", "Follow the camera (Look At sketches)": "Follow the camera (Look At sketches)", "Font": "Font", + "From Bodies": "From Bodies", "From edges": "From edges", "Full Length": "Full Length", + "Gap": "Gap", "Grid": "Grid", + "HISTORY": "HISTORY", "Height": "Height", "Hidden edges": "Hidden edges", "Holes": "Holes", "Holes (edges on them)": "Holes (edges on them)", "Home view": "Home view", + "Horiz./Vert.": "Horiz./Vert.", + "IMAGES": "IMAGES", "In This Design": "In This Design", "In place (surfaces)": "In place (surfaces)", "In plane": "In plane", "Inside": "Inside", "Interferes": "Interferes", + "Isocurve": "Isocurve", "Issue title": "Issue title", + "JOINTS": "JOINTS", "Joint Origin1": "Joint Origin1", "Keep (points on it)": "Keep (points on it)", "Keep Tools": "Keep Tools", "Keep of the other surface": "Keep of the other surface", + "LIBRARY": "LIBRARY", + "LINKS": "LINKS", "Later": "Later", "Leave it": "Leave it", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Legacy face attachment. Rebinding to a certified face creates an exact attachment.", @@ -153,8 +187,13 @@ "Library": "Library", "Line Spacing": "Line Spacing", "Loop": "Loop", + "MANAGE": "MANAGE", + "MATERIALS": "MATERIALS", + "MODEL": "MODEL", + "MOTION": "MOTION", "Margin": "Margin", "Mass": "Mass", + "Mass Center": "Mass Center", "Material": "Material", "Max": "Max", "Mid Radius": "Mid Radius", @@ -164,11 +203,14 @@ "Modeled": "Modeled", "More toolbar panels": "More toolbar panels", "Motion": "Motion", + "Move / Copy": "Move / Copy", "Move Type": "Move Type", "Move earlier": "Move earlier", "Move later": "Move later", "Name": "Name", "Nearest": "Nearest", + "New Comp.": "New Comp.", + "New Sketch": "New Sketch", "New study": "New study", "No crash reports.": "No crash reports.", "No matching appearances": "No matching appearances", @@ -177,6 +219,7 @@ "Normal to sketch": "Normal to sketch", "Not available yet": "Not available yet", "Notch": "Notch", + "OUTPUT": "OUTPUT", "Opacity": "Opacity", "Open GitHub draft": "Open GitHub draft", "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.", @@ -184,14 +227,18 @@ "Other surface (mutual trim)": "Other surface (mutual trim)", "Outside": "Outside", "Overall length": "Overall length", + "Param. Graph": "Param. Graph", "Parameter values": "Parameter values", + "Parts": "Parts", "Pass through": "Pass through", "Path": "Path", + "Pattern": "Pattern", "Per Edge": "Per Edge", "Pick the tool bodies": "Pick the tool bodies", "Picked": "Picked", "Picked point": "Picked point", "Place at the origin instead": "Place at the origin instead", + "Plastic Rules": "Plastic Rules", "Playback": "Playback", "Plot": "Plot", "Position": "Position", @@ -205,7 +252,9 @@ "Projection": "Projection", "Quantity": "Quantity", "RECENT": "RECENT", + "REFERENCE": "REFERENCE", "RULED SURFACE": "RULED SURFACE", + "RULES": "RULES", "Radius Fit": "Radius Fit", "Ratio": "Ratio", "Reattach selected face": "Reattach selected face", @@ -223,6 +272,8 @@ "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", "Reset Toolbar": "Reset Toolbar", + "Resize Part": "Resize Part", + "Restore View": "Restore View", "Restore outer boundary": "Restore outer boundary", "Restore the inherited component or physical material appearance": "Restore the inherited component or physical material appearance", "Result": "Result", @@ -231,18 +282,24 @@ "Reverse Direction": "Reverse Direction", "Revert": "Revert", "Revert All Positions": "Revert All Positions", + "Revert Pos.": "Revert Pos.", "Revert Position": "Revert Position", "Review the report and screenshot before opening GitHub.": "Review the report and screenshot before opening GitHub.", "Rim Edge": "Rim Edge", "Roll History Marker Here": "Roll History Marker Here", "Round": "Round", "Rule": "Rule", + "SECTION": "SECTION", + "SURFACE QUALITY": "SURFACE QUALITY", "Save Rule": "Save Rule", + "Save View": "Save View", "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", "Search": "Search", "Search commands": "Search commands", + "Section": "Section", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).", "Select bodies (a face picks its body)": "Select bodies (a face picks its body)", "Select bodies or faces instead": "Select bodies or faces instead", @@ -250,6 +307,7 @@ "Semantic faces share their appearance across instances.": "Semantic faces share their appearance across instances.", "Send your report on GitHub": "Send your report on GitHub", "Shape": "Shape", + "Sheet Rules": "Sheet Rules", "Show Agent Cursor": "Show Agent Cursor", "Show in folder": "Show in folder", "Show the pointer an AI agent moves (#35)": "Show the pointer an AI agent moves (#35)", @@ -263,6 +321,7 @@ "Sketch points": "Sketch points", "Slot width": "Slot width", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft closed before these designs were saved. Their last autosave can be opened.", + "Specialise": "Specialise", "Speed": "Speed", "Stand it up": "Stand it up", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Stand it up: a quarter turn about X, as one Move feature you can undo.", @@ -307,6 +366,7 @@ "Use saved fixed plane": "Use saved fixed plane", "Use selected face as fixed plane": "Use selected face as fixed plane", "VIEW": "VIEW", + "VIEWS": "VIEWS", "Value": "Value", "Velocity": "Velocity", "Vertices": "Vertices", @@ -319,6 +379,7 @@ "When": "When", "Width": "Width", "Will fail": "Will fail", + "Zebra": "Zebra", "angle, height": "angle, height", "appearance.dielectric_ior": "Dielectric IOR", "appearance.metallic": "Metallic", @@ -1070,8 +1131,8 @@ "ui.ai_tool_running": "running", "ui.ai_tool_unfold": "Click to show what it returned", "ui.ai_tool_waiting": "waiting", - "ui.ai_toolbar_button": "Show button in toolbar", - "ui.ai_toolbar_button_note": "The AI button at the right end of the toolbar. Ctrl+Shift+A and the View menu still open the panel.", + "ui.ai_toolbar_button": "Show Assistant button in application bar", + "ui.ai_toolbar_button_note": "The Assistant button in the application bar. Ctrl+Shift+A and the View menu still open the panel.", "ui.ai_undo_tip": "Undo everything the agent changed for this message, as one step", "ui.all": "All", "ui.ambient_occlusion": "Ambient occlusion", @@ -1087,6 +1148,8 @@ "ui.apply": "Apply", "ui.arc": "Arc", "ui.assemble": "Assemble", + "ui.assistant": "Assistant", + "ui.assistant_waiting": "{count} approvals waiting", "ui.autosave_every": "Autosave every", "ui.axes": "Axes", "ui.axis": "Axis", @@ -1476,6 +1539,9 @@ "ui.reverse_horizontal_pan_tip": "Horizontal two-finger scrolling and the thumb wheel pan the other way", "ui.reverse_zoom_direction": "Reverse zoom direction", "ui.revolve": "Revolve", + "ui.ribbon_exit": "Exit", + "ui.ribbon_pin_footer": "Pinned commands show on the ribbon. Hover a row to pin or unpin it.", + "ui.ribbon_workspace": "Workspace", "ui.right": "Right", "ui.save": "Save", "ui.save_as": "Save As", @@ -1569,6 +1635,7 @@ "ui.stand_up_tip": "After a STEP or IGES file opens with Z up, offer a quarter turn about X", "ui.start": "Start", "ui.start_over": "Start over", + "ui.start_page": "Start page", "ui.start_radius": "Start Radius", "ui.stretch": "Stretch", "ui.supersampling": "Supersampling (SSAA)", @@ -1626,6 +1693,18 @@ "ui.visual_style": "Visual style", "ui.visual_wireframe": "Wireframe", "ui.workspace": "workspace", + "ui.workspace_animation_description": "Exploded views, motion studies and storyboards", + "ui.workspace_available": "Available", + "ui.workspace_current": "Current", + "ui.workspace_design_description": "Sketch, model, assemble and inspect", + "ui.workspace_design_tabs": "Model · Surface · Assemble · Insert · Inspect · Manage · View", + "ui.workspace_drawing_description": "2D drawings with views, dimensions and title blocks", + "ui.workspace_footer": "Every workspace works on the same design, history and selection; only the ribbon tabs change. The switcher is locked while a sketch or feature is being edited.", + "ui.workspace_manufacture_description": "Slicing, toolpaths and setup", + "ui.workspace_planned": "Planned", + "ui.workspace_render_description": "Product preview, scene settings and rendered images", + "ui.workspace_render_tabs": "Scene · Image", + "ui.workspace_simulation_description": "Loads, constraints and results", "ui.x_distance": "X Distance", "ui.y_distance": "Y Distance", "ui.y_up": "Y up", diff --git a/assets/locales/es.json b/assets/locales/es.json index feb3db124..bfe8938f9 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -3,9 +3,11 @@ "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Abre el borrador de GitHub de abajo y pega el informe copiado al portapapeles.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Abre el borrador de GitHub de abajo. El título y el informe se rellenarán automáticamente.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Adjunta la captura de pantalla: cópiala y pégala, o guarda y sube el PNG.", + "2D": "2D", "3. Click Submit new issue on GitHub to send your report.": "3. Haz clic en «Submit new issue» en GitHub para enviar el informe.", "A new configuration, a copy of the active one": "Una configuración nueva, copia de la activa", "AI": "AI", + "ARRANGE": "ORGANIZAR", "About SolidCraft": "Acerca de SolidCraft", "Acceleration": "Aceleración", "Active": "Activo", @@ -39,6 +41,12 @@ "Body": "Cuerpo", "Boundary": "Contorno", "Bounding box": "Caja delimitadora", + "CHECK": "COMPROBAR", + "COMPONENTS": "COMPONENTES", + "CONFIGURATIONS": "CONFIGURACIONES", + "CONSTRAIN": "RESTRINGIR", + "CONTACT": "CONTACTO", + "CONVERT": "CONVERTIR", "CSV or JSON: updates existing parameters, adds new ones": "CSV o JSON: actualiza los parámetros existentes y añade otros nuevos", "Capture All Positions": "Capturar todas las posiciones", "Catch Direction": "Dirección de enganche", @@ -108,6 +116,8 @@ "Export hidden edges as dashed lines": "Exportar aristas ocultas como líneas discontinuas", "Extend to meet": "Extender hasta encontrarla", "Extents": "Extensión", + "FILES": "ARCHIVOS", + "FLAT": "DESPLEGADO", "Face": "Cara", "Face attachment lost": "Se ha perdido la vinculación de la cara", "Faces": "Caras", @@ -124,21 +134,26 @@ "From edges": "Aristas de origen", "Full Length": "Longitud total", "Grid": "Cuadrícula", + "HISTORY": "HISTORIAL", "Height": "Altura", "Hidden edges": "Aristas ocultas", "Holes": "Agujeros", "Holes (edges on them)": "Agujeros (aristas que contienen)", "Home view": "Vista de inicio", + "IMAGES": "IMÁGENES", "In This Design": "En este diseño", "In place (surfaces)": "En su posición (superficies)", "In plane": "En el plano", "Inside": "Interior", "Interferes": "Interfiere", "Issue title": "Título de la incidencia", + "JOINTS": "UNIONES", "Joint Origin1": "Origen de unión1", "Keep (points on it)": "Conservar (puntos sobre ella)", "Keep Tools": "Conservar herramientas", "Keep of the other surface": "Conservar de la otra superficie", + "LIBRARY": "BIBLIOTECA", + "LINKS": "VÍNCULOS", "Later": "Más tarde", "Leave it": "Dejar como está", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Vinculación antigua de cara. Volver a vincularla a una cara verificada crea una vinculación exacta.", @@ -148,6 +163,10 @@ "Library": "Biblioteca", "Line Spacing": "Interlineado", "Loop": "Bucle", + "MANAGE": "GESTIONAR", + "MATERIALS": "MATERIALES", + "MODEL": "MODELO", + "MOTION": "MOVIMIENTO", "Margin": "Margen", "Mass": "Masa", "Material": "Material", @@ -172,6 +191,7 @@ "Normal to sketch": "Normal al boceto", "Not available yet": "Todavía no disponible", "Notch": "Muesca", + "OUTPUT": "SALIDA", "Opacity": "Opacidad", "Open GitHub draft": "Abrir borrador de GitHub", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código abierto desarrollado en Rust. Licencia MIT O Apache-2.0.", @@ -200,7 +220,9 @@ "Projection": "Proyección", "Quantity": "Cantidad", "RECENT": "RECIENTES", + "REFERENCE": "REFERENCIA", "RULED SURFACE": "SUPERFICIE REGLADA", + "RULES": "REGLAS", "Radius Fit": "Ajuste de radio", "Ratio": "Relación", "Reattach selected face": "Volver a vincular la cara seleccionada", @@ -232,6 +254,8 @@ "Roll History Marker Here": "Desplazar marcador de la línea de tiempo hasta aquí", "Round": "Redondo", "Rule": "Regla", + "SECTION": "SECCIÓN", + "SURFACE QUALITY": "CALIDAD DE SUPERFICIE", "Save Rule": "Guardar regla", "Save the study as an animated GIF, seen as the viewport shows it": "Guardar el estudio como GIF animado, tal como se ve en el visor", "Saved preview. Geometry is being checked before editing.": "Vista previa guardada. Se está comprobando la geometría antes de editarla.", @@ -300,6 +324,7 @@ "Use saved fixed plane": "Usar plano fijo guardado", "Use selected face as fixed plane": "Usar la cara seleccionada como plano fijo", "VIEW": "VISTA", + "VIEWS": "VISTAS", "Value": "Valor", "Velocity": "Velocidad", "Vertices": "Vértices", @@ -1377,6 +1402,8 @@ "ui.restore_defaults": "Restaurar valores predeterminados", "ui.reverse_zoom_direction": "Invertir dirección del zoom", "ui.revolve": "Revolución", + "ui.ribbon_exit": "Salir", + "ui.ribbon_workspace": "Espacio de trabajo", "ui.right": "Derecha", "ui.save": "Guardar", "ui.save_as": "Guardar como", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 193312cf1..9387ef3f9 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -3,9 +3,11 @@ "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Ouvrir le brouillon GitHub ci-dessous, puis coller le rapport copié dans le presse-papiers.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Ouvrir le brouillon GitHub ci-dessous. Votre titre et votre rapport y seront déjà remplis.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Joindre votre capture d'écran : la copier-coller, ou enregistrer le PNG puis le téléverser.", + "2D": "2D", "3. Click Submit new issue on GitHub to send your report.": "3. Cliquer sur Submit new issue sur GitHub pour envoyer votre rapport.", "A new configuration, a copy of the active one": "Nouvelle configuration, copie de la configuration active", "AI": "IA", + "ARRANGE": "DISPOSER", "About SolidCraft": "À propos de SolidCraft", "Acceleration": "Accélération", "Active": "Actif", @@ -40,6 +42,12 @@ "Body": "Corps", "Boundary": "Contour", "Bounding box": "Boîte englobante", + "CHECK": "VÉRIFIER", + "COMPONENTS": "COMPOSANTS", + "CONFIGURATIONS": "CONFIGURATIONS", + "CONSTRAIN": "CONTRAINDRE", + "CONTACT": "CONTACT", + "CONVERT": "CONVERTIR", "CSV or JSON: updates existing parameters, adds new ones": "CSV ou JSON : met à jour les paramètres existants, ajoute les nouveaux", "Capture All Positions": "Capturer toutes les positions", "Catch Direction": "Direction de l'ergot", @@ -110,6 +118,8 @@ "Export hidden edges as dashed lines": "Exporter les arêtes cachées en tirets", "Extend to meet": "Prolonger jusqu'à la rencontre", "Extents": "Étendues", + "FILES": "FICHIERS", + "FLAT": "DÉPLIÉ", "Face": "Face", "Face attachment lost": "Rattachement à la face perdu", "Faces": "Faces", @@ -126,21 +136,26 @@ "From edges": "Arêtes de départ", "Full Length": "Longueur totale", "Grid": "Grille", + "HISTORY": "HISTORIQUE", "Height": "Hauteur", "Hidden edges": "Arêtes cachées", "Holes": "Trous", "Holes (edges on them)": "Trous (par leurs arêtes)", "Home view": "Vue d'accueil", + "IMAGES": "IMAGES", "In This Design": "Dans cette conception", "In place (surfaces)": "En place (surfaces)", "In plane": "Dans le plan", "Inside": "Intérieur", "Interferes": "Interfère", "Issue title": "Titre du ticket", + "JOINTS": "LIAISONS", "Joint Origin1": "Origine de liaison1", "Keep (points on it)": "À conserver (points dessus)", "Keep Tools": "Conserver les outils", "Keep of the other surface": "À conserver de l'autre surface", + "LIBRARY": "BIBLIOTHÈQUE", + "LINKS": "LIENS", "Later": "Plus tard", "Leave it": "Laisser tel quel", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Rattachement à la face hérité. Le relier à une face certifiée crée un rattachement exact.", @@ -150,6 +165,10 @@ "Library": "Bibliothèque", "Line Spacing": "Interligne", "Loop": "Boucle", + "MANAGE": "GÉRER", + "MATERIALS": "MATÉRIAUX", + "MODEL": "MODÈLE", + "MOTION": "MOUVEMENT", "Margin": "Marge", "Mass": "Masse", "Material": "Matériau", @@ -174,6 +193,7 @@ "Normal to sketch": "Normale à l'esquisse", "Not available yet": "Pas encore disponible", "Notch": "Encoche", + "OUTPUT": "SORTIE", "Opacity": "Opacité", "Open GitHub draft": "Ouvrir le brouillon GitHub", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAO 3D paramétrique open source en Rust. Sous licence MIT OR Apache-2.0.", @@ -202,7 +222,9 @@ "Projection": "Projection", "Quantity": "Grandeur", "RECENT": "RÉCENTS", + "REFERENCE": "RÉFÉRENCE", "RULED SURFACE": "SURFACE RÉGLÉE", + "RULES": "RÈGLES", "Radius Fit": "Ajustement du rayon", "Ratio": "Rapport", "Reattach selected face": "Rattacher la face sélectionnée", @@ -234,6 +256,8 @@ "Roll History Marker Here": "Placer le marqueur d'historique ici", "Round": "Arrondi", "Rule": "Règle", + "SECTION": "COUPE", + "SURFACE QUALITY": "QUALITÉ DE SURFACE", "Save Rule": "Enregistrer la règle", "Save the study as an animated GIF, seen as the viewport shows it": "Enregistrer l'étude en GIF animé, telle que la fenêtre d'affichage la montre", "Saved preview. Geometry is being checked before editing.": "Aperçu enregistré. La géométrie est en cours de vérification avant modification.", @@ -302,6 +326,7 @@ "Use saved fixed plane": "Utiliser le plan fixe enregistré", "Use selected face as fixed plane": "Utiliser la face sélectionnée comme plan fixe", "VIEW": "VUE", + "VIEWS": "VUES", "Value": "Valeur", "Velocity": "Vitesse", "Vertices": "Sommets", @@ -1438,6 +1463,8 @@ "ui.reverse_horizontal_pan_tip": "Le défilement horizontal à deux doigts et la molette latérale font le panoramique dans l'autre sens", "ui.reverse_zoom_direction": "Inverser le sens du zoom", "ui.revolve": "Révolution", + "ui.ribbon_exit": "Quitter", + "ui.ribbon_workspace": "Espace de travail", "ui.right": "Droite", "ui.save": "Enregistrer", "ui.save_as": "Enregistrer sous", diff --git a/assets/locales/gl.json b/assets/locales/gl.json index 2d5ec53fb..fd4ec7c6b 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -3,9 +3,11 @@ "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Abre o borrador de GitHub de abaixo e pega o informe copiado no portapapeis.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Abre o borrador de GitHub de abaixo. O título e o informe encheranse automaticamente.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Achega a captura de pantalla: cópiaa e pégaa, ou gárdaa e sube o PNG.", + "2D": "2D", "3. Click Submit new issue on GitHub to send your report.": "3. Preme Submit new issue en GitHub para enviar o informe.", "A new configuration, a copy of the active one": "Unha configuración nova, copia da activa", "AI": "IA", + "ARRANGE": "ORGANIZAR", "About SolidCraft": "Acerca de SolidCraft", "Active": "Activa", "Active rule": "Regra activa", @@ -36,6 +38,12 @@ "Body": "Corpo", "Boundary": "Contorno", "Bounding box": "Caixa delimitadora", + "CHECK": "COMPROBAR", + "COMPONENTS": "COMPOÑENTES", + "CONFIGURATIONS": "CONFIGURACIÓNS", + "CONSTRAIN": "RESTRINXIR", + "CONTACT": "CONTACTO", + "CONVERT": "CONVERTER", "CSV or JSON: updates existing parameters, adds new ones": "CSV ou JSON: actualiza os parámetros existentes e engade os novos", "Capture All Positions": "Capturar todas as posicións", "Catch Direction": "Dirección de captura", @@ -101,6 +109,8 @@ "Export hidden edges as dashed lines": "Exportar as arestas ocultas como liñas descontinuas", "Extend to meet": "Estender ata atopala", "Extents": "Extensións", + "FILES": "FICHEIROS", + "FLAT": "DESPREGADO", "Face": "Cara", "Face attachment lost": "Perdeuse a ancoraxe á cara", "Faces": "Caras", @@ -117,21 +127,26 @@ "From edges": "Arestas de orixe", "Full Length": "Lonxitude completa", "Grid": "Grella", + "HISTORY": "HISTORIAL", "Height": "Altura", "Hidden edges": "Arestas ocultas", "Holes": "Furados", "Holes (edges on them)": "Furados (arestas sobre eles)", "Home view": "Vista de inicio", + "IMAGES": "IMAXES", "In This Design": "Neste deseño", "In place (surfaces)": "No sitio (superficies)", "In plane": "No plano", "Inside": "Dentro", "Interferes": "Interfire", "Issue title": "Título da incidencia", + "JOINTS": "UNIÓNS", "Joint Origin1": "Orixe da unión1", "Keep (points on it)": "Manter (puntos sobre ela)", "Keep Tools": "Manter as ferramentas", "Keep of the other surface": "Manter da outra superficie", + "LIBRARY": "BIBLIOTECA", + "LINKS": "LIGAZÓNS", "Later": "Máis tarde", "Leave it": "Deixalo", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Ancoraxe á cara antiga. Volver vincular a unha cara certificada crea unha ancoraxe exacta.", @@ -141,6 +156,10 @@ "Library": "Biblioteca", "Line Spacing": "Espazado entre liñas", "Loop": "Bucle", + "MANAGE": "XESTIONAR", + "MATERIALS": "MATERIAIS", + "MODEL": "MODELO", + "MOTION": "MOVEMENTO", "Margin": "Marxe", "Mass": "Masa", "Material": "Material", @@ -163,6 +182,7 @@ "Normal to sketch": "Normal ao bosquexo", "Not available yet": "Aínda non dispoñible", "Notch": "Entalle", + "OUTPUT": "SAÍDA", "Opacity": "Opacidade", "Open GitHub draft": "Abrir o borrador de GitHub", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código aberto en Rust. Con licenza MIT OR Apache-2.0.", @@ -187,7 +207,9 @@ "Profiles/Curves": "Perfís/curvas", "Projection": "Proxección", "RECENT": "RECENTES", + "REFERENCE": "REFERENCIA", "RULED SURFACE": "SUPERFICIE REGRADA", + "RULES": "REGRAS", "Radius Fit": "Axuste do raio", "Ratio": "Proporción", "Reattach selected face": "Volver ancorar a cara seleccionada", @@ -219,6 +241,8 @@ "Roll History Marker Here": "Levar o marcador do historial aquí", "Round": "Redondo", "Rule": "Regra", + "SECTION": "SECCIÓN", + "SURFACE QUALITY": "CALIDADE DA SUPERFICIE", "Save Rule": "Gardar a regra", "Save the study as an animated GIF, seen as the viewport shows it": "Gardar o estudo como GIF animado, tal e como o mostra a vista", "Saved preview. Geometry is being checked before editing.": "Previsualización gardada. Estase a comprobar a xeometría antes de editar.", @@ -285,6 +309,7 @@ "Use saved fixed plane": "Usar o plano fixo gardado", "Use selected face as fixed plane": "Usar a cara seleccionada como plano fixo", "VIEW": "VISTA", + "VIEWS": "VISTAS", "Value": "Valor", "Vertices": "Vértices", "View navigator": "Navegador de vistas", @@ -1342,6 +1367,8 @@ "ui.restore_defaults": "Restaurar os valores predeterminados", "ui.reverse_zoom_direction": "Inverter a dirección do zoom", "ui.revolve": "Revolución", + "ui.ribbon_exit": "Saír", + "ui.ribbon_workspace": "Espazo de traballo", "ui.right": "Dereita", "ui.save": "Gardar", "ui.save_as": "Gardar como", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 3404d86a7..14bcd45b0 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -3,11 +3,14 @@ "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. 下のボタンでGitHubの下書きを開き、クリップボードにコピーされたレポートを貼り付けます。", "1. Open GitHub draft below. Your title and report will be filled in.": "1. 下のボタンでGitHubの下書きを開きます。タイトルとレポートは入力済みです。", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. スクリーンショットを添付します。コピーして貼り付けるか、PNGを保存してアップロードします。", + "2D": "2D", "3. Click Submit new issue on GitHub to send your report.": "3. GitHubでSubmit new issueをクリックしてレポートを送信します。", "A new configuration, a copy of the active one": "アクティブな構成をコピーして新しい構成を作成", "AI": "AI", + "ARRANGE": "配置", "About SolidCraft": "SolidCraft について", "Acceleration": "加速度", + "Access": "アクセス性", "Active": "アクティブ", "Active rule": "有効なルール", "Add": "追加", @@ -30,6 +33,8 @@ "Apply to selection": "選択項目に適用", "Arc length": "円弧の長さ", "Area": "表面積", + "As-Built": "現状位置", + "Assign Rule": "ルールを割当", "Attachment": "アタッチメント", "BLEND SURFACE": "ブレンドサーフェス", "BOUNDARY SURFACE": "境界サーフェス", @@ -37,12 +42,21 @@ "Bend Line Position": "曲げ線位置", "Bend Position": "曲げ位置", "Bend Radius": "曲げ半径", + "Bend Table": "曲げテーブル", "Bends": "曲げ", + "Bodies": "ボディ", "Body": "ボディ", "Boundary": "境界", "Bounding box": "境界ボックス", + "CHECK": "チェック", + "COMPONENTS": "コンポーネント", + "CONFIGURATIONS": "構成", + "CONSTRAIN": "拘束", + "CONTACT": "接触", + "CONVERT": "変換", "CSV or JSON: updates existing parameters, adds new ones": "CSVまたはJSON:既存のパラメータを更新し、新しいパラメータを追加します", "Capture All Positions": "すべての位置をキャプチャ", + "Capture Pos.": "位置を記録", "Catch Direction": "キャッチ方向", "Cells": "セル", "Center X": "中心 X", @@ -53,15 +67,18 @@ "Check collisions": "衝突チェック", "Checked": "チェック済み", "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "新しい平面を選択してください。スケッチジオメトリと寸法は2次元座標系のまま維持されます。", + "Circular": "円形", "Circumference": "円周", "Close draft": "下書きを閉じる", "Collisions": "衝突", "Colour": "色", "Component1": "コンポーネント1", + "Config Table": "構成テーブル", "Configuration": "構成", "Configuration rules": "構成ルール", "Construction": "コンストラクション", "Contact": "接触", + "Contact Sets": "接触セット", "Contact sets": "接触セット", "Continuity": "連続性", "Copy Error Message": "エラーメッセージをコピー", @@ -79,6 +96,7 @@ "Cube": "キューブ", "Current orthographic view (1:1 mm)": "現在の平行投影(実寸・mm)", "Current perspective view": "現在の透視投影", + "Curv. Comb": "曲率コーム", "Curvature (G2)": "曲率 (G2)", "Curvature change (G3)": "曲率変化 (G3)", "Customize Toolbar": "ツールバーのカスタマイズ", @@ -88,6 +106,7 @@ "Delete the set": "セットを削除", "Delete this parameter": "このパラメータを削除", "Density": "密度", + "Dependents": "依存先", "Designs you open or save appear here.": "開いたデザインや保存したデザインがここに表示されます。", "Determined by To Object. Choose Angle to edit the angular extent.": "「対象オブジェクトまで」により決定されます。角度範囲を編集するには「角度」を選択してください。", "Direction": "方向", @@ -109,41 +128,56 @@ "Export Animation…": "アニメーションをエクスポート…", "Export Current View as DXF": "現在の表示をDXFでエクスポート", "Export Current View as DXF…": "現在の表示をDXFでエクスポート…", + "Export DXF": "DXF出力", "Export DXF…": "DXFをエクスポート…", "Export hidden edges as dashed lines": "点線で出力", "Extend to meet": "交わるまで延長", "Extents": "範囲", + "FILES": "ファイル", + "FLAT": "展開", "Face": "面", "Face attachment lost": "面アタッチメントが失われました", "Faces": "面", "Faces / edges / vertices": "面 / エッジ / 頂点", + "Fastener": "締結部品", "Favourite": "お気に入り", "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "多くのCADではY軸を上向きとしているため、Z軸を上向きとするSolidCraftでは、読み込んだモデルが横倒しの向きで表示されることがあります。", "Filter": "フィルター", "Find in Browser": "ブラウザで検索", + "Finish": "終了", "Flat": "展開", + "Flat Pattern": "フラットパターン", "Flat size": "展開サイズ", "Follow camera (Look At sketches)": "カメラ追従(スケッチを正面視)", "Follow the camera (Look At sketches)": "カメラ追従(スケッチを正面視)", "Font": "フォント", + "From Bodies": "ボディから", "From edges": "開始側エッジ", "Full Length": "全長", + "Gap": "間隔", "Grid": "グリッド", + "HISTORY": "履歴", "Height": "高さ", "Hidden edges": "隠線", "Holes": "穴", "Holes (edges on them)": "穴(そのエッジ)", "Home view": "ホームビュー", + "Horiz./Vert.": "水平 / 垂直", + "IMAGES": "画像", "In This Design": "このデザイン内", "In place (surfaces)": "その場で(サーフェス)", "In plane": "平面内", "Inside": "内側", "Interferes": "干渉あり", + "Isocurve": "等パラメータ線", "Issue title": "Issueタイトル", + "JOINTS": "ジョイント", "Joint Origin1": "ジョイント原点1", "Keep (points on it)": "残す部分(その上の点)", "Keep Tools": "ツールボディを保持", "Keep of the other surface": "相手のサーフェスで残す部分", + "LIBRARY": "ライブラリ", + "LINKS": "リンク", "Later": "後で", "Leave it": "そのままにする", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "従来の面アタッチメントです。確定された面に再バインドすると正確なアタッチメントが作成されます。", @@ -153,8 +187,13 @@ "Library": "ライブラリ", "Line Spacing": "行間", "Loop": "ループ", + "MANAGE": "管理", + "MATERIALS": "材料", + "MODEL": "モデル", + "MOTION": "モーション", "Margin": "マージン", "Mass": "質量", + "Mass Center": "重心", "Material": "材料", "Max": "最大", "Mid Radius": "中間半径", @@ -164,11 +203,14 @@ "Modeled": "モデル化済み", "More toolbar panels": "その他のツールバーパネル", "Motion": "モーション", + "Move / Copy": "移動 / コピー", "Move Type": "移動タイプ", "Move earlier": "前へ移動", "Move later": "後へ移動", "Name": "名前", "Nearest": "最も近い", + "New Comp.": "新規コンポーネント", + "New Sketch": "新規スケッチ", "New study": "新規スタディ", "No crash reports.": "クラッシュレポートはありません。", "No matching appearances": "一致する外観がありません", @@ -177,6 +219,7 @@ "Normal to sketch": "スケッチに垂直", "Not available yet": "まだ利用できません", "Notch": "ノッチ", + "OUTPUT": "出力", "Opacity": "不透明度", "Open GitHub draft": "GitHubの下書きを開く", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Rust製オープンソース・パラメトリック3D CAD。ライセンス: MIT または Apache-2.0。", @@ -184,14 +227,18 @@ "Other surface (mutual trim)": "相手のサーフェス(相互トリム)", "Outside": "外側", "Overall length": "全長", + "Param. Graph": "パラメータ図", "Parameter values": "パラメータ値", + "Parts": "部品", "Pass through": "通過点", "Path": "パス", + "Pattern": "パターン", "Per Edge": "エッジごと", "Pick the tool bodies": "ツールボディを選択", "Picked": "選択したもの", "Picked point": "選択した点", "Place at the origin instead": "代わりに原点に配置", + "Plastic Rules": "樹脂ルール", "Playback": "再生", "Plot": "グラフ", "Position": "位置", @@ -205,7 +252,9 @@ "Projection": "投影", "Quantity": "量", "RECENT": "最近使用した項目", + "REFERENCE": "参照", "RULED SURFACE": "ルールドサーフェス", + "RULES": "ルール", "Radius Fit": "半径フィット", "Ratio": "比率", "Reattach selected face": "選択した面を再アタッチ", @@ -223,6 +272,8 @@ "Remove this point": "この点を削除", "Report a bug — review a screenshot and open a GitHub draft": "バグを報告 — スクリーンショットを確認してGitHub下書きを作成", "Reset Toolbar": "ツールバーをリセット", + "Resize Part": "部品サイズ変更", + "Restore View": "ビューを復元", "Restore outer boundary": "外側の境界を復元", "Restore the inherited component or physical material appearance": "コンポーネントまたは物理マテリアルから継承した外観に戻す", "Result": "結果", @@ -231,18 +282,24 @@ "Reverse Direction": "方向を反転", "Revert": "元に戻す", "Revert All Positions": "すべての位置を元に戻す", + "Revert Pos.": "位置を復元", "Revert Position": "位置を元に戻す", "Review the report and screenshot before opening GitHub.": "GitHubを開く前にレポートとスクリーンショットを確認してください。", "Rim Edge": "リムエッジ", "Roll History Marker Here": "履歴マーカーをここに移動", "Round": "丸め", "Rule": "ルール", + "SECTION": "断面", + "SURFACE QUALITY": "サーフェス品質", "Save Rule": "ルールを保存", + "Save View": "ビューを保存", "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": "シーン", "Search": "検索", "Search commands": "コマンドを検索", + "Section": "断面", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "その他を選択: モデル上で左ボタンを長押し(または右クリック › その他を選択…)するとカーソル下の要素が一覧表示されます。同じ場所を再度クリックすると次の要素が選択されます。中ボタンをダブルクリックするとホームビューに戻ります(環境設定 › ナビゲーション)。", "Select bodies (a face picks its body)": "ボディを選択(面をクリックするとそのボディが選択されます)", "Select bodies or faces instead": "代わりにボディまたは面を選択", @@ -250,6 +307,7 @@ "Semantic faces share their appearance across instances.": "セマンティック面はインスタンス間で外観を共有します。", "Send your report on GitHub": "GitHubでレポートを送信", "Shape": "形状", + "Sheet Rules": "板金ルール", "Show Agent Cursor": "エージェントカーソルを表示", "Show in folder": "フォルダに表示", "Show the pointer an AI agent moves (#35)": "エージェントが操作するポインターを表示 (#35)", @@ -263,6 +321,7 @@ "Sketch points": "スケッチ点", "Slot width": "長穴の幅", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "これらのデザインが保存される前にSolidCraftが終了しました。最後の自動保存ファイルを開くことができます。", + "Specialise": "特殊操作", "Speed": "速度", "Stand it up": "正立させる", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "正立させる: 取り消し可能な1つの移動フィーチャーとして、X軸周りに90度回転します。", @@ -307,6 +366,7 @@ "Use saved fixed plane": "保存された固定平面を使用", "Use selected face as fixed plane": "選択した面を固定平面として使用", "VIEW": "表示", + "VIEWS": "ビュー", "Value": "値", "Velocity": "速度", "Vertices": "頂点", @@ -319,6 +379,7 @@ "When": "条件 (When)", "Width": "幅", "Will fail": "失敗します", + "Zebra": "ゼブラ", "angle, height": "角度, 高さ", "appearance.dielectric_ior": "誘電体の屈折率", "appearance.metallic": "金属度", @@ -1070,8 +1131,8 @@ "ui.ai_tool_running": "実行中", "ui.ai_tool_unfold": "クリックして結果を表示", "ui.ai_tool_waiting": "待機中", - "ui.ai_toolbar_button": "ツールバーにボタンを表示", - "ui.ai_toolbar_button_note": "ツールバー右端の AI ボタン。Ctrl+Shift+A と表示メニューからも引き続きパネルを開けます。", + "ui.ai_toolbar_button": "アプリケーションバーにアシスタントボタンを表示", + "ui.ai_toolbar_button_note": "アプリケーションバーのアシスタントボタン。Ctrl+Shift+A と表示メニューからもパネルを開けます。", "ui.ai_undo_tip": "このメッセージでエージェントが行った変更を、1回でまとめて元に戻します", "ui.all": "すべて", "ui.ambient_occlusion": "アンビエントオクルージョン", @@ -1087,6 +1148,8 @@ "ui.apply": "適用", "ui.arc": "円弧", "ui.assemble": "アセンブリ", + "ui.assistant": "アシスタント", + "ui.assistant_waiting": "{count} 件の承認待ち", "ui.autosave_every": "自動保存の間隔", "ui.axes": "軸", "ui.axis": "軸", @@ -1476,6 +1539,9 @@ "ui.reverse_horizontal_pan_tip": "水平方向の2本指スクロールとサムホイールで、反対方向にパンします", "ui.reverse_zoom_direction": "ズーム方向を反転", "ui.revolve": "回転", + "ui.ribbon_exit": "終了", + "ui.ribbon_pin_footer": "ピン留めしたコマンドはリボンに表示されます。行にポインターを合わせて、ピン留めや解除ができます。", + "ui.ribbon_workspace": "ワークスペース", "ui.right": "右側面", "ui.save": "保存", "ui.save_as": "名前を付けて保存", @@ -1569,6 +1635,7 @@ "ui.stand_up_tip": "Z軸上向きで開いたSTEPまたはIGESファイルに対し、X軸周りに90度回転させるか確認します", "ui.start": "開始", "ui.start_over": "最初からやり直す", + "ui.start_page": "スタートページ", "ui.start_radius": "開始半径", "ui.stretch": "伸縮", "ui.supersampling": "スーパーサンプリング (SSAA)", @@ -1626,6 +1693,18 @@ "ui.visual_style": "表示スタイル", "ui.visual_wireframe": "ワイヤーフレーム", "ui.workspace": "ワークスペース", + "ui.workspace_animation_description": "分解図、モーション スタディ、ストーリーボード", + "ui.workspace_available": "利用可能", + "ui.workspace_current": "現在", + "ui.workspace_design_description": "スケッチ、モデリング、アセンブリ、検査", + "ui.workspace_design_tabs": "モデル · サーフェス · アセンブリ · 挿入 · 検査 · 管理 · 表示", + "ui.workspace_drawing_description": "ビュー、寸法、表題欄を含む2D図面", + "ui.workspace_footer": "すべてのワークスペースで同じデザイン、履歴、選択を使用し、リボンのタブだけが変わります。スケッチやフィーチャーの編集中は切り替えできません。", + "ui.workspace_manufacture_description": "スライス、ツールパス、セットアップ", + "ui.workspace_planned": "予定", + "ui.workspace_render_description": "製品プレビュー、シーン設定、レンダリング画像", + "ui.workspace_render_tabs": "シーン · 画像", + "ui.workspace_simulation_description": "荷重、拘束、結果", "ui.x_distance": "X 距離", "ui.y_distance": "Y 距離", "ui.y_up": "Y軸上向き", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 221e56a14..6bcb068c0 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -2,8 +2,10 @@ "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. 아래에서 GitHub 초안을 열고 클립보드에 복사된 보고서를 붙여넣으세요.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. 아래에서 GitHub 초안을 여세요. 제목과 보고서가 자동으로 입력됩니다.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. 스크린샷을 첨부하세요. 복사하여 붙여넣거나 PNG로 저장한 뒤 업로드하세요.", + "2D": "2D", "3. Click Submit new issue on GitHub to send your report.": "3. GitHub에서 Submit new issue를 클릭하여 보고서를 보내세요.", "AI": "AI", + "ARRANGE": "배치", "Acceleration": "가속도", "Against": "상대", "Alignment": "정렬", @@ -13,6 +15,12 @@ "BROWSER": "브라우저", "Bends": "벤딩", "Boundary": "경계", + "CHECK": "검사", + "COMPONENTS": "구성요소", + "CONFIGURATIONS": "구성", + "CONSTRAIN": "구속", + "CONTACT": "접촉", + "CONVERT": "변환", "Centre to centre": "중심 간", "Check collisions": "충돌 확인", "Circumference": "원주", @@ -41,20 +49,31 @@ "Export DXF…": "DXF 내보내기…", "Export hidden edges as dashed lines": "숨겨진 모서리를 파선으로 내보내기", "Extend to meet": "만날 때까지 연장", + "FILES": "파일", + "FLAT": "전개", "Face": "면", "Faces": "면", "Find in Browser": "브라우저에서 찾기", "Flat": "플랫", "From edges": "시작 모서리", + "HISTORY": "이력", "Hidden edges": "숨겨진 모서리", "Holes": "구멍", "Holes (edges on them)": "구멍 (구멍의 모서리)", + "IMAGES": "이미지", "In place (surfaces)": "제자리에서 (서피스)", "In plane": "평면 내", "Inside": "안쪽", + "JOINTS": "조인트", "Keep (points on it)": "유지할 부분(그 위의 점)", "Keep of the other surface": "다른 곡면에서 유지할 부분", + "LIBRARY": "라이브러리", + "LINKS": "링크", "Length": "길이", + "MANAGE": "관리", + "MATERIALS": "재질", + "MODEL": "모델", + "MOTION": "동작", "Max": "최대", "Min": "최소", "Mitre": "연귀", @@ -63,6 +82,7 @@ "None": "없음", "Normal to sketch": "스케치에 수직", "Notch": "노치", + "OUTPUT": "출력", "Other surface (mutual trim)": "다른 곡면(상호 트림)", "Outside": "바깥쪽", "Overall length": "전체 길이", @@ -75,7 +95,9 @@ "Profiles/Curves": "프로파일/곡선", "Projection": "투영", "Quantity": "양", + "REFERENCE": "참조", "RULED SURFACE": "룰드 서피스", + "RULES": "규칙", "Rectangular": "직사각형", "Reference face": "참조 면", "Report a bug — review a screenshot and open a GitHub draft": "버그 신고 — 스크린샷을 검토하고 GitHub 초안 열기", @@ -83,6 +105,8 @@ "Restore outer boundary": "외부 경계 복원", "Revert Position": "위치 복원", "Round": "둥글게", + "SECTION": "단면", + "SURFACE QUALITY": "곡면 품질", "Save the study as an animated GIF, seen as the viewport shows it": "뷰포트에 보이는 대로 스터디를 애니메이션 GIF로 저장", "Select bodies (a face picks its body)": "바디 선택(면을 클릭하면 해당 바디 선택)", "Selection filter": "선택 필터", @@ -108,6 +132,7 @@ "Turn off section analysis before exporting the view.": "뷰를 내보내기 전에 단면 분석을 끄세요.", "Type": "유형", "UNTRIM": "트림 해제", + "VIEWS": "뷰", "Velocity": "속도", "Vertices": "꼭짓점", "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "표시된 바디만 내보냅니다. 곡선은 선분으로 근사합니다 (허용오차 0.01 mm).", @@ -1131,6 +1156,8 @@ "ui.restore_defaults": "기본값 복원", "ui.reverse_zoom_direction": "확대/축소 방향 반전", "ui.revolve": "회전", + "ui.ribbon_exit": "종료", + "ui.ribbon_workspace": "작업 공간", "ui.right": "우측면", "ui.save": "저장", "ui.save_as": "다른 이름으로 저장", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index caef4b8fa..4ad1c0a48 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -3,9 +3,11 @@ "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Abra o rascunho do GitHub abaixo e cole o relatório copiado para a área de transferência.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Abra o rascunho do GitHub abaixo. O título e o relatório serão preenchidos.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Anexe a captura de tela: copie e cole, ou salve e envie o PNG.", + "2D": "2D", "3. Click Submit new issue on GitHub to send your report.": "3. Clique em Submit new issue no GitHub para enviar o relatório.", "A new configuration, a copy of the active one": "Uma nova configuração, cópia da ativa", "AI": "IA", + "ARRANGE": "ORGANIZAR", "About SolidCraft": "Sobre o SolidCraft", "Active": "Ativo", "Active rule": "Regra ativa", @@ -36,6 +38,12 @@ "Body": "Corpo", "Boundary": "Contorno", "Bounding box": "Caixa delimitadora", + "CHECK": "VERIFICAR", + "COMPONENTS": "COMPONENTES", + "CONFIGURATIONS": "CONFIGURAÇÕES", + "CONSTRAIN": "RESTRINGIR", + "CONTACT": "CONTATO", + "CONVERT": "CONVERTER", "CSV or JSON: updates existing parameters, adds new ones": "CSV ou JSON: atualiza parâmetros existentes e adiciona novos", "Capture All Positions": "Capturar todas as posições", "Catch Direction": "Direção do encaixe", @@ -101,6 +109,8 @@ "Export hidden edges as dashed lines": "Exportar arestas ocultas como linhas tracejadas", "Extend to meet": "Estender até encontrar", "Extents": "Extensões", + "FILES": "ARQUIVOS", + "FLAT": "PLANIFICAÇÃO", "Face": "Face", "Face attachment lost": "Fixação à face perdida", "Faces": "Faces", @@ -117,21 +127,26 @@ "From edges": "Arestas de origem", "Full Length": "Comprimento total", "Grid": "Grade", + "HISTORY": "HISTÓRICO", "Height": "Altura", "Hidden edges": "Arestas ocultas", "Holes": "Furos", "Holes (edges on them)": "Furos (arestas neles)", "Home view": "Vista inicial", + "IMAGES": "IMAGENS", "In This Design": "Neste projeto", "In place (surfaces)": "No lugar (superfícies)", "In plane": "No plano", "Inside": "Dentro", "Interferes": "Interfere", "Issue title": "Título da issue", + "JOINTS": "JUNTAS", "Joint Origin1": "Origem da junta1", "Keep (points on it)": "Manter (pontos sobre ela)", "Keep Tools": "Manter ferramentas", "Keep of the other surface": "Manter da outra superfície", + "LIBRARY": "BIBLIOTECA", + "LINKS": "VÍNCULOS", "Later": "Depois", "Leave it": "Deixar assim", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Fixação de face antiga. Vincular novamente a uma face certificada cria uma fixação exata.", @@ -141,6 +156,10 @@ "Library": "Biblioteca", "Line Spacing": "Espaçamento entre linhas", "Loop": "Laço", + "MANAGE": "GERENCIAR", + "MATERIALS": "MATERIAIS", + "MODEL": "MODELO", + "MOTION": "MOVIMENTO", "Margin": "Margem", "Mass": "Massa", "Material": "Material", @@ -163,6 +182,7 @@ "Normal to sketch": "Normal ao esboço", "Not available yet": "Ainda não disponível", "Notch": "Entalhe", + "OUTPUT": "SAÍDA", "Opacity": "Opacidade", "Open GitHub draft": "Abrir rascunho no GitHub", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código aberto em Rust. Licenciado sob MIT OU Apache-2.0.", @@ -187,7 +207,9 @@ "Profiles/Curves": "Perfis/Curvas", "Projection": "Projeção", "RECENT": "RECENTES", + "REFERENCE": "REFERÊNCIA", "RULED SURFACE": "SUPERFÍCIE REGRADA", + "RULES": "REGRAS", "Radius Fit": "Ajuste de raio", "Ratio": "Razão", "Reattach selected face": "Fixar novamente na face selecionada", @@ -219,6 +241,8 @@ "Roll History Marker Here": "Mover o marcador do histórico para cá", "Round": "Arredondado", "Rule": "Regra", + "SECTION": "SEÇÃO", + "SURFACE QUALITY": "QUALIDADE DA SUPERFÍCIE", "Save Rule": "Salvar regra", "Save the study as an animated GIF, seen as the viewport shows it": "Salvar o estudo como GIF animado, como a janela de visualização o mostra", "Saved preview. Geometry is being checked before editing.": "Visualização salva. A geometria está sendo verificada antes da edição.", @@ -285,6 +309,7 @@ "Use saved fixed plane": "Usar o plano fixo salvo", "Use selected face as fixed plane": "Usar a face selecionada como plano fixo", "VIEW": "VISTA", + "VIEWS": "VISTAS", "Value": "Valor", "Vertices": "Vértices", "View navigator": "Navegador de vistas", @@ -1325,6 +1350,8 @@ "ui.restore_defaults": "Restaurar padrões", "ui.reverse_zoom_direction": "Inverter direção do zoom", "ui.revolve": "Revolução", + "ui.ribbon_exit": "Sair", + "ui.ribbon_workspace": "Espaço de trabalho", "ui.right": "Direita", "ui.save": "Salvar", "ui.save_as": "Salvar como", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index dcabf2861..73cf19667 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -1,6 +1,8 @@ { "0 turns it off": "0 отключает", + "2D": "2D", "A new configuration, a copy of the active one": "Новая конфигурация — копия активной", + "ARRANGE": "РАСПОЛОЖЕНИЕ", "About SolidCraft": "О SolidCraft", "Acceleration": "Ускорение", "Active": "Активный", @@ -33,6 +35,12 @@ "Body": "Тело", "Boundary": "Граница", "Bounding box": "Габаритная рамка", + "CHECK": "ПРОВЕРКА", + "COMPONENTS": "КОМПОНЕНТЫ", + "CONFIGURATIONS": "КОНФИГУРАЦИИ", + "CONSTRAIN": "ОГРАНИЧЕНИЯ", + "CONTACT": "КОНТАКТ", + "CONVERT": "ПРЕОБРАЗОВАНИЕ", "CSV or JSON: updates existing parameters, adds new ones": "CSV или JSON: обновляет существующие параметры, добавляет новые", "Capture All Positions": "Зафиксировать все положения", "Catch Direction": "Направление защёлкивания", @@ -91,6 +99,8 @@ "Export Animation…": "Экспортировать анимацию…", "Extend to meet": "Продлить до пересечения", "Extents": "Пределы", + "FILES": "ФАЙЛЫ", + "FLAT": "РАЗВЁРТКА", "Face attachment lost": "Привязка к грани потеряна", "Faces": "Грани", "Faces / edges / vertices": "Грани / рёбра / вершины", @@ -106,16 +116,21 @@ "From edges": "Начальные рёбра", "Full Length": "Полная длина", "Grid": "Сетка", + "HISTORY": "ИСТОРИЯ", "Height": "Высота", "Home view": "Главный вид", + "IMAGES": "ИЗОБРАЖЕНИЯ", "In This Design": "В этом дизайне", "In plane": "В плоскости", "Interferes": "Пересекается", "Issue title": "Заголовок Issue", + "JOINTS": "СОЕДИНЕНИЯ", "Joint Origin1": "Точка сопряжения1", "Keep (points on it)": "Оставить (точки на нём)", "Keep Tools": "Оставить инструменты", "Keep of the other surface": "Оставить от другой поверхности", + "LIBRARY": "БИБЛИОТЕКА", + "LINKS": "ССЫЛКИ", "Later": "Позже", "Leave it": "Оставить как есть", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Устаревшая привязка к грани. Перепривязка к сертифицированной грани создаёт точную привязку.", @@ -125,6 +140,10 @@ "Library": "Библиотека", "Line Spacing": "Межстрочный интервал", "Loop": "Контур", + "MANAGE": "УПРАВЛЕНИЕ", + "MATERIALS": "МАТЕРИАЛЫ", + "MODEL": "МОДЕЛЬ", + "MOTION": "ДВИЖЕНИЕ", "Margin": "Отступ", "Mass": "Масса", "Material": "Материал", @@ -143,6 +162,7 @@ "Normal to sketch": "По нормали к эскизу", "Not available yet": "Пока недоступно", "Notch": "Вырез", + "OUTPUT": "ВЫВОД", "Opacity": "Непрозрачность", "Open GitHub draft": "Открыть черновик на GitHub", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Открытая параметрическая 3D CAD на Rust. Лицензия MIT OR Apache-2.0.", @@ -165,6 +185,8 @@ "Preview leaves the current design unchanged.": "Предпросмотр не меняет текущий дизайн.", "Quantity": "Величина", "RECENT": "НЕДАВНИЕ", + "REFERENCE": "ССЫЛОЧНАЯ ГЕОМЕТРИЯ", + "RULES": "ПРАВИЛА", "Radius Fit": "Подобрать радиус", "Ratio": "Отношение", "Reattach selected face": "Перепривязать выбранную грань", @@ -194,6 +216,8 @@ "Roll History Marker Here": "Переместить маркер истории сюда", "Round": "Круглая", "Rule": "Правило", + "SECTION": "СЕЧЕНИЕ", + "SURFACE QUALITY": "КАЧЕСТВО ПОВЕРХНОСТИ", "Save Rule": "Сохранить правило", "Save the study as an animated GIF, seen as the viewport shows it": "Сохранить исследование как анимированный GIF, как его показывает видовой экран", "Saved preview. Geometry is being checked before editing.": "Сохранённый предпросмотр. Геометрия проверяется перед редактированием.", @@ -254,6 +278,7 @@ "Use saved fixed plane": "Использовать сохранённую фиксированную плоскость", "Use selected face as fixed plane": "Использовать выбранную грань как фиксированную плоскость", "VIEW": "ВИД", + "VIEWS": "ВИДЫ", "Value": "Значение", "Velocity": "Скорость", "Vertices": "Вершины", @@ -1131,6 +1156,8 @@ "ui.restore_defaults": "Восстановить по умолчанию", "ui.reverse_zoom_direction": "Обратить направление масштабирования", "ui.revolve": "Вращение", + "ui.ribbon_exit": "Выход", + "ui.ribbon_workspace": "Рабочая область", "ui.right": "Справа", "ui.save": "Сохранить", "ui.save_as": "Сохранить как", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index cb505510b..907022a7c 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -3,9 +3,11 @@ "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Aşağıdaki GitHub taslağını açın, ardından panoya kopyalanan raporu yapıştırın.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Aşağıdaki GitHub taslağını açın. Başlığınız ve raporunuz otomatik olarak doldurulur.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Ekran görüntüsünü ekleyin: kopyalayıp yapıştırın veya PNG olarak kaydedip yükleyin.", + "2D": "2D", "3. Click Submit new issue on GitHub to send your report.": "3. Raporu göndermek için GitHub'da Submit new issue düğmesine tıklayın.", "A new configuration, a copy of the active one": "Etkin konfigürasyonun kopyası olan yeni bir konfigürasyon", "AI": "AI", + "ARRANGE": "DÜZENLE", "About SolidCraft": "SolidCraft hakkında", "Acceleration": "İvme", "Active": "Etkin", @@ -38,6 +40,12 @@ "Bends": "Bükümler", "Body": "Gövde", "Bounding box": "Sınırlayıcı kutu", + "CHECK": "DENETLE", + "COMPONENTS": "BİLEŞENLER", + "CONFIGURATIONS": "YAPILANDIRMALAR", + "CONSTRAIN": "KISITLA", + "CONTACT": "TEMAS", + "CONVERT": "DÖNÜŞTÜR", "CSV or JSON: updates existing parameters, adds new ones": "CSV veya JSON: mevcut parametreleri günceller, yenilerini ekler", "Capture All Positions": "Tüm konumları yakala", "Catch Direction": "Yakalama yönü", @@ -95,6 +103,8 @@ "Export Animation…": "Animasyonu dışa aktar…", "Extend to meet": "Buluşana kadar uzat", "Extents": "Kapsamlar", + "FILES": "DOSYALAR", + "FLAT": "AÇINIM", "Face": "Yüz", "Face attachment lost": "Yüze bağlama kayboldu", "Faces": "Yüzler", @@ -111,20 +121,25 @@ "From edges": "Başlangıç kenarları", "Full Length": "Tam uzunluk", "Grid": "Izgara", + "HISTORY": "GEÇMİŞ", "Height": "Yükseklik", "Holes": "Delikler", "Holes (edges on them)": "Delikler (kenarları)", "Home view": "Başlangıç görünümü", + "IMAGES": "GÖRSELLER", "In This Design": "Bu tasarımda", "In place (surfaces)": "Yerinde (yüzeyler)", "In plane": "Düzlemde", "Inside": "İç", "Interferes": "Girişim var", "Issue title": "Sorun başlığı", + "JOINTS": "MAFSALLAR", "Joint Origin1": "Bağlantı orijini1", "Keep (points on it)": "Koru (üzerindeki noktalar)", "Keep Tools": "Araçları koru", "Keep of the other surface": "Diğer yüzeyden korunacak", + "LIBRARY": "KİTAPLIK", + "LINKS": "BAĞLANTILAR", "Later": "Daha sonra", "Leave it": "Olduğu gibi bırak", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Eski tip yüz bağlaması. Doğrulanmış bir yüze yeniden bağlamak tam bir bağlama oluşturur.", @@ -134,6 +149,10 @@ "Library": "Kitaplık", "Line Spacing": "Satır aralığı", "Loop": "Döngü", + "MANAGE": "YÖNET", + "MATERIALS": "MALZEMELER", + "MODEL": "MODEL", + "MOTION": "HAREKET", "Margin": "Kenar boşluğu", "Mass": "Kütle", "Material": "Malzeme", @@ -155,6 +174,7 @@ "None": "Hiçbiri", "Normal to sketch": "Eskize dik", "Not available yet": "Henüz kullanılamıyor", + "OUTPUT": "ÇIKTI", "Opacity": "Opaklık", "Open GitHub draft": "GitHub taslağını aç", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Rust ile yazılmış açık kaynaklı parametrik 3D CAD. Lisans: MIT OR Apache-2.0.", @@ -179,7 +199,9 @@ "Profiles/Curves": "Profiller/Eğriler", "Quantity": "Büyüklük", "RECENT": "SON KULLANILANLAR", + "REFERENCE": "REFERANS", "RULED SURFACE": "REGLE YÜZEY", + "RULES": "KURALLAR", "Radius Fit": "Yarıçap uydurma", "Ratio": "Oran", "Reattach selected face": "Seçili yüze yeniden bağla", @@ -210,6 +232,8 @@ "Roll History Marker Here": "Geçmiş işaretçisini buraya taşı", "Round": "Yuvarlak", "Rule": "Kural", + "SECTION": "KESİT", + "SURFACE QUALITY": "YÜZEY KALİTESİ", "Save Rule": "Kuralı kaydet", "Save the study as an animated GIF, seen as the viewport shows it": "Etüdü görünüm alanında göründüğü gibi animasyonlu GIF olarak kaydet", "Saved preview. Geometry is being checked before editing.": "Kaydedilmiş önizleme. Düzenlemeden önce geometri kontrol ediliyor.", @@ -274,6 +298,7 @@ "Use saved fixed plane": "Kaydedilmiş sabit düzlemi kullan", "Use selected face as fixed plane": "Seçili yüzü sabit düzlem olarak kullan", "VIEW": "GÖRÜNÜM", + "VIEWS": "GÖRÜNÜMLER", "Value": "Değer", "Velocity": "Hız", "Vertices": "Köşe noktaları", @@ -1270,6 +1295,8 @@ "ui.restore_defaults": "Varsayılanları geri yükle", "ui.reverse_zoom_direction": "Yakınlaştırma yönünü tersine çevir", "ui.revolve": "Döndür", + "ui.ribbon_exit": "Çıkış", + "ui.ribbon_workspace": "Çalışma alanı", "ui.right": "Sağ", "ui.save": "Kaydet", "ui.save_as": "Farklı kaydet", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 5957aee15..05a8972d2 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -3,9 +3,11 @@ "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Відкрийте чернетку GitHub нижче, а потім вставте звіт, скопійований у буфер обміну.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Відкрийте чернетку GitHub нижче. Заголовок і звіт буде заповнено.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Додайте знімок екрана: скопіюйте й вставте його або збережіть і завантажте PNG.", + "2D": "2D", "3. Click Submit new issue on GitHub to send your report.": "3. Натисніть Submit new issue на GitHub, щоб надіслати звіт.", "A new configuration, a copy of the active one": "Нова конфігурація, копія активної", "AI": "ШІ", + "ARRANGE": "РОЗТАШУВАННЯ", "About SolidCraft": "Про SolidCraft", "Acceleration": "Прискорення", "Active": "Активна", @@ -40,6 +42,12 @@ "Body": "Тіло", "Boundary": "Межа", "Bounding box": "Обмежувальна рамка", + "CHECK": "ПЕРЕВІРКА", + "COMPONENTS": "КОМПОНЕНТИ", + "CONFIGURATIONS": "КОНФІГУРАЦІЇ", + "CONSTRAIN": "ОБМЕЖЕННЯ", + "CONTACT": "КОНТАКТ", + "CONVERT": "ПЕРЕТВОРЕННЯ", "CSV or JSON: updates existing parameters, adds new ones": "CSV або JSON: оновлює наявні параметри, додає нові", "Capture All Positions": "Зафіксувати всі положення", "Catch Direction": "Напрямок зачеплення", @@ -110,6 +118,8 @@ "Export hidden edges as dashed lines": "Експортувати приховані ребра як штрихові лінії", "Extend to meet": "Подовжити до перетину", "Extents": "Межі", + "FILES": "ФАЙЛИ", + "FLAT": "РОЗГОРТКА", "Face": "Грань", "Face attachment lost": "Втрачено прив'язку до грані", "Faces": "Грані", @@ -126,21 +136,26 @@ "From edges": "Початкові ребра", "Full Length": "Повна довжина", "Grid": "Сітка", + "HISTORY": "ІСТОРІЯ", "Height": "Висота", "Hidden edges": "Приховані ребра", "Holes": "Отвори", "Holes (edges on them)": "Отвори (ребра на них)", "Home view": "Головний вид", + "IMAGES": "ЗОБРАЖЕННЯ", "In This Design": "У цьому проєкті", "In place (surfaces)": "На місці (поверхні)", "In plane": "У площині", "Inside": "Усередину", "Interferes": "Перетинається", "Issue title": "Заголовок повідомлення", + "JOINTS": "З’ЄДНАННЯ", "Joint Origin1": "Початок з'єднання1", "Keep (points on it)": "Залишити (точки на ньому)", "Keep Tools": "Зберегти інструменти", "Keep of the other surface": "Залишити від іншої поверхні", + "LIBRARY": "БІБЛІОТЕКА", + "LINKS": "ПОСИЛАННЯ", "Later": "Пізніше", "Leave it": "Залишити як є", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Застаріла прив'язка до грані. Повторна прив'язка до перевіреної грані створює точну прив'язку.", @@ -150,6 +165,10 @@ "Library": "Бібліотека", "Line Spacing": "Міжрядковий інтервал", "Loop": "Контур", + "MANAGE": "КЕРУВАННЯ", + "MATERIALS": "МАТЕРІАЛИ", + "MODEL": "МОДЕЛЬ", + "MOTION": "РУХ", "Margin": "Відступ", "Mass": "Маса", "Material": "Матеріал", @@ -174,6 +193,7 @@ "Normal to sketch": "За нормаллю до ескізу", "Not available yet": "Ще недоступно", "Notch": "Виріз", + "OUTPUT": "ВИВЕДЕННЯ", "Opacity": "Непрозорість", "Open GitHub draft": "Відкрити чернетку GitHub", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Параметричний 3D-CAD з відкритим вихідним кодом на Rust. Ліцензовано за MIT OR Apache-2.0.", @@ -202,7 +222,9 @@ "Projection": "Проєкція", "Quantity": "Величина", "RECENT": "НЕДАВНІ", + "REFERENCE": "ДОПОМІЖНА ГЕОМЕТРІЯ", "RULED SURFACE": "ЛІНІЙЧАСТА ПОВЕРХНЯ", + "RULES": "ПРАВИЛА", "Radius Fit": "Підгонка за радіусом", "Ratio": "Співвідношення", "Reattach selected face": "Повторно приєднати вибрану грань", @@ -234,6 +256,8 @@ "Roll History Marker Here": "Перемістити маркер історії сюди", "Round": "Круглий", "Rule": "Правило", + "SECTION": "ПЕРЕРІЗ", + "SURFACE QUALITY": "ЯКІСТЬ ПОВЕРХНІ", "Save Rule": "Зберегти правило", "Save the study as an animated GIF, seen as the viewport shows it": "Зберегти дослідження як анімований GIF, як його показує вікно перегляду", "Saved preview. Geometry is being checked before editing.": "Збережений перегляд. Геометрію перевіряють перед редагуванням.", @@ -302,6 +326,7 @@ "Use saved fixed plane": "Використати збережену фіксовану площину", "Use selected face as fixed plane": "Використати вибрану грань як фіксовану площину", "VIEW": "ВИД", + "VIEWS": "ВИГЛЯДИ", "Value": "Значення", "Velocity": "Швидкість", "Vertices": "Вершини", @@ -1437,6 +1462,8 @@ "ui.reverse_horizontal_pan_tip": "Горизонтальна прокрутка двома пальцями та бічне колесо панорамують у зворотний бік", "ui.reverse_zoom_direction": "Змінити напрямок масштабування", "ui.revolve": "Обертання", + "ui.ribbon_exit": "Вихід", + "ui.ribbon_workspace": "Робоча область", "ui.right": "Справа", "ui.save": "Зберегти", "ui.save_as": "Зберегти як", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index f7854b458..219f03591 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -3,11 +3,14 @@ "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. 点击下方按钮打开 GitHub 草稿,然后粘贴已复制到剪贴板的报告。", "1. Open GitHub draft below. Your title and report will be filled in.": "1. 点击下方按钮打开 GitHub 草稿。标题和报告将自动填入。", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. 附上截图:复制并粘贴,或保存为 PNG 后上传。", + "2D": "2D", "3. Click Submit new issue on GitHub to send your report.": "3. 在 GitHub 上点击 Submit new issue 发送报告。", "A new configuration, a copy of the active one": "新建配置,为当前配置的副本", "AI": "AI", + "ARRANGE": "排列", "About SolidCraft": "关于 SolidCraft", "Acceleration": "加速度", + "Access": "可达性", "Active": "活动", "Active rule": "活动规则", "Add": "添加", @@ -30,6 +33,8 @@ "Apply to selection": "应用到选择", "Arc length": "弧长", "Area": "面积", + "As-Built": "现有位置", + "Assign Rule": "分配规则", "Attachment": "附着", "BLEND SURFACE": "混合曲面", "BOUNDARY SURFACE": "边界曲面", @@ -37,12 +42,21 @@ "Bend Line Position": "弯折线位置", "Bend Position": "折弯位置", "Bend Radius": "折弯半径", + "Bend Table": "折弯表", "Bends": "折弯", + "Bodies": "实体", "Body": "实体", "Boundary": "边界", "Bounding box": "边界框", + "CHECK": "检查", + "COMPONENTS": "组件", + "CONFIGURATIONS": "配置", + "CONSTRAIN": "约束", + "CONTACT": "接触", + "CONVERT": "转换", "CSV or JSON: updates existing parameters, adds new ones": "CSV 或 JSON:更新现有参数、添加新参数", "Capture All Positions": "捕获所有位置", + "Capture Pos.": "捕获位置", "Catch Direction": "卡扣方向", "Cells": "区域", "Center X": "中心 X", @@ -53,15 +67,18 @@ "Check collisions": "检查碰撞", "Checked": "已检查", "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "选择一个新平面。草图几何和尺寸在其二维坐标中保持不变。", + "Circular": "圆周", "Circumference": "周长", "Close draft": "关闭草稿", "Collisions": "碰撞", "Colour": "颜色", "Component1": "组件1", + "Config Table": "配置表", "Configuration": "配置", "Configuration rules": "配置规则", "Construction": "构造", "Contact": "接触", + "Contact Sets": "接触集", "Contact sets": "接触集", "Continuity": "连续性", "Copy Error Message": "复制错误消息", @@ -79,6 +96,7 @@ "Cube": "立方体", "Current orthographic view (1:1 mm)": "当前正交视图(1:1毫米)", "Current perspective view": "当前透视视图", + "Curv. Comb": "曲率梳", "Curvature (G2)": "曲率 (G2)", "Curvature change (G3)": "曲率变化 (G3)", "Customize Toolbar": "自定义工具栏", @@ -88,6 +106,7 @@ "Delete the set": "删除此集合", "Delete this parameter": "删除此参数", "Density": "密度", + "Dependents": "依赖项", "Designs you open or save appear here.": "你打开或保存的设计会显示在此处。", "Determined by To Object. Choose Angle to edit the angular extent.": "由“到对象”确定。选择“角度”可编辑角度范围。", "Direction": "方向", @@ -109,41 +128,56 @@ "Export Animation…": "导出动画…", "Export Current View as DXF": "将当前视图导出为DXF", "Export Current View as DXF…": "将当前视图导出为DXF…", + "Export DXF": "导出DXF", "Export DXF…": "导出DXF…", "Export hidden edges as dashed lines": "以虚线导出隐藏线", "Extend to meet": "延伸至相交", "Extents": "范围", + "FILES": "文件", + "FLAT": "展开", "Face": "面", "Face attachment lost": "面附着丢失", "Faces": "面", "Faces / edges / vertices": "面 / 边 / 顶点", + "Fastener": "紧固件", "Favourite": "收藏", "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "许多 CAD 程序的文件以 Y 为上轴,因此在此处打开时会平躺(Z 朝上)。", "Filter": "筛选", "Find in Browser": "在浏览器中查找", + "Finish": "完成", "Flat": "平面", + "Flat Pattern": "展开图", "Flat size": "平板尺寸", "Follow camera (Look At sketches)": "跟随相机(注视草图)", "Follow the camera (Look At sketches)": "跟随相机(注视草图)", "Font": "字体", + "From Bodies": "从实体创建", "From edges": "起始边", "Full Length": "全长", + "Gap": "间隙", "Grid": "网格", + "HISTORY": "历史", "Height": "高度", "Hidden edges": "隐藏线", "Holes": "孔", "Holes (edges on them)": "孔(孔上的边)", "Home view": "主视图", + "Horiz./Vert.": "水平 / 垂直", + "IMAGES": "图像", "In This Design": "在此设计中", "In place (surfaces)": "原位(曲面)", "In plane": "在平面内", "Inside": "内侧", "Interferes": "发生干涉", + "Isocurve": "等参线", "Issue title": "Issue 标题", + "JOINTS": "关节", "Joint Origin1": "接头原点1", "Keep (points on it)": "保留(其上的点)", "Keep Tools": "保留工具", "Keep of the other surface": "另一曲面保留的部分", + "LIBRARY": "库", + "LINKS": "链接", "Later": "稍后", "Leave it": "保持原样", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "旧版面附着。重新绑定到经验证的面可创建精确附着。", @@ -153,8 +187,13 @@ "Library": "零件库", "Line Spacing": "行间距", "Loop": "循环", + "MANAGE": "管理", + "MATERIALS": "材料", + "MODEL": "模型", + "MOTION": "运动", "Margin": "余量", "Mass": "质量", + "Mass Center": "质心", "Material": "材质", "Max": "最大", "Mid Radius": "中间半径", @@ -164,11 +203,14 @@ "Modeled": "已建模", "More toolbar panels": "更多工具栏面板", "Motion": "运动", + "Move / Copy": "移动 / 复制", "Move Type": "移动类型", "Move earlier": "向前移动", "Move later": "向后移动", "Name": "名称", "Nearest": "最近", + "New Comp.": "新建组件", + "New Sketch": "新建草图", "New study": "新建研究", "No crash reports.": "没有崩溃报告。", "No matching appearances": "没有匹配的外观", @@ -177,6 +219,7 @@ "Normal to sketch": "垂直于草图", "Not available yet": "暂不可用", "Notch": "缺口", + "OUTPUT": "输出", "Opacity": "不透明度", "Open GitHub draft": "打开 GitHub 草稿", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "使用 Rust 编写的开源参数化 3D CAD。基于 MIT OR Apache-2.0 许可。", @@ -184,14 +227,18 @@ "Other surface (mutual trim)": "另一曲面(相互修剪)", "Outside": "外侧", "Overall length": "总长", + "Param. Graph": "参数图", "Parameter values": "参数值", + "Parts": "零件", "Pass through": "通过点", "Path": "路径", + "Pattern": "阵列", "Per Edge": "每条边", "Pick the tool bodies": "选择工具实体", "Picked": "所选", "Picked point": "选取的点", "Place at the origin instead": "改为放置在原点", + "Plastic Rules": "塑料规则", "Playback": "播放", "Plot": "图表", "Position": "位置", @@ -205,7 +252,9 @@ "Projection": "投影", "Quantity": "物理量", "RECENT": "最近使用", + "REFERENCE": "参考", "RULED SURFACE": "直纹曲面", + "RULES": "规则", "Radius Fit": "半径拟合", "Ratio": "比率", "Reattach selected face": "重新附着所选面", @@ -223,6 +272,8 @@ "Remove this point": "移除此点", "Report a bug — review a screenshot and open a GitHub draft": "报告缺陷 — 复核截图并开启 GitHub 草稿", "Reset Toolbar": "重置工具栏", + "Resize Part": "调整零件大小", + "Restore View": "恢复视图", "Restore outer boundary": "恢复外边界", "Restore the inherited component or physical material appearance": "还原继承的组件或物理材质外观", "Result": "结果", @@ -231,18 +282,24 @@ "Reverse Direction": "反向", "Revert": "还原", "Revert All Positions": "还原所有位置", + "Revert Pos.": "还原位置", "Revert Position": "恢复位置", "Review the report and screenshot before opening GitHub.": "打开 GitHub 前请审阅报告和截图。", "Rim Edge": "轮缘边", "Roll History Marker Here": "将历史标记滚动到此处", "Round": "圆角", "Rule": "规则", + "SECTION": "剖面", + "SURFACE QUALITY": "曲面质量", "Save Rule": "保存规则", + "Save View": "保存视图", "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": "场景", "Search": "搜索", "Search commands": "搜索命令", + "Section": "剖面", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "“选择其他”:在模型上按住左键(或右键单击 › 选择其他…)列出光标下的所有对象;在同一位置再次单击可选择该处的下一个对象。双击中键转到主视图(首选项 › 导航)。", "Select bodies (a face picks its body)": "选择实体(单击面即选择其所属实体)", "Select bodies or faces instead": "改为选择实体或面", @@ -250,6 +307,7 @@ "Semantic faces share their appearance across instances.": "语义面在各实例间共享外观。", "Send your report on GitHub": "在 GitHub 上发送报告", "Shape": "形状", + "Sheet Rules": "钣金规则", "Show Agent Cursor": "显示代理光标", "Show in folder": "在文件夹中显示", "Show the pointer an AI agent moves (#35)": "显示 AI 代理移动的指针(#35)", @@ -263,6 +321,7 @@ "Sketch points": "草图点", "Slot width": "槽宽", "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft 在这些设计保存前已关闭。可以打开它们的上次自动保存。", + "Specialise": "专用操作", "Speed": "速度", "Stand it up": "将其立起", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "将其立起:绕 X 轴旋转四分之一周,作为一个可撤销的移动特征。", @@ -307,6 +366,7 @@ "Use saved fixed plane": "使用已保存的固定平面", "Use selected face as fixed plane": "使用所选面作为固定平面", "VIEW": "视图", + "VIEWS": "视图", "Value": "值", "Velocity": "速度", "Vertices": "顶点", @@ -319,6 +379,7 @@ "When": "条件", "Width": "宽度", "Will fail": "将失败", + "Zebra": "斑马纹", "angle, height": "角度、高度", "appearance.dielectric_ior": "电介质折射率", "appearance.metallic": "金属度", @@ -1087,6 +1148,8 @@ "ui.apply": "应用", "ui.arc": "圆弧", "ui.assemble": "装配", + "ui.assistant": "助手", + "ui.assistant_waiting": "{count} 个批准请求等待中", "ui.autosave_every": "自动保存间隔", "ui.axes": "轴", "ui.axis": "轴", @@ -1476,6 +1539,9 @@ "ui.reverse_horizontal_pan_tip": "水平双指滚动和拇指滚轮向相反方向平移", "ui.reverse_zoom_direction": "反转缩放方向", "ui.revolve": "旋转", + "ui.ribbon_exit": "退出", + "ui.ribbon_pin_footer": "固定的命令显示在功能区中。将指针悬停在行上可固定或取消固定。", + "ui.ribbon_workspace": "工作区", "ui.right": "右视", "ui.save": "保存", "ui.save_as": "另存为", @@ -1569,6 +1635,7 @@ "ui.stand_up_tip": "当 Z 朝上的 STEP 或 IGES 文件打开后,提示绕 X 轴旋转四分之一周", "ui.start": "开始", "ui.start_over": "重新开始", + "ui.start_page": "起始页", "ui.start_radius": "起始半径", "ui.stretch": "伸展", "ui.supersampling": "超级采样 (SSAA)", @@ -1626,6 +1693,18 @@ "ui.visual_style": "视觉样式", "ui.visual_wireframe": "线框", "ui.workspace": "工作区", + "ui.workspace_animation_description": "爆炸视图、运动研究和故事板", + "ui.workspace_available": "可用", + "ui.workspace_current": "当前", + "ui.workspace_design_description": "草图、建模、装配和检查", + "ui.workspace_design_tabs": "模型 · 曲面 · 装配 · 插入 · 检查 · 管理 · 视图", + "ui.workspace_drawing_description": "包含视图、尺寸和标题栏的二维图纸", + "ui.workspace_footer": "所有工作区使用同一设计、历史记录和选择,仅功能区选项卡发生变化。编辑草图或特征时,切换器将被锁定。", + "ui.workspace_manufacture_description": "切片、刀具路径和设置", + "ui.workspace_planned": "计划中", + "ui.workspace_render_description": "产品预览、场景设置和渲染图像", + "ui.workspace_render_tabs": "场景 · 图像", + "ui.workspace_simulation_description": "载荷、约束和结果", "ui.x_distance": "X 距离", "ui.y_distance": "Y 距离", "ui.y_up": "Y 朝上", diff --git a/assets/styles/ui/palettes.rs b/assets/styles/ui/palettes.rs index a03f75766..c2052dec1 100644 --- a/assets/styles/ui/palettes.rs +++ b/assets/styles/ui/palettes.rs @@ -8,7 +8,31 @@ const fn icon_primary(rgb: [u8; 3]) -> Color32 { impl Tokens { pub const fn light() -> Tokens { Tokens { + space_2: 2.0, + space_3: 3.0, + space_4: 4.0, + space_6: 6.0, + space_8: 8.0, + space_10: 10.0, + space_12: 12.0, + space_14: 14.0, + space_16: 16.0, + space_24: 24.0, + radius_sm: 4, + radius_md: 6, + radius_lg: 8, + radius_xl: 10, + font_badge: 9.5, + font_micro: 10.0, + font_panel: 10.5, + font_small: 11.0, + font_caption: 11.5, + font_body: 12.0, + font_label: 12.5, + font_button: 13.0, + font_heading: 14.0, app_bar: Color32::from_rgb(52, 56, 64), + app_bar_separator: Color32::from_rgb(136, 145, 160), toolbar: Color32::from_rgb(246, 247, 249), panel: Color32::from_rgb(250, 251, 252), panel_header: Color32::from_rgb(236, 238, 242), @@ -18,6 +42,14 @@ impl Tokens { accent: Color32::from_rgb(38, 120, 218), accent_soft: Color32::from_rgb(214, 230, 250), sketch_accent: icon_primary(crate::icon_svg::SKETCH_PRIMARY[0]), + // Icon palette active-3 ramps; these accents have no compiled constants yet. + surface_accent: Color32::from_rgb(164, 80, 0), + mesh_accent: Color32::from_rgb(130, 103, 0), + form_accent: Color32::from_rgb(115, 73, 205), + render_accent: Color32::from_rgb(174, 45, 113), + on_accent: Color32::WHITE, + agent_ok: Color32::from_rgb(76, 194, 122), + agent_busy: Color32::from_rgb(108, 180, 240), error: Color32::from_rgb(214, 54, 54), warning: Color32::from_rgb(222, 150, 30), icon: Color32::from_rgb(70, 78, 92), @@ -81,6 +113,10 @@ impl Tokens { rubber_band: Color32::from_rgb(30, 120, 230), app_bar_text: Color32::from_rgb(230, 234, 242), app_bar_hover: Color32::from_rgba_unmultiplied_const(255, 255, 255, 28), + app_bar_hover_subtle: Color32::from_rgba_unmultiplied_const(255, 255, 255, 18), + app_bar_hover_button: Color32::from_rgba_unmultiplied_const(255, 255, 255, 30), + app_bar_hover_strong: Color32::from_rgba_unmultiplied_const(255, 255, 255, 40), + app_bar_tab_active: Color32::from_rgb(53, 59, 71), timeline_item: Color32::WHITE, timeline_item_error: Color32::from_rgb(250, 220, 220), timeline_marker: Color32::from_rgb(70, 76, 88), @@ -135,7 +171,7 @@ impl Tokens { pub const fn dark() -> Tokens { let mut t = Tokens::light(); t.app_bar = Color32::from_rgb(28, 31, 38); - t.toolbar = Color32::from_rgb(37, 41, 49); + t.toolbar = Color32::from_rgb(39, 43, 52); t.panel = Color32::from_rgb(39, 43, 52); t.panel_header = Color32::from_rgb(47, 52, 62); t.border = Color32::from_rgb(63, 69, 82); @@ -144,6 +180,10 @@ impl Tokens { t.accent = Color32::from_rgb(58, 136, 238); t.accent_soft = Color32::from_rgb(42, 70, 110); t.sketch_accent = icon_primary(crate::icon_svg::SKETCH_PRIMARY[1]); + t.surface_accent = Color32::from_rgb(149, 104, 45); + t.mesh_accent = Color32::from_rgb(133, 113, 0); + t.form_accent = Color32::from_rgb(123, 99, 166); + t.render_accent = Color32::from_rgb(224, 116, 174); t.construction_geom = icon_primary(crate::icon_svg::CONSTRUCTION_PRIMARY[1]); t.error = Color32::from_rgb(240, 100, 96); t.warning = Color32::from_rgb(236, 170, 70); @@ -210,6 +250,9 @@ impl Tokens { t.icons.access = [good, Color32::from_rgb(217, 102, 13)]; t.construction_geom = icon_primary(crate::icon_svg::CONSTRUCTION_RED_GREEN[dark as usize]); t.icons.draft = [good, Color32::from_rgb(242, 230, 153)]; + t.surface_accent = if dark { Color32::from_rgb(200, 135, 55) } else { Color32::from_rgb(164, 80, 0) }; + t.mesh_accent = if dark { Color32::from_rgb(190, 175, 70) } else { Color32::from_rgb(130, 103, 0) }; + t.form_accent = if dark { Color32::from_rgb(165, 135, 220) } else { Color32::from_rgb(115, 73, 205) }; if dark { t.bend_up = Color32::from_rgb(110, 165, 255); t.bend_down = Color32::from_rgb(240, 180, 70); @@ -229,6 +272,11 @@ impl Tokens { pub(super) const fn blue_yellow(self, dark: bool) -> Tokens { let mut t = self; t.analysis.hatch = true; + t.surface_accent = if dark { Color32::from_rgb(210, 120, 95) } else { Color32::from_rgb(164, 65, 50) }; + t.mesh_accent = if dark { Color32::from_rgb(200, 175, 135) } else { Color32::from_rgb(130, 103, 65) }; + t.form_accent = if dark { Color32::from_rgb(150, 140, 210) } else { Color32::from_rgb(115, 73, 170) }; + // Green and blue status lights merge for tritan vision; use rose for working. + t.agent_busy = Color32::from_rgb(232, 150, 190); t.preview_sketch = Color32::from_rgb(125, 180, 105); t.glyph_text = icon_primary(crate::icon_svg::CONSTRAINT_BLUE_YELLOW[dark as usize]); t.construction_geom = icon_primary(crate::icon_svg::CONSTRUCTION_BLUE_YELLOW[dark as usize]); diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index 4dad5c60c..b1f8bb606 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -638,11 +638,67 @@ pub fn shown(app: &SolveApp) -> bool { app.preferences.ai_features && cfg!(not(target_arch = "wasm32")) } -/// The AI button at the toolbar row's right end is shown. -pub fn toolbar_button_shown(app: &SolveApp) -> bool { +/// The Assistant button in the application bar is shown (honours the existing preference). +pub fn app_bar_button_shown(app: &SolveApp) -> bool { shown(app) && app.preferences.ai_toolbar_button } +/// The application bar's status mark, independent of panel layout and painting. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum AssistantMark { + Quiet, + Ready, + Busy, + NeedsAuth, + Stopped, + Waiting(usize), +} + +fn assistant_mark_for(state: State, login: &str, configured: bool, waiting: usize, stopped: bool, failed: bool) -> AssistantMark { + if waiting > 0 { + return AssistantMark::Waiting(waiting); + } + if state == State::NeedsAuth { + return AssistantMark::NeedsAuth; + } + if state == State::Exited || stopped || failed { + return AssistantMark::Stopped; + } + match state { + State::Busy | State::Starting => AssistantMark::Busy, + // A live session is stronger evidence than an older discovery login probe. + State::Ready => AssistantMark::Ready, + State::Off if configured && matches!(login, "signed_in" | "key") => AssistantMark::Ready, + State::Off if configured && login == "signed_out" => AssistantMark::NeedsAuth, + _ => AssistantMark::Quiet, + } +} + +pub(crate) fn assistant_mark(app: &SolveApp) -> AssistantMark { + let chat = &app.agent_chat; + let current = agents::current(app); + assistant_mark_for( + chat.state(), + current.as_ref().map_or("", |e| e.login), + current.is_some(), + chat.waiting(), + chat.stopped, + chat.ended.as_deref() == Some("error"), + ) +} + +pub(crate) fn assistant_tip(mark: AssistantMark) -> String { + let state = match mark { + AssistantMark::Quiet => tr("ui.agent_chat_state_off").to_string(), + AssistantMark::Ready => tr("ui.agent_chat_state_ready").to_string(), + AssistantMark::Busy => tr("ui.agent_chat_state_busy").to_string(), + AssistantMark::NeedsAuth => tr("ui.agent_chat_state_auth").to_string(), + AssistantMark::Stopped => tr("ui.agent_chat_state_exited").to_string(), + AssistantMark::Waiting(count) => trf("ui.assistant_waiting", &[("count", &count.to_string())]), + }; + format!("{} (Ctrl+Shift+A) — {state}", tr("ui.assistant")) +} + /// Whether a permission question is about one of SolidCraft's own tools (which SolidCraft's own /// gate checks): the agents name MCP tools after their server. fn solidcraft_tool(title: &str) -> bool { diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 97bf62975..26246fd72 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -198,7 +198,7 @@ fn with_ai_features_off_nothing_of_the_chat_shows_or_runs() { let shortcut = json!({"key": "A", "shift": true, "cmd": true}); h.app.preferences.ai_features = false; h.frames(3); - assert!(handle_at("toolbar:ai").is_none(), "no toolbar button"); + assert!(handle_at("titlebar:assistant").is_none(), "no Assistant button"); h.call("ui.key", shortcut.clone()); h.frames(3); h.call("ui.agent_chat", json!({"open": true, "send": "hello", "connect": true})); @@ -216,7 +216,7 @@ fn with_ai_features_off_nothing_of_the_chat_shows_or_runs() { // On (the default): the button shows; discovery waits until the panel opens. h.app.preferences.ai_features = true; h.frames(3); - assert!(handle_at("toolbar:ai").is_some(), "the toolbar button"); + assert!(handle_at("titlebar:assistant").is_some(), "the Assistant button"); assert!(h.app.agent_chat.detection.is_none() && h.app.agent_chat.detecting.is_none(), "nothing looked for yet"); h.call("ui.key", shortcut.clone()); h.frames(3); @@ -227,7 +227,7 @@ fn with_ai_features_off_nothing_of_the_chat_shows_or_runs() { h.app.preferences.ai_toolbar_button = false; h.call("ui.key", shortcut); h.frames(3); - assert!(handle_at("toolbar:ai").is_none() && !h.app.agent_chat.open); + assert!(handle_at("titlebar:assistant").is_none() && !h.app.agent_chat.open); } #[test] @@ -1413,6 +1413,44 @@ fn an_agents_markdown_is_drawn_as_blocks() { h.frames(3); } +#[test] +fn assistant_marks_follow_chat_login_turns_and_approvals() { + use AssistantMark::*; + let mark = |state, login, configured| assistant_mark_for(state, login, configured, 0, false, false); + assert_eq!(mark(State::Off, "", false), Quiet); + assert_eq!(mark(State::Off, "signed_in", false), Quiet); + for login in ["", "unknown"] { + assert_eq!(mark(State::Off, login, true), Quiet); + } + for login in ["signed_in", "key"] { + assert_eq!(mark(State::Off, login, true), Ready); + } + assert_eq!(mark(State::Off, "signed_out", true), NeedsAuth); + for login in ["", "signed_out", "unknown", "signed_in"] { + for (state, expected) in + [(State::Ready, Ready), (State::Busy, Busy), (State::Starting, Busy), (State::NeedsAuth, NeedsAuth), (State::Exited, Stopped)] + { + assert_eq!(mark(state, login, true), expected); + assert_eq!(assistant_mark_for(state, login, true, 12, false, false), Waiting(12)); + } + } + assert_eq!(assistant_mark_for(State::Ready, "signed_in", true, 0, true, false), Stopped); + assert_eq!(assistant_mark_for(State::Ready, "signed_in", true, 0, false, true), Stopped); +} + +#[test] +fn assistant_click_and_shortcut_toggle_the_same_panel_without_a_connection() { + let mut h = crate::scenario::Harness::new(); + h.frames(3); + assert_eq!(assistant_mark(&h.app), AssistantMark::Quiet); + assert!(crate::scenario::handle_at("toolbar:ai").is_none()); + h.step(&json!({"click":{"handle":"titlebar:assistant"}})).unwrap(); + assert!(h.app.agent_chat.open); + h.step(&json!({"key":"A", "shift":true,"cmd":true})).unwrap(); + assert!(!h.app.agent_chat.open); + assert!(h.app.agent_chat.backend.is_none()); +} + /// A long message scrolls inside its box: the buttons under the box stay in the window (#2224). /// Measured against the panel's bottom once the agents on this machine have been looked for: /// what that finds (and the status it reports) arrives in its own time and may change what is diff --git a/crates/ui-egui/src/agent_cursor.rs b/crates/ui-egui/src/agent_cursor.rs index 7844ad6b3..530f285d6 100644 --- a/crates/ui-egui/src/agent_cursor.rs +++ b/crates/ui-egui/src/agent_cursor.rs @@ -197,7 +197,8 @@ const NOT_PLACES: [&str; 14] = /// A command's toolbar button, or its panel when the button sits in a drop-down. fn button(command: &str) -> Option { let spec = solidcraft_engine::find_command(command)?; - crate::scenario::handle_at(&format!("toolbar:{}", spec.id)).or_else(|| crate::scenario::handle_at(&format!("panel:{}:{}", spec.tab, spec.panel))) + crate::scenario::handle_at(&format!("toolbar:{}", spec.id)) + .or_else(|| crate::workspace::destination(spec).and_then(|(t, p)| crate::scenario::handle_at(&format!("panel:{t}:{p}")))) } /// Where the pointer goes for a command: its toolbar button (or its panel), then its picks on diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 04c457275..7a429b385 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -348,7 +348,7 @@ pub(crate) fn draw_row(ui: &mut egui::Ui, id: egui::Id, row: &Row) -> RowResp { let dragged_over = egui::DragAndDrop::has_any_payload(ui.ctx()) && ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| r.contains(p)); let mut out = RowResp { rect: Some(r), hovered: resp.hovered() || dragged_over, ..Default::default() }; if row.selected { - ui.painter().rect_filled(r, 3.0, t.accent_soft); + ui.painter().rect_filled(r, 3.0, crate::theme::TabAccent::current(ui.ctx()).soft); } else if resp.hovered() || row.mark == Mark::Here { ui.painter().rect_filled(r, 3.0, t.hover); } @@ -425,7 +425,7 @@ pub(crate) fn draw_row(ui: &mut egui::Ui, id: egui::Id, row: &Row) -> RowResp { } let col = row.color.unwrap_or(if row.dim { t.text_dim } else { t.text }); let label_display = if row.name { crate::i18n::tr_name(row.label) } else { crate::i18n::tr_dyn(row.label) }; - let galley = ui.painter().layout_no_wrap(label_display, FontId::proportional(12.5), col); + let galley = ui.painter().layout_no_wrap(label_display, FontId::proportional(t.font_label), col); let lw = galley.size().x; ui.painter().galley(pos2(x, cy - galley.size().y / 2.0), galley, col); let mut bx = (x + lw + 6.0).min(r.right() - 16.0); @@ -674,7 +674,7 @@ fn browser_panel(app: &mut SolveApp, ui: &mut egui::Ui, timeline_above: bool) { let panel = egui::Panel::left("sc_browser") .exact_size(width) .resizable(false) - .frame(egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin::symmetric(6, 6))) + .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(); @@ -702,13 +702,13 @@ fn browser_panel(app: &mut SolveApp, ui: &mut egui::Ui, timeline_above: bool) { } let arrow = if browser_collapsed { "▶" } else { "▼" }; let response = - ui.add(egui::Button::new(RichText::new(format!("{arrow} BROWSER")).size(11.0).strong().color(t.text_dim)).frame(false)); + ui.add(egui::Button::new(RichText::new(format!("{arrow} BROWSER")).size(t.font_small).strong().color(t.text_dim)).frame(false)); 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(4.0); + ui.add_space(t.space_4); browser_rows(app, ui, &mut acts); } } else { @@ -766,8 +766,8 @@ pub fn floating(app: &mut SolveApp, ui: &mut egui::Ui, viewport: egui::Rect) { fn browser_contents(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions) { let t = Tokens::get(); - ui.label(RichText::new(crate::i18n::tr_label("BROWSER")).size(11.0).strong().color(t.text_dim)); - ui.add_space(4.0); + ui.label(RichText::new(crate::i18n::tr_label("BROWSER")).size(t.font_small).strong().color(t.text_dim)); + ui.add_space(t.space_4); browser_rows(app, ui, acts); } @@ -2253,7 +2253,7 @@ pub fn dims_overlay(app: &SolveApp, ctx: &egui::Context) { let col = if c.driven { tk.dimension_driven } else { tk.dimension }; let galley = painter.layout_no_wrap( crate::dim_view::label(&c.kind, expr, c.driven, &app.session.doc.units, app.preferences.length_decimals), - FontId::proportional(11.5), + FontId::proportional(tk.font_caption), col, ); let size = galley.size() + vec2(6.0, 2.0); diff --git a/crates/ui-egui/src/colour_tokens_tests.rs b/crates/ui-egui/src/colour_tokens_tests.rs index 1576eb97d..82a1b7d74 100644 --- a/crates/ui-egui/src/colour_tokens_tests.rs +++ b/crates/ui-egui/src/colour_tokens_tests.rs @@ -75,17 +75,14 @@ const ALLOWED_LITERALS: &[(&str, usize, &str)] = &[ ("dialogs_library.rs", 1, "a library appearance's swatch: the colour is the fact"), ("dialogs_assembly.rs", 1, "the interference fill, shaded from its token"), ("dialogs_motion.rs", 1, "a white outline"), - ("documents.rs", 4, "white hover overlays on document tabs"), ("frame.rs", 1, "the window shadow"), ("gizmo.rs", 2, "the gizmo's neutral grey ball"), ("icons.rs", 1, "the white tint that carries an icon image's opacity"), - ("home.rs", 4, "white ink on accent buttons, and thumbnail tints"), + ("home.rs", 2, "thumbnail tints"), ("ref_images.rs", 1, "a reference image's opacity tint"), - ("sketch_palette.rs", 1, "white text on the accent button"), - ("sketch_text.rs", 1, "white text on the selection chip"), ("theme_files.rs", 1, "a colour read from a theme file, which sets tokens"), - ("titlebar.rs", 4, "the window close button's red hover (the system's convention), white hovers and ink"), - ("toolbar.rs", 3, "white hover overlays and the version text"), + ("titlebar.rs", 2, "the window close button's red hover (the system's convention) and white ink"), + ("toolbar.rs", 1, "the version text"), ]; const COLOUR_LITERALS: &[&str] = &[ diff --git a/crates/ui-egui/src/colour_vision_tests.rs b/crates/ui-egui/src/colour_vision_tests.rs index 9a96b8792..4e028c73b 100644 --- a/crates/ui-egui/src/colour_vision_tests.rs +++ b/crates/ui-egui/src/colour_vision_tests.rs @@ -356,6 +356,11 @@ fn groups(t: &Tokens) -> Vec { &[("app_bar_icon[0]", t.app_bar_icon[0]), ("app_bar_icon[1]", t.app_bar_icon[1]), ("app_bar_icon[2]", t.app_bar_icon[2])], &[("app_bar", t.app_bar)], ), + // Tab names and icons identify the tabs; each accent must read against the toolbar. + group("surface tab", &[("surface_accent", t.surface_accent)], &[("toolbar", t.toolbar)]), + group("mesh tab", &[("mesh_accent", t.mesh_accent)], &[("toolbar", t.toolbar)]), + group("form tab", &[("form_accent", t.form_accent)], &[("toolbar", t.toolbar)]), + group("agent status", &[("agent_ok", t.agent_ok), ("agent_busy", t.agent_busy)], &[("app_bar", t.app_bar)]), group("logo", &[("logo[0]", t.logo[0]), ("logo[1]", t.logo[1]), ("logo[2]", t.logo[2])], &[("app_bar", t.app_bar)]), ]; // The removed part of a cut preview is translucent over the body. @@ -371,6 +376,35 @@ const SHADED: [&str; 2] = ["analysis.draft", "analysis.access"]; /// Tokens no colour vision mode needs to keep apart, and why. A new token fails /// `every_token_is_measured_or_carries_no_meaning` until it is in a group above or here. const NO_MEANING: &[(&str, &str)] = &[ + ("space_2", "layout dimension"), + ("space_3", "layout dimension"), + ("space_4", "layout dimension"), + ("space_6", "layout dimension"), + ("space_8", "layout dimension"), + ("space_10", "layout dimension"), + ("space_12", "layout dimension"), + ("space_14", "layout dimension"), + ("space_16", "layout dimension"), + ("space_24", "layout dimension"), + ("radius_sm", "layout dimension"), + ("radius_md", "layout dimension"), + ("radius_lg", "layout dimension"), + ("radius_xl", "layout dimension"), + ("font_badge", "layout dimension"), + ("font_micro", "layout dimension"), + ("font_panel", "layout dimension"), + ("font_small", "layout dimension"), + ("font_caption", "layout dimension"), + ("font_body", "layout dimension"), + ("font_label", "layout dimension"), + ("font_button", "layout dimension"), + ("font_heading", "layout dimension"), + ("on_accent", "ink on an accent fill"), + ("app_bar_hover_subtle", "translucent hover chrome"), + ("app_bar_hover_button", "translucent hover chrome"), + ("app_bar_hover_strong", "translucent hover chrome"), + ("app_bar_tab_active", "the active document tab's surface"), + ("render_accent", "the Render workspace's identity colour"), // The window's chrome: grounds, text and borders (measured as grounds where meaning sits on them). ("panel_header", "chrome"), ("border", "chrome"), @@ -384,6 +418,7 @@ const NO_MEANING: &[(&str, &str)] = &[ ("subheading_bg", "chrome"), ("overlay", "a chip's ground over the view"), ("app_bar_text", "text"), + ("app_bar_separator", "neutral chrome divider"), ("app_bar_hover", "a hovered tab, translucent white"), ("timeline_marker", "the rollback marker, alone"), ("field", "a field's ground"), @@ -635,18 +670,51 @@ fn each_mode_changes_only_its_table() { "icons.draft", "bend_up", "bend_down", + "surface_accent", + "mesh_accent", + "form_accent", "sketch_accent", "preview_sketch", ]; - let mut red_green_light = red_green_both.to_vec(); + let mut red_green_light = + red_green_both.into_iter().filter(|name| !["surface_accent", "mesh_accent", "form_accent"].contains(name)).collect::>(); red_green_light.extend(["sketch_projected", "sketch_locked", "timeline_item_error", "construction_geom"]); for (dark, mode, want) in [ (false, ColorVision::Protan, set(&red_green_light)), (true, ColorVision::Protan, set(&red_green_both)), (false, ColorVision::Deutan, set(&red_green_light)), (true, ColorVision::Deutan, set(&red_green_both)), - (false, ColorVision::Tritan, set(&["sketch_locked", "box_crossing", "construction_geom", "preview_sketch", "analysis.hatch"])), - (true, ColorVision::Tritan, set(&["sketch_locked", "box_crossing", "construction_geom", "glyph_text", "preview_sketch", "analysis.hatch"])), + ( + false, + ColorVision::Tritan, + set(&[ + "surface_accent", + "mesh_accent", + "form_accent", + "agent_busy", + "sketch_locked", + "box_crossing", + "construction_geom", + "preview_sketch", + "analysis.hatch", + ]), + ), + ( + true, + ColorVision::Tritan, + set(&[ + "surface_accent", + "mesh_accent", + "form_accent", + "agent_busy", + "sketch_locked", + "box_crossing", + "construction_geom", + "glyph_text", + "preview_sketch", + "analysis.hatch", + ]), + ), ] { let base = Tokens::themed(dark, ColorVision::Off); assert_eq!(changed_fields(&base, &Tokens::themed(dark, mode)), want, "{mode:?}, dark {dark}"); diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 9f0a6315e..cd6bcc6fa 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -360,8 +360,8 @@ pub fn items(app: &SolveApp, target: &Target) -> Vec { .key(if rendering { "current" } else { "" }) .on(app.session.active_sketch.is_none() && app.tool.is_none() && app.dialog.is_none() && !app.file_load.busy()), ]; - for w in ["Animation", "Simulation", "Manufacture", "Drawing"] { - v.push(act("ui.workspace", w, "").key("coming later").on(false)); + for (w, icon) in [("Animation", "ws_animate"), ("Simulation", ""), ("Manufacture", ""), ("Drawing", "ws_drawing")] { + v.push(act("ui.workspace", w, icon).key("coming later").on(false)); } v } @@ -1672,7 +1672,9 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let pointer = ctx.input(|i| i.pointer.latest_pos()); let mut inside = app.menu.opener.is_some_and(|r| pointer.is_some_and(|p| r.contains(p))); - let list_at = if app.menu.radial { + let list_at = if target == Target::Workspace { + pos2(at.x.clamp(screen.left(), (screen.right() - 470.0).max(screen.left())), at.y) + } else if app.menu.radial { let c = radial_center(at, screen); let radial = radial_items(app); let area = Rect::from_center_size(c, vec2(2.0 * (RX + 165.0), 2.0 * (RY + 34.0))); @@ -1738,13 +1740,17 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let key_row = app.menu.key_row; let resp = crate::frame::area(egui::Id::new("sc_context_menu")).fixed_pos(list_at).constrain(true).order(egui::Order::Foreground).show(ctx, |ui| { - menu_frame(ui, |ui| { - for (k, item) in list.iter().enumerate() { - if let Some(p) = list_row_lit(ui, item, key_row == Some(k)) { - picked = Some(p); + if target == Target::Workspace { + picked = workspace_menu(ui, &list, key_row, (screen.bottom() - list_at.y).max(160.0)).or(picked.take()); + } else { + menu_frame(ui, |ui| { + for (k, item) in list.iter().enumerate() { + if let Some(p) = list_row_lit(ui, item, key_row == Some(k)) { + picked = Some(p); + } } - } - }); + }); + } }); inside |= resp.response.contains_pointer() || resp.response.rect.contains(pointer.unwrap_or(Pos2::ZERO)); @@ -1767,6 +1773,108 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } } +/// Workspace cards retain the context-menu items and dispatch, including keyboard and +/// control-channel picks. Only the presentation differs from ordinary command lists. +fn workspace_menu(ui: &mut egui::Ui, items: &[Item], key_row: Option, height: f32) -> Option { + let t = Tokens::get(); + let mut picked = None; + egui::Frame::popup(ui.style()).fill(t.panel).stroke(Stroke::new(1.0, t.border)).corner_radius(10.0).inner_margin(9).show(ui, |ui| { + ui.set_width(450.0); + ui.spacing_mut().item_spacing.y = 0.0; + ui.add_space(4.0); + ui.label(egui::RichText::new(crate::i18n::tr("ui.ribbon_workspace").to_uppercase()).size(11.0).strong().color(t.text_dim)); + ui.add_space(8.0); + egui::ScrollArea::vertical().id_salt("workspace_menu_rows").max_height((height - 116.0).max(60.0)).show(ui, |ui| { + for (k, item) in items.iter().enumerate() { + let (slug, description, tabs) = match item.label.as_str() { + "Design" => ("design", "ui.workspace_design_description", Some("ui.workspace_design_tabs")), + "Render" => ("render", "ui.workspace_render_description", Some("ui.workspace_render_tabs")), + "Animation" => ("animation", "ui.workspace_animation_description", None), + "Simulation" => ("simulation", "ui.workspace_simulation_description", None), + "Manufacture" => ("manufacture", "ui.workspace_manufacture_description", None), + "Drawing" => ("drawing", "ui.workspace_drawing_description", None), + _ => continue, + }; + let planned = tabs.is_none(); + let current = item.shortcut == "current"; + let accent = if planned { + t.text_dim + } else if slug == "render" { + t.render_accent + } else { + t.accent + }; + let soft = t.panel.lerp_to_gamma(accent, 0.10); + let (r, resp) = ui + .allocate_exact_size(vec2(450.0, if planned { 60.0 } else { 72.0 }), if item.enabled { Sense::click() } else { Sense::hover() }); + for handle in [format!("menu:{}", item.id), format!("workspace:menu:{slug}")] { + crate::scenario::publish_handle(&handle, r.center()); + crate::scenario::publish_rect(&handle, r); + } + if current || (item.enabled && (resp.hovered() || key_row == Some(k))) { + ui.painter().rect_filled(r, 5.0, soft); + } + ui.painter().rect_filled(Rect::from_min_max(r.min + vec2(2.0, 7.0), pos2(r.left() + 6.0, r.bottom() - 7.0)), 2.0, accent); + let tile = Rect::from_center_size(pos2(r.left() + 40.0, r.center().y), vec2(44.0, 44.0)); + ui.painter().rect_filled(tile, 9.0, if planned { t.panel_header } else { soft }); + if !item.icon.is_empty() { + icons::paint_icon(ui.painter(), tile.shrink(7.0), &item.icon, if item.enabled { 1.0 } else { 0.35 }); + } + let text = if item.enabled { t.text } else { t.text_dim }; + let name = crate::i18n::tr_label(&item.label); + let x = r.left() + 74.0; + let y = r.top() + 17.0; + let galley = egui::WidgetText::from(egui::RichText::new(name).strong().size(14.0).color(text)).into_galley( + ui, + Some(egui::TextWrapMode::Extend), + f32::INFINITY, + egui::TextStyle::Button, + ); + let badge_x = x + galley.size().x + 9.0; + let origin = pos2(x, y - galley.size().y / 2.0); + ui.painter().galley(origin - vec2(0.2, 0.0), galley.clone(), text); + ui.painter().galley(origin + vec2(0.2, 0.0), galley, text); + let badge = crate::i18n::tr(if planned { + "ui.workspace_planned" + } else if current { + "ui.workspace_current" + } else { + "ui.workspace_available" + }); + let badge = ui.painter().layout_no_wrap(badge.to_string(), FontId::proportional(11.0), if current { t.on_accent } else { accent }); + let badge_rect = Rect::from_min_size(pos2(badge_x, y - 8.0), badge.size() + vec2(12.0, 3.0)); + ui.painter().rect_filled(badge_rect, 8.0, if current { accent } else { soft }); + ui.painter().galley(badge_rect.min + vec2(6.0, 1.5), badge, accent); + let line = |label: &str, y: f32| { + let mut job = egui::text::LayoutJob::simple_singleline(label.to_string(), FontId::proportional(12.0), text); + job.wrap.max_width = r.right() - x - 6.0; + job.wrap.max_rows = 1; + job.wrap.break_anywhere = false; + let galley = ui.painter().layout_job(job); + ui.painter().galley(pos2(x, y), galley, text); + }; + line(crate::i18n::tr(description), r.top() + 29.0); + if let Some(tabs) = tabs { + // Reuse existing tab-name translations when a partial catalog falls back + // to the English summary; complete catalogs keep their translated summary. + let labels = crate::i18n::tr(tabs).split('·').map(|label| crate::i18n::tr_label(label.trim())).collect::>().join(" · "); + line(&labels, r.top() + 47.0); + } + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, item.enabled, name)); + if resp.clicked() && item.enabled { + picked = Some(item.clone()); + } + } + }); + ui.add_space(6.0); + ui.separator(); + ui.add_space(6.0); + ui.add(egui::Label::new(egui::RichText::new(crate::i18n::tr("ui.workspace_footer")).size(11.0).color(t.text_dim)).wrap()); + ui.add_space(4.0); + }); + picked +} + /// The frame every menu uses. pub fn menu_frame(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R { let t = Tokens::get(); @@ -2051,3 +2159,40 @@ mod tests { } } } + +#[cfg(test)] +mod workspace_menu_tests { + use super::*; + use crate::scenario::{Harness, rect_of}; + + #[test] + fn workspace_rows_keep_switching_handles_and_disabled_render_behavior() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1200,"height":1000})); + h.step(&json!({"click":{"handle":"ribbon:workspace"}})).unwrap(); + let opener = rect_of("ribbon:workspace").unwrap(); + let rows: Vec<_> = ["design", "render", "animation", "simulation", "manufacture", "drawing"] + .iter() + .map(|slug| rect_of(&format!("workspace:menu:{slug}")).unwrap()) + .collect(); + assert!(rows.windows(2).all(|pair| pair[0].bottom() <= pair[1].top())); + assert!(rows[0].top() > opener.bottom()); + assert_eq!(rows[0].width(), 450.0); + assert!(items(&h.app, &Target::Workspace).iter().skip(2).all(|item| !item.enabled)); + h.step(&json!({"click":{"handle":"workspace:menu:animation"}})).unwrap(); + assert!(!crate::render_workspace::active(&h.app)); + assert!(h.app.viewport.context_menu.is_some()); + h.step(&json!({"click":{"handle":"workspace:menu:render"}})).unwrap(); + assert!(crate::render_workspace::active(&h.app)); + h.step(&json!({"click":{"handle":"ribbon:workspace"}})).unwrap(); + h.step(&json!({"click":{"handle":"workspace:menu:design"}})).unwrap(); + assert!(!crate::render_workspace::active(&h.app)); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.frames(2); + h.step(&json!({"click":{"handle":"ribbon:workspace"}})).unwrap(); + assert!(!items(&h.app, &Target::Workspace).iter().find(|i| i.id == "ui.workspace.render").unwrap().enabled); + h.step(&json!({"click":{"handle":"workspace:menu:render"}})).unwrap(); + assert!(!crate::render_workspace::active(&h.app)); + assert!(h.app.viewport.context_menu.is_some()); + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 4720d5a7a..f33db5648 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -367,12 +367,13 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> } } match (serde_json::from_value::(cur), serde_json::from_value::(vis)) { - (Ok(u), Ok(v)) => { + (Ok(mut u), Ok(v)) => { if (u.tab == "RENDER") != crate::render_workspace::active(app) && let Err(e) = crate::render_workspace::enter(app, u.tab == "RENDER") { return err(e); } + u.ribbon_context = app.ui.ribbon_context.clone(); app.ui = u; app.session.visibility = v; ok(serde_json::to_value(&app.ui).unwrap_or_default()) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 911dbea68..529cc1fa1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1543,6 +1543,7 @@ fn plane_value(s: &Session, sel: Option<&Sel>) -> Option { /// A value field; true when Enter was pressed in it. pub(crate) fn field(ui: &mut egui::Ui, s: &mut String) -> bool { let r = ui.text_edit_singleline(s); + crate::theme::TabAccent::number_focus(ui, &r); publish_row(&r); crate::params_dialog::complete(ui, &r, s); r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) @@ -1584,7 +1585,7 @@ pub(crate) fn icon_choice(ui: &mut egui::Ui, labels: &[&str], icons: &[&str], se } else if resp.hovered() { ui.painter().rect_filled(r, 4.0, t.hover); } - let ink = if on { Color32::WHITE } else { t.icon }; + let ink = if on { t.on_accent } else { t.icon }; crate::icons::paint(ui.painter(), r.shrink(3.0), icons.get(i).copied().unwrap_or(""), ink, t.icon_fill, ink); crate::scenario::publish_handle(&format!("dialog:{row}:{label}"), r.center()); if on { @@ -1937,7 +1938,7 @@ fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std:: } else { crate::i18n::format("dialog.selected_count", &[("count", &inp.items.len().to_string())]) }) - .color(Color32::WHITE) + .color(t.on_accent) } else { RichText::new(crate::i18n::tr("dialog.select")).color(t.text) }; @@ -3341,7 +3342,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let buttons = close_width + if has_ok { ok_width + ui.spacing().item_spacing.x } else { 0.0 }; crate::frame::right_aligned(ui, total, buttons, |ui| { if has_ok { - let b = egui::Button::new(RichText::new(label).color(if valid { Color32::WHITE } else { t.text_dim })) + let b = egui::Button::new(RichText::new(label).color(if valid { t.on_accent } else { t.text_dim })) .fill(if valid { t.accent } else { Color32::TRANSPARENT }) .wrap_mode(egui::TextWrapMode::Extend) .min_size(vec2(ok_width, 24.0)); diff --git a/crates/ui-egui/src/dialogs_sheet_tests.rs b/crates/ui-egui/src/dialogs_sheet_tests.rs index 7d2d714db..01d6f5875 100644 --- a/crates/ui-egui/src/dialogs_sheet_tests.rs +++ b/crates/ui-egui/src/dialogs_sheet_tests.rs @@ -200,7 +200,12 @@ fn flat_pattern_islands_fit_before_the_actual_command_panel() { ui.label("Flat size: 50 × 10 × 2.5 mm"); }); let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Background, egui::Id::new("island-fit"))); - assert!(overlay(&mut app, &painter, Rect::from_min_max(pos2(250.0, 126.0), pos2(1400.0, 832.0)), &dialog)); + assert!(overlay( + &mut app, + &painter, + Rect::from_min_max(pos2(250.0, crate::toolbar::APP_BAR_HEIGHT + crate::toolbar::RIBBON_HEIGHT), pos2(1400.0, 832.0)), + &dialog + )); }); output.textures_delta.clear(); } diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index d5ba285e6..0a88aa69a 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -222,6 +222,7 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Surf) -> bool { Surf::Stitch { tolerance } => { row_label(ui, "Tolerance"); let r = ui.add(egui::TextEdit::singleline(tolerance).hint_text("tight")); + crate::theme::TabAccent::number_focus(ui, &r); crate::params_dialog::complete(ui, &r, tolerance); enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); ui.end_row(); diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rs index 7910a37e5..119d73534 100644 --- a/crates/ui-egui/src/dim_view.rs +++ b/crates/ui-egui/src/dim_view.rs @@ -701,6 +701,7 @@ fn edit_box(app: &mut SolveApp, ctx: &egui::Context) { ui.label(egui::RichText::new(format!("Dimension: {}", e.param)).strong()) .on_hover_text("Click another driving dimension to insert its name"); let r = ui.add(egui::TextEdit::singleline(&mut e.expr).id(id).desired_width(popup_width)); + crate::theme::TabAccent::number_focus(ui, &r); if r.has_focus() { e.selection = egui::TextEdit::load_state(ctx, id).and_then(|s| s.cursor.char_range()); } diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 6f240ecd3..4a41672e1 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -4,7 +4,7 @@ //! Closing a design with unsaved changes asks first, and so does quitting: one "save changes?" //! per design with unsaved changes ([`request_quit`]). -use egui::{Align2, Color32, FontId, Rect, Sense, Stroke, pos2, vec2}; +use egui::{Align2, FontId, Rect, Sense, pos2, vec2}; use serde_json::{Value, json}; use solidcraft_engine::Session; use solidcraft_engine::render::Camera; @@ -119,7 +119,9 @@ fn swap_in(app: &mut SolveApp, slot: DocSlot) -> DocSlot { app.session.auto_project = out.session.auto_project; // Views cache by revision: the incoming design must not look unchanged. app.session.invalidate_view(out_rev); - app.ui.tab = if app.session.active_sketch.is_some() { "SKETCH".into() } else { "SOLID".into() }; + app.ui.ribbon_context = None; + app.ui.tab = "MODEL".into(); + crate::workspace::sync_context(app); out } @@ -367,33 +369,31 @@ pub fn control(app: &mut SolveApp, p: &Value) -> Value { /// + for a new design. pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) { let t = Tokens::get(); - let home = Rect::from_min_size(pos2(x0, r.top() + 5.0), vec2(66.0, r.height() - 5.0)); - let response = ui.interact(home, ui.id().with("home_tab"), Sense::click()); - tab_shape(ui.painter(), &t, home, app.home.open, response.hovered()); - let home_text = app.tr("ui.home"); - ui.painter().text( - home.center(), - Align2::CENTER_CENTER, - home_text, - FontId::proportional(13.0), - if app.home.open { t.text } else { t.app_bar_text }, - ); - crate::scenario::publish_handle("tab:home", home.center()); - if response.clicked() && !app.file_load.busy() { - app.home.show(app.session.revision); - } - let x0 = x0 + 70.0; let info = tabs_info(app); let n = info.len(); let (first, shown, w) = layout(n, app.docs.active, x1 - x0); let mut x = x0; let mut pick: Option = None; let mut shut: Option = None; + // Each tab fits its name (up to MAX_FIT) while all of them fit; otherwise they share the room. + const MAX_FIT: f32 = 200.0; + let natural: Vec = info + .iter() + .map(|(name, dirty)| { + let shown_name = crate::i18n::Locale::for_language(&app.preferences.language).given_name(name); + let label = format!("{shown_name}{}", if *dirty { " •" } else { "" }); + let text = ui.painter().layout_no_wrap(label, FontId::proportional(13.0), t.app_bar_text).size().x; + (text + 40.0).clamp(72.0, MAX_FIT) + }) + .collect(); + let fit_all = shown == n && natural.iter().sum::() <= x1 - x0 - 34.0; for (i, (name, dirty)) in info.iter().enumerate().skip(first).take(shown) { - let tr = Rect::from_min_size(pos2(x, r.top() + 5.0), vec2(w - 2.0, r.height() - 5.0)); + let w = if fit_all { natural.get(i).copied().unwrap_or(w) } else { w }; + let tr = Rect::from_min_size(pos2(x, r.top() + 4.0), vec2(w - 2.0, r.height() - 8.0)); let active = !app.home.open && (i == app.docs.active || app.docs.slots.is_empty()); let resp = ui.interact(tr, ui.id().with(("doc_tab", i)), Sense::click_and_drag()); crate::scenario::publish_handle(&format!("tab:design:{i}"), tr.center()); + crate::scenario::publish_rect(&format!("tab:design:{i}"), tr); // The tabs are part of the title bar: dragging one moves the window, a double click // maximizes it. if app.custom_titlebar || app.integrated_titlebar { @@ -403,8 +403,8 @@ pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) { crate::titlebar::toggle_maximize(ui.ctx()); } } - tab_shape(ui.painter(), &t, tr, active, resp.hovered()); - let ink = if active { t.text } else { t.app_bar_text }; + tab_shape(ui.painter(), &t, tr, active, resp.hovered() || resp.has_focus()); + let ink = if active || resp.hovered() { t.app_bar_text } else { t.app_bar_text.gamma_multiply(0.7) }; let label = format!("{}{}", crate::i18n::Locale::for_language(&app.preferences.language).given_name(name), if *dirty { " •" } else { "" }); let g = ui.painter().layout_no_wrap(label, FontId::proportional(13.0), ink); let text_w = (tr.width() - 30.0).max(10.0); @@ -412,14 +412,21 @@ pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) { ui.painter().with_clip_rect(clip).galley(pos2(tr.left() + 10.0, tr.center().y - g.size().y / 2.0), g, ink); // × let xr = Rect::from_center_size(pos2(tr.right() - 13.0, tr.center().y), vec2(16.0, 16.0)); - let xresp = ui.interact(xr, ui.id().with(("doc_close", i)), Sense::click()); - if xresp.hovered() { - ui.painter().rect_filled(xr, 3.0, Color32::from_white_alpha(40)); + let show_close = active || resp.hovered() || ui.rect_contains_pointer(tr); + let xresp = ui.interact(xr, ui.id().with(("doc_close", i)), if show_close { Sense::click() } else { Sense::hover() }); + crate::scenario::publish_handle(&format!("tab:close:{i}"), xr.center()); + crate::scenario::publish_rect(&format!("tab:close:{i}"), xr); + if show_close && (xresp.hovered() || xresp.has_focus()) { + ui.painter().rect_filled(xr, 3.0, t.app_bar_hover_strong); + } + if show_close { + crate::icons::paint_app_bar( + ui.painter(), + Rect::from_center_size(xr.center(), vec2(14.0, 14.0)), + "close", + if xresp.hovered() || xresp.has_focus() { 1.0 } else { 0.55 }, + ); } - let c = xr.center(); - let s = Stroke::new(1.3, if active { t.text_dim } else { t.app_bar_text }); - ui.painter().line_segment([c - vec2(3.5, 3.5), c + vec2(3.5, 3.5)], s); - ui.painter().line_segment([c - vec2(3.5, -3.5), c + vec2(3.5, -3.5)], s); if xresp.on_hover_text("Close").clicked() { shut = Some(i); } else if resp.on_hover_text(name.as_str()).clicked() { @@ -429,10 +436,10 @@ pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) { } // More tabs than fit: a chevron lists them all. if shown < n { - let mr = Rect::from_center_size(pos2(x + 12.0, r.center().y + 2.0), vec2(20.0, 22.0)); + let mr = Rect::from_center_size(pos2(x + 12.0, r.center().y), vec2(20.0, 22.0)); let mresp = ui.interact(mr, ui.id().with("doc_more"), Sense::click()); if mresp.hovered() { - ui.painter().rect_filled(mr, 4.0, Color32::from_white_alpha(30)); + ui.painter().rect_filled(mr, 4.0, t.app_bar_hover_button); } ui.painter().text(mr.center(), egui::Align2::CENTER_CENTER, format!("»{}", n - shown), FontId::proportional(12.0), t.app_bar_text); let id = egui::Id::new("sc_doc_more"); @@ -463,15 +470,17 @@ pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) { x += 26.0; } // New design: a new tab showing the start page. - let pr = Rect::from_center_size(pos2(x + 14.0, r.center().y + 2.0), vec2(22.0, 22.0)); + let pr = Rect::from_center_size(pos2(x + 14.0, r.center().y), vec2(22.0, 22.0)); let presp = ui.interact(pr, ui.id().with("doc_new"), Sense::click()); if presp.hovered() { - ui.painter().rect_filled(pr, 4.0, Color32::from_white_alpha(30)); + ui.painter().rect_filled(pr, 4.0, t.app_bar_hover_button); } - let c = pr.center(); - let s = Stroke::new(1.6, t.app_bar_text); - ui.painter().line_segment([c - vec2(6.0, 0.0), c + vec2(6.0, 0.0)], s); - ui.painter().line_segment([c - vec2(0.0, 6.0), c + vec2(0.0, 6.0)], s); + crate::icons::paint_app_bar( + ui.painter(), + Rect::from_center_size(pr.center(), vec2(16.0, 16.0)), + "plus", + if presp.hovered() { 1.0 } else { 0.55 }, + ); // A file loading into the window keeps the tabs as they are (dragging still moves it). let idle = !app.file_load.busy(); if presp.on_hover_text("New Design (Ctrl+N)").clicked() && idle { @@ -485,18 +494,16 @@ pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) { } } -/// One tab of the strip: the active tab takes the toolbar's colour and runs into it; the others -/// sit on the application bar, lighter while hovered. +/// Tabs are rounded chips on the bar; the active design has the stronger fill. fn tab_shape(painter: &egui::Painter, t: &Tokens, r: Rect, active: bool, hovered: bool) { - let corners = egui::CornerRadius { nw: 5, ne: 5, sw: 0, se: 0 }; let fill = if active { - t.toolbar + t.app_bar_tab_active } else if hovered { t.app_bar_hover } else { - t.app_bar + egui::Color32::TRANSPARENT }; - painter.rect_filled(r, corners, fill); + painter.rect_filled(r, t.radius_md, fill); } /// Which tabs the strip shows in `room` points: (first, how many, tab width). Tabs shrink to @@ -637,6 +644,7 @@ pub(crate) fn saved_for_close(app: &mut SolveApp) { mod tests { use super::*; use crate::Services; + use egui::Color32; fn app() -> SolveApp { SolveApp::new(Session::default(), Services::default()) @@ -654,8 +662,7 @@ mod tests { assert_eq!(layout(12, 0, 600.0).0, 0); } - /// The tabs sit on the dark application bar in both themes: a hovered tab (the Home tab - /// included) keeps the bar's light text readable, and no tab is outlined. + /// Active and hovered document tabs keep the bar's light text readable in both themes. #[test] fn title_bar_tabs_keep_their_text_readable_on_hover() { fn luminance(c: Color32) -> f32 { @@ -682,11 +689,9 @@ mod tests { }) .collect(); let fill = rects.iter().find(|(rect, _)| rect.fill.a() > 0).map(|(rect, _)| rect.fill).unwrap_or_default(); - if !active { - let bg = over(fill, t.app_bar); - let (hi, lo) = (luminance(t.app_bar_text).max(luminance(bg)), luminance(t.app_bar_text).min(luminance(bg))); - assert!((hi + 0.05) / (lo + 0.05) >= 4.5, "text on a tab (hovered: {hovered}) must stay readable: {bg:?} {t:?}"); - } + let bg = over(fill, t.app_bar); + let (hi, lo) = (luminance(t.app_bar_text).max(luminance(bg)), luminance(t.app_bar_text).min(luminance(bg))); + assert!((hi + 0.05) / (lo + 0.05) >= 4.5, "text on a tab (hovered: {hovered}) must stay readable: {bg:?} {t:?}"); assert!(rects.iter().all(|(rect, _)| rect.stroke.width == 0.0), "tabs have no outline (active: {active})"); } } diff --git a/crates/ui-egui/src/frame.rs b/crates/ui-egui/src/frame.rs index 87f4d8389..e9ee18701 100644 --- a/crates/ui-egui/src/frame.rs +++ b/crates/ui-egui/src/frame.rs @@ -53,8 +53,8 @@ impl Side { pub fn dock_frame(ctx: &egui::Context, side: Side) -> egui::Frame { let t = crate::theme::Tokens::get(); let (corner_radius, shadow_x) = match side { - Side::Right => (egui::CornerRadius { nw: 4, sw: 4, ne: 0, se: 0 }, -2), - Side::Left => (egui::CornerRadius { nw: 0, sw: 0, ne: 4, se: 4 }, 2), + Side::Right => (egui::CornerRadius { nw: t.radius_sm, sw: t.radius_sm, ne: 0, se: 0 }, -2), + Side::Left => (egui::CornerRadius { nw: 0, sw: 0, ne: t.radius_sm, se: t.radius_sm }, 2), }; egui::Frame::window(&ctx.global_style()) .fill(t.dialog_bg) @@ -245,7 +245,7 @@ mod tests { fn feature_forms_use_available_height_and_keep_actions_visible() { use crate::scenario::Harness; use serde_json::json; - for (width, height, scale) in [(1400.0, 900.0, 1.0), (1400.0, 900.0, 2.0)] { + for (width, height, scale) in [(1400.0, 900.0, 1.0), (1400.0, 950.0, 2.0)] { let mut h = Harness::new(); h.app.preferences.ui_scale = scale; h.call("ui.resize", json!({"width":width / scale,"height":height / scale})); @@ -302,8 +302,8 @@ mod tests { h.frames(6); let hovered = h.app.viewport.dialog_rect.unwrap(); assert!((hovered.size() - rest.size()).length() < 0.01, "hovering resized the dialog: {rest:?} -> {hovered:?}"); - // Dragged by its title text. - let title = h.widget("CREATE SKETCH").map(|[x, y]| egui::pos2(x as f32, y as f32)).unwrap(); + // Drag the published title band, independent of similarly labelled toolbar controls. + let title = crate::scenario::handle_at("dialog:title").unwrap(); h.call("ui.drag", json!({"x0": title.x, "y0": title.y, "x1": title.x - 300.0, "y1": title.y + 120.0, "steps": 8})); h.frames(4); let moved = h.app.viewport.dialog_rect.unwrap(); diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rs index f9738b972..5ca150a4d 100644 --- a/crates/ui-egui/src/home.rs +++ b/crates/ui-egui/src/home.rs @@ -455,15 +455,15 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { ui.horizontal(|ui| { ui.label(RichText::new("SolidCraft").size(26.0).strong().color(t.text)); - ui.add_space(12.0); + ui.add_space(t.space_12); ui.label(RichText::new(crate::i18n::tr_label("Start")).size(16.0).color(t.text_dim)); }); - ui.add_space(16.0); + ui.add_space(t.space_16); ui.horizontal(|ui| { let big = |ui: &mut egui::Ui, icon: &str, label: &str, primary: bool| -> bool { // The label sets the width: a translation longer than the English one widens // the button instead of running past its edge. - let ink_text = if primary { Color32::WHITE } else { t.text }; + let ink_text = if primary { t.on_accent } else { t.text }; let galley = ui.painter().layout_no_wrap(label.to_owned(), egui::FontId::proportional(15.0), ink_text); let width = (56.0 + galley.size().x + 20.0).max(170.0); let (r, resp) = ui.allocate_exact_size(vec2(width, 64.0), Sense::click()); @@ -474,8 +474,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } else { t.field }; - ui.painter().rect(r, 6.0, fill, Stroke::new(1.0, if primary { t.accent } else { t.border }), egui::StrokeKind::Inside); - let ink = if primary { Color32::WHITE } else { t.icon }; + ui.painter().rect(r, t.radius_md, fill, Stroke::new(1.0, if primary { t.accent } else { t.border }), egui::StrokeKind::Inside); + let ink = if primary { t.on_accent } else { t.icon }; crate::icons::paint( ui.painter(), egui::Rect::from_center_size(r.left_center() + vec2(30.0, 0.0), vec2(30.0, 30.0)), @@ -490,7 +490,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if big(ui, "new", app.tr("ui.new_design"), true) { action = Some(Box::new(|app: &mut SolveApp| crate::documents::new_design(app))); } - ui.add_space(10.0); + ui.add_space(t.space_10); if big(ui, "open", app.tr("home.open"), false) { action = Some(Box::new(|app: &mut SolveApp| { app.pick_open(|app, path| { @@ -502,7 +502,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { })); } }); - ui.add_space(24.0); + ui.add_space(t.space_24); ui.horizontal_wrapped(|ui| { ui.hyperlink_to(app.tr("home.documentation"), crate::help::DOCS_URL); ui.hyperlink_to(app.tr("home.report_issue"), "https://github.com/tangency-labs/solidcraft/issues/new"); @@ -515,7 +515,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { crate::prefs::open_at(app, 0); } }); - ui.add_space(16.0); + ui.add_space(t.space_16); section(ui, app.tr("home.recent")); if recent.is_empty() { ui.label(RichText::new(crate::i18n::tr_label("Designs you open or save appear here.")).color(t.text_dim)); @@ -570,7 +570,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } }); } - ui.add_space(24.0); + ui.add_space(t.space_24); section(ui, app.tr("home.samples")); grid(ui, samples.len(), |ui, i| { let Some(s) = samples.get(i) else { return }; @@ -597,21 +597,22 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { fn section(ui: &mut egui::Ui, title: &str) { let t = Tokens::get(); ui.label(RichText::new(title).size(15.0).strong().color(t.text)); - ui.add_space(8.0); + ui.add_space(t.space_8); } /// Cards in rows that fill the width. fn grid(ui: &mut egui::Ui, n: usize, mut each: impl FnMut(&mut egui::Ui, usize)) { + let t = Tokens::get(); let w = THUMB[0] as f32 + 16.0; - let per_row = ((ui.available_width() + 14.0) / (w + 14.0)).floor().max(1.0) as usize; + let per_row = ((ui.available_width() + t.space_14) / (w + t.space_14)).floor().max(1.0) as usize; for row in 0..n.div_ceil(per_row) { ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 14.0; + ui.spacing_mut().item_spacing.x = t.space_14; for i in row * per_row..((row + 1) * per_row).min(n) { each(ui, i); } }); - ui.add_space(14.0); + ui.add_space(t.space_14); } } @@ -629,7 +630,7 @@ fn card(ui: &mut egui::Ui, pic: Pic, name: &str, sub: &str, dim: bool) -> egui:: let hover = resp.hovered(); ui.painter().rect( r, - 6.0, + t.radius_md, if hover { t.hover } else { t.field }, Stroke::new(1.0, if hover { t.accent } else { t.border }), egui::StrokeKind::Inside, @@ -637,7 +638,7 @@ fn card(ui: &mut egui::Ui, pic: Pic, name: &str, sub: &str, dim: bool) -> egui:: let img = egui::Rect::from_min_size(r.min + vec2(8.0, 8.0), vec2(THUMB[0] as f32, THUMB[1] as f32)); match pic { Pic::Icon(icon) => { - ui.painter().rect_filled(img, CornerRadius::same(4), t.panel_header); + ui.painter().rect_filled(img, CornerRadius::same(t.radius_sm), t.panel_header); crate::icons::paint(ui.painter(), egui::Rect::from_center_size(img.center(), vec2(56.0, 56.0)), icon, t.icon, t.icon_fill, t.icon); } Pic::Ready(Some(tx)) => { @@ -645,7 +646,7 @@ fn card(ui: &mut egui::Ui, pic: Pic, name: &str, sub: &str, dim: bool) -> egui:: ui.painter().image(tx.id(), img, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), tint); } Pic::Ready(None) => { - ui.painter().rect_filled(img, CornerRadius::same(4), t.panel_header); + ui.painter().rect_filled(img, CornerRadius::same(t.radius_sm), t.panel_header); if !dim { egui::Spinner::new().size(18.0).paint_at(ui, egui::Rect::from_center_size(img.center(), vec2(18.0, 18.0))); } @@ -654,8 +655,14 @@ fn card(ui: &mut egui::Ui, pic: Pic, name: &str, sub: &str, dim: bool) -> egui:: let ty = img.bottom() + 8.0; let clip = egui::Rect::from_min_max(egui::pos2(r.left() + 8.0, ty), egui::pos2(r.right() - 8.0, r.bottom())); let p = ui.painter().with_clip_rect(clip); - p.text(egui::pos2(r.left() + 10.0, ty), egui::Align2::LEFT_TOP, name, egui::FontId::proportional(14.0), if dim { t.text_dim } else { t.text }); - p.text(egui::pos2(r.left() + 10.0, ty + 20.0), egui::Align2::LEFT_TOP, sub, egui::FontId::proportional(11.5), t.text_dim); + p.text( + egui::pos2(r.left() + 10.0, ty), + egui::Align2::LEFT_TOP, + name, + egui::FontId::proportional(t.font_heading), + if dim { t.text_dim } else { t.text }, + ); + p.text(egui::pos2(r.left() + 10.0, ty + 20.0), egui::Align2::LEFT_TOP, sub, egui::FontId::proportional(t.font_caption), t.text_dim); if hover { ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index f91d46675..90dabc876 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -301,6 +301,10 @@ mod tests { let texts = english_texts(); let mut wanted: Vec<&str> = crate::toolbar::TABS.to_vec(); wanted.push(crate::toolbar_custom::WORKSPACE); + for section in crate::workspace::SECTIONS { + wanted.push(section.tab); + wanted.push(section.panel); + } for spec in solidcraft_engine::command_specs() { wanted.push(spec.tab); wanted.push(spec.panel); diff --git a/crates/ui-egui/src/i18n_ui_tests.rs b/crates/ui-egui/src/i18n_ui_tests.rs index 8614a0a60..6b07df6ff 100644 --- a/crates/ui-egui/src/i18n_ui_tests.rs +++ b/crates/ui-egui/src/i18n_ui_tests.rs @@ -95,7 +95,8 @@ fn window_chrome_renders_in_the_active_language() { // The browser heading is on screen from the start; the selection filter lives in the // SELECT panel, which is not the one shown by default. assert!(h.widget(browser).is_some(), "{lang}: the browser heading must show {browser:?}"); - let select = scenario::handle_at("panel:SOLID:SELECT").expect("the SELECT panel is on the SOLID tab"); + h.step(&json!({"click":{"handle":"tab:VIEW"}})).unwrap(); + let select = scenario::handle_at("panel:VIEW:SELECT").expect("the selection filter is on VIEW"); h.step(&json!({"click": [select.x, select.y]})).unwrap(); h.frames(2); assert!(h.widget(filter).is_some(), "{lang}: the selection filter must show {filter:?}"); @@ -248,10 +249,10 @@ fn translated_dialog_buttons_do_not_wrap() { } #[test] -fn long_panel_label_wraps_centred_and_its_button_is_centred() { +fn finish_exit_label_and_its_button_are_centred() { fn label_rows(shape: &egui::Shape) -> Option> { match shape { - egui::Shape::Text(text) if text.galley.job.text == "SKIZZE BEENDEN" => { + egui::Shape::Text(text) if text.galley.job.text == "Beenden" => { Some(text.galley.rows.iter().map(|row| row.rect().translate(text.pos.to_vec2())).collect()) } egui::Shape::Vec(shapes) => shapes.iter().find_map(label_rows), @@ -282,12 +283,11 @@ fn long_panel_label_wraps_centred_and_its_button_is_centred() { out.textures_delta.clear(); let mut out = h.ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| h.app.ui(ui)); let rows = out.shapes.iter().find_map(|shape| label_rows(&shape.shape)).expect("the Finish Sketch panel label is drawn"); - assert_eq!(rows.len(), 2, "the label wider than its one-button panel wraps: {rows:?}"); - assert!(rows[0].width() != rows[1].width(), "the lines differ in width: {rows:?}"); - assert!((rows[0].center().x - rows[1].center().x).abs() < 1.0, "each line is centred: {rows:?}"); + assert_eq!(rows.len(), 1, "the translated Exit section label fits one row: {rows:?}"); + assert!((rows[0].center().x - label.x).abs() < 1.0, "the label is centred: {rows:?}"); let hover = crate::theme::Tokens::get().hover; let lr = out.shapes.iter().find_map(|shape| hover_rect(&shape.shape, hover, label)).expect("the hovered label is highlighted"); - assert!(rows.iter().all(|row| lr.contains_rect(*row)), "the highlight holds both lines: {lr:?} {rows:?}"); + assert!(rows.iter().all(|row| lr.contains_rect(*row)), "the highlight holds the label: {lr:?} {rows:?}"); out.textures_delta.clear(); } diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 089fa4da9..4822471b0 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -22,7 +22,7 @@ pub(crate) mod pointer; /// Textures already rasterised: one per (master, look, pixel size). #[derive(Clone, Default)] -struct Cache(Arc>>); +struct Cache(Arc), TextureHandle>>>); /// Draw the icon `name` in `r`. The ink, fill and accent colours the callers pass are no longer /// used: the palette decides. Only the ink's opacity is kept, so a dimmed (disabled) button dims @@ -39,6 +39,20 @@ pub fn paint_icon(p: &Painter, r: Rect, name: &str, opacity: f32) { /// Draw the icon `name` for a surface that is always dark (the application bar), whatever the /// theme: `dark: Some(true)`. `None` follows the theme. pub fn paint_on(p: &Painter, r: Rect, name: &str, dark: Option, opacity: f32) { + paint_with_ink(p, r, name, dark, opacity, None); +} + +/// Monochrome flat controls on the application bar use its text token exactly. +pub(crate) fn paint_app_bar(p: &Painter, r: Rect, name: &str, opacity: f32) { + paint_with_ink(p, r, name, Some(true), opacity, Some(crate::theme::Tokens::get().app_bar_text)); +} + +/// Paint a single-colour icon in `ink`. +pub(crate) fn paint_ink(p: &Painter, r: Rect, name: &str, ink: Color32) { + paint_with_ink(p, r, name, Some(true), 1.0, Some(ink)); +} + +fn paint_with_ink(p: &Painter, r: Rect, name: &str, dark: Option, opacity: f32, ink: Option) { let ctx = p.ctx(); let ppp = ctx.pixels_per_point().max(0.5); let side = r.width().min(r.height()); @@ -47,11 +61,16 @@ pub fn paint_on(p: &Painter, r: Rect, name: &str, dark: Option, opacity: f let look = Look { dark: dark.unwrap_or_else(|| ctx.global_style().visuals.dark_mode), accent: resolved.accent, vision: crate::theme::vision() }; let cache = ctx.data_mut(|d| d.get_temp_mut_or_insert_with(egui::Id::new("sc_icon_cache"), Cache::default).clone()); let Ok(mut map) = cache.0.lock() else { return }; - let key = (resolved.master, look, px); + let key = (resolved.master, look, px, ink); if let std::collections::hash_map::Entry::Vacant(slot) = map.entry(key) { let Some(doc) = icon_svg::doc_for(resolved.master, px) else { return }; let Some(pm) = icon_svg::render(doc, look, px) else { return }; - let image = egui::ColorImage::from_rgba_premultiplied([px as usize, px as usize], pm.data()); + let mut image = egui::ColorImage::from_rgba_premultiplied([px as usize, px as usize], pm.data()); + if let Some(ink) = ink { + for pixel in &mut image.pixels { + *pixel = ink.gamma_multiply(f32::from(pixel.a()) / 255.0); + } + } slot.insert(ctx.load_texture(format!("icon:{}:{px}", resolved.master), image, TextureOptions::LINEAR)); } let Some(tex) = map.get(&key) else { return }; @@ -67,6 +86,24 @@ mod tests { use super::*; use crate::theme::{self, ColorVision}; + #[test] + fn assistant_pixels_use_the_application_bar_text_token() { + let previous = theme::is_dark(); + for dark in [false, true] { + let ctx = egui::Context::default(); + theme::set_dark(dark); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + paint_app_bar(ui.painter(), Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(32.0, 32.0)), "assistant", 1.0); + }); + let ink = theme::Tokens::get().app_bar_text; + assert!(out.textures_delta.set.iter().any(|(_, deltas)| deltas.iter().any(|delta| match &delta.image { + egui::ImageData::Color(image) => image.pixels.contains(&ink), + }))); + out.textures_delta.clear(); + } + theme::set_dark(previous); + } + #[test] fn actual_uploaded_icon_pixels_follow_semantics_and_vision_cache_changes() { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 44adfee3d..4f6ea1107 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -228,8 +228,11 @@ pub use control::{ControlRequest, ControlResponse}; #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct UiState { - /// Toolbar tab: SOLID, SURFACE, MESH, SHEET METAL, PLASTIC, UTILITIES (SKETCH while sketching). + /// Ribbon tab; contextual SKETCH and SHEET METAL join the seven design tabs. pub tab: String, + /// Last contextual body/sketch, only used to select on entry. + #[serde(skip)] + pub ribbon_context: Option, pub show_browser: bool, pub show_timeline: bool, pub show_grid: bool, @@ -262,7 +265,8 @@ pub struct UiState { impl Default for UiState { fn default() -> Self { UiState { - tab: "SOLID".into(), + tab: "MODEL".into(), + ribbon_context: None, show_browser: true, show_timeline: true, show_grid: true, @@ -781,12 +785,10 @@ impl SolveApp { self.set_status(msg, true); } } - if self.session.active_sketch.is_some() && self.ui.tab != "SKETCH" { - self.ui.tab = "SKETCH".into(); - } else if self.session.active_sketch.is_none() && self.ui.tab == "SKETCH" { - self.ui.tab = "SOLID".into(); + if self.session.active_sketch.is_none() && self.ui.tab == "SKETCH" { self.tool = None; } + workspace::sync_context(self); } /// Start a command the way a toolbar click does: interactive tools and dialogs for commands @@ -806,6 +808,7 @@ impl SolveApp { self.set_status(format!("{label}: {why}"), true); return; } + workspace::select_command_tab(self, id); if id == "material.properties.validate" { self.material_card_review = Some(material_card_review::ReviewWindow::default()); self.home.open = false; @@ -1485,6 +1488,7 @@ impl SolveApp { } } toolbar::toolbar(self, ui); + theme::TabAccent::publish(self, ui.ctx()); let show_timeline = self.ui.show_timeline && !render_workspace::active(self); let left_timeline = show_timeline && self.preferences.timeline_left; if show_timeline && !left_timeline { diff --git a/crates/ui-egui/src/menu_tests.rs b/crates/ui-egui/src/menu_tests.rs index cfe1c4792..2d9c1442d 100644 --- a/crates/ui-egui/src/menu_tests.rs +++ b/crates/ui-egui/src/menu_tests.rs @@ -627,25 +627,25 @@ fn occurrence_moves_turn_about_their_origin_then_move() { fn toolbar_pins_removes_reorders_and_keeps_its_layout() { use crate::toolbar_custom as tc; let mut app = sample_app(); - app.ui.tab = "SOLID".into(); + app.ui.tab = "MODEL".into(); let ids = |app: &SolveApp, panel: &str| -> Vec<&'static str> { - let lists = tc::panel_lists("SOLID"); + let lists = tc::panel_lists("MODEL"); let (_, cmds, n) = lists.iter().find(|(p, ..)| *p == panel).unwrap(); - tc::buttons(app, "SOLID", panel, cmds, *n).iter().map(|c| c.id).collect() + tc::buttons(app, "MODEL", panel, cmds, *n).iter().map(|c| c.id).collect() }; let create = ids(&app, "CREATE"); // Pin a command that isn't a button yet: it lands at the end of its panel. let extra = - tc::panel_lists("SOLID").iter().find(|(p, ..)| *p == "CREATE").unwrap().1.iter().map(|c| c.id).find(|id| !create.contains(id)).unwrap(); + tc::panel_lists("MODEL").iter().find(|(p, ..)| *p == "CREATE").unwrap().1.iter().map(|c| c.id).find(|id| !create.contains(id)).unwrap(); act(&mut app, &Target::ToolbarCommand { id: extra.into() }, "Pin to Toolbar"); assert_eq!(ids(&app, "CREATE").last(), Some(&extra)); // Remove a default button. act(&mut app, &Target::ToolbarCommand { id: create[0].into() }, "Remove from Toolbar"); assert!(!ids(&app, "CREATE").contains(&create[0])); // Reorder: the pinned one before the second default; then into another panel. - tc::reorder(&mut app, "SOLID", extra, "CREATE", Some(create[1])); + tc::reorder(&mut app, "MODEL", extra, "CREATE", Some(create[1])); assert_eq!(ids(&app, "CREATE")[0], extra); - tc::reorder(&mut app, "SOLID", extra, "MODIFY", None); + tc::reorder(&mut app, "MODEL", extra, "MODIFY", None); assert!(!ids(&app, "CREATE").contains(&extra) && ids(&app, "MODIFY").last() == Some(&extra)); // Pin to Shortcuts goes to the S box's favourites. act(&mut app, &Target::ToolbarCommand { id: "solid.extrude".into() }, "Pin to Shortcuts"); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index d56bdf027..bf13c6140 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -374,7 +374,7 @@ pub struct Prefs { /// AI features (docs/agent-chat.md): the master switch. Off: no AI button, shortcut, menu /// entry or panel, and nothing is looked for or started. pub ai_features: bool, - /// The AI button at the toolbar row's right end (the shortcut and View menu entry stay). + /// The Assistant button in the application bar (the shortcut and View menu entry stay). pub ai_toolbar_button: bool, /// Agents the user added (the installed ones are found by themselves). API keys are never /// here: they live in the system keychain. diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index 06be133f0..eb5079253 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -38,6 +38,17 @@ impl Colors { let c = |c: egui::Color32| c.to_srgba_unmultiplied(); Colors { body: c(t.body), added: c(t.preview_add), new_body: c(t.preview_new), removed: c(t.preview_cut), edge: c(t.body_edge) } } + + fn for_tool(t: &Tokens, tab: &str, active: bool) -> Colors { + let mut colors = Self::from_tokens(t); + let accent = crate::theme::TabAccent::for_tab(t, tab); + if active && accent.color != t.accent { + colors.added = accent.color.to_srgba_unmultiplied(); + colors.new_body = t.body.lerp_to_gamma(accent.color, 0.45).to_srgba_unmultiplied(); + } + // Removed material retains its warning colour and opacity. + colors + } } pub struct SketchPreview { @@ -308,7 +319,7 @@ pub fn update(app: &mut SolveApp, ctx: &egui::Context) { return; } }; - let colors = Colors::from_tokens(&Tokens::get()); + let colors = Colors::for_tool(&Tokens::get(), &app.ui.tab, app.tool.is_some() || app.dialog.is_some()); let key = job_key(&cmds, app.session.revision, colors); let stream_key = stream_key(&cmds, app.session.revision, colors); let tool = as_new_body(&cmds).is_some(); @@ -812,6 +823,32 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn tool_preview_follows_tab_without_recolouring_removal_or_idle_previews() { + for dark in [false, true] { + for vision in crate::theme::ColorVision::ALL { + let t = Tokens::themed(dark, vision); + let base = Colors::from_tokens(&t); + for tab in ["MODEL", "SKETCH", "SURFACE", "ASSEMBLE", "INSERT", "INSPECT", "MANAGE", "VIEW", "SHEET METAL", "RENDER"] { + for active in [false, true] { + let colors = Colors::for_tool(&t, tab, active); + assert_eq!(colors.removed, base.removed); + assert_eq!(colors.body, base.body); + assert_eq!(colors.edge, base.edge); + if !active || crate::theme::TabAccent::for_tab(&t, tab).color == t.accent { + assert_eq!(colors.added, base.added); + assert_eq!(colors.new_body, base.new_body); + } else { + let accent = crate::theme::TabAccent::for_tab(&t, tab); + assert_eq!(colors.added, accent.color.to_srgba_unmultiplied()); + assert_ne!(colors.new_body, colors.added); + } + } + } + } + } + } + fn colors() -> Colors { Colors { body: [1, 1, 1, 255], added: [2, 2, 2, 255], new_body: [4, 4, 4, 255], removed: [3, 3, 3, 100], edge: [0, 0, 0, 255] } } diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index e59adfe6f..df32b0816 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -125,11 +125,12 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { } pub fn reset_document(app: &mut SolveApp) { + app.ui.ribbon_context = None; let host = app.render_workspace.host.clone(); let image_host = app.render_workspace.image_host.clone(); app.render_workspace = State { host, image_host, ..Default::default() }; if active(app) { - app.ui.tab = "SOLID".into(); + app.ui.tab = "MODEL".into(); } sync_backend(app); } @@ -161,7 +162,7 @@ pub fn enter(app: &mut SolveApp, render: bool) -> Result<(), String> { app.ui.up_axis = camera.up; app.ui.perspective = perspective; } - app.ui.tab = "SOLID".into(); + app.ui.tab = "MODEL".into(); } app.cancel_view_animation(); Ok(()) diff --git a/crates/ui-egui/src/shortcut_box.rs b/crates/ui-egui/src/shortcut_box.rs index a2b341bcd..dbb2ea4b6 100644 --- a/crates/ui-egui/src/shortcut_box.rs +++ b/crates/ui-egui/src/shortcut_box.rs @@ -112,13 +112,14 @@ pub fn search(app: &SolveApp, q: &str) -> Vec { let mut v: Vec<(u32, Row)> = command_specs() .into_iter() .filter_map(|c| { - let (label, tab, panel) = (crate::i18n::tr_label(c.label), crate::i18n::tr_label(c.tab), crate::i18n::tr_label(c.panel)); - let place = (!c.tab.is_empty()).then_some((tab, panel)); + let (home_tab, home_panel) = crate::workspace::destination(c).unwrap_or(("", "")); + let (label, tab, panel) = (crate::i18n::tr_label(c.label), crate::i18n::tr_label(home_tab), crate::i18n::tr_label(home_panel)); + let place = (!home_tab.is_empty()).then_some((tab, panel)); let s = score(&q, label) .max(score(&q, c.label)) .max(score(&q, c.id) * 9 / 10) - .max(score(&q, tab).max(score(&q, c.tab)) / 3) - .max(score(&q, panel).max(score(&q, c.panel)) / 3); + .max(score(&q, tab).max(score(&q, home_tab)) / 3) + .max(score(&q, panel).max(score(&q, home_panel)) / 3); let recent = app.sbox.recent.iter().position(|r| r == c.id).map_or(0, |i| 2000 - i as u32); // Commands that can run now come before those that can't. let usable = if c.info(&app.session).enabled { 150 } else { 0 }; @@ -200,14 +201,15 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let mut picked: Option<&'static str> = None; let mut pin: Option<&'static str> = None; let mut menu: Option<(Pos2, &'static str)> = None; - let h = 380.0; + let w = W.min((screen.width() - 8.0).max(32.0)); + let h = 380.0_f32.min((screen.height() - 8.0).max(120.0)); let pos = pos2( - at.x.clamp(screen.left() + 4.0, (screen.right() - W - 4.0).max(screen.left())), - at.y.clamp(screen.top() + 4.0, (screen.bottom() - h).max(screen.top())), + at.x.clamp(screen.left() + 4.0, (screen.right() - w - 4.0).max(screen.left() + 4.0)), + at.y.clamp(screen.top() + 4.0, (screen.bottom() - h).max(screen.top() + 4.0)), ); let resp = crate::frame::area(egui::Id::new("sc_sbox")).fixed_pos(pos).order(egui::Order::Foreground).show(ctx, |ui| { crate::context_menu::menu_frame(ui, |ui| { - ui.set_width(W - 10.0); + ui.set_width(w - 10.0); // Pinned commands: a mini toolbar. if !app.sbox.pinned.is_empty() { ui.horizontal_wrapped(|ui| { @@ -228,7 +230,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let te = ui.add( egui::TextEdit::singleline(&mut app.sbox.text) .hint_text(crate::i18n::tr_label("Search commands")) - .desired_width(W - 20.0) + .desired_width(w - 20.0) .id(egui::Id::new("sc_sbox_text")), ); if std::mem::take(&mut app.sbox.focus) { @@ -245,7 +247,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { ui.spacing_mut().item_spacing.y = 0.0; for (i, (id, label, icon, place)) in list.iter().enumerate().take(80) { let enabled = solidcraft_engine::find_command(id).is_some_and(|c| c.info(&app.session).enabled); - let (r, resp) = ui.allocate_exact_size(vec2(W - 20.0, 26.0), Sense::click()); + let (r, resp) = ui.allocate_exact_size(vec2(w - 20.0, 26.0), Sense::click()); let lit = i == app.sbox.index || resp.hovered(); if lit { ui.painter().rect_filled(r, 4.0, t.hover); @@ -296,6 +298,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { }); }); }); + crate::scenario::publish_rect("ribbon:search_popup", resp.response.rect); if let Some(id) = pin { app.sbox.toggle_pin(id); } @@ -366,7 +369,7 @@ mod tests { let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); assert_eq!(search(&app, "extr").first().map(|x| x.0), Some("solid.extrude")); assert_eq!(search(&app, "solid.fil").first().map(|x| x.0), Some("solid.fillet")); - assert!(search(&app, "constraints").iter().any(|x| x.0 == "sketch.constraint.parallel"), "by panel"); + assert!(search(&app, "constrain").iter().any(|x| x.0 == "sketch.constraint.parallel"), "by panel"); app.sbox.used("solid.shell"); app.sbox.used("solid.revolve"); let all = search(&app, ""); @@ -393,6 +396,19 @@ mod tests { assert_eq!((row.1, row.3), (name, place), "{query:?}"); } assert_eq!(search(&app, name).first().map(|r| r.0), Some("sketch.rectangle.center"), "the exact name comes first"); + // Search shows and matches the redesigned destination, including translated panels. + for (id, tab, panel) in + [("solid.extrude", "MODEL", "CREATE"), ("inspect.draft", "INSPECT", "CHECK"), ("sketch.constraint.parallel", "SKETCH", "CONSTRAIN")] + { + let c = solidcraft_engine::find_command(id).unwrap(); + let label = ja.label(c.label); + let place = Some((ja.label(tab), ja.label(panel))); + for query in [label, c.label, id, ja.label(tab), tab, ja.label(panel), panel] { + let rows = search(&app, query); + let row = rows.iter().find(|r| r.0 == id).unwrap_or_else(|| panic!("{query:?} doesn't find {id}")); + assert_eq!((row.1, row.3), (label, place), "{query:?}: {id}"); + } + } // English is unchanged. drop(_ja); let row = search(&app, "center rect").into_iter().find(|r| r.0 == "sketch.rectangle.center").unwrap(); diff --git a/crates/ui-egui/src/sketch_dims.rs b/crates/ui-egui/src/sketch_dims.rs index 5e8addb11..c81b638f0 100644 --- a/crates/ui-egui/src/sketch_dims.rs +++ b/crates/ui-egui/src/sketch_dims.rs @@ -436,6 +436,7 @@ fn boxes(app: &SolveApp, ui: &mut egui::Ui, proj: &Proj, t: &mut Tool) -> Option ..Default::default() })) .on_hover_text(b.label); + crate::theme::TabAccent::number_focus(ui, &r); // A completion gets first use of forward Tab. Shift+Tab always moves back; // the box reached by egui's generic traversal must not complete its text. let changed = (source.is_none() || (source == Some(i) && tab != Some(true))) && crate::params_dialog::complete(ui, &r, &mut b.value); diff --git a/crates/ui-egui/src/sketch_modify_ui_tests.rs b/crates/ui-egui/src/sketch_modify_ui_tests.rs index 6686d596f..e1bec723c 100644 --- a/crates/ui-egui/src/sketch_modify_ui_tests.rs +++ b/crates/ui-egui/src/sketch_modify_ui_tests.rs @@ -583,7 +583,7 @@ fn sketch_pattern_tools_are_promoted_together_and_open_from_the_toolbar() { let panels = crate::toolbar_custom::panel_lists("SKETCH"); let (_, cmds, promoted) = panels.iter().find(|(panel, ..)| *panel == "PATTERN").unwrap(); let ids: Vec<_> = cmds.iter().take(*promoted).map(|c| c.id).collect(); - assert_eq!(ids, ["sketch.mirror", "sketch.pattern.rectangular", "sketch.pattern.circular"]); + assert_eq!(ids, ["sketch.mirror", "sketch.pattern.circular", "sketch.pattern.rectangular"]); for id in ids { h.settle(); h.step(&json!({"click":{"handle":format!("toolbar:{id}")}})).unwrap(); diff --git a/crates/ui-egui/src/sketch_palette.rs b/crates/ui-egui/src/sketch_palette.rs index 26924ad7d..276fccf7e 100644 --- a/crates/ui-egui/src/sketch_palette.rs +++ b/crates/ui-egui/src/sketch_palette.rs @@ -574,7 +574,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { ui.add_space((line - gap).max(0.0)); // A row as tall as the button, so the gap below it is just the line. ui.allocate_ui_with_layout(vec2(ui.available_width(), 0.0), egui::Layout::right_to_left(egui::Align::Min), |ui| { - let button = ui.add(egui::Button::new(RichText::new(app.tr("ui.finish_sketch")).color(Color32::WHITE)).fill(t.accent)); + let button = ui.add(egui::Button::new(RichText::new(app.tr("ui.finish_sketch")).color(t.on_accent)).fill(t.accent)); crate::scenario::publish_rect("sketch_palette:finish", button.rect); crate::scenario::publish_handle("sketch_palette:finish", button.rect.center()); if button.clicked() { diff --git a/crates/ui-egui/src/sketch_text.rs b/crates/ui-egui/src/sketch_text.rs index 69b352b41..57ed9b6da 100644 --- a/crates/ui-egui/src/sketch_text.rs +++ b/crates/ui-egui/src/sketch_text.rs @@ -513,7 +513,7 @@ fn path_row(ui: &mut egui::Ui, k: &mut Tx, inputs: &mut [SelInput], active: &mut ui.horizontal(|ui| { let on = k.style.path.is_some(); let text = if on { - egui::RichText::new(crate::i18n::format("dialog.selected_count", &[("count", "1")])).color(egui::Color32::WHITE) + egui::RichText::new(crate::i18n::format("dialog.selected_count", &[("count", "1")])).color(t.on_accent) } else { egui::RichText::new(crate::i18n::tr("dialog.select")).color(t.text) }; diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index 8ae0f8674..896561d6c 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -160,40 +160,6 @@ pub fn trim_drag_end(app: &mut SolveApp) -> bool { true } -/// Commands registered on one panel that another panel also lists: the analyses (sketch -/// INSPECT) on SOLID INSPECT, and Interference (SOLID INSPECT) on sketch INSPECT. -const ALSO_IN: &[(&str, &str, &str)] = &[ - ("SOLID", "INSPECT", "inspect.zebra"), - ("SOLID", "INSPECT", "inspect.draft"), - ("SOLID", "INSPECT", "inspect.curvature_map"), - ("SOLID", "INSPECT", "inspect.environment_map"), - ("SOLID", "INSPECT", "inspect.accessibility"), - ("SOLID", "INSPECT", "inspect.minimum_radius"), - ("SOLID", "INSPECT", "inspect.isocurve"), - ("SOLID", "INSPECT", "inspect.curvature_comb"), - ("SOLID", "INSPECT", "inspect.center_of_mass"), - ("SKETCH", "INSPECT", "inspect.interference"), -]; - -/// A panel's commands plus the ones it shares with another panel (see [`ALSO_IN`]). -pub fn also_in<'a>( - tab: &str, - panel: &str, - mut cmds: Vec<&'a solidcraft_engine::CommandSpec>, - specs: &[&'a solidcraft_engine::CommandSpec], -) -> Vec<&'a solidcraft_engine::CommandSpec> { - for (t, p, id) in ALSO_IN { - if *t == tab - && *p == panel - && !cmds.iter().any(|c| c.id == *id) - && let Some(c) = specs.iter().find(|c| c.id == *id) - { - cmds.push(c); - } - } - cmds -} - /// Run an analysis and keep its result as a marker. fn analysis(app: &mut SolveApp, cmd: &str, p: Value) { let Ok(v) = app.run(cmd, p) else { return }; diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 6ec46cf89..853e9227c 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -40,6 +40,52 @@ pub fn set_custom(custom: Option) -> bool { CUSTOM.with(|c| c.replace(custom) != custom) } +/// A tab's selection colours. This is deliberately separate from the global widget style: +/// application chrome, checkboxes, status colours and dialog actions retain their own tokens. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct TabAccent { + pub color: Color32, + pub soft: Color32, +} + +impl TabAccent { + pub fn for_tab(t: &Tokens, tab: &str) -> Self { + let color = match tab { + "SKETCH" => t.sketch_accent, + "SURFACE" => t.surface_accent, + "MESH" => t.mesh_accent, + "FORM" => t.form_accent, + _ => t.accent, + }; + // Preserve the existing Solid selection exactly. Other tabs blend against the same + // panel surface in either theme rather than introducing independent palette entries. + let soft = if color == t.accent { t.accent_soft } else { t.panel.lerp_to_gamma(color, 0.18) }; + Self { color, soft } + } + + pub fn current(ctx: &egui::Context) -> Self { + ctx.data(|d| d.get_temp::(egui::Id::new("sc_tab_accent"))).unwrap_or_else(|| Self::for_tab(&Tokens::get(), "MODEL")) + } + + pub fn publish(app: &crate::SolveApp, ctx: &egui::Context) { + let accent = Self::for_tab(&Tokens::get(), &app.ui.tab); + ctx.data_mut(|d| { + d.insert_temp(egui::Id::new("sc_tab_accent"), accent); + d.insert_temp(egui::Id::new("sc_tool_accent"), app.tool.is_some() || app.dialog.is_some()); + }); + } + + /// Paint only the focused numeric editor, without changing sibling buttons or checkboxes. + pub fn number_focus(ui: &egui::Ui, response: &egui::Response) { + let active = ui.ctx().data(|d| d.get_temp::(egui::Id::new("sc_tool_accent"))).unwrap_or(false); + let accent = Self::current(ui.ctx()); + let t = Tokens::get(); + if active && response.has_focus() && accent.color != t.accent { + ui.painter().rect_stroke(response.rect, t.radius_sm, Stroke::new(1.0, accent.color), egui::StrokeKind::Inside); + } + } +} + /// Is the dark theme on? pub fn is_dark() -> bool { DARK.get() @@ -170,7 +216,33 @@ pub struct IconColors { #[derive(Clone, Copy, Debug, PartialEq)] pub struct Tokens { + // Shared dimensions in logical pixels; identical in both themes. + pub space_2: f32, + pub space_3: f32, + pub space_4: f32, + pub space_6: f32, + pub space_8: f32, + pub space_10: f32, + pub space_12: f32, + pub space_14: f32, + pub space_16: f32, + pub space_24: f32, + pub radius_sm: u8, + pub radius_md: u8, + pub radius_lg: u8, + pub radius_xl: u8, + pub font_badge: f32, + pub font_micro: f32, + pub font_panel: f32, + pub font_small: f32, + pub font_caption: f32, + pub font_body: f32, + pub font_label: f32, + pub font_button: f32, + pub font_heading: f32, pub app_bar: Color32, + /// Dividers between the application bar groups. + pub app_bar_separator: Color32, pub toolbar: Color32, pub panel: Color32, pub panel_header: Color32, @@ -180,6 +252,15 @@ pub struct Tokens { pub accent: Color32, pub accent_soft: Color32, pub sketch_accent: Color32, + pub surface_accent: Color32, + pub mesh_accent: Color32, + pub form_accent: Color32, + pub render_accent: Color32, + /// Ink on accent-filled buttons and selection chips. + pub on_accent: Color32, + /// Agent status on the dark application bar, in either theme. + pub agent_ok: Color32, + pub agent_busy: Color32, pub error: Color32, pub warning: Color32, pub icon: Color32, @@ -279,6 +360,11 @@ pub struct Tokens { pub app_bar_text: Color32, /// A hovered tab on the application bar (keeps `app_bar_text` readable). pub app_bar_hover: Color32, + pub app_bar_hover_subtle: Color32, + pub app_bar_hover_button: Color32, + pub app_bar_hover_strong: Color32, + /// The active document tab: a solid surface lifted from the bar. + pub app_bar_tab_active: Color32, /// Timeline items: normal and failed. pub timeline_item: Color32, pub timeline_item_error: Color32, @@ -386,7 +472,7 @@ fn visuals(dark: bool) -> egui::Visuals { v.widgets.hovered.bg_fill = t.hover; // egui uses the open-state fill for a movable window's active title bar. v.widgets.open.weak_bg_fill = t.panel_header; - v.window_corner_radius = egui::CornerRadius::same(6); + v.window_corner_radius = egui::CornerRadius::same(t.radius_md); v } @@ -394,14 +480,51 @@ pub fn apply(ctx: &egui::Context) { let dark = is_dark(); ctx.set_theme(if dark { egui::Theme::Dark } else { egui::Theme::Light }); ctx.set_visuals(visuals(dark)); + let t = Tokens::get(); ctx.global_style_mut(|s| { - s.spacing.item_spacing = egui::vec2(6.0, 4.0); - s.spacing.button_padding = egui::vec2(6.0, 3.0); + s.spacing.item_spacing = egui::vec2(t.space_6, t.space_4); + s.spacing.button_padding = egui::vec2(t.space_6, t.space_3); }); } #[cfg(test)] mod tests { + #[test] + fn tab_accents_map_tokens_and_derive_selection_without_changing_solid() { + for dark in [false, true] { + for vision in super::ColorVision::ALL { + let t = super::Tokens::themed(dark, vision); + for (tab, color) in [("SKETCH", t.sketch_accent), ("SURFACE", t.surface_accent), ("MESH", t.mesh_accent), ("FORM", t.form_accent)] { + let accent = super::TabAccent::for_tab(&t, tab); + assert_eq!(accent.color, color); + assert_eq!(accent.soft, t.panel.lerp_to_gamma(color, 0.18)); + assert_ne!(accent.soft, color); + assert_ne!(accent.soft, t.panel); + } + for tab in ["MODEL", "ASSEMBLE", "INSERT", "INSPECT", "MANAGE", "VIEW", "SHEET METAL", "RENDER", "unknown"] { + assert_eq!(super::TabAccent::for_tab(&t, tab), super::TabAccent { color: t.accent, soft: t.accent_soft }); + } + } + } + } + + #[test] + fn tab_accent_context_is_per_app_and_does_not_change_widget_visuals() { + let mut harness = crate::scenario::Harness::new(); + let app = &mut harness.app; + let first = egui::Context::default(); + let second = egui::Context::default(); + let before = first.style_of(egui::Theme::Dark).visuals.clone(); + app.ui.tab = "SURFACE".into(); + super::TabAccent::publish(app, &first); + assert_eq!(super::TabAccent::current(&first).color, super::Tokens::get().surface_accent); + assert_eq!(super::TabAccent::current(&second).color, super::Tokens::get().accent); + assert_eq!(first.style_of(egui::Theme::Dark).visuals, before, "dialog OK, checkboxes and status styles must not inherit the tab"); + app.ui.tab = "MODEL".into(); + super::TabAccent::publish(app, &first); + assert_eq!(super::TabAccent::current(&first).soft, super::Tokens::get().accent_soft); + } + #[test] fn concurrent_ui_renderers_keep_their_own_theme_and_vision() { let barrier = std::sync::Barrier::new(2); diff --git a/crates/ui-egui/src/theme_files.rs b/crates/ui-egui/src/theme_files.rs index d3faad948..c5566856d 100644 --- a/crates/ui-egui/src/theme_files.rs +++ b/crates/ui-egui/src/theme_files.rs @@ -78,7 +78,14 @@ macro_rules! theme_keys { #[allow(dead_code)] fn every_colour_has_a_key(t: &Tokens) { // Not colours: the hover lift is a grey step, the analysis colours belong to shaders. - let Tokens { $($one: _,)* $($many: _,)* hover_face_lift: _, analysis: _, icons: _ } = t; + let Tokens { + $($one: _,)* $($many: _,)* + hover_face_lift: _, analysis: _, icons: _, + space_2: _, space_3: _, space_4: _, space_6: _, space_8: _, space_10: _, space_12: _, space_14: _, space_16: _, space_24: _, + radius_sm: _, radius_md: _, radius_lg: _, radius_xl: _, + font_badge: _, font_micro: _, font_panel: _, font_small: _, font_caption: _, font_body: _, font_label: _, font_button: _, + font_heading: _, + } = t; let IconColors { $($ione: _,)* $($imany: _,)* } = &t.icons; } }; @@ -96,6 +103,8 @@ theme_keys! { profile_fill, glyph_bg, glyph_edge, glyph_text, overlay, rubber_band, app_bar_text, app_bar_hover, timeline_item, timeline_item_error, timeline_marker, field, box_window, box_crossing, sketch_projected, sketch_lost, sketch_construction, sketch_centerline, bend_up, bend_down, interference, + app_bar_separator, surface_accent, mesh_accent, form_accent, render_accent, on_accent, agent_ok, agent_busy, app_bar_hover_subtle, + app_bar_hover_button, app_bar_hover_strong, app_bar_tab_active, ], many: [triad, gizmo, continuity, app_bar_icon, logo], icons_one: [ diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index de7539525..c9fe7edde 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -250,6 +250,7 @@ fn toggle_feature(app: &mut SolveApp, id: u64) { pub fn timeline(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); + let accent = crate::theme::TabAccent::for_tab(&t, &app.ui.tab); egui::Panel::bottom("sc_timeline").exact_size(40.0).frame(egui::Frame::NONE.fill(t.timeline)).show(ui, |ui| { let r = ui.max_rect(); let p = ui.painter().clone(); @@ -336,7 +337,7 @@ pub fn timeline(app: &mut SolveApp, ui: &mut egui::Ui) { let bg = if err.is_some() { t.timeline_item_error } else if sel { - t.accent_soft + accent.soft } else if resp.hovered() || from_view == Some(*id) { t.hover } else { @@ -345,7 +346,7 @@ pub fn timeline(app: &mut SolveApp, ui: &mut egui::Ui) { let edge = if err.is_some() { t.error } else if from_view == Some(*id) { - t.accent + accent.color } else { t.border }; @@ -459,7 +460,13 @@ pub fn timeline(app: &mut SolveApp, ui: &mut egui::Ui) { if resp.drag_started() { drag = Some(Drag::Marker); } - let col = if resp.hovered() || drag == Some(Drag::Marker) { t.accent } else { t.timeline_marker }; + let col = if resp.hovered() || drag == Some(Drag::Marker) { + accent.color + } else if accent.color == t.accent { + t.timeline_marker + } else { + accent.color + }; p.rect_filled(mr, 1.0, col); resp.on_hover_text("History marker: drag to roll the model back; new features go here"); } @@ -472,7 +479,7 @@ pub fn timeline(app: &mut SolveApp, ui: &mut egui::Ui) { 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) { t.accent } else { t.sketch_accent }), + Stroke::new(2.0, if matches!(dg, Drag::Marker) { accent.color } else { t.sketch_accent }), ); } let released = ui.input(|i| i.pointer.any_released()); diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs index f7db54a45..dfd22df38 100644 --- a/crates/ui-egui/src/timeline_left.rs +++ b/crates/ui-egui/src/timeline_left.rs @@ -195,7 +195,7 @@ fn vertical_marker(app: &mut SolveApp, ui: &mut egui::Ui, drag: &mut Option CLOSE_HOVER.gamma_multiply(0.8), - (_, true) if close => CLOSE_HOVER, - (true, _) => Color32::from_white_alpha(18), - (_, true) => Color32::from_white_alpha(30), + (true, _) => t.app_bar_hover_subtle, + (_, true) => t.app_bar_hover_button, + _ if resp.has_focus() => t.app_bar_hover_button, _ => Color32::TRANSPARENT, }; ui.painter().rect_filled(r, 0.0, fill); - let ink = if close && resp.hovered() { Color32::WHITE } else { t.app_bar_text }; + let ink = t.app_bar_text; paint_glyph(ui, c, max, r.center(), Stroke::new(1.0, ink)); let tip = match c { Caption::Minimize => "Minimize", @@ -288,6 +284,53 @@ mod tests { v } + #[test] + fn every_bar_control_uses_translucent_hover_chrome() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + let mut w = Win::new(1600.0); + w.app.home.open = false; + w.frame(vec![]); + w.frame(vec![]); + let t = Tokens::get(); + let mut controls: Vec = [ + "titlebar:home", + "appbar:file", + "titlebar:save", + "appbar:undo", + "appbar:redo", + "tab:design:0", + "tab:close:0", + "titlebar:assistant", + "titlebar:preferences", + "appbar:help", + "titlebar:report", + ] + .into_iter() + .map(|name| crate::scenario::rect_of(name).unwrap_or_else(|| panic!("{name}"))) + .collect(); + controls.extend(CAPTIONS.map(|c| w.caption(c))); + for rect in controls { + w.frame(vec![Event::PointerMoved(rect.center())]); + let out = w.frame(vec![]); + let fills: Vec<_> = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Rect(shape) if shape.rect == rect || shape.rect == rect.shrink(3.0) => Some(shape.fill), + _ => None, + }) + .collect(); + assert!( + fills.iter().any(|fill| [t.app_bar_hover, t.app_bar_hover_button, t.app_bar_hover_strong, t.app_bar_tab_active].contains(fill)), + "dark={dark}: {rect:?} has no application bar hover fill: {fills:?}" + ); + } + } + crate::theme::set_dark(previous); + } + #[test] fn caption_buttons_sit_in_the_corner_and_nothing_runs_under_them() { for width in [960.0, 1600.0] { diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index be868569c..d0665c7fe 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -1,6 +1,5 @@ //! Application bar, the workspace toolbar (tabs and panels) and keyboard shortcuts. -use crate::icons::glyphs::caret; use crate::icons::glyphs::pin_icon; use egui::{Align2, Color32, FontId, Rect, Sense, Stroke, pos2, vec2}; use serde_json::json; @@ -8,7 +7,7 @@ use serde_json::json; use crate::theme::Tokens; use crate::{SolveApp, icons}; -pub const TABS: &[&str] = &["SOLID", "SURFACE", "MESH", "SHEET METAL", "PLASTIC", "UTILITIES"]; +pub use crate::workspace::TABS; /// Legacy paint arguments and non-SVG affordances follow the same semantic palette as the icon. /// The requested icon id determines its meaning on ribbons, menus and drag previews alike. @@ -16,34 +15,17 @@ fn command_accent(icon: &str) -> Color32 { crate::icon_svg::primary(icon, crate::theme::is_dark(), crate::theme::vision()) } -/// Panels shown on each tab (in order). Commands come from the registry by (tab, panel). -pub fn panels(tab: &str) -> &'static [&'static str] { - if let Some(p) = crate::workspace::panels(tab) { - return p; - } - match tab { - "SOLID" => &["CREATE", "MODIFY", "ASSEMBLE", "CONSTRUCT", "INSPECT", "INSERT", "SELECT"], - "SKETCH" => &["CREATE", "MODIFY", "PATTERN", "CONSTRAINTS", "INSPECT", "INSERT", "SELECT", "FINISH SKETCH"], - "SURFACE" => &["CREATE", "MODIFY", "ASSEMBLE", "CONSTRUCT", "INSPECT", "INSERT", "SELECT"], - "MESH" => &["CREATE", "PREPARE", "MODIFY", "ASSEMBLE", "CONSTRUCT", "INSPECT", "INSERT", "SELECT"], - "SHEET METAL" => &["CREATE", "MODIFY", "ASSEMBLE", "CONSTRUCT", "INSPECT", "INSERT", "SELECT"], - "PLASTIC" => &["CREATE", "MODIFY", "ASSEMBLE", "CONSTRUCT", "INSPECT", "INSERT", "SELECT"], - "RENDER" => &["SCENE"], - _ => &["MAKE", "ADD-INS", "UTILITY", "INSPECT", "SELECT"], +/// Accent for a tab or a panel with a more specific semantic role. +fn panel_accent(t: &Tokens, tab: &str, panel: &str) -> Color32 { + if panel == "CONSTRAIN" { + return t.glyph_text; } + crate::theme::TabAccent::for_tab(t, tab).color } -/// How many commands of a panel get a button on a fresh (or reset) toolbar. The user's own -/// layout (`toolbar_custom`) has no cap: every pinned command gets a button. -pub fn promoted(tab: &str, panel: &str) -> usize { - match (tab, panel) { - ("SOLID", "CREATE") => 4, - ("SOLID", "MODIFY") => 4, - ("SKETCH", "CONSTRAINTS") => 6, - ("SKETCH", "PATTERN") => 3, - (_, "FINISH SKETCH") => 1, - _ => 2, - } +/// Panels shown on each tab (in order). Commands come from the registry by (tab, panel). +pub fn panels(tab: &str) -> Vec<&'static str> { + crate::workspace::panels(tab) } /// How a panel is drawn on a toolbar that may be too narrow for every button. @@ -58,73 +40,80 @@ pub enum Fit { More, } -/// One panel as [`fit`] sees it: how many buttons it has and whether they carry a label under the -/// icon (Sketch > Create). +/// A ribbon button's preferred and minimum widths. The constraint gallery is a fixed-width +/// block; ordinary buttons narrow as their labels wrap and truncate. #[derive(Clone, Copy, Debug, PartialEq)] -pub struct PanelSize { - pub buttons: usize, - pub labelled: bool, +pub struct ButtonSize { + pub width: f32, + pub min_width: f32, } -/// Where [`fit`] put a panel: how many of its buttons it draws, at which stride, and whether -/// their labels show. -#[derive(Clone, Copy, Debug, PartialEq)] +/// One panel as [`fit`] sees it, in button order (the gallery, if present, is last). +#[derive(Clone, Debug, PartialEq)] +pub struct PanelSize { + pub buttons: Vec, +} + +/// Where [`fit`] put a panel: its first buttons and their individual fitted widths. +#[derive(Clone, Debug, PartialEq)] pub struct Plan { pub fit: Fit, - /// Buttons drawn (the first ones of the panel). pub shown: usize, - /// Distance from one button to the next. - pub stride: f32, + pub widths: Vec, } impl Plan { + fn full(panel: &PanelSize) -> Self { + Self { fit: Fit::Buttons, shown: panel.buttons.len(), widths: panel.buttons.iter().map(|b| b.width).collect() } + } + + fn more() -> Self { + Self { fit: Fit::More, shown: 0, widths: Vec::new() } + } + /// The panel's width on the toolbar (0 in the » menu). pub fn width(&self) -> f32 { match self.fit { Fit::More => 0.0, Fit::Collapsed => COLLAPSED_WIDTH, - Fit::Buttons => (self.shown.max(1) as f32 * self.stride).max(PANEL_MIN) + 8.0, + Fit::Buttons => panel_width(self.widths.get(..self.shown).unwrap_or_default()), } } - - /// Whether labelled buttons show their label (shortened below [`LABELLED_STRIDE`]). - pub fn labels(&self) -> bool { - self.stride >= LABEL_MIN_STRIDE - } } -/// A panel's width with `buttons` buttons. -pub fn panel_width(buttons: usize) -> f32 { - (buttons.max(1) as f32 * STRIDE).max(PANEL_MIN) + 8.0 +/// A panel's width with these individual button widths. +pub fn panel_width(buttons: &[f32]) -> f32 { + (buttons.iter().sum::() + buttons.len().saturating_sub(1) as f32 * BUTTON_GAP + 8.0).max(COLLAPSED_WIDTH) } -/// An icon button's stride. -pub const STRIDE: f32 = 40.0; -/// A labelled button's stride with its whole label (Sketch > Create). -pub const LABELLED_STRIDE: f32 = 68.0; -/// Below this stride a labelled button drops its label and shows just the icon. -pub const LABEL_MIN_STRIDE: f32 = 50.0; -/// The narrowest a panel gets (beside its 8 px margins), so its label stays readable. -const PANEL_MIN: f32 = 64.0; - /// A collapsed panel's width: one button's panel. -pub const COLLAPSED_WIDTH: f32 = PANEL_MIN + 8.0; +pub const COLLAPSED_WIDTH: f32 = 72.0; /// The gap after each panel (its separator). -const PANEL_GAP: f32 = 2.0; +const PANEL_GAP: f32 = 1.0; +pub const TAB_ROW_HEIGHT: f32 = 30.0; +pub const GROUP_HEIGHT: f32 = 86.0; +pub const RIBBON_HEIGHT: f32 = TAB_ROW_HEIGHT + GROUP_HEIGHT + 1.0; +const WORKSPACE_WIDTH: f32 = 88.0; +const BUTTON_HEIGHT: f32 = 60.0; +const BUTTON_GAP: f32 = 3.0; +const BUTTON_MIN_WIDTH: f32 = 54.0; +const BUTTON_MAX_WIDTH: f32 = 76.0; +const BUTTON_LABEL_PADDING: f32 = 10.0; +const SECTION_HEIGHT: f32 = 20.0; /// The » button's room at the end of the panels, kept only while some panel is in it. pub const MORE_ROOM: f32 = 40.0; /// Fit panels into `room`, giving up as little as it takes, one small step at a time: -/// 1. labelled buttons narrow, their labels shortening and then going (icons only); +/// 1. buttons narrow from their measured label widths to their minimum, wrapping and truncating; /// 2. panels hand their last buttons to their drop-down one at a time, the panel showing the /// most buttons first (the rightmost of equals), down to one button (collapsed); /// 3. the last panels go into the » menu, and any room that frees goes back to buttons. /// -/// Every step frees at most one button's width, so the toolbar never leaves more than a button -/// of blank space while something is hidden. The result depends only on `room` (no state from -/// earlier frames), so it never flickers. Nothing is dropped. +/// Each removal frees at most one button (or the fixed-width constraint gallery), so the toolbar +/// never leaves a larger gap while something is hidden. The result depends only on `room` +/// (no state from earlier frames), so it never flickers. Nothing is dropped. pub fn fit(panels: &[PanelSize], room: f32) -> Vec { let room = if room.is_finite() { room } else { 0.0 }; if let Some(plans) = shrink(panels, room) { @@ -134,11 +123,11 @@ pub fn fit(panels: &[PanelSize], room: f32) -> Vec { // ones left keep as many buttons as fit. for kept in (0..panels.len()).rev() { if let Some(mut plans) = shrink(panels.get(..kept).unwrap_or_default(), room - MORE_ROOM) { - plans.extend(panels.iter().skip(kept).map(|_| Plan { fit: Fit::More, shown: 0, stride: STRIDE })); + plans.extend(panels.iter().skip(kept).map(|_| Plan::more())); return plans; } } - panels.iter().map(|_| Plan { fit: Fit::More, shown: 0, stride: STRIDE }).collect() + panels.iter().map(|_| Plan::more()).collect() } /// The room plans take on the toolbar (each panel and its separator). @@ -149,24 +138,18 @@ fn used(plans: &[Plan]) -> f32 { /// Steps 1 and 2 of [`fit`]: every panel on the toolbar, or None when even one button each /// doesn't fit. fn shrink(panels: &[PanelSize], room: f32) -> Option> { - let mut plans: Vec = - panels.iter().map(|p| Plan { fit: Fit::Buttons, shown: p.buttons, stride: if p.labelled { LABELLED_STRIDE } else { STRIDE } }).collect(); + let mut plans: Vec = panels.iter().map(Plan::full).collect(); if used(&plans) <= room { return Some(plans); } - // 1. Labelled buttons narrow together, to the widest whole-pixel stride that fits (icons - // only at worst). - let narrow = |plans: &mut [Plan], stride: f32| { - for (p, s) in plans.iter_mut().zip(panels) { - if s.labelled { - p.stride = stride; + // 1. Narrow together in one-pixel steps, keeping each button's measured width until it + // reaches its minimum. The gallery's minimum equals its full width. + for reduction in 1..=((BUTTON_MAX_WIDTH - BUTTON_MIN_WIDTH) as usize) { + for (plan, panel) in plans.iter_mut().zip(panels) { + for (width, button) in plan.widths.iter_mut().zip(&panel.buttons) { + *width = (button.width - reduction as f32).max(button.min_width); } } - }; - let mut stride = LABELLED_STRIDE; - while stride > STRIDE { - stride -= 1.0; - narrow(&mut plans, stride); if used(&plans) <= room { return Some(plans); } @@ -177,11 +160,11 @@ fn shrink(panels: &[PanelSize], room: f32) -> Option> { let pick = plans .iter() .enumerate() - .filter(|(_, p)| p.fit == Fit::Buttons && p.shown > 1) + .filter(|(_, p)| p.fit == Fit::Buttons && (p.shown > 1 || p.width() > COLLAPSED_WIDTH)) .max_by(|(i, a), (j, b)| a.shown.cmp(&b.shown).then(i.cmp(j))); let (i, _) = pick?; if let Some(p) = plans.get_mut(i) { - p.shown -= 1; + p.shown = p.shown.saturating_sub(1).max(1); if p.shown == 1 { p.fit = Fit::Collapsed; } @@ -205,24 +188,24 @@ fn menu_commands( out } -/// What the right-hand group keeps clear between Report a bug and the window's caption buttons: -/// Help, Preferences and the version. -const RIGHT_GROUP: f32 = 120.0; +/// Room for the version between Report a bug and the caption buttons. +const RIGHT_GROUP: f32 = 60.0; +const CLUSTER_BUTTONS: f32 = 108.0; -/// The centre of the Help (?) button: left of Preferences. -fn help_x(bar: Rect, captions: f32) -> f32 { - bar.right() - captions - 101.0 +/// The centre of Help, between Settings and Report a bug. +fn help_x(report: Rect) -> f32 { + report.left() - 18.0 } /// The Report a bug button: labelled when there is room for its text (`label_width`, measured in /// the current language), otherwise just the icon. fn report_rect(bar: Rect, captions: f32, tabs_start: f32, label_width: f32) -> (Rect, bool) { - let right = bar.right() - captions - RIGHT_GROUP; - // Icon, text and a margin; never narrower than the English button. - let full = (REPORT_TEXT_X + label_width + 10.0).max(124.0); - let labeled = right - tabs_start >= 216.0 + full; + let right = bar.right() - captions - if bar.width() < 640.0 { 8.0 } else { RIGHT_GROUP }; + // Icon, text and a margin that mirrors the icon side. + let full = REPORT_TEXT_X + label_width + 11.0; + let labeled = right - CLUSTER_BUTTONS - tabs_start >= 216.0 + full; let width = if labeled { full } else { 28.0 }; - (Rect::from_min_size(pos2(right - width, bar.top() + 4.0), vec2(width, 26.0)), labeled) + (Rect::from_min_size(pos2(right - width, bar.center().y - 13.0), vec2(width, 26.0)), labeled) } /// The height of an application-bar pill ([`offer_pill`]), a little under the bar's 26 px buttons. @@ -243,7 +226,7 @@ pub(crate) fn offer_pill( handle: &str, ) -> Option<(Rect, egui::Response)> { let t = Tokens::get(); - let font = FontId::proportional(12.5); + let font = FontId::proportional(t.font_label); let (icon_x, text_x, right_pad) = (16.0, 29.0, 11.0); let last = labels.len().saturating_sub(1); let label = labels.iter().enumerate().filter(|_| labeled).find_map(|(i, text)| { @@ -263,7 +246,7 @@ pub(crate) fn offer_pill( crate::scenario::publish_handle(handle, rect.center()); crate::scenario::publish_rect(handle, rect); let hot = response.hovered() || response.has_focus(); - let fill = if hot { t.accent.lerp_to_gamma(t.app_bar_text, 0.18) } else { t.accent }; + let fill = if hot { t.app_bar_hover_button } else { t.accent }; let radius = PILL_HEIGHT / 2.0; ui.painter().rect_filled(rect, radius, fill); if response.has_focus() { @@ -271,7 +254,7 @@ pub(crate) fn offer_pill( } let glyph_x = if label.is_some() { rect.left() + icon_x } else { rect.center().x }; let glyph = Rect::from_center_size(pos2(glyph_x, rect.center().y), vec2(16.0, 16.0)); - icons::paint(ui.painter(), glyph, icon, t.app_bar_text, fill, t.app_bar_text); + icons::paint_on(ui.painter(), glyph, icon, Some(true), 1.0); if let Some((text, _)) = label { ui.painter().text(pos2(rect.left() + text_x, rect.center().y), Align2::LEFT_CENTER, text, font, t.app_bar_text); } @@ -302,16 +285,42 @@ pub fn app_bar(app: &mut SolveApp, ui: &mut egui::Ui) { crate::icons::glyphs::brand_mark(ui.painter(), c); } if !compact_actions { - ui.painter().text(pos2(left + 36.0, r.center().y), Align2::LEFT_CENTER, "SolidCraft", FontId::proportional(14.0), t.app_bar_text); + ui.painter().text( + pos2(left + 36.0, r.center().y), + Align2::LEFT_CENTER, + "SolidCraft", + FontId::proportional(t.font_heading), + t.app_bar_text, + ); } - let mut x = left + if compact_actions { 60.0 } else { 128.0 }; - // While a file loads the design waits: no menus or commands from the bar. + let mut x = left + if compact_actions { 56.0 } else { 128.0 }; + let home = Rect::from_center_size(pos2(x - 4.0, r.center().y), vec2(32.0, 32.0)); let idle = !app.file_load.busy(); + let home_response = ui.interact(home, ui.id().with("appbar_home"), if idle { Sense::click() } else { Sense::hover() }); + let home_tip = app.tr("ui.start_page"); + home_response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, idle, home_tip)); + crate::scenario::publish_handle("appbar:home", home.center()); + crate::scenario::publish_handle("titlebar:home", home.center()); + // Compatibility for scenarios that used the former Home tab. + crate::scenario::publish_handle("tab:home", home.center()); + crate::scenario::publish_rect("titlebar:home", home); + crate::scenario::publish_rect("appbar:home", home); + if idle && (home_response.hovered() || home_response.has_focus()) { + ui.painter().rect_filled(home.shrink(3.0), t.radius_sm, t.app_bar_hover_button); + } + icons::paint_app_bar(ui.painter(), home.shrink(7.0), "home", if idle { 1.0 } else { 0.35 }); + if home_response.on_hover_text(home_tip).clicked() && idle { + app.home.show(app.session.revision); + } + x = home.right() + 8.0; + app_bar_separator(ui, r, x, "brand"); + x += 16.0; + // While a file loads the design waits: no menus or commands from the bar. // The File menu: a text button (New, Open, Save, Save As, Export…). Its handle keeps the // old `appbar:folder` name too, for scripts written against the folder button. let file = { let label = app.tr("ui.file").to_string(); - let galley = ui.painter().layout_no_wrap(label.clone(), FontId::proportional(13.0), t.app_bar_text); + let galley = ui.painter().layout_no_wrap(label.clone(), FontId::proportional(t.font_button), t.app_bar_text); let br = Rect::from_min_size(pos2(x - 13.0, r.center().y - 13.0), vec2(galley.size().x + 16.0, 26.0)); x = br.right() + 17.0; let resp = ui.interact(br, ui.id().with(("ab", "file")), if idle { Sense::click() } else { Sense::hover() }); @@ -320,8 +329,8 @@ pub fn app_bar(app: &mut SolveApp, ui: &mut egui::Ui) { crate::scenario::publish_handle("appbar:folder", br.center()); crate::scenario::publish_rect("appbar:file", br); let open = ui.ctx().data(|d| d.get_temp::(egui::Id::new("sc_file_menu")).unwrap_or(false)); - if idle && (resp.hovered() || open) { - ui.painter().rect_filled(br, 4.0, t.app_bar_hover); + if idle && (resp.hovered() || resp.has_focus() || open) { + ui.painter().rect_filled(br, t.radius_sm, t.app_bar_hover); } let ink = if idle { t.app_bar_text } else { t.app_bar_text.gamma_multiply(0.35) }; ui.painter().galley(pos2(br.left() + 8.0, br.center().y - galley.size().y / 2.0), galley, ink); @@ -330,28 +339,34 @@ pub fn app_bar(app: &mut SolveApp, ui: &mut egui::Ui) { }; // A disabled button is dimmed and ignores clicks (its tooltip still shows). let click = |ui: &mut egui::Ui, at: f32, icon: &str, tip: &str, enabled: bool| -> bool { - let width = if compact_actions { 22.0 } else { 26.0 }; - let br = Rect::from_center_size(pos2(at, r.center().y), vec2(width, 26.0)); + let width = if compact_actions && matches!(icon, "save" | "undo" | "redo") { 22.0 } else { 32.0 }; + let br = Rect::from_center_size(pos2(at, r.center().y), vec2(width, 32.0)); let resp = ui.interact(br, ui.id().with(("ab", icon)), if enabled { Sense::click() } else { Sense::hover() }); resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, enabled, tip)); crate::scenario::publish_handle(&format!("appbar:{icon}"), br.center()); crate::scenario::publish_rect(&format!("appbar:{icon}"), br); - if enabled && resp.hovered() { - ui.painter().rect_filled(br, 4.0, Color32::from_white_alpha(30)); + crate::scenario::publish_handle(&format!("titlebar:{icon}"), br.center()); + crate::scenario::publish_rect(&format!("titlebar:{icon}"), br); + if enabled && (resp.hovered() || resp.has_focus()) { + ui.painter().rect_filled(br.shrink(3.0), t.radius_sm, t.app_bar_hover_button); } - icons::paint_on(ui.painter(), br.shrink(5.0), icon, Some(true), if enabled { 1.0 } else { 0.35 }); + icons::paint_app_bar(ui.painter(), Rect::from_center_size(br.center(), vec2(18.0, 18.0)), icon, if enabled { 1.0 } else { 0.35 }); let clicked = resp.on_hover_text(tip).clicked(); enabled && clicked }; - let step = if compact_actions { 22.0 } else { 30.0 }; - // Undo and Redo act on the design, which Home hides. Save lives in the File menu (Ctrl+S). + let step = if compact_actions { 22.0 } else { 34.0 }; + // Save, Undo and Redo use the same actions as the File menu and shortcuts. let shown = design_shown(app) && idle; let tip = |id: &str, key: &str| { let label = app.tr(id); if shown { format!("{label} ({key})") } else { crate::i18n::format("ui.needs_design", &[("command", label)]) } }; - let (undo_tip, redo_tip) = (tip("ui.undo", "Ctrl+Z"), tip("ui.redo", "Ctrl+Y")); - // A very narrow window keeps its room for the tabs (Home first); Ctrl+Z and Ctrl+Y still undo and redo. + let (save_tip, undo_tip, redo_tip) = (tip("ui.save", "Ctrl+S"), tip("ui.undo", "Ctrl+Z"), tip("ui.redo", "Ctrl+Y")); + if click(ui, x, "save", &save_tip, shown) { + save(app); + } + x += step; + // Narrow windows retain Save; Undo and Redo remain available from their shortcuts and menus. if !compact_actions { if click(ui, x, "undo", &undo_tip, shown) { let _ = app.run("edit.undo", json!({})); @@ -374,27 +389,30 @@ pub fn app_bar(app: &mut SolveApp, ui: &mut egui::Ui) { d.insert_temp(egui::Id::new("sc_file_menu_opened"), pass); }); } - // Document tabs (Home first), on the left after File, Undo and Redo. + // Document tabs follow the file actions; the house opens the start page. let captions = if app.custom_titlebar { crate::titlebar::WIDTH } else { 0.0 }; - let tabs_start = x - step + 25.0; + let separator_x = x - step + if compact_actions { 19.0 } else { 24.0 }; + app_bar_separator(ui, r, separator_x, "documents"); + let tabs_start = separator_x + 10.0; let report_text = crate::i18n::tr("ui.report_a_bug"); - let report_font = FontId::proportional(13.0); + let report_font = FontId::proportional(t.font_button); let label_width = ui.painter().layout_no_wrap(report_text.to_string(), report_font.clone(), t.app_bar_text).size().x; let (report, report_label) = report_rect(r, captions, tabs_start, label_width); - // Help, on the right between Report a bug and Preferences. - if click(ui, help_x(r, captions), "help", app.tr("ui.help"), true) { + // Assistant, Settings, Help and Report a bug form the right-hand cluster. + if click(ui, help_x(report), "help", app.tr("ui.help"), true) { app.help.menu = !app.help.menu; - let at = help_x(r, captions); + let at = help_x(report); ui.ctx().data_mut(|d| { d.insert_temp(egui::Id::new("sc_help_opened"), true); d.insert_temp(egui::Id::new("sc_help_anchor"), at); }); } - // A newer release: its Update button, left of Report a bug (`update`), in the space up to - // the bar's own buttons on the left (File, Undo and Redo, which end before `x`). - let span = Rect::from_min_max(pos2(x, report.top()), pos2(report.left() - 6.0, report.bottom())); - let update = crate::update::button(app, ui, span, report_label); - let tabs_end = update.map_or(report.left(), |u| u.left()) - 8.0; + // A newer release: its Update button stays before the right cluster, in the space up to + // the bar's own file actions on the left. + let span = Rect::from_min_max(pos2(x, report.top()), pos2(report.left() - CLUSTER_BUTTONS - 2.0, report.bottom())); + let update_labeled = report_label; + let update = crate::update::button(app, ui, span, update_labeled); + let tabs_end = update.map_or(report.left() - CLUSTER_BUTTONS, |u| u.left()) - 8.0; // Narrow title bars can fit only part of the tab strip. Its hit regions must not // extend into the persistent report and window controls. let tabs_rect = Rect::from_min_max(pos2(tabs_start.min(tabs_end), r.top()), pos2(tabs_end, r.bottom())); @@ -405,23 +423,27 @@ pub fn app_bar(app: &mut SolveApp, ui: &mut egui::Ui) { response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), report_text)); crate::scenario::publish_handle("titlebar:report", report.center()); crate::scenario::publish_rect("titlebar:report", report); - ui.painter().rect_filled(report, 4.0, if response.hovered() || response.has_focus() { t.hover } else { t.app_bar }); - ui.painter().rect_stroke(report, 4.0, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + ui.painter().rect_filled(report, t.radius_sm, if response.hovered() || response.has_focus() { t.app_bar_hover_button } else { t.app_bar }); + ui.painter().rect_stroke(report, t.radius_sm, Stroke::new(1.0, t.app_bar_separator), egui::StrokeKind::Inside); let icon = Rect::from_center_size(pos2(report.left() + 14.0, report.center().y), vec2(18.0, 18.0)); - icons::paint_on(ui.painter(), icon, "bug_report", Some(true), 1.0); + icons::paint_app_bar(ui.painter(), icon, "bug_report", 1.0); if report_label { ui.painter().text(pos2(report.left() + REPORT_TEXT_X, report.center().y), Align2::LEFT_CENTER, report_text, report_font, t.app_bar_text); } if response.on_hover_text(crate::i18n::tr_label("Report a bug — review a screenshot and open a GitHub draft")).clicked() { crate::help::run(app, &ui.ctx().clone(), "report"); } - // Preferences, at the top right (also Ctrl+,). - let gear = Rect::from_center_size(pos2(r.right() - captions - 70.0, r.center().y), vec2(24.0, 24.0)); + // Settings sits immediately left of Help (also Ctrl+,). + let gear = Rect::from_center_size(pos2(report.left() - 52.0, r.center().y), vec2(32.0, 32.0)); let gresp = ui.interact(gear, ui.id().with("sc_prefs_button"), Sense::click()); - if gresp.hovered() { - ui.painter().rect_filled(gear, 4.0, Color32::from_white_alpha(30)); + if gresp.hovered() || gresp.has_focus() { + ui.painter().rect_filled(gear.shrink(3.0), t.radius_sm, t.app_bar_hover_button); + } + icons::paint_app_bar(ui.painter(), gear.shrink(7.0), "settings", 1.0); + crate::scenario::publish_rect("titlebar:preferences", gear); + if crate::agent_chat::app_bar_button_shown(app) { + assistant_button(app, ui, Rect::from_center_size(pos2(report.left() - 86.0, r.center().y), vec2(32.0, 32.0))); } - icons::paint_on(ui.painter(), gear.shrink(4.0), "settings", Some(true), 1.0); crate::scenario::publish_handle("titlebar:preferences", gear.center()); let prefs_tip = if cfg!(target_os = "macos") { format!("{} (Cmd+,)", app.tr("ui.preferences")) @@ -431,20 +453,22 @@ pub fn app_bar(app: &mut SolveApp, ui: &mut egui::Ui) { if gresp.on_hover_text(prefs_tip).clicked() { crate::prefs::open_at(app, 0); } - ui.painter().text( - pos2(r.right() - 12.0 - captions, r.center().y), - Align2::RIGHT_CENTER, - format!("v{}", crate::update::current_version()), - FontId::proportional(11.0), - Color32::from_rgb(160, 168, 182), - ); + if r.width() >= 640.0 { + ui.painter().text( + pos2(r.right() - 12.0 - captions, r.center().y), + Align2::RIGHT_CENTER, + format!("v{}", crate::update::current_version()), + FontId::proportional(t.font_small), + t.app_bar_text, + ); + } if app.custom_titlebar { crate::titlebar::caption_buttons(app, ui, r); } }); file_menu(app, ui.ctx()); let help_x = ui.ctx().data(|d| d.get_temp::(egui::Id::new("sc_help_anchor")).unwrap_or(300.0)); - crate::help::show(app, &ui.ctx().clone(), pos2(help_x - 14.0, 34.0)); + crate::help::show(app, &ui.ctx().clone(), pos2(help_x - 14.0, APP_BAR_HEIGHT)); } fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { @@ -454,7 +478,7 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { } let mut close = false; let resp = crate::frame::area(egui::Id::new("sc_file_area")) - .fixed_pos(pos2(ctx.data(|d| d.get_temp::(egui::Id::new("sc_file_menu_x"))).unwrap_or(100.0), 34.0)) + .fixed_pos(pos2(ctx.data(|d| d.get_temp::(egui::Id::new("sc_file_menu_x"))).unwrap_or(100.0), APP_BAR_HEIGHT)) .order(egui::Order::Foreground) .show(ctx, |ui| { egui::Frame::popup(ui.style()).show(ui, |ui| { @@ -664,84 +688,261 @@ fn export_as(app: &mut SolveApp, ext: &str, format: Option<&str>) { }); } +/// Choose at most two lines at spaces or after `/`, then truncate each line at +/// Unicode character boundaries. An oversized word stays on one line with an ellipsis. +fn ribbon_button_lines(painter: &egui::Painter, label: &str, width: f32) -> Vec { + let mut lines = ribbon_label_lines(painter, label, width); + for line in &mut lines { + if ribbon_label_width(painter, line) > width { + while !line.is_empty() { + line.pop(); + if ribbon_label_width(painter, &format!("{}…", line.trim_end())) <= width { + break; + } + } + *line = format!("{}…", line.trim_end()); + } + } + lines +} + +fn ribbon_label_width(painter: &egui::Painter, text: &str) -> f32 { + let mut job = egui::text::LayoutJob::simple(text.to_owned(), FontId::proportional(12.0), Color32::WHITE, f32::INFINITY); + job.halign = egui::Align::Center; + painter.layout_job(job).size().x +} + +fn ribbon_button_width(painter: &egui::Painter, label: &str) -> f32 { + let widest = ribbon_label_lines(painter, label, BUTTON_MAX_WIDTH - BUTTON_LABEL_PADDING) + .iter() + .map(|line| ribbon_label_width(painter, line)) + .fold(0.0_f32, f32::max); + (widest + BUTTON_LABEL_PADDING).clamp(BUTTON_MIN_WIDTH, BUTTON_MAX_WIDTH) +} + +fn ribbon_label_lines(painter: &egui::Painter, label: &str, width: f32) -> Vec { + let measure = |text: &str| ribbon_label_width(painter, text); + let normalized = label.split_whitespace().collect::>().join(" "); + let label = normalized.as_str(); + let mut end = 0; + for token in label.split_inclusive(|c: char| c.is_whitespace() || c == '/') { + let next = end + token.len(); + if end > 0 && measure(label.get(..next).unwrap_or_default().trim()) > width { + break; + } + end = next; + } + let (first, rest) = label.split_at(end); + let mut lines = vec![first.trim().to_owned()]; + if !rest.trim().is_empty() { + lines.push(rest.trim().to_owned()); + } + lines +} + +fn ribbon_button_galley(painter: &egui::Painter, label: &str, width: f32, color: Color32) -> std::sync::Arc { + let lines = ribbon_button_lines(painter, label, width); + // Explicit newlines only: egui must never split an oversized word. + let mut job = egui::text::LayoutJob::simple(lines.join("\n"), FontId::proportional(12.0), color, f32::INFINITY); + job.halign = egui::Align::Center; + painter.layout_job(job) +} + +/// Ribbon headings use the translated labels, with normal word casing instead of registry caps. +fn ribbon_label(app: &SolveApp, label: &str) -> String { + let label = app + .tr_label(label) + .split_whitespace() + .map(|word| { + let lower = word.to_lowercase(); + let mut chars = lower.chars(); + chars.next().map(|c| c.to_uppercase().collect::() + chars.as_str()).unwrap_or_default() + }) + .collect::>() + .join(" "); + // Partial catalogs may already translate the word-cased name (for example "Model"). + app.tr_label(&label).to_string() +} + +fn ribbon_text(ui: &egui::Ui, at: egui::Pos2, text: &str, size: f32, color: Color32, bold: bool) { + let text = egui::RichText::new(text).size(size).color(color); + let text = if bold { text.strong() } else { text }; + let galley = egui::WidgetText::from(text).into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Button); + let origin = at - galley.size() / 2.0; + // egui's `strong` only changes colour. A small overstrike adds weight while retaining + // the user's interface font and its language fallbacks, without another font asset. + if bold { + ui.painter().galley(origin - vec2(0.2, 0.0), galley.clone(), color); + } + ui.painter().galley(origin + vec2(if bold { 0.2 } else { 0.0 }, 0.0), galley, color); +} + +/// The ribbon and S shortcut share one popup anchor, including after resizing. +fn search_anchor(ctx: &egui::Context) -> Option { + ctx.data(|d| d.get_temp::(egui::Id::new("sc_ribbon_search"))).map(|r| r.left_bottom() + vec2(0.0, 3.0)) +} + +fn ribbon_tabs(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect) { + let t = Tokens::get(); + let tabs = crate::workspace::visible_tabs(app); + let widths: Vec<_> = + tabs.iter().map(|tab| ui.painter().layout_no_wrap(ribbon_label(app, tab), FontId::proportional(13.0), t.text).size().x + 24.0).collect(); + let tabs_width: f32 = widths.iter().sum::() + + tabs.len().saturating_sub(1) as f32 * 2.0 + + tabs.iter().filter(|tab| matches!(**tab, "SKETCH" | "SHEET METAL")).count() as f32 * 6.0; + let search_width = if row.width() >= tabs_width + 188.0 + 16.0 { 188.0 } else { 24.0 }; + let search = Rect::from_min_size(pos2((row.right() - search_width - 6.0).max(row.left()), row.top() + 3.0), vec2(search_width, 24.0)); + let resp = ui.interact(search, ui.id().with("ribbon_search"), Sense::click()); + crate::scenario::publish_handle("ribbon:search", search.center()); + crate::scenario::publish_rect("ribbon:search", search); + ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("sc_ribbon_search"), search)); + ui.painter().rect(search, 5.0, t.field, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + // The existing zoom glyph is the icon system's magnifier; no new artwork. + icons::paint_icon(ui.painter(), Rect::from_center_size(search.left_center() + vec2(12.0, 0.0), vec2(16.0, 16.0)), "zoom", 1.0); + let label = app.tr_label("Search commands"); + if search_width > 24.0 { + ui.painter().text(search.left_center() + vec2(29.0, 0.0), Align2::LEFT_CENTER, label, FontId::proportional(12.5), t.text_dim); + let cap = Rect::from_center_size(search.right_center() - vec2(14.0, 0.0), vec2(16.0, 16.0)); + ui.painter().rect(cap, 3.0, t.toolbar, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + ribbon_text(ui, cap.center(), "S", 11.0, t.text_dim, false); + } + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label)); + if resp.on_hover_text(label).clicked() { + crate::shortcut_box::open(app, search_anchor(ui.ctx())); + } + let changed = ui.ctx().data_mut(|d| { + let id = egui::Id::new("sc_ribbon_visible_tab"); + let state = (app.ui.tab.clone(), row.width()); + let changed = d.get_temp::<(String, f32)>(id) != Some(state.clone()); + d.insert_temp(id, state); + changed + }); + let span = Rect::from_min_max(row.left_top() + vec2(4.0, 0.0), pos2((search.left() - 6.0).max(row.left() + 4.0), row.bottom())); + ui.scope_builder(egui::UiBuilder::new().max_rect(span), |ui| { + ui.set_clip_rect(span); + egui::ScrollArea::horizontal() + .id_salt("ribbon_tabs") + .animated(false) + .auto_shrink([false, false]) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden) + .show(ui, |ui| { + let (all, _) = ui.allocate_exact_size(vec2(tabs_width, TAB_ROW_HEIGHT), Sense::hover()); + let mut x = all.left(); + for (tab, width) in tabs.into_iter().zip(widths) { + let contextual = matches!(tab, "SKETCH" | "SHEET METAL"); + if contextual { + x += 6.0; + } + let tr = Rect::from_min_size(pos2(x, all.top() + 3.0), vec2(width, 24.0)); + let active = app.ui.tab == tab; + if active && changed { + ui.scroll_to_rect(tr, Some(egui::Align::Center)); + } + let response = ui.interact(tr, ui.id().with(("tab", tab)), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, ribbon_label(app, tab))); + let accent = crate::theme::TabAccent::for_tab(&t, tab); + let fill = if contextual { + accent.color + } else if active { + accent.soft + } else if response.hovered() { + t.hover + } else { + Color32::TRANSPARENT + }; + ui.painter().rect_filled(tr, t.radius_sm.saturating_add(1), fill); + ribbon_text( + ui, + tr.center(), + &ribbon_label(app, tab), + 13.0, + if contextual { + t.on_accent + } else if active { + selected_ink(&accent) + } else { + t.text + }, + active || contextual, + ); + if ui.clip_rect().contains(tr.center()) { + crate::scenario::publish_handle(&format!("tab:{tab}"), tr.center()); + crate::scenario::publish_rect(&format!("tab:{tab}"), tr); + crate::scenario::publish_rect(&format!("toolbar_tab:{tab}"), tr); + let aliases: &[&str] = match tab { + "MODEL" => &["SOLID", "PLASTIC"], + "SURFACE" => &["MESH"], + "MANAGE" => &["UTILITIES"], + _ => &[], + }; + for alias in aliases { + crate::scenario::publish_handle(&format!("tab:{alias}"), tr.center()); + } + } + if response.clicked() { + app.ui.tab = tab.to_string(); + } + x += width + 2.0; + } + }); + }); + if matches!(app.ui.tab.as_str(), "SKETCH" | "SHEET METAL") { + ui.painter().line_segment( + [row.left_bottom() - vec2(0.0, 1.0), row.right_bottom() - vec2(0.0, 1.0)], + Stroke::new(2.0, panel_accent(&t, &app.ui.tab, "")), + ); + } else { + ui.painter().line_segment( + [row.left_bottom() - vec2(0.0, 0.5), row.right_bottom() - vec2(0.0, 0.5)], + Stroke::new(1.0, t.toolbar.lerp_to_gamma(t.border, 0.5)), + ); + } +} + +/// The dropdown chevron every ribbon menu shares. +fn chevron(painter: &egui::Painter, at: egui::Pos2, ink: Color32) { + crate::icons::paint_ink(painter, Rect::from_center_size(at, vec2(10.0, 10.0)), "chevron", ink); +} + +/// The label colour on a selected tab or open section: on the dark ribbon a lighter tint of the accent. +fn selected_ink(accent: &crate::theme::TabAccent) -> Color32 { + if crate::theme::is_dark() { accent.color.lerp_to_gamma(Tokens::get().on_accent, 0.5) } else { accent.color } +} + pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); - let sketching = app.session.active_sketch.is_some(); - egui::Panel::top("sc_toolbar").exact_size(92.0).frame(egui::Frame::NONE.fill(t.toolbar)).show(ui, |ui| { + crate::workspace::sync_context(app); + egui::Panel::top("sc_toolbar").exact_size(RIBBON_HEIGHT).show_separator_line(false).frame(egui::Frame::NONE.fill(t.toolbar)).show(ui, |ui| { let r = ui.max_rect(); let painter = ui.painter().clone(); - // Right-click on the toolbar's empty space: its own menu. Interacted first, so every - // button, tab and panel label is above it. let bg = ui.interact(r, ui.id().with("toolbar_bg"), Sense::click()); if bg.secondary_clicked() { crate::context_menu::open_for(app, bg.interact_pointer_pos().unwrap_or(r.left_bottom()), crate::context_menu::Target::Toolbar); } - // Workspace selector and tabs. - let tabs_y = r.top() + 2.0; - // The workspace switcher spans the toolbar's height (the tab row and the panel row). - let ws = Rect::from_min_max(pos2(r.left() + 6.0, r.top() + 4.0), pos2(r.left() + 104.0, r.bottom() - 5.0)); + let ws = Rect::from_min_size(r.left_top(), vec2(WORKSPACE_WIDTH, RIBBON_HEIGHT - 1.0)); let wresp = ui.interact(ws, ui.id().with("workspace_switcher"), Sense::click()); - painter.rect(ws, 4.0, if wresp.hovered() { t.hover } else { t.field }, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - let workspace_icon = if crate::render_workspace::active(app) { "ws_render" } else { "ws_design" }; - icons::paint( - &painter, - Rect::from_center_size(pos2(ws.center().x, ws.top() + 24.0), vec2(26.0, 26.0)), - workspace_icon, - t.icon, - t.icon_fill, - t.accent, - ); - painter.text( - pos2(ws.center().x - 5.0, ws.top() + 52.0), - Align2::CENTER_CENTER, - app.tr_label(if crate::render_workspace::active(app) { "RENDER" } else { crate::toolbar_custom::WORKSPACE }), - FontId::proportional(12.0), - t.text, - ); - caret(&painter, pos2(ws.center().x + 27.0, ws.top() + 52.0), t.text); - painter.text(pos2(ws.center().x, ws.top() + 69.0), Align2::CENTER_CENTER, app.tr("ui.workspace"), FontId::proportional(10.0), t.text_dim); + let open = app.viewport.context_menu.is_some() && app.menu.target == crate::context_menu::Target::Workspace; + if wresp.hovered() || open { + painter.rect_filled(ws, 0.0, t.hover); + } + painter.rect_filled(Rect::from_min_size(ws.left_top(), vec2(WORKSPACE_WIDTH, 3.0)), 0.0, t.accent); + painter.line_segment([ws.right_top(), ws.right_bottom()], Stroke::new(1.0, t.border)); + let render = crate::render_workspace::active(app); + let workspace_icon = if render { "ws_render" } else { "ws_design" }; + icons::paint_icon(&painter, Rect::from_center_size(pos2(ws.center().x, ws.top() + 39.0), vec2(30.0, 30.0)), workspace_icon, 1.0); + ribbon_text(ui, pos2(ws.center().x, ws.top() + 69.0), app.tr(if render { "ui.render" } else { "ui.design" }), 13.0, t.text, true); + let label = app.tr("ui.ribbon_workspace"); + let label_width = painter.layout_no_wrap(label.to_string(), FontId::proportional(11.0), t.text_dim).size().x; + ribbon_text(ui, pos2(ws.center().x - 6.0, ws.top() + 89.0), label, 11.0, t.text_dim, false); + chevron(&painter, pos2(ws.center().x - 6.0 + label_width / 2.0 + 7.0, ws.top() + 89.5), t.text_dim); if wresp.on_hover_text(app.tr("ui.change_workspace")).clicked() { crate::context_menu::toggle_for(app, ws, ws.left_bottom(), crate::context_menu::Target::Workspace); } crate::scenario::publish_rect("toolbar", r); crate::scenario::publish_rect("workspace_switcher", ws); - let mut x = r.left() + 112.0; - let mut tabs: Vec<&str> = Vec::new(); - if sketching { - tabs.push("SKETCH"); - } - if crate::render_workspace::active(app) { - tabs.push("RENDER"); - } else { - tabs.extend(TABS.iter()); - } - for tab in tabs { - let display_tab = app.tr_label(tab); - let text_width = painter.layout_no_wrap(display_tab.to_string(), FontId::proportional(12.0), t.text).size().x; - let w = 12.0 + text_width.max(28.0); - let tr = Rect::from_min_size(pos2(x, tabs_y), vec2(w, 22.0)); - let active = app.ui.tab == tab; - let resp = ui.interact(tr, ui.id().with(("tab", tab)), Sense::click()); - crate::scenario::publish_rect(&format!("toolbar_tab:{tab}"), tr); - if active { - let c = if tab == "SKETCH" { t.sketch_accent } else { t.accent }; - painter.line_segment([pos2(tr.left() + 4.0, tr.bottom() - 1.0), pos2(tr.right() - 4.0, tr.bottom() - 1.0)], Stroke::new(2.0, c)); - } else if resp.hovered() { - painter.rect_filled(tr, 4.0, t.hover); - } - let col = if tab == "SKETCH" { - t.sketch_accent - } else if active { - t.text - } else { - t.text_dim - }; - painter.text(tr.center(), Align2::CENTER_CENTER, display_tab, FontId::proportional(12.0), col); - if resp.clicked() { - app.ui.tab = tab.to_string(); - } - x += w + 4.0; - } + crate::scenario::publish_rect("ribbon:workspace", ws); + crate::scenario::publish_handle("ribbon:workspace", ws.center()); + ribbon_tabs(app, ui, Rect::from_min_max(pos2(ws.right() + 1.0, r.top()), pos2(r.right(), r.top() + TAB_ROW_HEIGHT))); // Panels. let tab = app.ui.tab.clone(); // The command whose tool or dialog is open right now, shown pressed in the toolbar. @@ -752,8 +953,8 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { (None, Some(_)) => app.last_command.as_ref().map(|(id, _)| id.clone()), _ => None, }; - let mut px = r.left() + 112.0; - let top = r.top() + 26.0; + let mut px = r.left() + WORKSPACE_WIDTH + 1.0; + let top = r.top() + TAB_ROW_HEIGHT; let mut drop: Option<(&'static str, &'static str, Option<&'static str>)> = None; let mut menu: Option<(egui::Pos2, &'static str)> = None; // A drop-down row's pin icon clicked: pin or unpin that command. @@ -762,25 +963,49 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let mut popup_rect: Option = None; let mut overflow = Vec::new(); // Every panel with all its buttons (the user's pins have no cap); a toolbar too narrow - // for them collapses panels into their drop-down, then into the » menu. + // for them narrows the buttons, then trims panels into their drop-down and the » menu. let lists: Vec<_> = crate::toolbar_custom::panel_lists(&tab) .into_iter() .map(|(panel, cmds, promote)| { - let shown = crate::toolbar_custom::buttons(app, &tab, panel, &cmds, promote); + let mut shown = crate::toolbar_custom::buttons(app, &tab, panel, &cmds, promote); + // Gallery cells are painted together after the large buttons, in reading order. + if tab == "SKETCH" && panel == "CONSTRAIN" { + shown.sort_by_key(|c| crate::workspace::CONSTRAINT_GALLERY.iter().position(|id| *id == c.id).map(|i| i + 1).unwrap_or(0)); + } (panel, cmds, shown) }) .collect(); - let sizes: Vec = - lists.iter().map(|(panel, _, shown)| PanelSize { buttons: shown.len(), labelled: tab == "SKETCH" && *panel == "CREATE" }).collect(); - // The AI button keeps the toolbar row's right end, whatever the ribbon's width - // (docs/agent-chat.md); panels that no longer fit go to the » menu as usual. - let right = if crate::agent_chat::toolbar_button_shown(app) { r.right() - AI_BUTTON_ROOM } else { r.right() }; - let plans = fit(&sizes, right - 4.0 - px); + let sizes: Vec = lists + .iter() + .map(|(panel, _, shown)| { + let mut widths: Vec<_> = shown + .iter() + .filter(|c| !(tab == "SKETCH" && *panel == "CONSTRAIN" && crate::workspace::CONSTRAINT_GALLERY.contains(&c.id))) + .map(|c| { + let family = crate::sketch_families::family(c.id) + .filter(|f| tab == "SKETCH" && *panel == "CREATE" && f.commands.first().copied() == Some(c.id)); + let label = family.map_or_else(|| crate::workspace::ribbon_button_label(c), |f| f.label); + ButtonSize { width: ribbon_button_width(&painter, app.tr_label(label)), min_width: BUTTON_MIN_WIDTH } + }) + .collect(); + if tab == "SKETCH" && *panel == "CONSTRAIN" && shown.iter().any(|c| crate::workspace::CONSTRAINT_GALLERY.contains(&c.id)) { + widths.push(ButtonSize { width: CONSTRAINT_GRID_WIDTH, min_width: CONSTRAINT_GRID_WIDTH }); + } + PanelSize { buttons: widths } + }) + .collect(); + let right = r.right(); + // Keep the Sketch exit group at the far right and reachable at every width. + let finish_plan = sizes.last().filter(|_| tab == "SKETCH").map(Plan::full); + let finish_width = finish_plan.as_ref().map_or(0.0, |p| p.width().max(80.0)); + let normal_count = sizes.len().saturating_sub(usize::from(finish_plan.is_some())); + let mut plans = fit(sizes.get(..normal_count).unwrap_or_default(), right - 4.0 - px - finish_width); + plans.extend(finish_plan); crate::scenario::publish_count("toolbar_collapsed", plans.iter().filter(|p| p.fit == Fit::Collapsed).count() as f64); crate::scenario::publish_count("toolbar_more", plans.iter().filter(|p| p.fit == Fit::More).count() as f64); crate::scenario::publish_count( "toolbar_trimmed", - plans.iter().zip(&sizes).filter(|(p, s)| p.fit == Fit::Buttons && p.shown < s.buttons).count() as f64, + plans.iter().zip(&sizes).filter(|(p, s)| p.fit == Fit::Buttons && p.shown < s.buttons.len()).count() as f64, ); for ((panel, cmds, shown), plan) in lists.into_iter().zip(plans) { let panel: &&str = &panel; @@ -789,61 +1014,73 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { continue; } let collapsed = plan.fit == Fit::Collapsed; - let width = plan.width(); + let trimmed = plan.shown < plan.widths.len(); + let finish = tab == "SKETCH" && *panel == "FINISH SKETCH"; + let width = if finish { finish_width } else { plan.width() }; + if finish { + px = right - finish_width; + painter.line_segment([pos2(px, top), pos2(px, r.bottom() - 1.0)], Stroke::new(1.0, t.border)); + } + let button_widths = &plan.widths; let sketch_create = tab == "SKETCH" && *panel == "CREATE"; - let stride = plan.stride; - // Sketch > Create's buttons carry their label while there's room for one. - let labelled = sketch_create && plan.labels(); - // Buttons that went into the drop-down for want of room are still listed there. - let trimmed = plan.shown < shown.len(); let enabled_panel = !cmds.is_empty() || *panel == "SELECT"; // Per tab: panels of the same name on other tabs (MODIFY, CREATE…) list other commands, // and the drop-down's area remembers its size by this id (#874). let popup_id = ui.id().with(("panel_menu", &tab, panel)); // Dropped on the panel's free space (all of a collapsed panel): the button goes to // its end. - let drawn = if collapsed { 0 } else { plan.shown.min(shown.len()) }; + let gallery: Vec<_> = shown + .iter() + .copied() + .filter(|c| tab == "SKETCH" && *panel == "CONSTRAIN" && crate::workspace::CONSTRAINT_GALLERY.contains(&c.id)) + .collect(); + let large: Vec<_> = shown.iter().copied().filter(|c| !gallery.iter().any(|g| g.id == c.id)).collect(); + let drawn = if collapsed { 0 } else { plan.shown.min(button_widths.len()) }; // Buttons narrower than the panel's minimum width (a one-button panel) are centred. - let inset = if drawn == 0 { 0.0 } else { ((width - 8.0 - (drawn as f32 * stride - 2.0)) / 2.0).max(0.0).floor() }; + let buttons_width = button_widths.iter().take(drawn).sum::() + drawn.saturating_sub(1) as f32 * BUTTON_GAP; + let inset = if drawn == 0 { 0.0 } else { ((width - 8.0 - buttons_width) / 2.0).max(0.0).floor() }; let bx = px + 4.0 + inset; - let free_x = bx + drawn as f32 * stride; - let free = Rect::from_min_size(pos2(free_x, top + 2.0), vec2((px + width - 4.0 - free_x).max(8.0), 38.0)); + let free_x = bx + buttons_width + BUTTON_GAP; + let free = Rect::from_min_size(pos2(free_x, top + 2.0), vec2((px + width - 4.0 - free_x).max(0.0), BUTTON_HEIGHT)); let fresp = ui.interact(free, ui.id().with(("panel_free", panel)), if collapsed { Sense::click() } else { Sense::hover() }); let mut opened = false; if collapsed { // One button: the panel's first command's icon over a caret; it opens the // drop-down, which lists every command of the panel. - let br = Rect::from_center_size(free.center(), vec2(38.0, 38.0)); + let br = Rect::from_center_size(free.center(), vec2((width - 8.0).max(0.0), BUTTON_HEIGHT)); crate::scenario::publish_handle(&format!("collapsed:{tab}:{panel}"), br.center()); if fresp.hovered() && enabled_panel { - painter.rect_filled(br, 4.0, t.hover); + painter.rect_filled(br, t.radius_sm, t.hover); } if let Some(c) = shown.first().or(cmds.first()) { let acc = command_accent(c.icon); icons::paint(&painter, Rect::from_center_size(br.center() - vec2(0.0, 3.0), vec2(26.0, 26.0)), c.icon, t.icon, t.icon_fill, acc); } - caret(&painter, pos2(br.center().x, br.bottom() - 3.0), t.text_dim); + chevron(&painter, pos2(br.center().x, br.bottom() - 3.0), t.text_dim); let tip = format!("{} ({})", app.tr_label(panel), shown.len().max(cmds.len())); if fresp.on_hover_text(tip).clicked() && enabled_panel { ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("sc_panel_open"), popup_id)); opened = true; } } - for (i, c) in shown.iter().enumerate().take(drawn) { + let mut button_x = bx; + for (c, button_width) in large.iter().zip(button_widths.iter().copied()).take(drawn) { // Only the family's default pin follows the part's choice. Explicitly pinned // variants remain exact commands, including in customised toolbars. let family = crate::sketch_families::family(c.id).filter(|f| sketch_create && f.commands.first().copied() == Some(c.id)); let selected = family.and_then(|f| app.sketch_choices.selected(f)).unwrap_or(c); - let whole = Rect::from_min_size(pos2(bx + i as f32 * stride, top + 2.0), vec2(stride - 2.0, 38.0)); + let whole = Rect::from_min_size(pos2(button_x, top + 2.0), vec2(button_width, BUTTON_HEIGHT)); + button_x += button_width + BUTTON_GAP; let mut br = whole; if family.is_some() { - br.max.y -= 12.0; + br.max.y = whole.top() + 32.0; } let info = selected.info(&app.session); let resp = ui.interact(br, ui.id().with(("cmd", c.id)), Sense::click_and_drag()); crate::scenario::publish_handle(&format!("toolbar:{}", c.id), br.center()); // The button itself (`toolbar:` is also a drop-down row's while one is open). crate::scenario::publish_handle(&format!("button:{}", c.id), br.center()); + crate::scenario::publish_rect(&format!("button:{}", c.id), whole); if selected.id != c.id { crate::scenario::publish_handle(&format!("button:{}", selected.id), br.center()); } @@ -864,101 +1101,123 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { if resp.secondary_clicked() { menu = Some((resp.interact_pointer_pos().unwrap_or(br.left_bottom()), c.id)); } - if running.as_deref() == Some(selected.id) { - painter.rect_filled(br, 4.0, t.border.gamma_multiply(0.7)); + let accent = crate::theme::TabAccent::for_tab(&t, &tab); + let family_open = family.is_some_and(|f| egui::Popup::is_id_open(ui.ctx(), ui.id().with(("family", f.label)).with("popup"))); + if !finish && (resp.is_pointer_button_down_on() || running.as_deref() == Some(selected.id) || family_open) { + painter.rect(whole, t.radius_sm, accent.soft, Stroke::new(1.0, accent.color), egui::StrokeKind::Inside); } else if resp.hovered() && info.enabled { - painter.rect_filled(br, 4.0, t.hover); + painter.rect_filled(whole, t.radius_sm, t.hover); } - let (ink, fill, acc) = - if info.enabled { (t.icon, t.icon_fill, command_accent(selected.icon)) } else { (t.border, t.panel_header, t.border) }; - let icon = match selected.id { - "sketch.finish" => "finish", - _ => selected.icon, - }; - let icon_rect = if labelled { - Rect::from_center_size(pos2(br.center().x, br.top() + 13.0), vec2(24.0, 24.0)) - } else if sketch_create { - Rect::from_center_size(br.center(), vec2(24.0, 24.0)) - } else { - br.shrink(6.0) - }; - icons::paint(&painter, icon_rect, icon, ink, fill, acc); - let label = match c.id { - "parameters.change" if *panel == "CONFIGURE" => "Parameters", - "config.table" if *panel == "CONFIGURE" => "Configurations", - _ => selected.label, - }; - let tr_label = app.tr_label(label); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled() && info.enabled, tr_label)); - let tip = match &info.disabled_reason { - Some(why) => format!("{}\n{why}", tr_label), - None => format!("{}{}", tr_label, selected.shortcut.map(|k| format!(" ({k})")).unwrap_or_default()), - }; - if resp.on_hover_text(tip).clicked() && info.enabled { + let icon = if selected.id == "sketch.finish" { "finish" } else { selected.icon }; + let side = if finish { 30.0 } else { 26.0 }; + let icon_rect = Rect::from_center_size(pos2(br.center().x, whole.top() + 16.0), vec2(side, side)); + icons::paint_icon(&painter, icon_rect, icon, if info.enabled { 1.0 } else { 0.35 }); + let tr_label = app.tr_label(selected.label).to_string(); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled() && info.enabled, &tr_label)); + if ribbon_tooltip(app, resp, selected, info.disabled_reason.as_deref()).clicked() && info.enabled { let id = selected.id; app.start(id); } if let Some(f) = family { - let ar = Rect::from_min_max(pos2(whole.left(), br.bottom()), whole.right_bottom()); + let ar = Rect::from_min_max(pos2(whole.left(), whole.top() + 30.0), pos2(whole.right(), whole.top() + 48.0)); let arrow = ui.interact(ar, ui.id().with(("family", f.label)), Sense::click()); crate::scenario::publish_handle(&format!("family:{}", f.label), ar.center()); if arrow.hovered() { - painter.rect_filled(ar, 3.0, t.hover); + painter.rect_filled(ar, t.radius_sm, t.hover); } - if labelled { - let g = short_label(&painter, app.tr_label(f.label), ar.width() - 12.0, t.text); - painter.galley(ar.center() - vec2(4.0 + g.size().x / 2.0, g.size().y / 2.0), g, t.text); - caret(&painter, pos2(ar.right() - 5.0, ar.center().y), t.text); - } else { - caret(&painter, ar.center(), t.text); - } - arrow.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, format!("{} variants", f.label))); + // The title sits on the same line as the other buttons' labels. + let title_y = whole.top() + 39.0; + let galley = ribbon_button_galley(&painter, app.tr_label(f.label), ar.width() - 16.0, t.text); + painter.galley(pos2(ar.center().x - 4.0, title_y - galley.size().y / 2.0), galley, t.text); + chevron(&painter, pos2(ar.right() - 6.0, title_y + 0.5), t.text_dim); + arrow.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, app.tr_label(f.label))); egui::Popup::menu(&arrow).show(|ui| { let variants: Vec<_> = f.commands.iter().filter_map(|id| solidcraft_engine::find_command(id)).collect(); dropdown_keys(app, ui, &variants); sketch_menu_rows(app, ui, &variants, &mut menu, &mut toggle); }); - } else if labelled { - let g = short_label(&painter, app.tr_label(c.label), br.width() - 4.0, t.text); - painter.galley(pos2(br.center().x - g.size().x / 2.0, br.bottom() - 5.0 - g.size().y / 2.0), g, t.text); + } else { + let label = app.tr_label(crate::workspace::ribbon_button_label(selected)); + let color = if info.enabled { t.text } else { t.text_dim }; + let galley = ribbon_button_galley(&painter, label, whole.width() - BUTTON_LABEL_PADDING, color); + painter.galley(pos2(whole.center().x, whole.top() + 32.0), galley, t.text); } } - if shown.is_empty() && !collapsed { - let br = Rect::from_min_size(pos2(px + 4.0, top + 2.0), vec2(width - 8.0, 38.0)); - painter.text(br.center(), Align2::CENTER_CENTER, "—", FontId::proportional(14.0), t.border); + if !collapsed && drawn > large.len() { + if !gallery.is_empty() { + // A quiet rule sets the grid apart from the large button before it. + painter.line_segment( + [pos2(button_x - 1.5, top + 8.0), pos2(button_x - 1.5, top + 46.0)], + Stroke::new(1.0, t.toolbar.lerp_to_gamma(t.border, 0.5)), + ); + } + for c in &gallery { + let index = crate::workspace::CONSTRAINT_GALLERY.iter().position(|id| *id == c.id).unwrap_or(0); + let cell = + Rect::from_min_size(pos2(button_x + (index % 3) as f32 * 27.0, top + 6.0 + (index / 3) as f32 * 23.0), vec2(24.0, 20.0)); + let info = c.info(&app.session); + let resp = ui.interact(cell, ui.id().with(("cmd", c.id)), Sense::click_and_drag()); + let active = running.as_deref() == Some(c.id); + painter.rect( + cell, + 4.0, + if active { + t.panel.lerp_to_gamma(command_accent(c.icon), 0.18) + } else if resp.hovered() && info.enabled { + t.hover + } else { + t.panel + }, + Stroke::new(1.0, if active { command_accent(c.icon) } else { t.border }), + egui::StrokeKind::Inside, + ); + icons::paint_icon( + &painter, + Rect::from_center_size(cell.center(), vec2(15.0, 15.0)), + c.icon, + if info.enabled { 1.0 } else { 0.35 }, + ); + for prefix in ["toolbar", "button", "ribbon:constraint"] { + crate::scenario::publish_handle(&format!("{prefix}:{}", c.id), cell.center()); + crate::scenario::publish_rect(&format!("{prefix}:{}", c.id), cell); + } + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, info.enabled, app.tr_label(c.label))); + if resp.drag_started() { + resp.dnd_set_drag_payload(ToolbarDrag { id: c.id, from_menu: false }); + } + if let Some(d) = resp.dnd_release_payload::() + && d.id != c.id + { + drop = Some((d.id, *panel, Some(c.id))); + } + if resp.secondary_clicked() { + menu = Some((resp.interact_pointer_pos().unwrap_or(cell.left_bottom()), c.id)); + } + if ribbon_tooltip(app, resp, c, info.disabled_reason.as_deref()).clicked() && info.enabled { + app.start(c.id); + } + } } - // Panel label with drop-down. - let label = app.tr_label(panel).to_string(); - let lc = if *panel == "FINISH SKETCH" { - t.sketch_accent - } else if enabled_panel { - t.text - } else { - t.text_dim - }; - // A label too wide for its panel (beside the caret) wraps between words onto a - // second line; a single word wider than the panel stays whole. Each line is - // centred, and the hover area grows to hold them. - let font = FontId::proportional(10.5); - let widest_word = label.split_whitespace().map(|w| painter.layout_no_wrap(w.to_string(), font.clone(), lc).size().x).fold(0.0, f32::max); - let mut job = egui::text::LayoutJob::simple(label, font, lc, (width - 14.0).max(widest_word + 1.0)); - job.wrap.max_rows = 2; - job.halign = egui::Align::Center; - let g = painter.layout_job(job); - let gw = g.size().x; - let lr = Rect::from_center_size(pos2(px + width / 2.0, top + 51.0), vec2(width, (g.size().y + 2.0).max(18.0))); + // A 20 px label row is also the section's existing command-list button. + let lr = Rect::from_min_size(pos2(px + 3.0, top + GROUP_HEIGHT - SECTION_HEIGHT - 3.0), vec2((width - 6.0).max(0.0), SECTION_HEIGHT)); let lresp = ui.interact(lr, ui.id().with(("panel", panel)), Sense::click()); crate::scenario::publish_handle(&format!("panel:{tab}:{panel}"), lr.center()); - if lresp.hovered() && enabled_panel { - painter.rect_filled(lr, 3.0, t.hover); + crate::scenario::publish_handle(&format!("ribbon:section:{tab}:{panel}"), lr.center()); + crate::scenario::publish_rect(&format!("ribbon:section:{tab}:{panel}"), lr); + let panel_open = ui.ctx().data(|d| d.get_temp::(egui::Id::new("sc_panel_open"))) == Some(popup_id); + let accent = crate::theme::TabAccent::for_tab(&t, &tab); + let hot = lresp.hovered() && enabled_panel; + if panel_open || hot { + painter.rect_filled(lr, 4.0, if panel_open { accent.soft } else { t.hover }); } - // Centred rows sit around x = 0, so the galley is placed at the text's centre. - let gx = lr.center().x - 4.5; - let gy = lr.center().y - g.size().y / 2.0; - painter.galley(pos2(gx, gy), g, lc); - caret(&painter, pos2(gx + gw / 2.0 + 6.0, lr.center().y), lc); - // The label toggles its drop-down (#1522). - if lresp.clicked() { + let label = if finish { app.tr("ui.ribbon_exit").to_string() } else { ribbon_label(app, panel) }; + let label_width = painter.layout_no_wrap(label.clone(), FontId::proportional(11.5), t.text_dim).size().x; + let ink = if panel_open { selected_ink(&accent) } else { t.text_dim }; + ribbon_text(ui, lr.center() - vec2(if finish { 0.0 } else { 6.0 }, 0.0), &label, 11.5, ink, panel_open || hot); + if !finish { + chevron(&painter, pos2(lr.center().x + label_width / 2.0 + 1.0, lr.center().y + 0.5), ink); + } + if lresp.clicked() && enabled_panel { ui.ctx().data_mut(|d| { let key = egui::Id::new("sc_panel_open"); if d.get_temp::(key) == Some(popup_id) { @@ -973,7 +1232,12 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let panel_rect = Rect::from_min_max(pos2(px, top + 2.0), pos2(px + width, r.bottom())); crate::scenario::publish_rect(&format!("panel:{tab}:{panel}"), panel_rect); let over_button = ui.input(|input| input.pointer.hover_pos()).is_some_and(|p| { - (0..drawn).any(|i| Rect::from_min_size(pos2(bx + i as f32 * stride, top + 2.0), vec2(stride - 2.0, 38.0)).contains(p)) + let mut x = bx; + button_widths.iter().take(drawn).any(|width| { + let rect = Rect::from_min_size(pos2(x, top + 2.0), vec2(*width, BUTTON_HEIGHT)); + x += width + BUTTON_GAP; + rect.contains(p) + }) }); if !over_button && ui.rect_contains_pointer(panel_rect) && egui::DragAndDrop::payload::(ui.ctx()).is_some() { painter.line_segment([pos2(px + width - 4.0, top + 4.0), pos2(px + width - 4.0, top + 38.0)], Stroke::new(2.0, t.accent)); @@ -987,7 +1251,8 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { if open { let cmds = if collapsed || trimmed { menu_commands(&cmds, &shown) } else { cmds.clone() }; let area = crate::frame::area(popup_id).fixed_pos(lr.left_bottom()).order(egui::Order::Foreground).show(ui.ctx(), |ui| { - egui::Frame::popup(ui.style()).show(ui, |ui| { + section_frame(ui).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; ui.set_min_width(200.0); if *panel == "SELECT" { selection_filter(app, ui); @@ -996,9 +1261,13 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { } if sketch_create { sketch_create_menu(app, ui, &cmds, &mut menu, &mut toggle); + section_footer(ui); return; } + let grouped = crate::workspace::grouped_commands(&tab, panel, &cmds); + let cmds: Vec<_> = grouped.iter().map(|(_, c)| *c).collect(); let row_w = dropdown_width(app, ui, &cmds); + ui.set_width(row_w); // Up and Down move the keyboard focus through the enabled rows (from none // focused: the first or the last), instead of egui's own spatial move. let (down, up) = ui.input(|i| (i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::ArrowUp))); @@ -1023,9 +1292,12 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { // The rows scroll when the drop-down would run past the window's bottom. // `min_scrolled_height` lets the rows grow past the size the area kept from // an earlier, shorter list (#874); they still shrink to fit their content. - let room = (ui.ctx().content_rect().bottom() - ui.cursor().top() - 12.0).max(ROW_H * 3.0); + let room = (ui.ctx().content_rect().bottom() - ui.cursor().top() - 64.0).max(ROW_H * 3.0); egui::ScrollArea::vertical().id_salt("panel_menu_rows").max_height(room).min_scrolled_height(room).show(ui, |ui| { - for c in &cmds { + for (heading, c) in &grouped { + if let Some(heading) = heading { + section_heading(ui, heading, row_w); + } let pinned = crate::toolbar_custom::pinned_on(app, &tab, c.id).is_some(); match dropdown_row(app, ui, c, row_w, pinned) { RowAction::None => {} @@ -1038,6 +1310,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { } } }); + section_footer(ui); }); }); popup_rect = Some(area.response.rect); @@ -1049,11 +1322,11 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { } } px += width; - painter.line_segment([pos2(px, top + 4.0), pos2(px, top + 58.0)], Stroke::new(1.0, t.border)); - px += 2.0; + painter.line_segment([pos2(px, top + 4.0), pos2(px, top + GROUP_HEIGHT - 3.0)], Stroke::new(1.0, t.border)); + px += PANEL_GAP; } if !overflow.is_empty() { - let at = Rect::from_min_size(pos2(px.min(right - 40.0), top + 4.0), vec2(38.0, 52.0)); + let at = Rect::from_min_size(pos2(px.min(right - finish_width - 40.0), top + 4.0), vec2(38.0, BUTTON_HEIGHT)); ui.scope_builder(egui::UiBuilder::new().max_rect(at), |ui| { let response = ui.menu_button("»", |ui| { for (panel, cmds) in &overflow { @@ -1082,9 +1355,6 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { response.response.on_hover_text(crate::i18n::tr_label("More toolbar panels")); }); } - if right < r.right() { - ai_button(app, ui, Rect::from_min_max(pos2(right + 4.0, r.top() + 4.0), pos2(r.right() - 6.0, r.bottom() - 5.0))); - } painter.line_segment([pos2(r.left(), r.bottom() - 0.5), pos2(r.right(), r.bottom() - 0.5)], Stroke::new(1.0, t.border)); // Dragging a command: its icon follows the pointer; a toolbar button dragged off the // toolbar (or into the open drop-down) shows it will be removed. @@ -1114,44 +1384,73 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { }); } -/// A button's label on one line in `max_width`, shortened with an ellipsis when it doesn't fit. -fn short_label(painter: &egui::Painter, text: &str, max_width: f32, color: Color32) -> std::sync::Arc { - let mut job = egui::text::LayoutJob::simple_singleline(text.to_string(), FontId::proportional(10.0), color); - job.wrap = egui::text::TextWrapping { max_width: max_width.max(8.0), max_rows: 1, break_anywhere: true, overflow_character: Some('…') }; - painter.layout_job(job) +/// A short divider between the brand, file actions and document tabs. +fn app_bar_separator(ui: &egui::Ui, bar: Rect, x: f32, group: &str) { + let rect = Rect::from_center_size(pos2(x, bar.center().y), vec2(1.0, 20.0)); + ui.painter().line_segment( + [rect.center_top(), rect.center_bottom()], + Stroke::new(1.0, Tokens::get().app_bar.lerp_to_gamma(Tokens::get().app_bar_separator, 0.4)), + ); + crate::scenario::publish_rect(&format!("titlebar:separator:{group}"), rect); } -/// Room the AI button takes at the toolbar row's right end. -const AI_BUTTON_ROOM: f32 = 52.0; - -/// The AI button: shows and hides the agent chat panel (lit while it is open). -fn ai_button(app: &mut SolveApp, ui: &mut egui::Ui, at: Rect) { +/// The chat panel's compact entry point. State stays in agent_chat; the bar only paints it. +fn assistant_button(app: &mut SolveApp, ui: &mut egui::Ui, at: Rect) { + use crate::agent_chat::AssistantMark; let t = Tokens::get(); - let resp = ui.interact(at, ui.id().with("ai_button"), Sense::click()); - crate::scenario::publish_handle("toolbar:ai", at.center()); - crate::scenario::publish_rect("toolbar:ai", at); - let open = app.agent_chat.open; - let painter = ui.painter(); - painter.line_segment([pos2(at.left() - 4.0, at.top() + 4.0), pos2(at.left() - 4.0, at.bottom() - 4.0)], Stroke::new(1.0, t.border)); - if open || resp.hovered() { - painter.rect_filled(at, 4.0, if open { t.accent_soft } else { t.hover }); + let resp = ui.interact(at, ui.id().with("assistant_button"), Sense::click()); + crate::scenario::publish_handle("titlebar:assistant", at.center()); + crate::scenario::publish_rect("titlebar:assistant", at); + let mark = crate::agent_chat::assistant_mark(app); + let tip = crate::agent_chat::assistant_tip(mark); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &tip)); + // The highlight is a 26 px square, like the other icon buttons; the mark sits on the bubble's corner. + let mut ring = t.app_bar; + if app.agent_chat.open || resp.hovered() || resp.has_focus() { + let fill = if app.agent_chat.open { t.app_bar_hover_strong } else { t.app_bar_hover_button }; + ui.painter().rect_filled(at.shrink(3.0), t.radius_sm, fill); + ring = t.app_bar.blend(fill); } - icons::paint( - painter, - Rect::from_center_size(pos2(at.center().x, at.top() + 24.0), vec2(26.0, 26.0)), - "agent_chat", - t.icon, - t.icon_fill, - t.accent, - ); - painter.text(pos2(at.center().x, at.top() + 52.0), Align2::CENTER_CENTER, crate::i18n::tr("ui.ai_button"), FontId::proportional(11.0), t.text); - let waiting = app.agent_chat.waiting(); - if waiting > 0 { - let c = pos2(at.right() - 6.0, at.top() + 9.0); - painter.circle_filled(c, 6.0, t.warning); - painter.text(c, Align2::CENTER_CENTER, waiting.min(9).to_string(), FontId::proportional(9.5), t.toolbar); + icons::paint_app_bar(ui.painter(), at.shrink(7.0), "assistant", 1.0); + let c = at.min + vec2(23.5, 9.5); + match mark { + AssistantMark::Quiet => {} + AssistantMark::Ready | AssistantMark::NeedsAuth | AssistantMark::Stopped => { + let color = match mark { + AssistantMark::Ready => t.agent_ok, + AssistantMark::NeedsAuth => t.warning, + _ => t.error, + }; + ui.painter().circle_filled(c, 5.5, ring); + ui.painter().circle_filled(c, 4.0, color); + } + AssistantMark::Busy => { + let phase = if app.preferences.look_at_anim { + ui.ctx().request_repaint(); + ui.input(|i| i.time) as f32 * 3.0 + } else { + 0.0 + }; + ui.painter().circle_filled(c, 6.0, ring); + let points = (0..=24) + .map(|i| { + let angle = phase + i as f32 / 24.0 * std::f32::consts::TAU * 0.75; + c + vec2(angle.cos(), angle.sin()) * 4.0 + }) + .collect(); + ui.painter().add(egui::Shape::line(points, Stroke::new(1.8, t.agent_busy))); + } + AssistantMark::Waiting(count) => { + let text = count.to_string(); + let font = FontId::proportional(t.font_badge); + let galley = ui.painter().layout_no_wrap(text, font, t.app_bar); + let badge = Rect::from_center_size(c, vec2((galley.size().x + 6.0).max(14.0), 14.0)); + ui.painter().rect_filled(badge.expand(1.5), 8.5, ring); + ui.painter().rect_filled(badge, 7.0, t.warning); + ui.painter().galley(badge.center() - galley.size() / 2.0, galley, t.app_bar); + } } - if resp.on_hover_text(crate::agent_chat::panel_tip()).clicked() { + if resp.on_hover_text(tip).clicked() { crate::agent_chat::toggle(app); } } @@ -1164,11 +1463,77 @@ enum RowAction { TogglePin, } -const ROW_H: f32 = 24.0; +const ROW_H: f32 = 30.0; -/// The id of a drop-down row (for keyboard focus). -/// A drop-down row's id, the same inside and outside the rows' scroll area (one drop-down is -/// open at a time). +const CONSTRAINT_GRID_WIDTH: f32 = 82.0; + +/// Registry parameter syntax is not a user-facing description. Reuse existing catalog prose +/// where present; other commands intentionally show only their name and registered shortcut. +fn ribbon_tooltip(app: &SolveApp, response: egui::Response, command: &solidcraft_engine::CommandSpec, disabled: Option<&str>) -> egui::Response { + response.on_hover_ui(|ui| { + let t = Tokens::get(); + let name = app.tr_label(command.label); + let name_width = ui.painter().layout_no_wrap(name.to_string(), FontId::proportional(14.0), t.text).size().x; + let key_width = command + .shortcut + .map(|key| ui.painter().layout_no_wrap(key.to_string(), FontId::monospace(12.0), t.text_dim).size().x + 24.0) + .unwrap_or(0.0); + ui.set_width(280.0_f32.max(name_width + key_width + 12.0)); + ui.horizontal(|ui| { + let (rect, _) = ui.allocate_exact_size(vec2(name_width, 20.0), Sense::hover()); + ribbon_text(ui, rect.center(), name, 14.0, t.text, true); + if let Some(key) = command.shortcut { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + egui::Frame::new() + .fill(t.panel_header) + .stroke(Stroke::new(1.0, t.border)) + .corner_radius(3.0) + .inner_margin(egui::Margin::symmetric(5, 1)) + .show(ui, |ui| { + ui.label(egui::RichText::new(key).monospace().color(t.text_dim)); + }); + }); + } + }); + let description = match command.id { + "render.scene" => Some(app.tr("render.preview_help")), + "render.start" => Some(app.tr("render.image_help")), + _ => None, + }; + if let Some(description) = description { + ui.add(egui::Label::new(description).wrap()); + } + if let Some(reason) = disabled { + ui.add(egui::Label::new(egui::RichText::new(reason).color(t.text_dim)).wrap()); + } + }) +} + +fn section_frame(ui: &egui::Ui) -> egui::Frame { + let t = Tokens::get(); + egui::Frame::popup(ui.style()).fill(t.panel).stroke(Stroke::new(1.0, t.border)).corner_radius(8.0) +} + +fn section_heading(ui: &mut egui::Ui, label: &str, width: f32) { + let t = Tokens::get(); + let (rect, _) = ui.allocate_exact_size(vec2(width, 24.0), Sense::hover()); + ui.painter().text( + rect.left_center() + vec2(6.0, 0.0), + Align2::LEFT_CENTER, + crate::i18n::tr_label(label).to_uppercase(), + FontId::proportional(11.0), + t.text_dim, + ); +} + +fn section_footer(ui: &mut egui::Ui) { + ui.separator(); + ui.add_space(4.0); + ui.add(egui::Label::new(egui::RichText::new(crate::i18n::tr("ui.ribbon_pin_footer")).size(11.0).color(Tokens::get().text_dim)).wrap()); + ui.add_space(4.0); +} + +/// Stable row id inside and outside the scrolling list, for keyboard focus. fn dropdown_row_id(id: &str) -> egui::Id { egui::Id::new(("dropdown_row", id)) } @@ -1176,12 +1541,15 @@ fn dropdown_row_id(id: &str) -> egui::Id { /// How wide a panel drop-down's rows are: the widest label and shortcut, at least 200. fn dropdown_width(app: &SolveApp, ui: &egui::Ui, cmds: &[&'static solidcraft_engine::CommandSpec]) -> f32 { let t = Tokens::get(); - let font = FontId::proportional(13.0); + let font = FontId::proportional(t.font_button); cmds.iter() .map(|c| { let label = ui.painter().layout_no_wrap(app.tr_label(c.label).to_string(), font.clone(), t.text).size().x; - let key = c.shortcut.map(|k| ui.painter().layout_no_wrap(k.to_string(), font.clone(), t.text).size().x + 24.0).unwrap_or(0.0); - 6.0 + 18.0 + 8.0 + label + key + 30.0 + let key = c + .shortcut + .map(|k| ui.painter().layout_no_wrap(k.to_string(), FontId::monospace(t.font_button), t.text).size().x + 24.0) + .unwrap_or(0.0); + 6.0 + 20.0 + 8.0 + label + key + 30.0 }) .fold(200.0, f32::max) } @@ -1195,8 +1563,9 @@ fn dropdown_row(app: &SolveApp, ui: &mut egui::Ui, c: &'static solidcraft_engine // Every row drags onto the toolbar (to pin it there); enabled rows also start their command. let sense = if info.enabled { Sense::click_and_drag() } else { Sense::drag() }; let resp = ui.interact(rect, dropdown_row_id(c.id), sense); - // Rows reached with the arrow keys scroll into view in a drop-down taller than the window. - if resp.has_focus() && ui.input(|i| i.key_pressed(egui::Key::ArrowDown) || i.key_pressed(egui::Key::ArrowUp)) { + // Focus can settle on the following frame, after the key event has gone. + // Keep the focused row visible even then in a drop-down taller than the window. + if resp.has_focus() && !ui.clip_rect().contains_rect(rect) { resp.scroll_to_me_animation(None, egui::style::ScrollAnimation::none()); } if resp.drag_started() { @@ -1223,11 +1592,11 @@ fn dropdown_row(app: &SolveApp, ui: &mut egui::Ui, c: &'static solidcraft_engine } else { (t.border, t.panel_header, t.border, t.text_dim) }; - let ir = Rect::from_center_size(pos2(rect.left() + 6.0 + 9.0, rect.center().y), vec2(18.0, 18.0)); + let ir = Rect::from_center_size(pos2(rect.left() + 6.0 + 10.0, rect.center().y), vec2(20.0, 20.0)); icons::paint(p, ir, c.icon, ink, fill, acc); - p.text(pos2(ir.right() + 8.0, rect.center().y), Align2::LEFT_CENTER, &label, FontId::proportional(13.0), text); + p.text(pos2(ir.right() + 8.0, rect.center().y), Align2::LEFT_CENTER, &label, FontId::proportional(t.font_button), text); if let Some(k) = c.shortcut { - p.text(pos2(pr.left() - 4.0, rect.center().y), Align2::RIGHT_CENTER, k, FontId::proportional(13.0), t.text_dim); + p.text(pos2(pr.left() - 4.0, rect.center().y), Align2::RIGHT_CENTER, k, FontId::monospace(t.font_button), t.text_dim); } if pointer_on || resp.has_focus() { if pin.hovered() { @@ -1261,7 +1630,7 @@ fn sketch_create_menu( menu: &mut Option<(egui::Pos2, &'static str)>, toggle: &mut Option<&'static str>, ) { - let room = (ui.ctx().content_rect().bottom() - ui.cursor().top() - 12.0).max(ROW_H * 3.0); + let room = (ui.ctx().content_rect().bottom() - ui.cursor().top() - 64.0).max(ROW_H * 3.0); egui::ScrollArea::vertical().id_salt("sketch_create_rows").max_height(room).show(ui, |ui| { for f in crate::sketch_families::FAMILIES { let variants: Vec<_> = f.commands.iter().filter_map(|id| cmds.iter().find(|c| c.id == *id).copied()).collect(); @@ -1351,7 +1720,7 @@ fn drag_ghost(ctx: &egui::Context, id: &str, at: egui::Pos2, removing: bool) { let Some(c) = solidcraft_engine::find_command(id) else { return }; let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("sc_toolbar_drag"))); let r = Rect::from_center_size(at + vec2(14.0, 16.0), vec2(30.0, 30.0)); - p.rect(r, 4.0, t.toolbar.gamma_multiply(0.92), Stroke::new(1.0, if removing { t.error } else { t.accent }), egui::StrokeKind::Inside); + p.rect(r, t.radius_sm, t.toolbar.gamma_multiply(0.92), Stroke::new(1.0, if removing { t.error } else { t.accent }), egui::StrokeKind::Inside); icons::paint(&p, r.shrink(5.0), c.icon, t.icon, t.icon_fill, command_accent(c.icon)); if removing { let s = Stroke::new(2.0, t.error); @@ -1365,7 +1734,7 @@ fn drag_ghost(ctx: &egui::Context, id: &str, at: egui::Pos2, removing: bool) { /// The SELECT panel: what a click in the view picks. fn selection_filter(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); - ui.label(egui::RichText::new(crate::i18n::tr_label("Selection filter")).color(t.text_dim).size(11.0)); + ui.label(egui::RichText::new(crate::i18n::tr_label("Selection filter")).color(t.text_dim).size(t.font_small)); ui.checkbox(&mut app.ui.pick_bodies, crate::i18n::tr_label("Select bodies (a face picks its body)")); for (k, label) in [ ("faces", "Faces"), @@ -1462,7 +1831,7 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) { // is what leaves it, so a second Escape after putting a tool down is harmless. } Key::S if !mods.shift && !mods.alt => { - let at = ctx.input(|i| i.pointer.latest_pos()); + let at = search_anchor(ctx).or_else(|| ctx.input(|i| i.pointer.latest_pos())); crate::shortcut_box::open(app, at); } Key::V => crate::context_menu::toggle_visibility(app), @@ -1535,7 +1904,7 @@ mod header_report_tests { } fn sizes(buttons: &[usize]) -> Vec { - buttons.iter().map(|&b| PanelSize { buttons: b, labelled: false }).collect() + buttons.iter().map(|&b| PanelSize { buttons: vec![ButtonSize { width: BUTTON_MIN_WIDTH, min_width: BUTTON_MIN_WIDTH }; b] }).collect() } fn used_with_more(plans: &[Plan]) -> f32 { @@ -1546,7 +1915,7 @@ mod header_report_tests { fn panels_give_up_one_button_at_a_time_then_move_to_more_and_none_is_dropped() { // A panel with 14 buttons and three default ones. let panels = sizes(&[14, 4, 2, 2]); - let full: f32 = [14, 4, 2, 2].iter().map(|&b| panel_width(b) + PANEL_GAP).sum(); + let full: f32 = [14, 4, 2, 2].iter().map(|&b| panel_width(&vec![BUTTON_MIN_WIDTH; b]) + PANEL_GAP).sum(); let all = |plans: &[Plan]| plans.iter().map(|p| (p.fit, p.shown)).collect::>(); assert_eq!(all(&fit(&panels, full)), [(Fit::Buttons, 14), (Fit::Buttons, 4), (Fit::Buttons, 2), (Fit::Buttons, 2)]); // A little short: the widest panel hands one button to its drop-down; the others keep all theirs. @@ -1556,13 +1925,16 @@ mod header_report_tests { assert_eq!(all(&fit(&panels, collapsed)), [(Fit::Collapsed, 1); 4]); // Narrower: the last one goes into the » menu, and the room it frees goes back to buttons. let more = fit(&panels, collapsed - 1.0); - assert_eq!(more.iter().map(|p| p.fit).collect::>(), [Fit::Buttons, Fit::Buttons, Fit::Collapsed, Fit::More]); + assert_eq!(more.iter().map(|p| p.fit).collect::>(), [Fit::Collapsed, Fit::Collapsed, Fit::Collapsed, Fit::More]); assert!(more.iter().take(3).all(|p| p.shown >= 1)); + let more = fit(&sizes(&[14, 4, 2, 2, 2, 2]), 5.0 * (COLLAPSED_WIDTH + PANEL_GAP) + MORE_ROOM - 1.0); + assert_eq!(more.last().unwrap().fit, Fit::More); + assert!(more.iter().any(|p| p.fit == Fit::Buttons && p.shown > 1), "overflow room restores buttons"); // Then all of them. assert!(fit(&panels, 0.0).iter().all(|p| p.fit == Fit::More)); assert_eq!(fit(&panels, f32::NAN).len(), 4); - // No cap: 40 px a button however many there are. - assert_eq!(panel_width(30) - panel_width(20), 400.0); + // No cap: every additional button keeps its width and gap. + assert_eq!(panel_width(&[BUTTON_MIN_WIDTH; 30]) - panel_width(&[BUTTON_MIN_WIDTH; 20]), 10.0 * (BUTTON_MIN_WIDTH + BUTTON_GAP)); } /// #2108: whatever the room, the toolbar uses it. It never leaves more than one button's width @@ -1579,7 +1951,17 @@ mod header_report_tests { vec![(14, false), (4, false), (2, false), (2, false)], ]; for layout in layouts { - let panels: Vec = layout.iter().map(|&(buttons, labelled)| PanelSize { buttons, labelled }).collect(); + let panels: Vec = layout + .iter() + .map(|&(buttons, labelled)| PanelSize { + buttons: (0..buttons) + .map(|i| ButtonSize { + width: if labelled { BUTTON_MAX_WIDTH - (i % 3) as f32 * 5.0 } else { BUTTON_MIN_WIDTH }, + min_width: BUTTON_MIN_WIDTH, + }) + .collect(), + }) + .collect(); let mut last: Option<(f32, usize)> = None; for room in (0..=2000).rev().map(|r| r as f32) { let plans = fit(&panels, room); @@ -1587,13 +1969,13 @@ mod header_report_tests { let hidden = plans .iter() .zip(&panels) - .any(|(p, s)| p.fit != Fit::Buttons || p.shown < s.buttons || p.stride < if s.labelled { LABELLED_STRIDE } else { STRIDE }); + .any(|(p, s)| p.fit != Fit::Buttons || p.shown < s.buttons.len() || p.widths.iter().zip(&s.buttons).any(|(w, b)| *w < b.width)); let more = plans.iter().filter(|p| p.fit == Fit::More).count(); if more < panels.len() { assert!(width <= room + 0.01, "{layout:?} at {room}: {width} overruns"); } // One button: an icon's stride, or a collapsed panel's when the next panel waits in the » menu. - let button = if more > 0 { COLLAPSED_WIDTH + PANEL_GAP } else { STRIDE }; + let button = if more > 0 { COLLAPSED_WIDTH + PANEL_GAP } else { BUTTON_MIN_WIDTH + BUTTON_GAP }; if hidden && more < panels.len() { assert!(room - width < button, "{layout:?} at {room}: {} px blank while something is hidden", room - width); } @@ -1604,7 +1986,7 @@ mod header_report_tests { last = Some((width, more)); // A panel shows its icons: one at the very least. for (p, s) in plans.iter().zip(&panels) { - if p.fit != Fit::More && s.buttons > 0 { + if p.fit != Fit::More && !s.buttons.is_empty() { assert!(p.shown >= 1, "{layout:?} at {room}: a panel without icons"); } } @@ -1612,29 +1994,85 @@ mod header_report_tests { } } + #[test] + fn variable_width_buttons_narrow_before_rightmost_equal_panels_lose_buttons() { + let panels = vec![PanelSize { + buttons: vec![ + ButtonSize { width: 76.0, min_width: BUTTON_MIN_WIDTH }, + ButtonSize { width: 63.0, min_width: BUTTON_MIN_WIDTH }, + ButtonSize { width: 54.0, min_width: BUTTON_MIN_WIDTH }, + ], + }]; + let full = used(&panels.iter().map(Plan::full).collect::>()); + let narrow = fit(&panels, full - 1.0); + assert_eq!(narrow[0].shown, 3); + assert_eq!(narrow[0].widths, [75.0, 62.0, 54.0]); + let minimum = panel_width(&[BUTTON_MIN_WIDTH; 3]) + PANEL_GAP; + let narrow = fit(&panels, minimum); + assert_eq!(narrow[0].shown, 3); + assert_eq!(narrow[0].widths, [BUTTON_MIN_WIDTH; 3]); + assert_eq!(fit(&panels, minimum - 1.0)[0].shown, 2); + + let equal = sizes(&[3, 3]); + let full = used(&equal.iter().map(Plan::full).collect::>()); + assert_eq!(fit(&equal, full - 1.0).iter().map(|p| p.shown).collect::>(), [3, 2]); + } + + #[test] + fn constraint_gallery_stays_fixed_and_hands_all_cells_to_the_menu_together() { + let panels = vec![PanelSize { + buttons: vec![ + ButtonSize { width: BUTTON_MAX_WIDTH, min_width: BUTTON_MIN_WIDTH }, + ButtonSize { width: CONSTRAINT_GRID_WIDTH, min_width: CONSTRAINT_GRID_WIDTH }, + ], + }]; + let minimum = panel_width(&[BUTTON_MIN_WIDTH, CONSTRAINT_GRID_WIDTH]) + PANEL_GAP; + let narrow = fit(&panels, minimum); + assert_eq!(narrow[0].shown, 2); + assert_eq!(narrow[0].widths, [BUTTON_MIN_WIDTH, CONSTRAINT_GRID_WIDTH]); + let collapsed = fit(&panels, minimum - 1.0); + assert_eq!((collapsed[0].fit, collapsed[0].shown), (Fit::Collapsed, 1)); + } + fn captured_frame(h: &mut crate::scenario::Harness) { let token = h.app.shot_token; crate::issue_report::receive(&mut h.app, token, std::sync::Arc::new(egui::ColorImage::new([2, 2], vec![Color32::GREEN; 4]))); h.frames(3); } + #[test] + fn panel_accents_share_the_tab_mapping_but_constraints_keep_their_role() { + for dark in [false, true] { + for vision in crate::theme::ColorVision::ALL { + let t = Tokens::themed(dark, vision); + for tab in TABS.iter().copied().chain(["SKETCH", "FORM", "RENDER"]) { + assert_eq!(panel_accent(&t, tab, "CREATE"), crate::theme::TabAccent::for_tab(&t, tab).color); + assert_eq!(panel_accent(&t, tab, "CONSTRAIN"), t.glyph_text); + } + } + } + } + #[test] fn header_report_reserves_controls_at_normal_and_double_scale_widths() { for physical_width in [900.0, 1400.0] { for scale in [1.0, 2.0] { let width = physical_width / scale; - let bar = Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 34.0)); + let bar = Rect::from_min_size(egui::Pos2::ZERO, vec2(width, APP_BAR_HEIGHT)); for captions in [0.0, crate::titlebar::WIDTH] { // The English label, and a longer one (Russian is about 125 px). for label_width in [80.0, 125.0] { let (report, labeled) = report_rect(bar, captions, 354.0, label_width); assert!(bar.contains_rect(report)); - let prefs = Rect::from_center_size(pos2(width - captions - 70.0, 17.0), vec2(24.0, 24.0)); - let help = Rect::from_center_size(pos2(help_x(bar, captions), 17.0), vec2(26.0, 26.0)); + let prefs = Rect::from_center_size(pos2(report.left() - 52.0, APP_BAR_HEIGHT / 2.0), vec2(32.0, 32.0)); + let help = Rect::from_center_size(pos2(help_x(report), APP_BAR_HEIGHT / 2.0), vec2(32.0, 32.0)); assert!(!report.intersects(prefs) && !report.intersects(help) && !help.intersects(prefs)); - assert!(report.right() < help.left() && help.right() < prefs.left()); - let full = (REPORT_TEXT_X + label_width + 10.0).max(124.0); - assert_eq!(labeled, width - captions - RIGHT_GROUP - 354.0 >= 216.0 + full); + assert!(prefs.right() < help.left() && help.right() < report.left()); + let full = REPORT_TEXT_X + label_width + 11.0; + assert_eq!( + labeled, + width - captions - if width < 640.0 { 8.0 } else { RIGHT_GROUP } - CLUSTER_BUTTONS - 354.0 >= 216.0 + full + ); if labeled { assert!(REPORT_TEXT_X + label_width < report.width(), "{label_width}: the text overruns its button"); } @@ -1644,9 +2082,7 @@ mod header_report_tests { } } - /// The title bar: the File menu, Undo, Redo and every tab on the left; Help, Report a bug, - /// Preferences and the window's buttons on the right. Home is a tab and the theme a - /// preference, so neither has a button of its own, and Save is in the File menu (Ctrl+S). + /// The 34 px bar groups brand/home, File/Save/Undo/Redo, documents, then the right cluster. #[test] fn title_bar_keeps_tabs_left_and_help_right() { let mut h = crate::scenario::Harness::new(); @@ -1655,22 +2091,40 @@ mod header_report_tests { h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); h.call("ui.resize", json!({"width":1400,"height":720})); h.frames(3); - for gone in ["appbar:home", "appbar:sun", "appbar:moon", "appbar:save"] { + for gone in ["appbar:sun", "appbar:moon", "toolbar:ai"] { assert!(crate::scenario::handle_at(gone).is_none(), "{gone} is no longer in the title bar"); } let at = |name: &str| crate::scenario::handle_at(name).unwrap_or_else(|| panic!("{name}")).x; let [report, _] = h.widget("Report a bug").unwrap(); let file = h.widget("File").expect("the File menu has a label"); assert_eq!(file[0] as f32, at("appbar:file")); - assert!(at("appbar:file") < at("appbar:undo") && at("appbar:undo") < at("appbar:redo")); - assert!(at("appbar:redo") < at("tab:home") && at("tab:home") < at("tab:design:0")); - assert!((at("tab:design:0") as f64) < report && report < at("appbar:help") as f64); - assert!(at("appbar:help") < at("titlebar:preferences")); + assert_eq!(APP_BAR_HEIGHT, 34.0); + let rect = |name: &str| crate::scenario::rect_of(name).unwrap(); + let first = rect("titlebar:separator:brand"); + let second = rect("titlebar:separator:documents"); + assert_eq!(first.size(), vec2(1.0, 20.0)); + assert_eq!(second.size(), vec2(1.0, 20.0)); + assert_eq!(first.center().y, 17.0); + assert_eq!(second.center().y, 17.0); + assert!(rect("titlebar:home").right() < first.left()); + assert!(first.right() < rect("appbar:file").left()); + assert!(at("appbar:file") < at("titlebar:save") && at("titlebar:save") < at("appbar:undo") && at("appbar:undo") < at("appbar:redo")); + assert!(rect("appbar:redo").right() < second.left()); + assert!(second.right() < rect("tab:design:0").left()); + assert!(at("tab:design:0") < at("titlebar:assistant")); + assert!(at("titlebar:assistant") < at("titlebar:preferences")); + for name in ["titlebar:assistant", "titlebar:preferences", "appbar:help"] { + assert_eq!(rect(name).size(), vec2(32.0, 32.0)); + assert!(rect(name).top() >= 0.0 && rect(name).bottom() <= APP_BAR_HEIGHT); + } + assert!(at("titlebar:preferences") < at("appbar:help") && (at("appbar:help") as f64) < report); + assert!(at("appbar:home") < at("appbar:file")); + assert!(h.widget("Start page").is_some(), "the house button has an accessible name"); h.step(&json!({"click":{"handle":"appbar:help"}})).unwrap(); assert!(h.app.help.menu, "? opens the Help menu"); h.step(&json!({"key":"Escape"})).unwrap(); - h.step(&json!({"click":{"handle":"tab:home"}})).unwrap(); - assert!(h.app.home.open, "the Home tab shows the start page"); + h.step(&json!({"click":{"handle":"appbar:home"}})).unwrap(); + assert!(h.app.home.open, "the house button shows the start page"); let dark = h.app.ui.dark; h.call("ui.prefs", json!({"theme": if dark { "light" } else { "dark" }})); h.frames(2); @@ -1691,9 +2145,9 @@ mod header_report_tests { 2.0 * (1400.0 - crate::titlebar::WIDTH - RIGHT_GROUP - center.x) }; let (en, ru) = (width_in("en"), width_in("ru")); - assert!((en - 124.0).abs() < 0.5, "{en}"); - // "Сообщить об ошибке" needs more than the English button's 124 px. - assert!(ru > 124.0 + 10.0, "{ru}"); + assert!((en - 115.2).abs() < 0.5, "{en}"); + // "Сообщить об ошибке" needs more than the English button's 115 px. + assert!(ru > en + 10.0, "{ru}"); } #[test] @@ -1894,14 +2348,14 @@ mod dropdown_tests { fn a_tall_drop_down_scrolls_inside_a_short_window() { let mut h = crate::scenario::Harness::new(); h.app.home.open = false; - h.call("ui.resize", json!({"width":1200,"height":480})); + h.call("ui.resize", json!({"width":1200,"height":320})); h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); h.frames(4); h.step(&json!({"click":{"handle":"panel:SKETCH:CREATE"}})).unwrap(); h.frames(4); let menu = crate::scenario::rect_of("toolbar_dropdown").expect("the drop-down is open"); - assert!(menu.bottom() <= 480.0, "the drop-down runs past the window: {menu:?}"); - assert!(crate::scenario::handle_at("dropdown:sketch.intersect").is_some_and(|p| !menu.contains(p)), "Intersect starts below the fold"); + assert!(menu.bottom() <= 320.0, "the drop-down runs past the window: {menu:?}"); + assert!(crate::scenario::handle_at("dropdown:sketch.text").is_some_and(|p| !menu.contains(p)), "Text starts below the fold"); // Up from no focus goes to the last enabled row; it scrolls into view. h.step(&json!({"key":"ArrowUp"})).unwrap(); h.frames(10); @@ -1918,10 +2372,10 @@ mod dropdown_tests { let mut h = crate::scenario::Harness::new(); h.app.home.open = false; h.call("ui.resize", json!({"width":1600,"height":1000})); - let open = |h: &mut crate::scenario::Harness, tab: &str| { + let open = |h: &mut crate::scenario::Harness, tab: &str, panel: &str| { h.app.ui.tab = tab.into(); h.frames(4); - h.step(&json!({"click":{"handle":format!("panel:{tab}:MODIFY")}})).unwrap(); + h.step(&json!({"click":{"handle":format!("panel:{tab}:{panel}")}})).unwrap(); h.frames(6); let menu = crate::scenario::rect_of("toolbar_dropdown").expect("the drop-down is open"); let rows = crate::scenario::handles("dropdown:"); @@ -1929,9 +2383,9 @@ mod dropdown_tests { h.frames(4); (menu, rows) }; - let (short, short_rows) = open(&mut h, "MESH"); - let (menu, rows) = open(&mut h, "PLASTIC"); - assert!(rows.len() > short_rows.len(), "PLASTIC MODIFY lists more than MESH MODIFY: {rows:?} vs {short_rows:?}"); + let (short, short_rows) = open(&mut h, "MANAGE", "RULES"); + let (menu, rows) = open(&mut h, "MODEL", "MODIFY"); + assert!(rows.len() > short_rows.len(), "MODEL MODIFY lists more than MANAGE RULES: {rows:?} vs {short_rows:?}"); assert!(menu.height() > short.height(), "the longer list is taller: {menu:?} vs {short:?}"); for (id, at) in &rows { assert!(menu.contains(*at), "{id} at {at:?} is cut off by the drop-down {menu:?}"); @@ -1947,21 +2401,22 @@ mod panel_drop_tests { fn panel_label_gap_and_margins_append_while_buttons_insert_before() { for target in ["label", "gap", "left margin", "right margin", "button"] { let mut h = crate::scenario::Harness::new(); - h.step(&json!({"click":{"handle":"panel:SOLID:CREATE"}})).unwrap(); - let label = crate::scenario::handle_at("panel:SOLID:CREATE").unwrap(); + h.step(&json!({"click":{"handle":"panel:MODEL:CREATE"}})).unwrap(); + let label = crate::scenario::handle_at("panel:MODEL:CREATE").unwrap(); + let panel = crate::scenario::rect_of("panel:MODEL:CREATE").unwrap(); let destination = match target { "gap" => label - vec2(0.0, 10.0), - "left margin" => pos2(label.x - panel_width(4) / 2.0 + 1.0, label.y - 30.0), - "right margin" => pos2(label.x + panel_width(4) / 2.0 - 1.0, label.y - 30.0), + "left margin" => pos2(panel.left() + 1.0, label.y - 30.0), + "right margin" => pos2(panel.right() - 1.0, label.y - 30.0), "button" => crate::scenario::handle_at("button:solid.extrude").unwrap(), _ => label, }; h.step(&json!({"drag":[{"handle":"dropdown:solid.cylinder"}, [destination.x,destination.y]],"steps":12})).unwrap(); h.step(&json!({"key":"Escape"})).unwrap(); let order = if target == "button" { - json!(["button:sketch.create", "button:solid.cylinder", "button:solid.extrude", "button:solid.revolve", "button:solid.sweep"]) + json!(["button:solid.cylinder", "button:solid.extrude", "button:solid.revolve", "button:solid.hole"]) } else { - json!(["button:sketch.create", "button:solid.extrude", "button:solid.revolve", "button:solid.sweep", "button:solid.cylinder"]) + json!(["button:solid.extrude", "button:solid.revolve", "button:solid.hole", "button:solid.cylinder"]) }; h.step(&json!({"expect":{"handle_order":order,"tool":null,"dialog":null,"errors":0}})).unwrap(); assert!(h.app.session.doc.features.is_empty(), "{target}: pinning must not run the command"); @@ -1973,10 +2428,10 @@ mod panel_drop_tests { #[test] fn panel_label_drop_moves_a_button_between_panels() { let mut h = crate::scenario::Harness::new(); - h.step(&json!({"drag":[{"handle":"button:solid.extrude"},{"handle":"panel:SOLID:MODIFY"}],"steps":12})).unwrap(); - h.step(&json!({"expect":{"handle_order":["button:solid.fillet","button:solid.chamfer","button:solid.scale","button:solid.extrude"],"tool":null,"dialog":null,"errors":0}})).unwrap(); + h.step(&json!({"drag":[{"handle":"button:solid.extrude"},{"handle":"panel:MODEL:MODIFY"}],"steps":12})).unwrap(); + h.step(&json!({"expect":{"handle_order":["button:solid.fillet","button:solid.chamfer","button:solid.shell","button:solid.extrude"],"tool":null,"dialog":null,"errors":0}})).unwrap(); h.step(&json!({"restart":"close"})).unwrap(); - h.step(&json!({"expect":{"handle_order":["button:solid.scale","button:solid.extrude"]}})).unwrap(); + h.step(&json!({"expect":{"handle_order":["button:solid.shell","button:solid.extrude"]}})).unwrap(); } } @@ -2001,15 +2456,188 @@ mod dropdown_toggle_tests { assert!(h.app.viewport.context_menu.is_some(), "and a third opens it again"); h.step(&json!({"key": "Escape"})).unwrap(); - h.step(&json!({"click": {"handle": "panel:SOLID:CREATE"}})).unwrap(); + h.step(&json!({"click": {"handle": "panel:MODEL:CREATE"}})).unwrap(); h.frames(2); assert!(rect_of("toolbar_dropdown").is_some(), "the first click opens the panel's list"); - h.step(&json!({"click": {"handle": "panel:SOLID:CREATE"}})).unwrap(); + h.step(&json!({"click": {"handle": "panel:MODEL:CREATE"}})).unwrap(); h.frames(2); assert!(rect_of("toolbar_dropdown").is_none(), "the second click closes it"); } } +#[cfg(test)] +mod app_bar_tests { + use super::*; + + #[test] + fn bar_hover_inks_and_dividers_remain_readable_in_both_themes() { + fn luminance(c: Color32) -> f32 { + let c = egui::Rgba::from(c); + 0.2126 * c.r() + 0.7152 * c.g() + 0.0722 * c.b() + } + fn contrast(a: Color32, b: Color32) -> f32 { + let (a, b) = (luminance(a), luminance(b)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) + } + for dark in [false, true] { + for vision in crate::theme::ColorVision::ALL { + let t = Tokens::themed(dark, vision); + for fill in [t.app_bar_hover, t.app_bar_hover_subtle, t.app_bar_hover_button, t.app_bar_hover_strong] { + let channel = |fg: u8, bg: u8| fg.saturating_add((u16::from(bg) * u16::from(255 - fill.a()) / 255) as u8); + let bg = Color32::from_rgb(channel(fill.r(), t.app_bar.r()), channel(fill.g(), t.app_bar.g()), channel(fill.b(), t.app_bar.b())); + assert!(contrast(t.app_bar_text, bg) >= 4.5, "dark={dark}, {vision:?}, {fill:?}"); + } + assert!(contrast(t.app_bar_separator, t.app_bar) >= 3.0); + assert!(contrast(t.app_bar, t.warning) >= 4.5, "approval counts need dark ink on amber"); + } + } + } + + /// Save writes on a worker thread: frames until it has finished. + fn wait_for_save(h: &mut crate::scenario::Harness) { + for _ in 0..500 { + if h.app.saving.is_none() { + break; + } + h.frames(1); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + h.frames(1); + } + + #[test] + fn save_button_uses_the_existing_save_flow_for_new_and_named_designs() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length":2,"width":3,"height":4})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"titlebar:save"}})).unwrap(); + wait_for_save(&mut h); + let path = h.app.session.path.clone().expect("Save chooses a path for an untitled design"); + h.app.run("solid.box", json!({"length":1,"width":1,"height":1,"corner":[10,0,0]})).unwrap(); + h.step(&json!({"click":{"handle":"titlebar:save"}})).unwrap(); + wait_for_save(&mut h); + assert_eq!(h.app.session.path.as_deref(), Some(path.as_str())); + let saved = solidcraft_engine::io::read_design(&std::fs::read(path).unwrap()).unwrap(); + assert_eq!(saved, *h.app.session.doc); + } +} + +#[cfg(test)] +mod ribbon_label_tests { + use super::*; + + #[test] + fn every_promoted_label_wraps_only_at_word_boundaries() { + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + let painter = ui.painter().clone(); + let specs = solidcraft_engine::command_specs(); + for section in crate::workspace::SECTIONS { + let (commands, count) = crate::workspace::layout(section.tab, section.panel, &specs).unwrap(); + for command in commands.iter().take(count) { + for catalog in crate::i18n::LOCALES { + let locale = crate::i18n::Locale::for_language(catalog.id); + let label = locale.label(crate::workspace::ribbon_button_label(command)); + let width = ribbon_button_width(&painter, label) - BUTTON_LABEL_PADDING; + let galley = ribbon_button_galley(&painter, label, width, Color32::WHITE); + assert!(galley.rows.len() <= 2, "{}: {label}", command.id); + assert!(galley.size().x <= width + 0.01, "{}: {label}: {} > {width}", command.id, galley.size().x); + let first = galley.rows.first().unwrap().text(); + let visible = first.strip_suffix('…').unwrap_or(&first); + assert!(label.starts_with(visible), "{}: {label} -> {first}", command.id); + if let Some(second) = galley.rows.get(1) { + let second = second.text(); + let next = second.strip_suffix('…').unwrap_or(&second); + // The second line must start at a legal source boundary, + // including when the first line was ellipsized. + assert!( + label.char_indices().any(|(at, ch)| { + let end = at + ch.len_utf8(); + (ch.is_whitespace() || ch == '/') + && label[end..].trim_start().starts_with(next) + && (first.ends_with('…') || label[..end].trim() == first) + }), + "{}: {label} -> {first:?}, {second:?} breaks inside a word", + command.id + ); + } + } + } + } + for label in ["Rectangular", "Dimension", "Coincident"] { + let width = ribbon_button_width(&painter, label); + assert_eq!(ribbon_button_lines(&painter, label, width - BUTTON_LABEL_PADDING), vec![label]); + assert!((BUTTON_MIN_WIDTH..=BUTTON_MAX_WIDTH).contains(&width)); + } + let finish = solidcraft_engine::find_command("sketch.finish").unwrap(); + let label = crate::workspace::ribbon_button_label(finish); + let width = ribbon_button_width(&painter, label); + assert_eq!(ribbon_button_lines(&painter, label, width - BUTTON_LABEL_PADDING), vec!["Finish", "Sketch"]); + // Exercise full labels and pinned commands too, not just compact defaults. + for (label, width, expected) in [ + ("Coincident", 50.0, vec!["Coincident"]), + ("Rectangular Pattern", 50.0, vec!["Rectangular", "Pattern"]), + ("Move/Copy", 40.0, vec!["Move/", "Copy"]), + ] { + let lines = ribbon_button_lines(&painter, label, width); + // Exact glyph widths depend on the bundled font: verify the source + // word stays on its own line, with only an optional suffix omitted. + assert_eq!(lines.len(), expected.len(), "{label}: {lines:?}"); + for (actual, word) in lines.iter().zip(expected) { + assert!(actual == word || actual.strip_suffix('…').is_some_and(|prefix| word.starts_with(prefix)), "{label}: {lines:?}"); + } + } + let lines = ribbon_button_lines(&painter, "one two three four five", 50.0); + assert_eq!(lines.len(), 2); + assert!(lines[1].ends_with('…')); + let lines = ribbon_button_lines(&painter, "長い日本語のラベル 続き", 50.0); + assert_eq!(lines.len(), 2); + assert!(lines[0].ends_with('…')); + }); + output.textures_delta.clear(); + } +} + +#[cfg(test)] +mod ribbon_gallery_tests { + use super::*; + use crate::scenario::{Harness, rect_of}; + + #[test] + fn constraint_gallery_preserves_button_handles_order_and_pin_actions() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1800,"height":900})); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.frames(3); + let dimension = rect_of("button:sketch.dimension").unwrap(); + let mut cells = Vec::new(); + for id in crate::workspace::CONSTRAINT_GALLERY { + let cell = rect_of(&format!("ribbon:constraint:{id}")).unwrap(); + assert_eq!(cell.size(), vec2(24.0, 20.0)); + assert_eq!(rect_of(&format!("button:{id}")), Some(cell)); + assert!(cell.left() > dimension.right()); + cells.push(cell); + } + for row in cells.chunks(3) { + assert!(row.windows(2).all(|pair| pair[0].right() < pair[1].left() && pair[0].top() == pair[1].top())); + } + for col in 0..3 { + assert_eq!(cells[col].left(), cells[col + 3].left()); + assert!(cells[col].bottom() < cells[col + 3].top()); + } + h.step(&json!({"click":{"handle":"ribbon:constraint:sketch.constraint.equal"}})).unwrap(); + assert_eq!(h.app.tool.as_ref().map(|t| t.cmd), Some("sketch.constraint.equal")); + h.step(&json!({"key":"Escape"})).unwrap(); + crate::toolbar_custom::remove(&mut h.app, "SKETCH", "sketch.constraint.equal"); + h.frames(2); + assert!(rect_of("ribbon:constraint:sketch.constraint.equal").is_none()); + crate::toolbar_custom::pin(&mut h.app, "SKETCH", "sketch.constraint.equal").unwrap(); + h.frames(2); + assert!(rect_of("ribbon:constraint:sketch.constraint.equal").is_some()); + } +} + #[cfg(test)] mod fill_width_tests { use super::*; @@ -2028,15 +2656,15 @@ mod fill_width_tests { if sketch { h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); } - let tab = if sketch { "SKETCH" } else { "SOLID" }; + let tab = if sketch { "SKETCH" } else { "MODEL" }; h.app.ui.tab = tab.into(); for w in [1920.0, 1600.0, 1440.0, 1366.0, 1280.0, 1100.0, 900.0, 700.0] { h.call("ui.resize", json!({"width":w,"height":900})); h.frames(3); let at = format!("{tab} at {w}"); let bar = crate::scenario::rect_of("toolbar").unwrap(); - let ai = crate::scenario::rect_of("toolbar:ai"); - let right = ai.map_or(bar.right(), |a| a.left() - 4.0); + let finish = crate::scenario::rect_of("panel:SKETCH:FINISH SKETCH"); + let right = finish.map_or(bar.right() - 4.0, |f| f.left() - 4.0); let count = |name: &str| crate::scenario::count_of(name).unwrap_or(-1.0); let (collapsed, trimmed, more) = (count("toolbar_collapsed"), count("toolbar_trimmed"), count("toolbar_more")); let lists = crate::toolbar_custom::panel_lists(tab); @@ -2045,7 +2673,9 @@ mod fill_width_tests { for (panel, cmds, promote) in &lists { let Some(rect) = crate::scenario::rect_of(&format!("panel:{tab}:{panel}")) else { continue }; on_bar += 1; - end = end.max(rect.right() + PANEL_GAP); + if *panel != "FINISH SKETCH" { + end = end.max(rect.right() + PANEL_GAP); + } if crate::toolbar_custom::buttons(&h.app, tab, panel, cmds, *promote).is_empty() { continue; } @@ -2059,7 +2689,13 @@ mod fill_width_tests { let gap = right - end - if more > 0.0 { MORE_ROOM } else { 0.0 }; assert!(gap >= -0.5, "{at}: the panels run {} px past the room", -gap); let hidden = collapsed + trimmed + more > 0.0; - let button = if more > 0.0 { COLLAPSED_WIDTH + PANEL_GAP } else { STRIDE }; + let button = if more > 0.0 { + COLLAPSED_WIDTH + PANEL_GAP + } else if sketch { + CONSTRAINT_GRID_WIDTH + BUTTON_GAP + } else { + BUTTON_MIN_WIDTH + BUTTON_GAP + }; if hidden { assert!(gap < button, "{at}: {gap} px left blank while buttons are hidden"); } @@ -2071,21 +2707,32 @@ mod fill_width_tests { assert!(!hidden, "{at}: buttons hidden on a wide window"); } if let Some(o) = overflow { - assert!(o.right() <= right + 4.0, "{at}: the » button under the AI button"); + assert!(o.right() <= right + 4.0, "{at}: the » button overlaps Finish or the right edge"); } - // The tab row stops short of the AI button. + if sketch { + let finish = finish.expect("Finish group stays visible"); + assert_eq!(finish.right(), bar.right(), "{at}: Finish stays anchored right"); + assert!(crate::scenario::handle_at("button:sketch.finish").is_some(), "{at}: Finish stays reachable"); + } + // The assistant lives in the title bar; visible ribbon tabs fit before search. + let search = crate::scenario::rect_of("ribbon:search").unwrap(); for t in TABS.iter().chain(["SKETCH"].iter()) { - if let (Some(r), Some(ai)) = (crate::scenario::rect_of(&format!("toolbar_tab:{t}")), ai) { - assert!(r.right() < ai.left(), "{at}: the {t} tab runs into the AI button"); + if let Some(r) = crate::scenario::rect_of(&format!("toolbar_tab:{t}")) { + assert!(r.right() < search.left(), "{at}: the {t} tab runs into search"); } } - // The title bar: its document tabs end before Report a bug, Help and Preferences. + // The title bar keeps document tabs before Assistant, Preferences, Help and Report. let report = crate::scenario::rect_of("titlebar:report").unwrap(); - let tabs_end = crate::scenario::handles("tab:").iter().map(|(_, p)| p.x).fold(0.0, f32::max); + let tabs_end = crate::scenario::handles("tab:design:").iter().map(|(_, p)| p.x).fold(0.0, f32::max); assert!(tabs_end < report.left(), "{at}: the document tabs run into Report a bug"); - let help = crate::scenario::handle_at("appbar:help").unwrap(); - let prefs = crate::scenario::handle_at("titlebar:preferences").unwrap(); - assert!(report.right() < help.x && help.x < prefs.x, "{at}: the title bar's right-hand controls overlap"); + let assistant = crate::scenario::rect_of("titlebar:assistant").unwrap(); + let help = crate::scenario::rect_of("appbar:help").unwrap(); + let prefs = crate::scenario::rect_of("titlebar:preferences").unwrap(); + assert!(tabs_end < assistant.left(), "{at}: the document tabs run into Assistant"); + assert!( + assistant.right() <= prefs.left() && prefs.right() <= help.left() && help.right() <= report.left(), + "{at}: the title bar's right-hand controls overlap" + ); } } } diff --git a/crates/ui-egui/src/toolbar_custom.rs b/crates/ui-egui/src/toolbar_custom.rs index 2e503e784..26258cb2d 100644 --- a/crates/ui-egui/src/toolbar_custom.rs +++ b/crates/ui-egui/src/toolbar_custom.rs @@ -30,10 +30,12 @@ pub struct ToolbarCustom { impl ToolbarCustom { pub fn prefs(&self) -> Value { - json!(self.panels) + json!({"version": 2, "panels": self.panels}) } pub fn load(&mut self, v: &Value) { - self.panels = v + let current = v.get("version").and_then(Value::as_u64) == Some(2); + let panels = if current { v.get("panels").unwrap_or(&Value::Null) } else { v }; + self.panels = panels .as_object() .map(|o| { o.iter() @@ -45,6 +47,63 @@ impl ToolbarCustom { .collect() }) .unwrap_or_default(); + if !current { + self.migrate(); + } + } + fn migrate(&mut self) { + use std::collections::BTreeSet; + let specs = command_specs(); + let mut pins: BTreeMap> = BTreeMap::new(); + let mut removals: BTreeMap> = BTreeMap::new(); + let old = std::mem::take(&mut self.panels); + for (k, ids) in old { + let parts: Vec<_> = k.split('/').collect(); + let ["DESIGN", tab, panel] = parts.as_slice() else { + self.panels.insert(k, ids); + continue; + }; + if crate::workspace::legacy_panel(tab, panel).is_none() { + self.panels.insert(k, ids); + continue; + } + if let Some((t, p)) = crate::workspace::legacy_panel(tab, panel) { + pins.entry(key(t, p)).or_default(); + } + for id in crate::workspace::legacy_buttons(tab, panel) { + if !ids.iter().any(|x| x == id) + && let Some((t, p)) = crate::workspace::legacy_destination(tab, panel, id) + { + removals.entry(key(t, p)).or_default().insert(id.into()); + } + } + for id in ids { + if let Some((t, p)) = crate::workspace::legacy_destination(tab, panel, &id) { + let list = pins.entry(key(t, p)).or_default(); + if !list.contains(&id) { + list.push(id); + } + } + } + } + let touched: BTreeSet<_> = pins.keys().chain(removals.keys()).cloned().collect(); + for k in touched { + if self.panels.contains_key(&k) { + continue; + } // An existing new destination wins. + let mut ids = pins.remove(&k).unwrap_or_default(); + let parts: Vec<_> = k.split('/').collect(); + if let [_, tab, panel] = parts.as_slice() + && let Some((cmds, n)) = crate::workspace::layout(tab, panel, &specs) + { + for c in cmds.iter().take(n) { + if !ids.iter().any(|id| id == c.id) && !removals.get(&k).is_some_and(|r| r.contains(c.id)) { + ids.push(c.id.into()); + } + } + } + self.panels.insert(k, ids); + } } } @@ -65,13 +124,9 @@ pub fn panel_lists(tab: &str) -> Vec<(&'static str, Vec<&'static CommandSpec>, u let specs = command_specs(); crate::toolbar::panels(tab) .iter() - .map(|panel| { - let (cmds, promote) = match crate::workspace::layout(tab, panel, &specs) { - Some(l) => l, - None => (specs.iter().filter(|c| c.tab == tab && c.panel == *panel).copied().collect(), crate::toolbar::promoted(tab, panel)), - }; - let cmds = crate::sketch_tools::also_in(tab, panel, cmds, &specs); - (*panel, cmds, promote) + .filter_map(|panel| { + let (cmds, n) = crate::workspace::layout(tab, panel, &specs)?; + (!cmds.is_empty() || *panel == "SELECT").then_some((*panel, cmds, n)) }) .collect() } @@ -280,3 +335,44 @@ pub fn window(app: &mut SolveApp, ctx: &egui::Context) { } app.toolbar_custom.customizing = open; } + +#[cfg(test)] +mod migration_tests { + use super::*; + + #[test] + fn legacy_pins_split_merge_and_preserve_removals_and_unknown_keys() { + let mut custom = ToolbarCustom::default(); + custom.load(&json!({ + "DESIGN/SOLID/CREATE":["solid.hole","solid.revolve","solid.move"], + "DESIGN/PLASTIC/CREATE":["plastic.boss","plastic.rest","sketch.create"], + "DESIGN/SOLID/MODIFY":["solid.chamfer"], + "DESIGN/UTILITIES/SELECT":[], + "DESIGN/future/panel":["future.command"], + "OTHER/SOLID/CREATE":["solid.extrude"] + })); + let create = &custom.panels["DESIGN/MODEL/CREATE"]; + assert_eq!(create, &["plastic.boss", "plastic.rest", "solid.hole", "solid.revolve"]); + assert!(!create.iter().any(|id| id == "solid.extrude")); + assert!(custom.panels["DESIGN/MODEL/ARRANGE"].contains(&"solid.move".into())); + assert!(!custom.panels["DESIGN/MODEL/MODIFY"].contains(&"solid.fillet".into())); + assert!(custom.panels["DESIGN/MODEL/MODIFY"].contains(&"solid.chamfer".into())); + assert_eq!(custom.panels["DESIGN/future/panel"], vec!["future.command"]); + assert!(custom.panels.contains_key("OTHER/SOLID/CREATE")); + assert!(!custom.panels.contains_key("DESIGN/SOLID/CREATE")); + let saved = custom.prefs(); + let mut reloaded = ToolbarCustom::default(); + reloaded.load(&saved); + assert_eq!(custom, reloaded, "migration runs once, even for unchanged SKETCH/SURFACE keys"); + } + + #[test] + fn empty_old_panels_keep_default_button_removals() { + let mut custom = ToolbarCustom::default(); + custom.load(&json!({"DESIGN/SOLID/CREATE":[],"DESIGN/SKETCH/CONSTRAINTS":[],"DESIGN/PLASTIC/SETUP":[]})); + assert!(!custom.panels["DESIGN/MODEL/SKETCH"].contains(&"sketch.create".into())); + assert!(!custom.panels["DESIGN/MODEL/CREATE"].contains(&"solid.extrude".into())); + assert!(!custom.panels["DESIGN/MANAGE/RULES"].contains(&"plastic.manage_rules".into())); + assert_eq!(custom.panels["DESIGN/SKETCH/CONSTRAIN"], vec!["sketch.dimension"]); + } +} diff --git a/crates/ui-egui/src/update/tests.rs b/crates/ui-egui/src/update/tests.rs index 0baa62f77..e4724c578 100644 --- a/crates/ui-egui/src/update/tests.rs +++ b/crates/ui-egui/src/update/tests.rs @@ -369,12 +369,13 @@ fn the_title_bar_offers_the_new_version_and_opens_the_update_window() { h.frame(); wait_for_check(&mut h); h.frames(2); - // An accent pill reading "Update to ", just left of Report a bug, on the bar. + // An accent pill reading "Update to ", left of the Settings/Help/Report cluster. let label = format!("Update to {version}"); let at = h.widget(&label).unwrap_or_else(|| panic!("no `{label}` in the title bar")); let pill = crate::scenario::rect_of("titlebar:update").unwrap(); assert!(pill.contains(egui::pos2(at[0] as f32, at[1] as f32))); - assert!(pill.right() <= report.left() && report.left() - pill.right() < 12.0, "beside Report a bug: {pill:?} {report:?}"); + let assistant = crate::scenario::rect_of("titlebar:assistant").unwrap(); + assert!(pill.right() < assistant.left() && assistant.left() - pill.right() < 12.0, "beside Assistant: {pill:?} {assistant:?}"); assert!((pill.center().y - report.center().y).abs() < 1.0 && pill.height() <= report.height()); assert_eq!(crate::scenario::rect_of("titlebar:report"), Some(report), "Report a bug stays where it was"); assert!(!h.app.updater.open, "no window pops up by itself"); @@ -419,7 +420,7 @@ fn the_pill_shortens_in_a_narrow_title_bar() { last = p.width(); } shortened |= pill.is_none_or(|p| p.width() < wide.width()); - if width == 800.0 { + if width == 1000.0 { assert!(h.widget("Update").is_some() && h.widget(&label).is_none(), "the short label keeps room for the tabs"); } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 64d36b710..5d56643c2 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1671,13 +1671,13 @@ fn analysis_legend(app: &SolveApp, painter: &egui::Painter, rect: Rect) { let (pad, row) = (8.0, 18.0); let h = pad * 2.0 + 18.0 + along.as_ref().map_or(0.0, |_| row) + row * rows.len() as f32; let r = Rect::from_min_size(pos2(rect.left() + 12.0, rect.bottom() - 12.0 - h), vec2(230.0, h)); - painter.rect(r, 6.0, t.overlay, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + painter.rect(r, t.radius_md, t.overlay, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); crate::scenario::publish_handle("analysis:legend", r.center()); let mut y = r.top() + pad; - painter.text(pos2(r.left() + pad, y), Align2::LEFT_TOP, title, FontId::proportional(13.0), t.text); + painter.text(pos2(r.left() + pad, y), Align2::LEFT_TOP, title, FontId::proportional(t.font_button), t.text); y += 18.0; if let Some(along) = along { - painter.text(pos2(r.left() + pad, y), Align2::LEFT_TOP, along, FontId::proportional(11.5), t.text_dim); + painter.text(pos2(r.left() + pad, y), Align2::LEFT_TOP, along, FontId::proportional(t.font_caption), t.text_dim); y += row; } for (c, text, hatched) in rows { @@ -1692,7 +1692,7 @@ fn analysis_legend(app: &SolveApp, painter: &egui::Painter, rect: Rect) { ); } } - painter.text(pos2(sw.right() + 8.0, y), Align2::LEFT_TOP, text, FontId::proportional(12.0), t.text); + painter.text(pos2(sw.right() + 8.0, y), Align2::LEFT_TOP, text, FontId::proportional(t.font_body), t.text); y += row; } } @@ -2941,7 +2941,13 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { && let Some((low, high)) = sketch.bounds() && let Some(at) = proj.to_screen(plane.to_world(solidcraft_engine::geom::Vec2::new((low.x + high.x) * 0.5, high.y))) { - painter.text(at - vec2(0.0, 12.0), Align2::CENTER_BOTTOM, "Saved sketch plane — attachment lost", FontId::proportional(12.0), t.warning); + painter.text( + at - vec2(0.0, 12.0), + Align2::CENTER_BOTTOM, + "Saved sketch plane — attachment lost", + FontId::proportional(t.font_body), + t.warning, + ); } if let Some(bx) = app.viewport.boxsel { let col = if bx.crossing { t.box_crossing } else { t.box_window }; @@ -2970,9 +2976,9 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let seconds = ((crate::now_ms() - since) / 1000.0).floor().max(0.0); let text = crate::i18n::format("dialog.computing", &[("seconds", &format!("{seconds:.0}"))]); let pos = pos2(rect.left() + 12.0, rect.bottom() - 76.0); - let galley = painter.layout_no_wrap(text, FontId::proportional(12.5), t.text); + let galley = painter.layout_no_wrap(text, FontId::proportional(t.font_label), t.text); let r = Rect::from_min_size(pos, galley.size() + vec2(34.0, 8.0)); - painter.rect_filled(r, 4.0, t.overlay); + painter.rect_filled(r, t.radius_sm, t.overlay); egui::Spinner::new().size(12.0).paint_at(ui, Rect::from_center_size(pos2(r.left() + 13.0, r.center().y), vec2(12.0, 12.0))); painter.galley(pos + vec2(26.0, 4.0), galley, t.text); ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); @@ -2981,9 +2987,9 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if let Some((msg, at, err)) = app.status.clone() { if crate::now_ms() - at < 6000.0 { let pos = pos2(rect.left() + 12.0, rect.bottom() - 46.0); - let galley = painter.layout_no_wrap(msg, FontId::proportional(12.5), if err { t.error } else { t.text }); + let galley = painter.layout_no_wrap(msg, FontId::proportional(t.font_label), if err { t.error } else { t.text }); let r = Rect::from_min_size(pos, galley.size() + vec2(16.0, 8.0)); - painter.rect_filled(r, 4.0, t.overlay); + painter.rect_filled(r, t.radius_sm, t.overlay); painter.galley(pos + vec2(8.0, 4.0), galley, t.text); // A click opens every message of the run, to read and copy (#2763). crate::scenario::publish_handle("status:chip", r.center()); @@ -3447,7 +3453,7 @@ fn overlays(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { format!("{} — {} degrees of freedom", ss.name, ss.report.dof) }; let c = if ss.report.ok() { t.sketch_accent } else { t.error }; - painter.text(pos2(r.left() + 12.0, r.top() + 12.0), Align2::LEFT_TOP, msg, FontId::proportional(13.0), c); + painter.text(pos2(r.left() + 12.0, r.top() + 12.0), Align2::LEFT_TOP, msg, FontId::proportional(t.font_button), c); } } @@ -3720,7 +3726,7 @@ fn nav_bar(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) { || menu_open; let mut painter = ui.painter_at(rect); painter.set_opacity(if active || app.preferences.navigator_style == crate::prefs::NavigatorStyle::Axes { 1.0 } else { 0.45 }); - painter.rect(bar, 6.0, t.overlay, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + painter.rect(bar, t.radius_md, t.overlay, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); let columns = ((bar.width() - 10.0) / 30.0).round().clamp(1.0, 10.0) as usize; for (i, (icon, tip)) in items.iter().enumerate() { let br = Rect::from_min_size( @@ -3738,7 +3744,7 @@ fn nav_bar(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) { _ => false, }; if active || resp.hovered() { - painter.rect_filled(br, 4.0, if active { t.accent_soft } else { t.hover }); + painter.rect_filled(br, t.radius_sm, if active { t.accent_soft } else { t.hover }); } icons::paint(&painter, br.shrink(4.0), icon, t.icon, t.icon_fill, t.accent); if resp.on_hover_text(*tip).clicked() { @@ -3772,6 +3778,7 @@ fn nav_bar(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) { /// The View settings above the navigation bar's last button: grid, ground shadow and the agent /// cursor (#35). False once it should close (a click outside it). fn view_menu(app: &mut SolveApp, ui: &mut egui::Ui, button: Rect) -> bool { + let t = crate::theme::Tokens::get(); // A preset dropdown extends beyond this menu; let it consume its own clicks. let child_popup_open = egui::Popup::is_any_open(ui.ctx()); let area = crate::frame::area(egui::Id::new("sc_view_menu")) @@ -3781,7 +3788,7 @@ fn view_menu(app: &mut SolveApp, ui: &mut egui::Ui, button: Rect) -> bool { let r = area.show(ui.ctx(), |ui| { egui::Frame::popup(ui.style()).show(ui, |ui| { ui.set_width(220.0); - ui.label(egui::RichText::new(crate::i18n::tr_label("VIEW")).strong().size(11.5)); + ui.label(egui::RichText::new(crate::i18n::tr_label("VIEW")).strong().size(t.font_caption)); ui.label(app.tr("ui.graphics_preset")); crate::prefs::graphics_preset_selector(app, ui); ui.separator(); diff --git a/crates/ui-egui/src/viewport_layout_tests.rs b/crates/ui-egui/src/viewport_layout_tests.rs index 71e827f4d..ff2d81352 100644 --- a/crates/ui-egui/src/viewport_layout_tests.rs +++ b/crates/ui-egui/src/viewport_layout_tests.rs @@ -6,7 +6,7 @@ use solidcraft_engine::render::StandardView; #[test] fn thin_rotated_bounds_fit_using_the_original_full_projection() { for (width, height, scale) in [(1400.0, 900.0, 1.0), (700.0, 450.0, 2.0), (700.0, 360.0, 2.0), (900.0, 720.0, 1.0)] { - let vp = Rect::from_min_max(pos2(250.0, 126.0), pos2(width, height - 30.0)); + let vp = Rect::from_min_max(pos2(250.0, crate::toolbar::APP_BAR_HEIGHT + crate::toolbar::RIBBON_HEIGHT), pos2(width, height - 30.0)); let dock = Rect::from_min_max(pos2(width - 205.0, vp.top()), vp.max); let layout = Layout::new(vp, &[dock], scale, crate::prefs::NavigatorStyle::Axes); assert!(layout.drawable.width() >= 80.0 && layout.drawable.height() >= 30.0, "{layout:?}"); @@ -46,7 +46,7 @@ fn measured_palette_fit_exposes_endpoints_and_layout_changes_preserve_manual_vie h.app.run("sketch.line", json!({"points":[[0,0],[20,0]]})).unwrap(); h.call("ui.view", json!({"view":"top"})); h.settle(); - for (scale, width, height) in [(1.0, 1400.0, 900.0), (2.0, 700.0, 450.0), (2.0, 700.0, 360.0), (1.0, 900.0, 720.0)] { + for (scale, width, height) in [(1.0, 1400.0, 900.0), (2.0, 700.0, 475.0), (2.0, 700.0, 385.0), (1.0, 900.0, 720.0)] { h.call("ui.prefs", json!({"ui_scale":scale})); h.call("ui.resize", json!({"width":width,"height":height})); h.settle(); @@ -124,7 +124,7 @@ fn fit_home_animation_and_manual_takeover_use_one_layout_solution() { #[test] fn measured_navigator_targets_home_and_drag_work_beside_the_palette_at_hidpi() { for style in crate::prefs::NavigatorStyle::ALL { - for (scale, width, height) in [(1.0, 900.0, 720.0), (2.0, 700.0, 450.0), (2.0, 700.0, 360.0)] { + for (scale, width, height) in [(1.0, 900.0, 720.0), (2.0, 700.0, 475.0), (2.0, 700.0, 385.0)] { let mut h = Harness::new(); h.call("ui.prefs", json!({"navigator_style":style})); h.app.preferences.look_at_anim = false; @@ -221,7 +221,7 @@ fn immediate_standard_view_cancels_fit_before_the_measured_frame() { #[test] fn navigation_anchors_ignore_positioned_resized_and_covering_dialogs() { for (width, height, scale) in [(1400.0, 900.0, 1.0), (700.0, 450.0, 2.0), (700.0, 360.0, 2.0)] { - let vp = Rect::from_min_max(pos2(250.0, 126.0), pos2(width, height - 30.0)); + let vp = Rect::from_min_max(pos2(250.0, crate::toolbar::APP_BAR_HEIGHT + crate::toolbar::RIBBON_HEIGHT), pos2(width, height - 30.0)); let baseline = Layout::new(vp, &[], scale, crate::prefs::NavigatorStyle::Axes); assert!(baseline.axis_view.is_positive() && baseline.navigation.is_positive()); assert_eq!(baseline.axis_view.right_top(), vp.right_top()); diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index c8ad5afb9..b6c2ca324 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -1,144 +1,392 @@ -//! Explicit toolbar layouts: Sketch CREATE, the SOLID tab's ASSEMBLE panel, SHEET METAL and -//! PLASTIC. A command is registered on one tab and panel; -//! these panels list the commands they show in order (the first few get big buttons), so Extrude -//! or Joint appear on several tabs. Commands registered on such a panel but not listed follow at -//! the end. +//! Ribbon structure is UI data; command registrations retain their original placements. +//! Explicit ids override the old placement table and can also share a command across sections. use solidcraft_engine::CommandSpec; use solidcraft_engine::doc::FeatureKind; -const ASSEMBLE: &[&str] = &[ - "component.create", - "joint.create", - "joint.as_built", - "component.insert_design", - "joint.origin", - "joint.rigid_group", - "joint.drive", - "joint.motion_link", - "joint.gear", - "joint.rack_pinion", - "joint.screw", - "joint.cam", - "motion.study", - "motion.trace", - "explode.create", - "contact.enable_sets", - "contact.enable_all", - "contact.disable_all", - "contact.create", - "inspect.interference", +pub const TABS: &[&str] = &["MODEL", "SURFACE", "ASSEMBLE", "INSERT", "INSPECT", "MANAGE", "VIEW"]; + +/// Reading order of the compact, three-column constraint gallery. Icons come from each spec. +pub const CONSTRAINT_GALLERY: &[&str] = &[ + "sketch.constraint.horizontal_vertical", + "sketch.constraint.coincident", + "sketch.constraint.tangent", + "sketch.constraint.equal", + "sketch.constraint.parallel", + "sketch.constraint.perpendicular", ]; -const SHEET_CREATE: &[&str] = &[ - "sketch.create", - "sheet.flange", - "sheet.flat_pattern", - "sheet.hem", - "sheet.fold", - "sheet.convert", - "component.create", - "solid.extrude", - "solid.hole", - "solid.thread", - "solid.pattern.rectangular", - "solid.pattern.circular", - "solid.pattern.path", - "solid.mirror", - "joint.origin", -]; +pub struct CommandGroup { + pub label: &'static str, + pub ids: &'static [&'static str], +} -const SHEET_MODIFY: &[&str] = &[ - "sheet.manage_rules", - "sheet.unfold", - "sheet.refold", - "solid.fillet", - "solid.chamfer", - "solid.move", - "solid.align", - "timeline.delete", - "solid.remove", - "material.assign", - "parameters.change", -]; - -const PLASTIC_SETUP: &[&str] = &["plastic.manage_rules", "plastic.assign_rule"]; - -const PLASTIC_CREATE: &[&str] = &[ - "sketch.create", - "plastic.boss", - "plastic.snap_fit", - "plastic.lip", - "plastic.rest", - "component.create", - "solid.extrude", - "solid.revolve", - "solid.sweep", - "solid.loft", - "solid.rib", - "solid.web", - "solid.emboss", - "solid.hole", - "solid.thread", - "solid.box", - "solid.cylinder", - "solid.sphere", - "solid.torus", - "solid.coil", - "solid.pipe", - "solid.pattern.rectangular", - "solid.pattern.circular", - "solid.pattern.path", - "solid.mirror", - "joint.origin", -]; - -/// Panels of a tab, when this module lays the tab out. -pub fn panels(tab: &str) -> Option<&'static [&'static str]> { - match tab { - "SOLID" => Some(&["CREATE", "MODIFY", "ASSEMBLE", "CONFIGURE", "CONSTRUCT", "INSPECT", "INSERT", "SELECT"]), - "PLASTIC" => Some(&["SETUP", "CREATE", "MODIFY", "ASSEMBLE", "CONSTRUCT", "INSPECT", "INSERT", "SELECT"]), - _ => None, +/// Optional headings for section lists. Unlisted commands retain their order at the end. +pub fn groups(tab: &str, panel: &str) -> &'static [CommandGroup] { + match (tab, panel) { + ("MODEL", "MODIFY") => &[ + CommandGroup { label: "Edges", ids: &["solid.fillet", "solid.chamfer"] }, + CommandGroup { + label: "Faces", + ids: &["solid.press_pull", "solid.draft", "solid.offset_face", "solid.replace_face", "solid.split_face", "face.delete"], + }, + CommandGroup { label: "Bodies", ids: &["solid.shell", "solid.combine", "solid.split_body", "solid.scale", "solid.remove"] }, + CommandGroup { label: "Specialise", ids: &["sheet.convert"] }, + ], + _ => &[], } } -/// The commands a panel shows, in order, and how many get a big button; `None` leaves the panel -/// to the registry. -pub fn layout<'a>(tab: &str, panel: &str, specs: &[&'a CommandSpec]) -> Option<(Vec<&'a CommandSpec>, usize)> { - let (ids, promoted, own_tab): (&[&str], usize, &str) = match (tab, panel) { - ("SKETCH", "CREATE") => ( - &[ - "sketch.line", - "sketch.rectangle.two_point", - "sketch.circle.center", - "sketch.arc.three_point", - "sketch.slot.center_to_center", - "sketch.polygon.inscribed", - "sketch.spline.fit_point", - "sketch.point", - ], - 8, - tab, - ), - ("SOLID", "CONFIGURE") => (&["parameters.change", "config.table"], 2, tab), - ("SKETCH", "PATTERN") => (&["sketch.mirror", "sketch.pattern.rectangular", "sketch.pattern.circular"], 3, tab), - ("SOLID" | "SHEET METAL" | "PLASTIC", "ASSEMBLE") => (ASSEMBLE, 3, tab), - ("SHEET METAL", "CREATE") => (SHEET_CREATE, 3, tab), - ("SHEET METAL", "MODIFY") => (SHEET_MODIFY, 2, tab), - ("PLASTIC", "SETUP") => (PLASTIC_SETUP, 2, tab), - ("PLASTIC", "CREATE") => (PLASTIC_CREATE, 5, tab), - // The solid tab's panels. - ("PLASTIC", "MODIFY") => (&[], 4, "SOLID"), - ("SHEET METAL" | "PLASTIC", "CONSTRUCT" | "INSPECT" | "INSERT") => (&[], 2, "SOLID"), - _ => return None, +/// Menu order is independent of the ribbon's promoted-button order. +pub fn grouped_commands<'a>(tab: &str, panel: &str, commands: &[&'a CommandSpec]) -> Vec<(Option<&'static str>, &'a CommandSpec)> { + let groups = groups(tab, panel); + let mut out = Vec::new(); + for group in groups { + let mut heading = Some(group.label); + for id in group.ids { + if let Some(command) = commands.iter().find(|c| c.id == *id) { + out.push((heading.take(), *command)); + } + } + } + out.extend(commands.iter().filter(|c| !groups.iter().any(|g| g.ids.contains(&c.id))).map(|c| (None, *c))); + out +} + +pub struct Section { + pub tab: &'static str, + pub panel: &'static str, + pub promoted: usize, + pub ids: &'static [&'static str], +} + +pub const SECTIONS: &[Section] = &[ + Section { + tab: "MODEL", + panel: "SKETCH", + promoted: 1, + ids: &["sketch.create", "sketch.edit", "sketch.line3d", "sketch.spline3d", "sketch.point3d", "sketch.move3d"], + }, + Section { tab: "MODEL", panel: "CREATE", promoted: 3, ids: &["solid.extrude", "solid.revolve", "solid.hole"] }, + Section { + tab: "MODEL", + panel: "MODIFY", + promoted: 4, + ids: &["solid.fillet", "solid.chamfer", "solid.shell", "solid.press_pull", "sheet.convert"], + }, + Section { + tab: "MODEL", + panel: "ARRANGE", + promoted: 3, + ids: &["solid.move", "solid.mirror", "solid.pattern.rectangular", "solid.align", "solid.pattern.circular", "solid.pattern.path"], + }, + Section { tab: "MODEL", panel: "CONSTRUCT", promoted: 1, ids: &["construct.plane.offset"] }, + Section { tab: "SURFACE", panel: "CREATE", promoted: 4, ids: &["surface.extrude", "surface.revolve", "surface.sweep", "surface.loft"] }, + Section { tab: "SURFACE", panel: "EDIT", promoted: 4, ids: &["surface.trim", "surface.untrim", "surface.extend", "surface.stitch"] }, + Section { tab: "SURFACE", panel: "CONVERT", promoted: 2, ids: &["surface.thicken", "mesh.convert"] }, + Section { + tab: "ASSEMBLE", + panel: "COMPONENTS", + promoted: 4, + ids: &["component.create", "component.from_bodies", "component.insert_design", "parts.library"], + }, + Section { + tab: "ASSEMBLE", + panel: "JOINTS", + promoted: 4, + ids: &[ + "joint.create", + "joint.as_built", + "joint.origin", + "joint.rigid_group", + "joint.limits", + "joint.gear", + "joint.rack_pinion", + "joint.screw", + "joint.cam", + "joint.reach", + ], + }, + Section { + tab: "ASSEMBLE", + panel: "POSITION", + promoted: 3, + ids: &["occurrence.ground", "component.capture_position", "component.revert_position"], + }, + Section { + tab: "ASSEMBLE", + panel: "MOTION", + promoted: 4, + ids: &["joint.drive", "joint.motion_link", "motion.study", "motion.trace", "explode.create"], + }, + Section { + tab: "ASSEMBLE", + panel: "CONTACT", + promoted: 2, + ids: &["contact.enable_sets", "contact.check", "contact.enable_all", "contact.disable_all", "contact.create", "contact.edit", "contact.list"], + }, + Section { + tab: "INSERT", + panel: "FILES", + promoted: 3, + ids: &["file.insert_step", "file.insert_mesh", "component.insert_design", "file.save_mesh"], + }, + Section { tab: "INSERT", panel: "IMAGES", promoted: 3, ids: &["canvas.insert", "canvas.decal", "canvas.edit"] }, + Section { tab: "INSERT", panel: "2D", promoted: 2, ids: &["sketch.insert_dxf", "sketch.insert_svg"] }, + Section { tab: "INSERT", panel: "LIBRARY", promoted: 3, ids: &["parts.fastener", "parts.library", "parts.resize", "parts.insert"] }, + Section { tab: "INSERT", panel: "LINKS", promoted: 2, ids: &["component.update_links", "component.break_link"] }, + Section { tab: "INSPECT", panel: "MEASURE", promoted: 3, ids: &["inspect.measure", "inspect.center_of_mass", "component.properties"] }, + Section { tab: "INSPECT", panel: "SECTION", promoted: 1, ids: &["inspect.section"] }, + Section { + tab: "INSPECT", + panel: "CHECK", + promoted: 4, + ids: &["inspect.interference", "inspect.draft", "inspect.accessibility", "contact.check", "inspect.compare"], + }, + Section { + tab: "INSPECT", + panel: "SURFACE QUALITY", + promoted: 4, + ids: &[ + "inspect.zebra", + "inspect.curvature_map", + "inspect.curvature_comb", + "inspect.isocurve", + "inspect.minimum_radius", + "inspect.environment_map", + "inspect.continuity", + ], + }, + Section { tab: "INSPECT", panel: "HISTORY", promoted: 2, ids: &["timeline.dependents", "document.inspect"] }, + Section { + tab: "MANAGE", + panel: "PARAMETERS", + promoted: 2, + ids: &["parameters.change", "parameters.graph", "parameters.move", "parameters.import", "parameters.export"], + }, + Section { tab: "MANAGE", panel: "CONFIGURATIONS", promoted: 2, ids: &["config.table", "config.configure", "config.rules", "config.preview"] }, + Section { + tab: "MANAGE", + panel: "MATERIALS", + promoted: 2, + ids: &["material.assign", "appearance.assign", "material.properties.validate", "library.inspect", "library.export", "library.apply"], + }, + Section { tab: "MANAGE", panel: "RULES", promoted: 3, ids: &["sheet.manage_rules", "plastic.manage_rules", "plastic.assign_rule"] }, + Section { + tab: "MANAGE", + panel: "DESIGN", + promoted: 2, + ids: &["document.units", "timeline.compute_all", "edit.checkpoint", "edit.restore_checkpoint"], + }, + Section { + tab: "VIEW", + panel: "VIEWS", + promoted: 2, + ids: &["view.apply", "view.save", "view.rename", "view.delete", "view.list", "view.navigate"], + }, + Section { tab: "VIEW", panel: "SELECT", promoted: 0, ids: &[] }, + Section { + tab: "SKETCH", + panel: "CREATE", + promoted: 4, + ids: &["sketch.line", "sketch.rectangle.two_point", "sketch.circle.center", "sketch.arc.three_point", "sketch.infinite"], + }, + Section { + tab: "SKETCH", + panel: "MODIFY", + promoted: 3, + ids: &["sketch.trim", "sketch.offset", "sketch.fillet", "sketch.copy", "sketch.cut", "sketch.paste"], + }, + Section { tab: "SKETCH", panel: "PATTERN", promoted: 3, ids: &["sketch.mirror", "sketch.pattern.circular", "sketch.pattern.rectangular"] }, + Section { + tab: "SKETCH", + panel: "CONSTRAIN", + promoted: 7, + ids: &[ + "sketch.dimension", + "sketch.constraint.horizontal_vertical", + "sketch.constraint.coincident", + "sketch.constraint.tangent", + "sketch.constraint.equal", + "sketch.constraint.parallel", + "sketch.constraint.perpendicular", + "sketch.construction", + "sketch.constrainer", + ], + }, + Section { + tab: "SKETCH", + panel: "REFERENCE", + promoted: 1, + ids: &[ + "sketch.project", + "sketch.intersect", + "sketch.include_3d", + "sketch.project_to_surface", + "sketch.intersection_curve", + "sketch.spun_profile", + "sketch.isoparametric_curve", + "sketch.fit_curves_to_section", + "sketch.insert_dxf", + "sketch.insert_svg", + "canvas.insert", + ], + }, + Section { tab: "SKETCH", panel: "FINISH SKETCH", promoted: 1, ids: &["sketch.finish"] }, + Section { + tab: "SHEET METAL", + panel: "CREATE", + promoted: 4, + ids: &["sheet.flange", "sheet.hem", "sheet.fold", "sheet.perforate", "sheet.convert"], + }, + Section { tab: "SHEET METAL", panel: "FLAT", promoted: 3, ids: &["sheet.unfold", "sheet.refold", "sheet.flat_pattern"] }, + Section { tab: "SHEET METAL", panel: "OUTPUT", promoted: 2, ids: &["sheet.export_dxf", "sheet.export_bend_table"] }, + Section { tab: "SHEET METAL", panel: "RULES", promoted: 1, ids: &["sheet.manage_rules"] }, + Section { tab: "RENDER", panel: "SCENE", promoted: 2, ids: &["render.scene"] }, + Section { tab: "RENDER", panel: "IMAGE", promoted: 1, ids: &["render.start"] }, +]; + +/// Compact source labels for painted big buttons only. Menus, search and tooltips +/// retain the engine label. Route these through `tr_label`, like other UI labels. +pub const RIBBON_LABELS: &[(&str, &str)] = &[ + ("appearance.assign", "Appearance"), + ("component.capture_position", "Capture Pos."), + ("component.create", "New Comp."), + ("component.from_bodies", "From Bodies"), + ("component.insert_design", "Insert"), + ("component.properties", "Properties"), + ("component.revert_position", "Revert Pos."), + ("config.table", "Config Table"), + ("contact.check", "Contact"), + ("contact.enable_sets", "Contact Sets"), + ("document.inspect", "Inspect"), + ("document.units", "Units"), + ("inspect.accessibility", "Access"), + ("inspect.center_of_mass", "Mass Center"), + ("inspect.curvature_comb", "Curv. Comb"), + ("inspect.curvature_map", "Curvature"), + ("inspect.draft", "Draft"), + ("inspect.interference", "Interference"), + ("inspect.isocurve", "Isocurve"), + ("inspect.section", "Section"), + ("inspect.zebra", "Zebra"), + ("joint.as_built", "As-Built"), + ("material.assign", "Material"), + ("parameters.change", "Parameters"), + ("parameters.graph", "Param. Graph"), + ("parts.fastener", "Fastener"), + ("parts.library", "Parts"), + ("parts.resize", "Resize Part"), + ("plastic.assign_rule", "Assign Rule"), + ("plastic.manage_rules", "Plastic Rules"), + ("render.scene", "Scene"), + ("sheet.export_bend_table", "Bend Table"), + ("sheet.export_dxf", "Export DXF"), + ("sheet.flat_pattern", "Flat Pattern"), + ("sheet.manage_rules", "Sheet Rules"), + ("sketch.circle.center", "Circle"), + ("sketch.constraint.coincident", "Coincident"), + ("sketch.constraint.horizontal_vertical", "Horiz./Vert."), + ("sketch.create", "New Sketch"), + ("sketch.dimension", "Dimension"), + ("sketch.finish", "Finish Sketch"), + ("sketch.pattern.circular", "Circular"), + ("sketch.pattern.rectangular", "Rectangular"), + ("sketch.rectangle.two_point", "Rectangle"), + ("solid.move", "Move / Copy"), + ("solid.pattern.rectangular", "Pattern"), + ("surface.extrude", "Extrude"), + ("surface.revolve", "Revolve"), + ("surface.sweep", "Sweep"), + ("timeline.dependents", "Dependents"), + ("view.apply", "Restore View"), + ("view.save", "Save View"), +]; + +pub fn ribbon_button_label(command: &CommandSpec) -> &str { + RIBBON_LABELS.iter().find(|(id, _)| *id == command.id).map_or(command.label, |(_, label)| *label) +} + +/// Registry placement → default ribbon destination, after explicit id overrides. +pub const PLACEMENTS: &[(&str, &str, &str, &str)] = &[ + ("SOLID", "CREATE", "MODEL", "CREATE"), + ("SOLID", "MODIFY", "MODEL", "MODIFY"), + ("SOLID", "CONSTRUCT", "MODEL", "CONSTRUCT"), + ("SOLID", "ASSEMBLE", "ASSEMBLE", "JOINTS"), + ("SOLID", "POSITION", "ASSEMBLE", "POSITION"), + ("SOLID", "CONFIGURE", "MANAGE", "CONFIGURATIONS"), + ("SOLID", "INSPECT", "INSPECT", "CHECK"), + ("SOLID", "INSERT", "INSERT", "FILES"), + ("SURFACE", "CREATE", "SURFACE", "CREATE"), + ("SURFACE", "MODIFY", "SURFACE", "EDIT"), + ("SURFACE", "INSPECT", "INSPECT", "SURFACE QUALITY"), + ("SKETCH", "CREATE", "SKETCH", "CREATE"), + ("SKETCH", "MODIFY", "SKETCH", "MODIFY"), + ("SKETCH", "PATTERN", "SKETCH", "PATTERN"), + ("SKETCH", "CONSTRAINTS", "SKETCH", "CONSTRAIN"), + ("SKETCH", "INSERT", "INSERT", "IMAGES"), + ("SKETCH", "INSPECT", "INSPECT", "SURFACE QUALITY"), + ("SKETCH", "FINISH SKETCH", "SKETCH", "FINISH SKETCH"), + ("SHEET METAL", "CREATE", "SHEET METAL", "CREATE"), + ("SHEET METAL", "MODIFY", "SHEET METAL", "FLAT"), + ("PLASTIC", "CREATE", "MODEL", "CREATE"), + ("PLASTIC", "SETUP", "MANAGE", "RULES"), + ("MESH", "MODIFY", "INSERT", "FILES"), + ("RENDER", "SCENE", "RENDER", "SCENE"), + ("RENDER", "IMAGE", "RENDER", "IMAGE"), +]; + +pub fn panels(tab: &str) -> Vec<&'static str> { + SECTIONS.iter().filter(|s| s.tab == tab).map(|s| s.panel).collect() +} + +pub fn destination(c: &CommandSpec) -> Option<(&'static str, &'static str)> { + // A few shared commands have a canonical home that differs from their first occurrence. + let primary = match c.id { + "sheet.manage_rules" => Some(("MANAGE", "RULES")), + "sheet.convert" => Some(("MODEL", "MODIFY")), + _ => None, }; - let mut out: Vec<&CommandSpec> = ids.iter().filter_map(|id| specs.iter().find(|c| c.id == *id).copied()).collect(); - for c in specs.iter().filter(|c| (c.tab == tab || c.tab == own_tab) && c.panel == panel) { + primary + .or_else(|| SECTIONS.iter().find(|s| s.ids.contains(&c.id)).map(|s| (s.tab, s.panel))) + .or_else(|| PLACEMENTS.iter().find(|(t, p, ..)| *t == c.tab && *p == c.panel).map(|(_, _, t, p)| (*t, *p))) +} + +/// Ordered menu commands, with the promoted commands first. Empty sections are omitted by +/// panel_lists, except the selection filter, which has its own existing controls. +pub fn layout<'a>(tab: &str, panel: &str, specs: &[&'a CommandSpec]) -> Option<(Vec<&'a CommandSpec>, usize)> { + let section = SECTIONS.iter().find(|s| s.tab == tab && s.panel == panel)?; + let mut out: Vec<_> = section.ids.iter().filter_map(|id| specs.iter().find(|c| c.id == *id).copied()).collect(); + for c in specs.iter().filter(|c| destination(c) == Some((section.tab, section.panel))) { if !out.iter().any(|o| o.id == c.id) { out.push(*c); } } - Some((out, promoted)) + Some((out, section.promoted)) +} + +/// Old keys may be split across sections. Resolve each saved button by the same command map; +/// unknown command ids follow the old panel's default destination. +pub fn legacy_destination(tab: &str, panel: &str, id: &str) -> Option<(&'static str, &'static str)> { + legacy_panel(tab, panel)?; + solidcraft_engine::find_command(id).and_then(destination).or_else(|| legacy_panel(tab, panel)) +} + +pub fn legacy_panel(tab: &str, panel: &str) -> Option<(&'static str, &'static str)> { + if panel == "SELECT" && matches!(tab, "SOLID" | "SURFACE" | "MESH" | "SHEET METAL" | "PLASTIC" | "UTILITIES" | "SKETCH") { + return Some(("VIEW", "SELECT")); + } + PLACEMENTS.iter().find(|(t, p, ..)| *t == tab && *p == panel).map(|(_, _, t, p)| (*t, *p)).or(match (tab, panel) { + ("PLASTIC" | "SHEET METAL", "MODIFY") => Some(("MODEL", "MODIFY")), + ("PLASTIC" | "SHEET METAL" | "SURFACE" | "MESH", "ASSEMBLE") => Some(("ASSEMBLE", "JOINTS")), + ("PLASTIC" | "SHEET METAL" | "SURFACE" | "MESH", "CONSTRUCT") => Some(("MODEL", "CONSTRUCT")), + ("PLASTIC" | "SHEET METAL" | "SURFACE" | "MESH", "INSPECT") => Some(("INSPECT", "CHECK")), + ("PLASTIC" | "SHEET METAL" | "SURFACE" | "MESH", "INSERT") => Some(("INSERT", "FILES")), + ("MESH", "CREATE" | "PREPARE") => Some(("SURFACE", "CONVERT")), + ("UTILITIES", "MAKE" | "ADD-INS" | "UTILITY") => Some(("MANAGE", "DESIGN")), + ("UTILITIES", "INSPECT") => Some(("INSPECT", "CHECK")), + _ => None, + }) } /// Timeline and browser icon of the sheet metal and plastic features (`None`: not one of them). @@ -160,23 +408,279 @@ pub fn feature_icon(k: &FeatureKind) -> Option<&'static str> { }) } +/// Selected geometry identifies the active body; without a body selection use the last body +/// of the active component, matching feature dialogs. Rules on unrelated bodies do not count. +pub fn sheet_body(app: &crate::SolveApp) -> Option { + use solidcraft_engine::Sel; + let state = app.session.model.state(); + let selected = app.session.selection.iter().find_map(|s| match s { + Sel::Body { name } => Some(name.as_str()), + Sel::Face { body, .. } | Sel::Edge { body, .. } => Some(body.as_str()), + _ => None, + }); + let body = selected.or_else(|| { + state.bodies.iter().rev().find(|b| app.session.doc.model_body_component(b) == app.session.active_component).map(|b| b.name.as_str()) + })?; + state.sheets.iter().find(|s| s.body == body).map(|s| s.body.clone()) +} + +pub fn visible_tabs(app: &crate::SolveApp) -> Vec<&'static str> { + if crate::render_workspace::active(app) { + return vec!["RENDER"]; + } + let mut tabs = TABS.to_vec(); + if app.session.active_sketch.is_some() { + tabs.push("SKETCH"); + } + if sheet_body(app).is_some() { + tabs.push("SHEET METAL"); + } + tabs +} + +/// Select contextual tabs on entry (or a different sheet body), allowing the other tabs to +/// remain usable for the rest of that context. Sketch takes precedence over sheet metal. +pub fn sync_context(app: &mut crate::SolveApp) { + if crate::render_workspace::active(app) { + return; + } + let context = app.session.active_sketch.map(|id| format!("sketch:{id}")).or_else(|| sheet_body(app).map(|body| format!("sheet:{body}"))); + if app.ui.ribbon_context != context { + app.ui.tab = if app.session.active_sketch.is_some() { + "SKETCH" + } else if context.is_some() { + "SHEET METAL" + } else { + "MODEL" + } + .into(); + app.ui.ribbon_context = context; + } + if !visible_tabs(app).contains(&app.ui.tab.as_str()) { + app.ui.tab = "MODEL".into(); + } +} + +pub fn select_command_tab(app: &mut crate::SolveApp, id: &str) { + sync_context(app); + let Some(c) = solidcraft_engine::find_command(id) else { return }; + // Keep the tab a toolbar click came from when it already lists this shared command. + if crate::toolbar_custom::panel_lists(&app.ui.tab).iter().any(|(_, cmds, _)| cmds.iter().any(|c| c.id == id)) { + return; + } + if let Some((tab, _)) = destination(c) { + if tab == "RENDER" { + return; + } // The Render workspace owns its entry/exit lifecycle. + if visible_tabs(app).contains(&tab) { + app.ui.tab = tab.into(); + } + } +} + +/// Defaults from the previous ribbon, used only to carry removals into the new layout. +pub fn legacy_buttons(tab: &str, panel: &str) -> Vec<&'static str> { + let (ids, n, source): (&[&str], usize, &str) = match (tab, panel) { + ("SKETCH", "CREATE") => ( + &[ + "sketch.line", + "sketch.rectangle.two_point", + "sketch.circle.center", + "sketch.arc.three_point", + "sketch.slot.center_to_center", + "sketch.polygon.inscribed", + "sketch.spline.fit_point", + "sketch.point", + ], + 8, + tab, + ), + ("SKETCH", "PATTERN") => (&["sketch.mirror", "sketch.pattern.rectangular", "sketch.pattern.circular"], 3, tab), + ("SKETCH", "CONSTRAINTS") => (&[], 6, tab), + ("SOLID", "CONFIGURE") => (&["parameters.change", "config.table"], 2, tab), + ("SOLID" | "SHEET METAL" | "PLASTIC", "ASSEMBLE") => (&["component.create", "joint.create", "joint.as_built"], 3, tab), + ("SHEET METAL", "CREATE") => (&["sketch.create", "sheet.flange", "sheet.flat_pattern"], 3, tab), + ("SHEET METAL", "MODIFY") => (&["sheet.manage_rules", "sheet.unfold"], 2, tab), + ("PLASTIC", "SETUP") => (&["plastic.manage_rules", "plastic.assign_rule"], 2, tab), + ("PLASTIC", "CREATE") => (&["sketch.create", "plastic.boss", "plastic.snap_fit", "plastic.lip", "plastic.rest"], 5, tab), + ("SOLID" | "PLASTIC", "MODIFY") => (&[], 4, "SOLID"), + ("SOLID", "CREATE") => (&[], 4, tab), + ("SHEET METAL" | "PLASTIC", "CONSTRUCT" | "INSPECT" | "INSERT") => (&[], 2, "SOLID"), + (_, "FINISH SKETCH") => (&[], 1, tab), + _ => (&[], 2, tab), + }; + let mut out = ids.to_vec(); + for c in solidcraft_engine::command_specs().into_iter().filter(|c| c.tab == source && c.panel == panel) { + if !out.contains(&c.id) { + out.push(c.id); + } + } + out.truncate(n); + out +} + #[cfg(test)] mod tests { use super::*; + use serde_json::json; - fn ids(tab: &str, panel: &str) -> Vec<&'static str> { + #[test] + fn modify_groups_order_commands_and_keep_unlisted_commands_at_the_end() { let specs = solidcraft_engine::command_specs(); - layout(tab, panel, &specs).map(|(v, _)| v.iter().map(|c| c.id).collect()).unwrap_or_default() + let (commands, _) = layout("MODEL", "MODIFY", &specs).unwrap(); + let grouped = grouped_commands("MODEL", "MODIFY", &commands); + assert_eq!(grouped.iter().filter_map(|(h, _)| *h).collect::>(), ["Edges", "Faces", "Bodies", "Specialise"]); + assert_eq!(grouped.len(), commands.len()); + assert_eq!( + grouped.iter().map(|(_, c)| c.id).collect::>(), + [ + "solid.fillet", + "solid.chamfer", + "solid.press_pull", + "solid.draft", + "solid.offset_face", + "solid.replace_face", + "solid.split_face", + "face.delete", + "solid.shell", + "solid.combine", + "solid.split_body", + "solid.scale", + "solid.remove", + "sheet.convert", + "timeline.delete", + ] + ); + let plain = grouped_commands("SURFACE", "CREATE", &commands); + assert!(plain.iter().all(|(h, _)| h.is_none())); + assert_eq!(plain.iter().map(|(_, c)| c.id).collect::>(), commands.iter().map(|c| c.id).collect::>()); } #[test] - fn configure_header_clicks_open_parameters_and_configurations_separately() { + fn promoted_long_labels_have_compact_ribbon_names() { + let specs = solidcraft_engine::command_specs(); + let english: std::collections::BTreeMap = serde_json::from_str(include_str!("../../../assets/locales/en.json")).unwrap(); + for section in SECTIONS { + let (commands, count) = layout(section.tab, section.panel, &specs).unwrap(); + for command in commands.iter().take(count) { + // Gallery cells are icon-only; they retain full names in their tooltips. + if section.tab == "SKETCH" && section.panel == "CONSTRAIN" && CONSTRAINT_GALLERY.contains(&command.id) { + continue; + } + if command.label.chars().count() > 12 || command.label.split_whitespace().any(|word| word.chars().count() > 9) { + assert!(RIBBON_LABELS.iter().any(|(id, _)| *id == command.id), "missing compact label for {}", command.id); + } + } + } + for (id, label) in RIBBON_LABELS { + assert!(solidcraft_engine::find_command(id).is_some(), "unknown command {id}"); + assert!(label.chars().count() <= 13, "{id}: {label}"); + assert!(english.values().any(|value| value == label), "untranslated ribbon label {label}"); + } + assert_eq!(ribbon_button_label(solidcraft_engine::find_command("sketch.create").unwrap()), "New Sketch"); + assert_eq!(solidcraft_engine::find_command("sketch.create").unwrap().label, "Create Sketch"); + } + + #[test] + fn every_placed_command_is_reachable_and_every_layout_id_exists() { + let specs = solidcraft_engine::command_specs(); + let lists: Vec<_> = SECTIONS.iter().map(|s| (s, layout(s.tab, s.panel, &specs).unwrap())).collect(); + for c in specs.iter().filter(|c| !c.tab.is_empty()) { + assert!(lists.iter().any(|(_, (cmds, _))| cmds.iter().any(|x| x.id == c.id)), "lost toolbar command {} ({}/{})", c.id, c.tab, c.panel); + } + for (s, (cmds, n)) in lists { + assert!(n <= 4 || (s.tab == "SKETCH" && s.panel == "CONSTRAIN" && n == 7), "{}/{} promotes {n} commands", s.tab, s.panel); + for id in s.ids { + assert!(specs.iter().any(|c| c.id == *id), "unknown layout id {id}"); + } + let unique: std::collections::BTreeSet<_> = cmds.iter().map(|c| c.id).collect(); + assert_eq!(unique.len(), cmds.len()); + } + } + + #[test] + fn model_defaults_and_shared_commands_follow_the_map() { + let specs = solidcraft_engine::command_specs(); + for (panel, expected) in [ + ("SKETCH", vec!["sketch.create"]), + ("CREATE", vec!["solid.extrude", "solid.revolve", "solid.hole"]), + ("MODIFY", vec!["solid.fillet", "solid.chamfer", "solid.shell", "solid.press_pull"]), + ("ARRANGE", vec!["solid.move", "solid.mirror", "solid.pattern.rectangular"]), + ("CONSTRUCT", vec!["construct.plane.offset"]), + ] { + let (cmds, n) = layout("MODEL", panel, &specs).unwrap(); + assert_eq!(cmds.iter().take(n).map(|c| c.id).collect::>(), expected); + } + for (tab, panel, id) in [ + ("MODEL", "CREATE", "plastic.boss"), + ("INSERT", "FILES", "component.insert_design"), + ("ASSEMBLE", "COMPONENTS", "component.insert_design"), + ("SHEET METAL", "CREATE", "sheet.convert"), + ("SKETCH", "REFERENCE", "canvas.insert"), + ] { + assert!(layout(tab, panel, &specs).unwrap().0.iter().any(|c| c.id == id)); + } + } + + #[test] + fn contextual_tabs_follow_the_active_body_and_allow_other_tabs() { + let mut h = crate::scenario::Harness::new(); + assert_eq!(visible_tabs(&h.app), TABS); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + assert_eq!(h.app.ui.tab, "SKETCH"); + h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[40,30]})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.app.run("sheet.flange", json!({"name":"Sheet", "body_name":"Sheet"})).unwrap(); + assert_eq!(h.app.ui.tab, "SHEET METAL"); + assert!(visible_tabs(&h.app).contains(&"SHEET METAL")); + let path = h.dir.join("sheet.solidcraft"); + h.app.run("file.save", json!({"path":path})).unwrap(); + h.app.ui.tab = "INSPECT".into(); + h.app.run("doc.open", json!({"path":path})).unwrap(); + assert_eq!(h.app.ui.tab, "SHEET METAL", "opening a document re-enters its sheet context"); + + h.app.ui.tab = "INSPECT".into(); + sync_context(&mut h.app); + assert_eq!(h.app.ui.tab, "INSPECT"); + h.app.run("solid.box", json!({"body_name":"Solid", "operation":"new", "length":10, "width":10, "height":10})).unwrap(); + h.app.run("select.set", json!({"items":[{"type":"body","name":"Solid"}]})).unwrap(); + sync_context(&mut h.app); + assert!(!visible_tabs(&h.app).contains(&"SHEET METAL")); + h.app.run("select.set", json!({"items":[{"type":"body","name":"Sheet"}]})).unwrap(); + sync_context(&mut h.app); + assert_eq!(h.app.ui.tab, "SHEET METAL"); + } + + #[test] + fn starts_palette_and_control_use_the_new_destinations() { + let mut h = crate::scenario::Harness::new(); + for (id, tab) in [("parameters.change", "MANAGE"), ("solid.box", "MODEL"), ("surface.patch", "SURFACE")] { + h.step(&json!({"start":id})).unwrap(); + assert_eq!(h.app.ui.tab, tab, "{id}"); + h.step(&json!({"key":"Escape"})).unwrap(); + } + h.step(&json!({"key":"S"})).unwrap(); + h.step(&json!({"text":"Change Parameters"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + assert_eq!(h.app.ui.tab, "MANAGE"); + h.step(&json!({"key":"Escape"})).unwrap(); + crate::palette::submit(&mut h.app, "parameters.change"); + assert_eq!(h.app.ui.tab, "MANAGE"); + h.frames(2); + for tab in TABS { + assert!(crate::scenario::handle_at(&format!("tab:{tab}")).is_some(), "{tab}"); + } + } + + #[test] + fn parameters_and_configurations_open_separately() { use serde_json::json; let mut h = crate::scenario::Harness::new(); - let commands = ids("SOLID", "CONFIGURE"); - assert_eq!(&commands[..2], &["parameters.change", "config.table"]); - assert!(commands.contains(&"config.configure"), "Configure remains available in the dropdown"); - h.step(&json!({"widget":"Parameters"})).unwrap(); + let specs = solidcraft_engine::command_specs(); + let (commands, _) = layout("MANAGE", "CONFIGURATIONS", &specs).unwrap(); + assert!(commands.iter().any(|c| c.id == "config.configure")); + h.step(&json!({"click":{"handle":"tab:MANAGE"}})).unwrap(); + h.step(&json!({"click":{"handle":"button:parameters.change"}})).unwrap(); assert!(h.app.params.is_some(), "the ordinary Parameters button opens the editor"); assert!(h.app.dialog.is_none()); assert!(h.widget("User Parameters").is_some()); @@ -191,7 +695,7 @@ mod tests { assert!(values["parameters"].as_array().unwrap().iter().any(|p| p["name"] == "width" && p["value"] == 25.0)); h.step(&json!({"click":{"handle":"params:close"}})).unwrap(); assert!(h.app.params.is_none()); - h.step(&json!({"widget":"Configurations"})).unwrap(); + h.step(&json!({"click":{"handle":"button:config.table"}})).unwrap(); assert!(h.app.params.is_none()); assert!(matches!( h.app.dialog.as_ref().map(|d| &d.kind), @@ -201,24 +705,46 @@ mod tests { assert!(h.widget("Add Row").is_some()); } - /// Layout: joints on every tab's ASSEMBLE panel, sheet metal and plastic tabs - /// reach the shared solid commands, the plastic rules sit on SETUP. + /// Shared assembly, sheet and plastic commands remain reachable in their ribbon sections. #[test] - fn tabs_share_commands_in_fusion_order() { - for tab in ["SOLID", "SHEET METAL", "PLASTIC"] { - let a = ids(tab, "ASSEMBLE"); - assert_eq!(a.get(1).copied(), Some("joint.create"), "{tab}: {a:?}"); - assert!(a.contains(&"joint.drive") && a.contains(&"component.create")); + fn ribbon_sections_keep_shared_commands_reachable() { + let specs = solidcraft_engine::command_specs(); + let ids = |tab, panel| layout(tab, panel, &specs).unwrap().0.iter().map(|c| c.id).collect::>(); + let joints = ids("ASSEMBLE", "JOINTS"); + assert_eq!(joints.first().copied(), Some("joint.create")); + assert!(ids("ASSEMBLE", "MOTION").contains(&"joint.drive")); + assert!(ids("ASSEMBLE", "COMPONENTS").contains(&"component.create")); + let sheet = ids("SHEET METAL", "CREATE"); + assert_eq!(sheet.first().copied(), Some("sheet.flange")); + assert!(ids("MODEL", "CREATE").contains(&"solid.extrude")); + assert!(ids("SHEET METAL", "FLAT").contains(&"sheet.flat_pattern")); + assert!(ids("SHEET METAL", "FLAT").contains(&"sheet.unfold")); + assert!(ids("MANAGE", "RULES").contains(&"plastic.manage_rules")); + let create = ids("MODEL", "CREATE"); + assert!(create.contains(&"plastic.boss") && create.contains(&"solid.rib") && create.contains(&"plastic.lip")); + assert!(ids("MODEL", "MODIFY").contains(&"solid.shell")); + assert_eq!(panels("MANAGE"), ["PARAMETERS", "CONFIGURATIONS", "MATERIALS", "RULES", "DESIGN"]); + // The former sketch/solid INSPECT panels now share a global INSPECT tab. + for (panel, commands) in [ + ("CHECK", vec!["inspect.interference", "inspect.draft", "inspect.accessibility"]), + ("MEASURE", vec!["inspect.center_of_mass"]), + ( + "SURFACE QUALITY", + vec![ + "inspect.zebra", + "inspect.curvature_map", + "inspect.environment_map", + "inspect.minimum_radius", + "inspect.isocurve", + "inspect.curvature_comb", + ], + ), + ] { + let actual = ids("INSPECT", panel); + for id in commands { + assert!(actual.contains(&id), "{panel}: {id}"); + } } - let c = ids("SHEET METAL", "CREATE"); - assert_eq!(c.get(1).copied(), Some("sheet.flange")); - assert!(c.contains(&"solid.extrude") && c.contains(&"sheet.flat_pattern")); - assert!(ids("SHEET METAL", "MODIFY").contains(&"sheet.unfold")); - assert!(ids("PLASTIC", "SETUP").contains(&"plastic.manage_rules")); - let p = ids("PLASTIC", "CREATE"); - assert!(p.contains(&"plastic.boss") && p.contains(&"solid.rib") && p.contains(&"plastic.lip")); - assert!(ids("PLASTIC", "MODIFY").contains(&"solid.shell")); - assert!(panels("PLASTIC").is_some_and(|p| p.first() == Some(&"SETUP"))); } /// #1240: a saved part reaches an assembly from the ASSEMBLE panel (and the File menu) as a @@ -226,10 +752,8 @@ mod tests { #[test] fn insert_design_is_on_the_assemble_panel_and_inserts_a_saved_part() { use serde_json::json; - for tab in ["SOLID", "SHEET METAL", "PLASTIC"] { - assert!(ids(tab, "ASSEMBLE").contains(&"component.insert_design"), "{tab}"); - } - assert!(!ids("SOLID", "ASSEMBLE")[..3].contains(&"component.insert_design"), "Component, Joint and As-built Joint keep the big buttons"); + let specs = solidcraft_engine::command_specs(); + assert!(layout("ASSEMBLE", "COMPONENTS", &specs).unwrap().0.iter().any(|c| c.id == "component.insert_design")); let mut h = crate::scenario::Harness::new(); let part = h.dir.join("part1.solidcraft"); let mut s = solidcraft_engine::Session::default(); diff --git a/crates/ui-egui/tests/parameter_enter.rs b/crates/ui-egui/tests/parameter_enter.rs index 87f68f097..2c5c545bd 100644 --- a/crates/ui-egui/tests/parameter_enter.rs +++ b/crates/ui-egui/tests/parameter_enter.rs @@ -5,7 +5,10 @@ use solidcraft_ui_egui::scenario::Harness; fn open() -> Harness { let mut h = Harness::new(); - h.step(&json!({"widget":"Parameters"})).unwrap(); + // The Browser's Parameters row starts this command; the ribbon shows only the active tab, so no + // Parameters button is on screen to click. + h.call("ui.start", json!({"command":"parameters.change"})); + h.frames(3); assert!(h.app.params.is_some()); h } diff --git a/crates/ui-egui/tests/parameter_order.rs b/crates/ui-egui/tests/parameter_order.rs index 578344410..20edad879 100644 --- a/crates/ui-egui/tests/parameter_order.rs +++ b/crates/ui-egui/tests/parameter_order.rs @@ -13,7 +13,9 @@ fn arrows_move_user_parameters_up_and_down() { for (n, e) in [("a", "1 mm"), ("b", "2 mm"), ("c", "3 mm")] { h.app.session.execute("parameters.add", &json!({"name": n, "expression": e})).unwrap(); } - h.step(&json!({"widget":"Parameters"})).unwrap(); + // The Browser's Parameters row starts this command; the ribbon shows only the active tab. + h.call("ui.start", json!({"command":"parameters.change"})); + h.frames(3); assert!(h.app.params.is_some()); h.frames(3); h.run(&json!([{"click":{"handle":"param:after:a"}}])).unwrap(); diff --git a/crates/ui-egui/tests/scenarios.rs b/crates/ui-egui/tests/scenarios.rs index e6a5b618e..bd5753090 100644 --- a/crates/ui-egui/tests/scenarios.rs +++ b/crates/ui-egui/tests/scenarios.rs @@ -190,15 +190,12 @@ fn narrow_toolbar_reaches_collapsed_commands() { use serde_json::json; let mut h = Harness::new(); h.run(&json!([ - // Too narrow for every button: the last panels collapse into their drop-down. + // The compact ribbon still fits every button at 640 wide. {"call":"ui.resize","params":{"width":640,"height":800}}, - {"expect":{"shown_handles":["collapsed:SOLID:CONSTRUCT"],"hidden_handles":["button:construct.plane.offset"]}}, - {"click":{"handle":"collapsed:SOLID:CONSTRUCT"}}, - {"expect":{"shown_handles":["dropdown:construct.plane.offset"]}}, - {"key":"Escape"}, - // Narrower: they go into the » menu. - {"call":"ui.resize","params":{"width":480,"height":800}}, - {"expect":{"shown_handles":["toolbar:overflow"],"hidden_handles":["collapsed:SOLID:CONSTRUCT"]}}, + {"expect":{"shown_handles":["button:construct.plane.offset"],"hidden_handles":["toolbar:overflow"]}}, + // Too narrow for every button: the panels go into the » menu. + {"call":"ui.resize","params":{"width":440,"height":800}}, + {"expect":{"shown_handles":["toolbar:overflow"],"hidden_handles":["button:construct.plane.offset"]}}, {"click":{"handle":"toolbar:overflow"}}, {"widget":"CONSTRUCT"}, {"expect":{"shown_handles":["toolbar:construct.plane.offset"]}}, diff --git a/crates/ui-egui/tests/scenarios/ribbon_docked.json b/crates/ui-egui/tests/scenarios/ribbon_docked.json new file mode 100644 index 000000000..488ff2835 --- /dev/null +++ b/crates/ui-egui/tests/scenarios/ribbon_docked.json @@ -0,0 +1,26 @@ +[ + {"note":"Docked ribbon entry points keep the existing workspace menu, section menus, command search and Sketch exit usable after resizing."}, + {"expect":{"shown_handles":["ribbon:workspace","ribbon:search","ribbon:section:MODEL:CREATE","tab:MODEL"],"spans":{"inner":"ribbon:workspace","outer":"toolbar","axis":"y","tol":1}}}, + {"click":{"handle":"ribbon:workspace"}}, + {"call":"ui.menuPick","params":{"item":"ui.workspace.render"}}, + {"expect":{"shown_handles":["tab:RENDER","ribbon:search","ribbon:workspace"]}}, + {"click":{"handle":"ribbon:workspace"}}, + {"call":"ui.menuPick","params":{"item":"ui.workspace.design"}}, + {"click":{"handle":"ribbon:section:MODEL:CREATE"}}, + {"expect":{"shown_handles":["dropdown:solid.extrude"]}}, + {"key":"Escape"}, + {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}}, + {"call":"ui.resize","params":{"width":640,"height":800}}, + {"expect":{"shown_handles":["ribbon:search","button:sketch.finish","ribbon:section:SKETCH:FINISH SKETCH"]}}, + {"click":{"handle":"ribbon:search"}}, + {"text":"sketch.line"}, + {"key":"Enter"}, + {"expect":{"tool":"sketch.line","errors":0}}, + {"key":"Escape"}, + {"click":{"handle":"button:sketch.finish"}}, + {"expect":{"sketching":false,"errors":0}}, + {"call":"ui.resize","params":{"width":320,"height":800}}, + {"key":"S"}, + {"key":"Escape"}, + {"expect":{"errors":0,"shown_handles":["ribbon:search","ribbon:workspace"]}} +] diff --git a/crates/ui-egui/tests/scenarios/s09_step_roundtrip_hole.json b/crates/ui-egui/tests/scenarios/s09_step_roundtrip_hole.json index 46de4f33b..54fc6b196 100644 --- a/crates/ui-egui/tests/scenarios/s09_step_roundtrip_hole.json +++ b/crates/ui-egui/tests/scenarios/s09_step_roundtrip_hole.json @@ -48,10 +48,7 @@ } }, { - "click": [ - 127, - 16 - ] + "click": {"handle": "appbar:file"} }, { "widget": "Export STEP\u2026" @@ -75,10 +72,7 @@ "choose_file": "Untitled.step" }, { - "click": [ - 127, - 16 - ] + "click": {"handle": "appbar:file"} }, { "widget": "Insert STEP\u2026" diff --git a/crates/ui-egui/tests/scenarios/s13_plastic_enclosure.json b/crates/ui-egui/tests/scenarios/s13_plastic_enclosure.json index 610af4458..9de9d17bc 100644 --- a/crates/ui-egui/tests/scenarios/s13_plastic_enclosure.json +++ b/crates/ui-egui/tests/scenarios/s13_plastic_enclosure.json @@ -2,7 +2,7 @@ { "call": "ui.set", "params": { - "tab": "PLASTIC" + "tab": "MODEL" } }, { diff --git a/crates/ui-egui/tests/scenarios/s14_appearance_export.json b/crates/ui-egui/tests/scenarios/s14_appearance_export.json index e97d86cff..ebeb2e1e3 100644 --- a/crates/ui-egui/tests/scenarios/s14_appearance_export.json +++ b/crates/ui-egui/tests/scenarios/s14_appearance_export.json @@ -77,10 +77,7 @@ } }, { - "click": [ - 127, - 16 - ] + "click": {"handle": "appbar:file"} }, { "widget": "Export STEP\u2026" @@ -95,10 +92,7 @@ } }, { - "click": [ - 127, - 16 - ] + "click": {"handle": "appbar:file"} }, { "widget": "Save as mesh\u2026" diff --git a/crates/ui-egui/tests/scenarios/s15_start_page_sample_save_reopen.json b/crates/ui-egui/tests/scenarios/s15_start_page_sample_save_reopen.json index 72746ed98..d0950e537 100644 --- a/crates/ui-egui/tests/scenarios/s15_start_page_sample_save_reopen.json +++ b/crates/ui-egui/tests/scenarios/s15_start_page_sample_save_reopen.json @@ -1,5 +1,5 @@ [ - {"click": [248, 17]}, + {"click": {"handle": "titlebar:home"}}, {"expect": {"home": true}}, {"call": "ui.home", "params": {"sample": 0}}, {"until": {"home": false}}, @@ -12,7 +12,7 @@ {"key": "Enter"}, {"widget": "Close window"}, {"expect": {"param": {"width": 100}, "errors": 0}}, - {"key": "S", "cmd": true}, + {"click": {"handle": "titlebar:save"}}, {"expect": {"file": "Sample Plate.solidcraft"}}, {"key": "N", "cmd": true}, {"expect": {"bodies": 0}}, diff --git a/crates/ui-egui/tests/scenarios/s40_toolbar_customize_persists.json b/crates/ui-egui/tests/scenarios/s40_toolbar_customize_persists.json index 0fa286180..451ee4e0e 100644 --- a/crates/ui-egui/tests/scenarios/s40_toolbar_customize_persists.json +++ b/crates/ui-egui/tests/scenarios/s40_toolbar_customize_persists.json @@ -1,6 +1,6 @@ [ { - "note": "Toolbar customizing like Fusion survives a restart: Pin to Toolbar, Remove from Toolbar, drag to reorder. Toolbar buttons publish handles `toolbar:`. The workspace switcher spans the toolbar's height." + "note": "Toolbar customization survives a restart: Pin to Toolbar, Remove from Toolbar, drag to reorder. Toolbar buttons publish handles `toolbar:`. The workspace switcher spans the toolbar's height." }, { "expect": { @@ -19,7 +19,7 @@ "toolbar:solid.revolve" ], "hidden_handles": [ - "toolbar:solid.shell" + "toolbar:solid.draft" ] } }, @@ -30,7 +30,7 @@ "y": 80, "target": { "type": "toolbar_command", - "id": "solid.shell" + "id": "solid.draft" } } }, @@ -43,7 +43,7 @@ { "expect": { "shown_handles": [ - "toolbar:solid.shell" + "toolbar:solid.draft" ] } }, @@ -74,7 +74,7 @@ { "drag": [ { - "handle": "toolbar:solid.shell" + "handle": "toolbar:solid.draft" }, { "handle": "toolbar:solid.extrude" @@ -85,7 +85,7 @@ { "expect": { "handle_order": [ - "toolbar:solid.shell", + "toolbar:solid.draft", "toolbar:solid.extrude" ] } @@ -96,7 +96,7 @@ { "expect": { "shown_handles": [ - "toolbar:solid.shell" + "toolbar:solid.draft" ], "hidden_handles": [ "toolbar:solid.revolve" @@ -106,7 +106,7 @@ { "expect": { "handle_order": [ - "toolbar:solid.shell", + "toolbar:solid.draft", "toolbar:solid.extrude" ] } diff --git a/crates/ui-egui/tests/scenarios/s46_toolbar_dropdown_hover.json b/crates/ui-egui/tests/scenarios/s46_toolbar_dropdown_hover.json index 675bdf604..1c38cb07a 100644 --- a/crates/ui-egui/tests/scenarios/s46_toolbar_dropdown_hover.json +++ b/crates/ui-egui/tests/scenarios/s46_toolbar_dropdown_hover.json @@ -4,7 +4,7 @@ }, { "click": { - "handle": "panel:SOLID:CREATE" + "handle": "panel:MODEL:CREATE" } }, { @@ -52,7 +52,7 @@ }, { "expect": { - "shown_handles": ["dropdown_hot:sketch.create"] + "shown_handles": ["dropdown_hot:solid.extrude"] } }, { @@ -60,8 +60,8 @@ }, { "expect": { - "shown_handles": ["dropdown_hot:solid.extrude"], - "hidden_handles": ["dropdown_hot:sketch.create"] + "shown_handles": ["dropdown_hot:solid.revolve"], + "hidden_handles": ["dropdown_hot:solid.extrude"] } }, { diff --git a/crates/ui-egui/tests/scenarios/s47_toolbar_drag_from_dropdown.json b/crates/ui-egui/tests/scenarios/s47_toolbar_drag_from_dropdown.json index f207487d3..6f9345186 100644 --- a/crates/ui-egui/tests/scenarios/s47_toolbar_drag_from_dropdown.json +++ b/crates/ui-egui/tests/scenarios/s47_toolbar_drag_from_dropdown.json @@ -9,7 +9,7 @@ } }, { - "click": {"handle": "panel:SOLID:CREATE"} + "click": {"handle": "panel:MODEL:CREATE"} }, { "drag": [{"handle": "dropdown:solid.sphere"}, {"handle": "button:solid.extrude"}], @@ -41,7 +41,7 @@ "note": "The pin icon on a hovered drop-down row pins the command." }, { - "click": {"handle": "panel:SOLID:CREATE"} + "click": {"handle": "panel:MODEL:CREATE"} }, { "move": {"handle": "dropdown:solid.torus"} @@ -74,7 +74,7 @@ "note": "A button dragged back into its open drop-down leaves the toolbar." }, { - "click": {"handle": "panel:SOLID:CREATE"} + "click": {"handle": "panel:MODEL:CREATE"} }, { "drag": [{"handle": "button:solid.torus"}, {"handle": "dropdown:solid.box"}], diff --git a/crates/ui-egui/tests/scenarios/s48_toolbar_many_pins.json b/crates/ui-egui/tests/scenarios/s48_toolbar_many_pins.json index 494576e72..21141b20f 100644 --- a/crates/ui-egui/tests/scenarios/s48_toolbar_many_pins.json +++ b/crates/ui-egui/tests/scenarios/s48_toolbar_many_pins.json @@ -1,6 +1,6 @@ [ { - "note": "#323: every pinned command gets a toolbar button, with no fixed cap. Ten commands pinned to SOLID > CREATE all show as buttons at a wide window; at a narrower one the panel keeps the buttons that fit and its drop-down lists the rest (#2108), then it moves into the » menu, and none is dropped." + "note": "#323: every pinned command gets a toolbar button, with no fixed cap. Ten commands pinned to MODEL > CREATE all show as buttons at a wide window; at a narrower one the panel keeps the buttons that fit and its drop-down lists the rest (#2108), then it moves into the » menu, and none is dropped." }, { "call": "ui.resize", @@ -18,8 +18,8 @@ "button:solid.torus", "button:solid.coil", "button:solid.loft", - "button:solid.mirror", - "button:solid.hole", + "button:solid.rib", + "button:solid.sweep", "button:solid.pipe", "button:solid.thread" ] @@ -134,7 +134,7 @@ "y": 60, "target": { "type": "toolbar_command", - "id": "solid.mirror" + "id": "solid.rib" } } }, @@ -151,7 +151,7 @@ "y": 60, "target": { "type": "toolbar_command", - "id": "solid.hole" + "id": "solid.sweep" } } }, @@ -204,8 +204,8 @@ "button:solid.torus", "button:solid.coil", "button:solid.loft", - "button:solid.mirror", - "button:solid.hole", + "button:solid.rib", + "button:solid.sweep", "button:solid.pipe", "button:solid.thread" ], @@ -217,8 +217,8 @@ "button:solid.torus", "button:solid.coil", "button:solid.loft", - "button:solid.mirror", - "button:solid.hole", + "button:solid.rib", + "button:solid.sweep", "button:solid.pipe", "button:solid.thread" ], @@ -246,13 +246,13 @@ ], "shown_handles": [ "button:solid.extrude", - "panel:SOLID:CREATE" + "panel:MODEL:CREATE" ] } }, { "click": { - "handle": "panel:SOLID:CREATE" + "handle": "panel:MODEL:CREATE" } }, { @@ -264,8 +264,8 @@ "dropdown:solid.torus", "dropdown:solid.coil", "dropdown:solid.loft", - "dropdown:solid.mirror", - "dropdown:solid.hole", + "dropdown:solid.rib", + "dropdown:solid.sweep", "dropdown:solid.pipe", "dropdown:solid.thread" ] @@ -283,8 +283,8 @@ "dropdown:solid.torus", "dropdown:solid.coil", "dropdown:solid.loft", - "dropdown:solid.mirror", - "dropdown:solid.hole", + "dropdown:solid.rib", + "dropdown:solid.sweep", "dropdown:solid.pipe", "dropdown:solid.thread" ] @@ -303,16 +303,16 @@ { "expect": { "hidden_handles": [ - "panel:SOLID:CREATE", - "collapsed:SOLID:CREATE", + "panel:MODEL:CREATE", + "collapsed:MODEL:CREATE", "button:solid.box", "button:solid.cylinder", "button:solid.sphere", "button:solid.torus", "button:solid.coil", "button:solid.loft", - "button:solid.mirror", - "button:solid.hole", + "button:solid.rib", + "button:solid.sweep", "button:solid.pipe", "button:solid.thread" ], @@ -338,8 +338,8 @@ "toolbar:solid.torus", "toolbar:solid.coil", "toolbar:solid.loft", - "toolbar:solid.mirror", - "toolbar:solid.hole", + "toolbar:solid.rib", + "toolbar:solid.sweep", "toolbar:solid.pipe", "toolbar:solid.thread" ] @@ -370,8 +370,8 @@ "button:solid.torus", "button:solid.coil", "button:solid.loft", - "button:solid.mirror", - "button:solid.hole", + "button:solid.rib", + "button:solid.sweep", "button:solid.pipe", "button:solid.thread" ], @@ -406,8 +406,8 @@ "button:solid.torus", "button:solid.coil", "button:solid.loft", - "button:solid.mirror", - "button:solid.hole", + "button:solid.rib", + "button:solid.sweep", "button:solid.pipe", "button:solid.thread" ], diff --git a/crates/ui-egui/tests/scenarios/s49_sketch_point_toolbar.json b/crates/ui-egui/tests/scenarios/s49_sketch_point_toolbar.json index 4dcf2f73e..63300633c 100644 --- a/crates/ui-egui/tests/scenarios/s49_sketch_point_toolbar.json +++ b/crates/ui-egui/tests/scenarios/s49_sketch_point_toolbar.json @@ -1,7 +1,10 @@ [ - {"note":"#191: Point remains a default Sketch CREATE button alongside the drawing families."}, + {"note":"#191: Point is in the Sketch CREATE list; a saved pin can promote it alongside the four drawing families."}, {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}}, - {"expect":{"shown_handles":["button:sketch.line","family:Rectangle","family:Circle","family:Arc","family:Slot","family:Polygon","family:Spline","button:sketch.point"]}}, + {"expect":{"shown_handles":["button:sketch.line","family:Rectangle","family:Circle","family:Arc"],"hidden_handles":["button:sketch.point"]}}, + {"call":"ui.menu","params":{"x":400,"y":80,"target":{"type":"toolbar_command","id":"sketch.point"}}}, + {"call":"ui.menuPick","params":{"item":"Pin to Toolbar"}}, + {"expect":{"shown_handles":["button:sketch.point"]}}, {"click":{"handle":"button:sketch.point"}}, {"expect":{"tool":"sketch.point","dialog":null}}, {"click":{"sketch":[20,15]}}, @@ -19,7 +22,7 @@ {"key":"Escape"}, {"call":"ui.menu","params":{"x":400,"y":80,"target":{"type":"toolbar"}}}, {"call":"ui.menuPick","params":{"item":"Reset Toolbar"}}, - {"expect":{"shown_handles":["button:sketch.point","button:sketch.line"],"errors":0}}, + {"expect":{"shown_handles":["button:sketch.line"],"hidden_handles":["button:sketch.point"],"errors":0}}, {"call":"ui.resize","params":{"width":640,"height":720}}, {"click":{"handle":"panel:SKETCH:CREATE"}}, {"click":{"handle":"dropdown:sketch.point"}}, diff --git a/crates/ui-egui/tests/scenarios/s50_toolbar_panel_drops.json b/crates/ui-egui/tests/scenarios/s50_toolbar_panel_drops.json index 46497bf6b..a064cf716 100644 --- a/crates/ui-egui/tests/scenarios/s50_toolbar_panel_drops.json +++ b/crates/ui-egui/tests/scenarios/s50_toolbar_panel_drops.json @@ -1,20 +1,20 @@ [ {"note":"#333: dropping a dropdown command on a panel label appends it; moving between labels keeps the chosen order after restart."}, - {"click":{"handle":"panel:SOLID:CREATE"}}, - {"drag":[{"handle":"dropdown:solid.cylinder"},{"handle":"panel:SOLID:CREATE"}],"steps":12}, + {"click":{"handle":"panel:MODEL:CREATE"}}, + {"drag":[{"handle":"dropdown:solid.cylinder"},{"handle":"panel:MODEL:CREATE"}],"steps":12}, {"key":"Escape"}, - {"expect":{"handle_order":["button:solid.sweep","button:solid.cylinder"],"dialog":null,"tool":null,"errors":0}}, - {"click":{"handle":"panel:SOLID:CREATE"}}, - {"drag":[{"handle":"dropdown:solid.torus"},{"handle":"panel:SOLID:MODIFY"}],"steps":12}, + {"expect":{"handle_order":["button:solid.hole","button:solid.cylinder"],"dialog":null,"tool":null,"errors":0}}, + {"click":{"handle":"panel:MODEL:CREATE"}}, + {"drag":[{"handle":"dropdown:solid.torus"},{"handle":"panel:MODEL:MODIFY"}],"steps":12}, {"key":"Escape"}, - {"expect":{"handle_order":["button:solid.scale","button:solid.torus"],"dialog":null,"tool":null,"errors":0}}, - {"drag":[{"handle":"button:solid.torus"},{"handle":"panel:SOLID:CREATE"}],"steps":12}, + {"expect":{"handle_order":["button:solid.press_pull","button:solid.torus"],"dialog":null,"tool":null,"errors":0}}, + {"drag":[{"handle":"button:solid.torus"},{"handle":"panel:MODEL:CREATE"}],"steps":12}, {"expect":{"handle_order":["button:solid.cylinder","button:solid.torus"]}}, {"restart":"close"}, - {"expect":{"handle_order":["button:solid.sweep","button:solid.cylinder","button:solid.torus"],"errors":0}}, + {"expect":{"handle_order":["button:solid.hole","button:solid.cylinder","button:solid.torus"],"errors":0}}, {"call":"ui.resize","params":{"width":640,"height":720}}, - {"click":{"handle":"panel:SOLID:CREATE"}}, - {"drag":[{"handle":"dropdown:solid.box"},{"handle":"panel:SOLID:CREATE"}],"steps":12}, + {"click":{"handle":"panel:MODEL:CREATE"}}, + {"drag":[{"handle":"dropdown:solid.box"},{"handle":"panel:MODEL:CREATE"}],"steps":12}, {"key":"Escape"}, {"call":"ui.resize","params":{"width":1600,"height":1000}}, {"expect":{"handle_order":["button:solid.torus","button:solid.box"],"tool":null,"dialog":null,"errors":0}} diff --git a/crates/ui-egui/tests/scenarios/sketch_centerline_toolbar_icon.json b/crates/ui-egui/tests/scenarios/sketch_centerline_toolbar_icon.json index e3e345ca9..dab30c702 100644 --- a/crates/ui-egui/tests/scenarios/sketch_centerline_toolbar_icon.json +++ b/crates/ui-egui/tests/scenarios/sketch_centerline_toolbar_icon.json @@ -6,7 +6,10 @@ {"click": {"plane": "XY"}}, {"expect": {"dialog": null}}, {"click": {"handle": "panel:SKETCH:CREATE"}}, - {"expect": {"shown_handles": ["toolbar:sketch.construction", "toolbar:sketch.centerline"]}}, + {"expect": {"shown_handles": ["toolbar:sketch.centerline"]}}, + {"key": "Escape"}, + {"click": {"handle": "panel:SKETCH:CONSTRAIN"}}, + {"expect": {"shown_handles": ["toolbar:sketch.construction"]}}, {"click": [1000, 500]}, {"start": "sketch.rectangle.two_point"}, {"click": {"sketch": [0, 0]}}, diff --git a/crates/ui-egui/tests/ui_layout.rs b/crates/ui-egui/tests/ui_layout.rs index eb4acd28c..0baefd9c8 100644 --- a/crates/ui-egui/tests/ui_layout.rs +++ b/crates/ui-egui/tests/ui_layout.rs @@ -64,3 +64,78 @@ fn other_windows_fit_on_screen() { } assert!(bad.is_empty(), "{}", bad.join("\n")); } + +/// The docked ribbon reserves the same space in both themes and at narrow widths. The +/// existing panel menus and S box remain usable through the new painted hit targets. +#[test] +fn docked_ribbon_geometry_and_search() { + use solidcraft_ui_egui::{scenario::handle_at, toolbar}; + for theme in ["light", "dark"] { + let mut h = harness(); + h.app.preferences.theme = theme.into(); + for width in [1600.0, 640.0, 320.0] { + h.call("ui.resize", json!({"width":width,"height":1000})); + h.frames(4); + let ribbon = rect_of("toolbar").unwrap(); + let workspace = rect_of("ribbon:workspace").unwrap(); + let search = rect_of("ribbon:search").unwrap(); + assert_eq!(ribbon.top(), toolbar::APP_BAR_HEIGHT); + assert_eq!(ribbon.height(), 117.0); + assert_eq!(ribbon.width(), width); + assert_eq!(workspace.width(), 88.0); + assert_eq!(workspace.top(), ribbon.top()); + assert_eq!(workspace.bottom(), ribbon.bottom() - 1.0); + assert_eq!(search.height(), 24.0); + assert_eq!(search.width(), if width == 1600.0 { 188.0 } else { 24.0 }); + assert!(ribbon.contains_rect(search)); + assert!(search.left() > workspace.right()); + assert!(h.app.viewport.rect.unwrap().top() >= toolbar::APP_BAR_HEIGHT + toolbar::RIBBON_HEIGHT); + h.step(&json!({"click":{"handle":"ribbon:search"}})).unwrap(); + assert!(h.app.ui.palette_open); + let popup = rect_of("ribbon:search_popup").unwrap(); + assert!(popup.top() >= search.bottom()); + assert!(popup.left() <= search.left()); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!h.app.ui.palette_open); + h.step(&json!({"key":"S"})).unwrap(); + assert!(h.app.ui.palette_open); + assert_eq!(rect_of("ribbon:search_popup").unwrap().min, popup.min); + h.step(&json!({"key":"Escape"})).unwrap(); + } + h.call("ui.resize", json!({"width":1600,"height":1000})); + h.frames(4); + let button = rect_of("button:solid.extrude").unwrap(); + assert_eq!(button.height(), 60.0); + assert!(button.width() >= 54.0); + let section = rect_of("ribbon:section:MODEL:CREATE").unwrap(); + assert_eq!(section.height(), 20.0); + assert!(section.top() > button.bottom()); + assert_eq!(section.bottom(), rect_of("toolbar").unwrap().bottom() - 4.0); + assert_eq!(handle_at("panel:MODEL:CREATE"), handle_at("ribbon:section:MODEL:CREATE")); + h.step(&json!({"click":{"handle":"ribbon:section:MODEL:CREATE"}})).unwrap(); + assert!(rect_of("toolbar_dropdown").is_some()); + h.step(&json!({"key":"Escape"})).unwrap(); + h.step(&json!({"click":{"handle":"ribbon:workspace"}})).unwrap(); + assert!(h.app.viewport.context_menu.is_some()); + } +} + +#[test] +fn finish_sketch_stays_at_the_right_when_groups_collapse() { + use solidcraft_ui_egui::scenario::handle_at; + let mut h = Harness::new(); + h.call("engine.execute", json!({"command":"sketch.create","params":{"plane":"XY"}})); + for width in [1600.0, 640.0, 320.0] { + h.call("ui.resize", json!({"width":width,"height":1000})); + h.frames(5); + let ribbon = rect_of("toolbar").unwrap(); + let exit = rect_of("ribbon:section:SKETCH:FINISH SKETCH").unwrap(); + let finish = rect_of("button:sketch.finish").unwrap(); + assert_eq!(exit.right(), ribbon.right() - 3.0); + assert!(ribbon.contains_rect(finish)); + assert!(finish.bottom() < exit.top()); + assert!(handle_at("tab:SKETCH").is_some(), "the selected contextual tab scrolls into view"); + } + h.step(&json!({"click":{"handle":"button:sketch.finish"}})).unwrap(); + assert!(h.app.session.active_sketch.is_none()); +} diff --git a/docs/agent-chat.md b/docs/agent-chat.md index b86aa3adc..c4c80edaa 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -16,13 +16,13 @@ Everything about it is on one page: **Preferences → AI**. - **Show AI features** (on by default) is the master switch. Turned off, SolidCraft shows nothing of it: no AI button, no shortcut, no menu entry, no panel, and nothing is looked for or started. The page stays, so you can turn it back on. -- **Show button in toolbar** (on by default): the **AI** button at the right end of the toolbar +- **Show Assistant button in application bar** (on by default): the **Assistant** icon in the application bar row, which stays there however wide the window is. Turn it off to keep only the shortcut and the menu entry. With AI features on, the panel opens from: -- the **AI** button at the right end of the toolbar; +- the **Assistant** icon in the application bar; - **Ctrl+Shift+A** (Cmd+Shift+A on a Mac), which also works from the chat's own text box; - **View settings** (the last button of the navigation bar under the view) → **Agent chat**. diff --git a/docs/book/src/guide/parameters.md b/docs/book/src/guide/parameters.md index 6ed4fcc01..e0cc5892b 100644 --- a/docs/book/src/guide/parameters.md +++ b/docs/book/src/guide/parameters.md @@ -13,8 +13,8 @@ cursor, replacing selected text and keeping what you typed, so typing `10 + ` an the expression or **Escape** to cancel the edit. Add and edit user parameters through the existing **Change Parameters** command. -In the SOLID toolbar's CONFIGURE panel, click **Parameters** to open the user and model -parameter editor. The separate **Configurations** button opens the configuration table; +In the MANAGE tab's PARAMETERS section, click **Parameters** to open the user and model +parameter editor. The **Configurations** button in CONFIGURATIONS opens the configuration table; **Configure** remains in the dropdown for configuring columns. Press **Enter** in the new parameter's name, expression or comment field to add it. diff --git a/docs/book/src/guide/plastic.md b/docs/book/src/guide/plastic.md index 65cf88cae..b9eadfc0d 100644 --- a/docs/book/src/guide/plastic.md +++ b/docs/book/src/guide/plastic.md @@ -1,6 +1,6 @@ # Plastic parts -The PLASTIC tab has a small enclosure subset: +MODEL → CREATE lists the plastic enclosure features: - **Boss** (`plastic.boss`): screw bosses with a hole, fillets and optional ribs. - **Lip / Groove** (`plastic.lip`): the mating lip and groove along a shell's opening. @@ -9,5 +9,5 @@ The PLASTIC tab has a small enclosure subset: - **Plastic Rules** (`plastic.manage_rules`, `plastic.assign_rule`): wall thickness, draft and clearance per material, used as the features' defaults. -Rib and web (on the SOLID tab) complete the set. These features are checked against +Plastic Rules are in MANAGE → RULES. Rib and web in MODEL → CREATE complete the set. These features are checked against hand-computed geometry. diff --git a/docs/book/src/guide/sheet-metal.md b/docs/book/src/guide/sheet-metal.md index 8e8f3a4b3..e0cc1a1d6 100644 --- a/docs/book/src/guide/sheet-metal.md +++ b/docs/book/src/guide/sheet-metal.md @@ -1,6 +1,7 @@ # Sheet metal -The SHEET METAL tab builds parts from a sheet of constant thickness under a **sheet metal rule** +MODEL → MODIFY offers Convert to Sheet Metal. The contextual SHEET METAL tab appears +when the active body is a sheet, and builds parts from a sheet of constant thickness under a **sheet metal rule** (thickness, bend radius, K-factor), set in **Sheet Metal Rules** (`sheet.manage_rules`). - **Flange** (`sheet.flange`): a base flange from a sketch profile, a contour flange from an open diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md index 16c5d2808..a2648a213 100644 --- a/docs/book/src/guide/ui-tour.md +++ b/docs/book/src/guide/ui-tour.md @@ -7,8 +7,10 @@ and one tab per open design (each with its own undo history, selection and camera; a dot marks unsaved changes). On the right: Report a bug, Help (?), Preferences (which hold the theme) and the window's buttons. -- **Toolbar.** The workspace switcher (DESIGN) sits on the left. The tabs (SOLID, SURFACE, - SHEET METAL, PLASTIC, UTILITIES, and SKETCH while you sketch) hold panels of commands. Click a +- **Toolbar.** The workspace switcher (DESIGN) sits on the left. The tabs (MODEL, SURFACE, + ASSEMBLE, INSERT, INSPECT, MANAGE and VIEW) hold sections of commands. SKETCH appears while + editing a sketch; SHEET METAL appears for the active sheet body. Both select automatically + when entered, and the other tabs remain available. Click a panel's name for all its commands. Drag a command from the dropdown onto a panel's label or empty space to append it; the insertion line shows its destination. Drop onto an existing button to insert before it. Buttons can also move between panels, and the layout is saved. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 12bffc15f..f2c29879b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -139,7 +139,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox. | `ui.sketchToScreen` | `points`: `[[x, y]…]` in active-sketch coordinates | their screen points (null when behind the camera) | | `ui.dialogInput` | `index` | what clicking an input's Select chip does: picks go to that input | | `ui.at` | `world: [x,y,z]` \| `sketch: [x,y]` \| `plane: "XY"` \| `axis: "Z"` \| `dimension: "d1"` (its value text) \| `handle: "arrow"` (a manipulator handle, see `scenario::publish_handle`) | the screen point (a scenario step's target; see `crates/ui-egui/src/scenario.rs`) | -| `ui.handles` | `prefix?` | the handles drawn last frame, `[{name, x, y}]`: toolbar buttons and drop-down items `toolbar:` (the button alone: `button:`; a drop-down row: `dropdown:`, highlighted `dropdown_hot:`, its pin `dropdown_pin:`; Customize Toolbar's check boxes `customize:`), panel labels `panel::`, browser rows `row: