From 9919825ea3fe2ad1f8facb487f83fa8d4f45c6a7 Mon Sep 17 00:00:00 2001 From: Matt Van Horn Date: Sat, 24 Oct 2026 20:46:04 +0000 Subject: [PATCH] Expand All and Collapse All in the Browser (#5190) (#5335) Open or close every Browser folder from the design or a component menu, including folders that start closed. Display only: not saved, not an undo step. --- ROADMAP.md | 2 +- assets/locales/en.json | 2 + assets/locales/ja.json | 2 + assets/locales/zh.json | 2 + crates/engine/src/cmd/browser.rs | 232 ++++++++++++++++++++++++++++- crates/ui-egui/src/browser.rs | 20 +++ crates/ui-egui/src/context_menu.rs | 4 + crates/ui-egui/src/control.rs | 11 +- crates/ui-egui/src/lib.rs | 14 ++ crates/ui-egui/src/menu_tests.rs | 25 ++++ docs/book/src/guide/ui-tour.md | 4 +- docs/control-protocol.md | 2 + 12 files changed, 316 insertions(+), 4 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index e976e5ae3..497786f3b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -55,7 +55,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | M3 | General fillets and chamfers (curved edges, chains, vertex blends); saddle rolling-ball surfaces now use continuous seam sections and arc-length fitting with shared contact boundaries and bounded accuracy checks; tiny rim edges remain selected instead of nearby wall seams when filleting (#2498) | in progress | 30 | | M4 | Files: STEP import (done — [docs/step-import.md](docs/step-import.md)), FreeCAD/Rhino solids through cadmpeg (done, desktop, browser and CLI), 3MF export and 3MF/STL import as mesh bodies (done), 3MF with B-rep face tags ([docs/formats/3mf-face-tags.md](docs/formats/3mf-face-tags.md), done), constant-section parametric mesh reconstruction, DXF sketches, OBJ import | in progress | 6 | | M5 | Persistent naming of faces and edges (docs/book/src/dev/naming.md): faces named from their exact kernel-reported history (sketch curve sides, caps, revolve sections, primitive sides, blends, shell inner walls, pattern/mirror copies; split pieces told apart by the faces around them, lumps of a cut body named after their faces), edges by their faces; fillets/chamfers, sketches on faces, shell/draft/offset/replace faces, hole placements, joint origins and face appearances resolve by name first and warn when the entity split or vanished: done. sheet metal edges by base sketch line and flange side, shell inner faces, sweep and loft roles: done. kernel-reported face history: done (merged faces answer to every name; operations without history yet fall back to geometric names, flagged unverified; format 14 keeps older designs' geometric names). Left: history through sheet metal, plastic, surface and emboss features; FaceSource certificates through history | in progress | 20 | -| M6 | UI depth: selection feedback and origin (done), timeline editing (done: hover and selection highlight modifier faces, including fillets and chamfers; edit feature, history marker drag, dependency-checked single and multi-item reorder, suppress, rename, delete with dependents, re-resolved references; redefining selections refreshes persistent edge/face references while retaining feature identity and dimension names; responsive feature history with width-driven icons/names/title, snapping width resize, bottom/left/browser-stack docking, shared-column collapse, rollback bar, multi-selection and persistent folders), right-docked dialogs (done), live previews for every feature dialog (done), keyboard-first commands with on-canvas value boxes and sketch inline dimensions (done), drag manipulators with automatic join/cut (done: extrude incl. two sides, fillet, shell, hole depth, move, pattern spacing, revolve rotator, extrude taper), dark theme (done), right-click menu with Repeat (done), measure tool (done), section analysis (done), selection filter (done), drag-solve of sketch points (done); appearance controls now preserve body/face/component targeting, named transparent looks, reuse/search and override removal; preferences | in progress | 6 | +| M6 | UI depth: selection feedback and origin (done), timeline editing (done: hover and selection highlight modifier faces, including fillets and chamfers; edit feature, history marker drag, dependency-checked single and multi-item reorder, suppress, rename, delete with dependents, re-resolved references; redefining selections refreshes persistent edge/face references while retaining feature identity and dimension names; responsive feature history with width-driven icons/names/title, snapping width resize, bottom/left/browser-stack docking, shared-column collapse, rollback bar, multi-selection and persistent folders), right-docked dialogs (done), live previews for every feature dialog (done), keyboard-first commands with on-canvas value boxes and sketch inline dimensions (done), drag manipulators with automatic join/cut (done: extrude incl. two sides, fillet, shell, hole depth, move, pattern spacing, revolve rotator, extrude taper), dark theme (done), right-click menu with Repeat (done), measure tool (done), section analysis (done), selection filter (done), drag-solve of sketch points (done); appearance controls now preserve body/face/component targeting, named transparent looks, reuse/search and override removal; Browser Expand All / Collapse All (`browser.expand_all`, `browser.collapse_all`) on the design and component menus; preferences | in progress | 6 | | M7 | Thin extrude (walls along open or closed curves: centre, inside, outside or two sides; mitred corners, crossing walls joined; #721), sweep, loft (incl. to a point), rib and web (to next / depth), emboss (planar faces and exact radial emboss/deboss of bounded orthogonal profiles on complete exterior cylinders/sleeves), thread (cosmetic, and modelled M3–M20 outside and inside: the ISO profile screwed in as a faceted cut), coil (smooth B-spline helical walls), pipe, pattern on path, patterns of bodies and components, replace face (parallel), align, remove, feature copy/paste: done. Unique eligible cylindrical targets are inferred for new Emboss features. Left: general curved-face emboss and exact (unfaceted) modelled threads | in progress | 12 | | M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane, a face or sketch curves swept onto the surface, keeping a side or the picked regions; mutual trim of two surfaces, extended to meet and stitched, #767), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764: edge chains along one or several faces, closed rims paired seam to seam or from picked seams, a dialog), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two sketch curves exact with G0–G3, three or four as the flat patch of their loop, and curve networks: Coons and Gordon surfaces through sketch, 3D-sketch or edge curves, a point for a three-sided side, G1/G2 against the faces along one direction's edges, joined into their body on request; G1/G2 on two sides that meet at a corner waits for the Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770; a toolbar tool with edge markers and a legend, and curvature combs along face isocurves) and a multi-section **loft** with per-end continuity and crown, and guide rails on solid and surface lofts (one or two, scaling or stretching the sections between; #201). Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), and every remaining #757–#772 item | deferred | — | | M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), cams (`joint.cam`: a revolute cam drives a slider or revolute follower along a closed sketch profile or the cam's edges, knife, roller or flat followers, worked out again when the profile changes; drives, studies, closed loops, contact sets), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), motion analysis (joint values and a point's path charted over a study as value, velocity and acceleration; the parts that collide along a study, with the steps where they do), Exploded views (automatic or by hand, shown without changing placements, and exported as an animation coming apart and back together); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Cam and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | diff --git a/assets/locales/en.json b/assets/locales/en.json index 652dda8af..ab5761882 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -645,6 +645,8 @@ "cmd.appearance_list": "List Appearances", "cmd.assembly_bom": "Bill of Materials", "cmd.body_rename": "Rename Body", + "cmd.browser_collapse_all": "Collapse All", + "cmd.browser_expand_all": "Expand All", "cmd.browser_group": "New Group", "cmd.browser_move": "Move Browser Items", "cmd.browser_order": "Order Browser Items", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 3aa0e8bbc..a0a54ec2e 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -645,6 +645,8 @@ "cmd.appearance_list": "外観を一覧表示", "cmd.assembly_bom": "部品表", "cmd.body_rename": "ボディの名前を変更", + "cmd.browser_collapse_all": "すべて折りたたむ", + "cmd.browser_expand_all": "すべて展開", "cmd.browser_group": "新規グループ", "cmd.browser_move": "ブラウザ項目を移動", "cmd.browser_order": "ブラウザ項目の並び順を変更", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index fe36fa52a..ec2262293 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -645,6 +645,8 @@ "cmd.appearance_list": "列出外观", "cmd.assembly_bom": "物料清单", "cmd.body_rename": "重命名实体", + "cmd.browser_collapse_all": "全部折叠", + "cmd.browser_expand_all": "全部展开", "cmd.browser_group": "新建组", "cmd.browser_move": "移动浏览器项目", "cmd.browser_order": "排列浏览器项目", diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rs index 336813879..01c1c36d6 100644 --- a/crates/engine/src/cmd/browser.rs +++ b/crates/engine/src/cmd/browser.rs @@ -2,7 +2,10 @@ //! groups and item order (kept in the design, so they are saved and undone like features). //! //! Browser items are keyed per component folder (`bodies`, `sketches`, `construction`): a body -//! by name, a sketch or construction plane by feature id. +//! by name, a sketch or construction plane by feature id. Expand All / Collapse All return the +//! tree keys the UI opens or closes; they do not change the design. + +use std::collections::BTreeSet; use std::collections::BTreeMap; @@ -46,6 +49,15 @@ pub static COMMANDS: &[CommandSpec] = &[ or tree_folders?: [browser folder or group key: c0/bodies, o:4/sketches, c0/g7, c0/joints, c0/canvases] (the folder or group itself: its items keep their own state); \ or paths?: [[occurrence ids]] (exact placements and descendants), isolate?: bool (requires paths and visible:true). Saved with the design; not an undo step", ), + CommandSpec::new("browser.expand_all", "Expand All", expand_all).icon("folder").noundo().params( + "path?: [occurrence ids] (that placement and its descendants); component?: id (that component's own folders); \ + omit both for the whole tree, including folders that start closed (Origin, Named Views, Features). \ + Display only: open/closed rows are not saved in the design and are not an undo step → open, open_by_default, closed_by_default", + ), + CommandSpec::new("browser.collapse_all", "Collapse All", collapse_all).icon("folder").noundo().params( + "path?: [occurrence ids]; component?: id; omit both for the whole tree (the design row stays open so the first level remains visible). \ + Display only; not an undo step → open, open_by_default, closed_by_default", + ), ]; const FOLDERS: [&str; 3] = ["bodies", "sketches", "construction"]; @@ -376,6 +388,156 @@ fn visibility(s: &mut Session, p: &Value) -> Result { Ok(json!({ "visible": visible, "changed": items.len(), "visibility": s.visibility })) } +/// Browser rows that start open (`c0`, Bodies, placements) vs closed (Origin, Features). +struct FoldKeys { + open: BTreeSet, + closed: BTreeSet, +} + +enum FoldScope { + Tree, + Component(u64), + Occurrence(Vec), +} + +const MAX_FOLD_KEYS: usize = 10_000; +const MAX_FOLD_PLACEMENTS: usize = 100_000; + +fn occurrence_fold_key(path: &[u64]) -> String { + format!("o:{}", path.iter().map(u64::to_string).collect::>().join("/")) +} + +fn fold_path(s: &Session, p: &Value, cmd: &str) -> Result> { + let value = p.get("path").ok_or_else(|| bad(cmd, "`path` is required"))?; + let path = value + .as_array() + .filter(|a| !a.is_empty() && a.len() <= 64) + .and_then(|a| a.iter().map(Value::as_u64).collect::>>()) + .ok_or_else(|| bad(cmd, "`path` must list 1..64 occurrence ids"))?; + s.occurrence_placement(&path).map_err(|e| bad(cmd, e.to_string()))?; + Ok(path) +} + +fn fold_scope(s: &Session, p: &Value, cmd: &str) -> Result { + let has_path = p.get("path").is_some(); + let has_component = p.get("component").is_some(); + if has_path && has_component { + return Err(bad(cmd, "give `path` or `component`, not both")); + } + if has_path { + return Ok(FoldScope::Occurrence(fold_path(s, p, cmd)?)); + } + if has_component { + let id = p.get("component").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "`component` must be a component id"))?; + if id != 0 && !s.doc.components.iter().any(|c| c.id == id) { + return Err(bad(cmd, format!("no component {id}"))); + } + return Ok(if id == 0 { FoldScope::Tree } else { FoldScope::Component(id) }); + } + Ok(FoldScope::Tree) +} + +fn folder_has_items(s: &Session, component: u64, folder: &str) -> bool { + match folder { + "bodies" => s.model.state().bodies.iter().any(|b| s.doc.model_body_component(b) == component), + "sketches" => s.doc.features.iter().any(|f| f.component == component && matches!(f.kind, FeatureKind::Sketch { .. })), + "construction" => s.doc.features.iter().any(|f| f.component == component && is_construction(&f.kind)), + _ => false, + } +} + +fn has_native_features(s: &Session, component: u64) -> bool { + s.doc.features.iter().any(|f| f.component == component && !matches!(f.kind, FeatureKind::Sketch { .. })) +} + +fn collect_component_keys(s: &Session, prefix: &str, component: u64, root_extras: bool, keys: &mut FoldKeys) { + keys.open.insert(prefix.to_string()); + for folder in FOLDERS { + if folder_has_items(s, component, folder) { + keys.open.insert(format!("{prefix}/{folder}")); + } + } + for g in s.doc.browser_groups.iter().filter(|g| g.component == component) { + keys.open.insert(format!("{prefix}/g{}", g.id)); + } + if has_native_features(s, component) { + keys.closed.insert(format!("{prefix}/features")); + } + let occurrence = prefix.starts_with("o:"); + for f in s.doc.features.iter().filter(|f| f.component == component) { + if let FeatureKind::Sketch { sketch, .. } = &f.kind + && !sketch.patterns.is_empty() + { + let key = if occurrence { format!("{prefix}/s:{}/patterns", f.id) } else { format!("s:{}/patterns", f.id) }; + keys.open.insert(key); + } + } + if root_extras { + keys.closed.insert("docsettings".into()); + keys.closed.insert("namedviews".into()); + keys.closed.insert("origin".into()); + if !s.doc.canvases.is_empty() { + keys.open.insert("canvases".into()); + } + if !s.doc.assembly.joints.is_empty() { + keys.open.insert("c0/joints".into()); + } + if s.section.is_some() { + keys.open.insert("analysis".into()); + } + } +} + +fn walk_fold(s: &Session, start: &[u64], root_extras: bool, keys: &mut FoldKeys, cmd: &str) -> Result<()> { + let mut stack = vec![start.to_vec()]; + let mut count = 0usize; + while let Some(path) = stack.pop() { + count += 1; + if count > MAX_FOLD_PLACEMENTS { + return Err(bad(cmd, "expand/collapse exceeds 100000 placements")); + } + let component = if path.is_empty() { 0 } else { s.occurrence_placement(&path)?.component }; + let prefix = if path.is_empty() { "c0".to_string() } else { occurrence_fold_key(&path) }; + collect_component_keys(s, &prefix, component, root_extras && path.is_empty(), keys); + for child in s.occurrence_children(&path)? { + if child.path.len() > 64 { + continue; + } + stack.push(child.path); + } + } + Ok(()) +} + +fn fold_tree(s: &mut Session, p: &Value, open: bool, cmd: &str) -> Result { + let scope = fold_scope(s, p, cmd)?; + let mut keys = FoldKeys { open: BTreeSet::new(), closed: BTreeSet::new() }; + match &scope { + FoldScope::Component(id) => collect_component_keys(s, &format!("c{id}"), *id, false, &mut keys), + FoldScope::Tree => walk_fold(s, &[], true, &mut keys, cmd)?, + FoldScope::Occurrence(path) => walk_fold(s, path, false, &mut keys, cmd)?, + } + if !open && matches!(scope, FoldScope::Tree) { + keys.open.remove("c0"); + } + if keys.open.len().saturating_add(keys.closed.len()) > MAX_FOLD_KEYS { + return Err(bad(cmd, "expand/collapse exceeds 10000 browser rows")); + } + Ok(json!({ + "open": open, + "open_by_default": keys.open.into_iter().collect::>(), + "closed_by_default": keys.closed.into_iter().collect::>(), + })) +} + +fn expand_all(s: &mut Session, p: &Value) -> Result { + fold_tree(s, p, true, "browser.expand_all") +} + +fn collapse_all(s: &mut Session, p: &Value) -> Result { + fold_tree(s, p, false, "browser.collapse_all") +} + fn document_units(s: &mut Session, p: &Value) -> Result { let cmd = "document.units"; let u = str_(p, "units").ok_or_else(|| bad(cmd, "`units` is required"))?; @@ -1383,4 +1545,72 @@ mod tests { } assert_eq!(s.visibility.hidden_folders, vec!["o:4/sketches".to_string()]); } + + fn strs(v: &Value, k: &str) -> Vec { + v.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default() + } + + #[test] + fn expand_and_collapse_all_return_tree_keys_and_are_not_undoable() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + let g = run(&mut s, "browser.group", json!({"folder": "bodies"}))["group"].as_u64().unwrap(); + let created = run(&mut s, "component.create", json!({"name": "Part"})); + let occ = created["occurrence"].as_u64().unwrap(); + let n = s.undo.len(); + + let expanded = run(&mut s, "browser.expand_all", json!({})); + assert_eq!(expanded["open"], true); + let open = strs(&expanded, "open_by_default"); + let closed = strs(&expanded, "closed_by_default"); + assert!(open.contains(&"c0".into()), "{open:?}"); + assert!(open.contains(&"c0/bodies".into()), "{open:?}"); + assert!(open.contains(&format!("c0/g{g}")), "{open:?}"); + assert!(open.contains(&"c0/sketches".into()), "{open:?}"); + assert!(open.contains(&format!("o:{occ}")), "{open:?}"); + assert!(closed.contains(&"origin".into()) && closed.contains(&"namedviews".into()) && closed.contains(&"docsettings".into()), "{closed:?}"); + assert!(closed.contains(&"c0/features".into()), "{closed:?}"); + assert_eq!(s.undo.len(), n, "display-only: no undo step"); + + let collapsed = run(&mut s, "browser.collapse_all", json!({})); + assert_eq!(collapsed["open"], false); + let open = strs(&collapsed, "open_by_default"); + assert!(!open.contains(&"c0".into()), "the design row stays visible: {open:?}"); + assert!(open.contains(&"c0/bodies".into()) && open.contains(&format!("o:{occ}")), "{open:?}"); + + let below = run(&mut s, "browser.collapse_all", json!({"path": [occ]})); + let open = strs(&below, "open_by_default"); + assert!(open.contains(&format!("o:{occ}")), "{open:?}"); + assert!(!open.contains(&"c0/bodies".into()), "{open:?}"); + assert!(strs(&below, "closed_by_default").iter().all(|k| !k.starts_with("c0") && k != "origin"), "{below}"); + + let only = run(&mut s, "browser.expand_all", json!({"component": created["component"]})); + let open = strs(&only, "open_by_default"); + assert!(open.iter().any(|k| k.starts_with('c') && k != "c0" && !k.starts_with("c0/")), "{open:?}"); + assert!(!open.contains(&format!("o:{occ}")), "{open:?}"); + } + + #[test] + fn expand_and_collapse_all_refuse_hostile_scope() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + let created = run(&mut s, "component.create", json!({"name": "Part"})); + let occ = created["occurrence"].as_u64().unwrap(); + for (cmd, p) in [ + ("browser.expand_all", json!({"path": []})), + ("browser.expand_all", json!({"path": "o:1"})), + ("browser.expand_all", json!({"path": [999]})), + ("browser.expand_all", json!({"component": "root"})), + ("browser.collapse_all", json!({"component": 99})), + ("browser.collapse_all", json!({"path": [occ], "component": 0})), + ( + "browser.expand_all", + json!({"path": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65]}), + ), + ] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + } + assert!(s.execute("browser.expand_all", &json!({})).is_ok()); + } } diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 7d669c5d5..59f2875e9 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -570,6 +570,26 @@ pub(crate) fn toggle(app: &mut SolveApp, key: &str, default: bool) { } } +/// Apply Expand All / Collapse All: open-by-default keys live in `collapsed` when closed; +/// closed-by-default keys live in `expanded` when open. +pub fn apply_fold(app: &mut SolveApp, open: bool, open_by_default: &[String], closed_by_default: &[String]) { + if open { + for key in open_by_default { + app.tree.collapsed.remove(key); + } + for key in closed_by_default { + app.tree.expanded.insert(key.clone()); + } + } else { + for key in open_by_default { + app.tree.collapsed.insert(key.clone()); + } + for key in closed_by_default { + app.tree.expanded.remove(key); + } + } +} + /// Everything a frame's rows want done, applied after drawing. #[derive(Default)] struct Actions { diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index ab3499478..8fb0deda0 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -761,6 +761,7 @@ fn occurrence_items(app: &SolveApp, path: &[u64]) -> Vec { item.params = Some(json!({"path": path})); } "ui.export" | "ui.saveMesh" => item.params = Some(json!({"bodies": bodies})), + "browser.expand_all" | "browser.collapse_all" => item.params = Some(json!({"path": path})), _ => {} } } @@ -851,6 +852,9 @@ fn component_items(app: &SolveApp, id: u64) -> Vec { v.push(act("ui.showAll", "Show All Bodies", "eye")); v.push(act("ui.isolate", "Isolate", "body").with(json!({ "bodies": names })).on(!bodies.is_empty() && id != 0)); v.push(act("ui.newGroup", "New Group", "folder").with(json!({ "component": id }))); + v.push(Item::sep()); + v.push(cmd(app, "browser.expand_all", "Expand All").with(json!({ "component": id }))); + v.push(cmd(app, "browser.collapse_all", "Collapse All").with(json!({ "component": id }))); v } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index daf0bef99..e94cba31b 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -119,7 +119,16 @@ fn key_from(name: &str) -> Option { fn execute(app: &mut SolveApp, id: &str, params: Value) -> Result { let r = app.run(id, params); if r.is_ok() - && !matches!(id, "view.layout" | "view.navigate" | "view.ambient_occlusion" | "view.graphics_preset" | "view.history_layout") + && !matches!( + id, + "view.layout" + | "view.navigate" + | "view.ambient_occlusion" + | "view.graphics_preset" + | "view.history_layout" + | "browser.expand_all" + | "browser.collapse_all" + ) && app.session.active_sketch.is_none() && app.session.world_state().bodies.len() == 1 && app.session.undo.len() <= 2 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1fb2775ee..55c11daac 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -812,6 +812,20 @@ impl SolveApp { self.preferences.layout = layout; self.ui.layout = layout; } + if matches!(id, "browser.expand_all" | "browser.collapse_all") { + let strings = |key: &str| -> Vec { + v.get(key) + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).take(10_000).collect()) + .unwrap_or_default() + }; + browser::apply_fold( + self, + v.get("open").and_then(Value::as_bool).unwrap_or(id == "browser.expand_all"), + &strings("open_by_default"), + &strings("closed_by_default"), + ); + } if id == "view.history_layout" { if let Some(width) = v.get("width").and_then(Value::as_f64) { self.preferences.timeline_left_width = ui_kit::history_snap_width(width as f32); diff --git a/crates/ui-egui/src/menu_tests.rs b/crates/ui-egui/src/menu_tests.rs index 338ae6115..ad131cd78 100644 --- a/crates/ui-egui/src/menu_tests.rs +++ b/crates/ui-egui/src/menu_tests.rs @@ -392,6 +392,31 @@ fn browser_folds_are_kept_in_the_preferences() { assert!(other.tree.collapsed.contains("c0/sketches") && other.tree.expanded.contains("origin")); } +#[test] +fn expand_and_collapse_all_open_the_browser_tree_from_the_design_menu() { + let mut app = sample_app(); + let n = app.session.undo.len(); + let root = Target::Component { id: 0 }; + assert!(context_menu::items(&app, &root).iter().any(|i| i.label == "Expand All" && i.id == "browser.expand_all")); + act(&mut app, &root, "Collapse All"); + assert!(app.tree.collapsed.contains("c0/bodies"), "{:?}", app.tree.collapsed); + assert!(!app.tree.collapsed.contains("c0"), "the design row stays open: {:?}", app.tree.collapsed); + assert_eq!(app.session.undo.len(), n); + act(&mut app, &root, "Expand All"); + assert!(!app.tree.collapsed.contains("c0/bodies"), "{:?}", app.tree.collapsed); + assert!(app.tree.expanded.contains("origin") && app.tree.expanded.contains("c0/features"), "{:?}", app.tree.expanded); + assert_eq!(app.session.undo.len(), n); + + let created = app.run("component.create", json!({"name": "Part"})).unwrap(); + let occ = created["occurrence"].as_u64().unwrap(); + let path = vec![occ]; + act(&mut app, &Target::Occurrence { path: path.clone() }, "Collapse All"); + assert!(app.tree.collapsed.contains(&format!("o:{occ}")), "{:?}", app.tree.collapsed); + assert!(!app.tree.collapsed.contains("c0/bodies"), "a placement's collapse leaves the rest of the tree: {:?}", app.tree.collapsed); + act(&mut app, &Target::Occurrence { path }, "Expand All"); + assert!(!app.tree.collapsed.contains(&format!("o:{occ}")), "{:?}", app.tree.collapsed); +} + #[test] fn delete_key_handles_every_kind_and_asks_about_dependents() { use solidcraft_engine::Sel; diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md index 97593d1e0..08bcb9967 100644 --- a/docs/book/src/guide/ui-tour.md +++ b/docs/book/src/guide/ui-tour.md @@ -17,7 +17,9 @@ - **Browser** (left). The design as a tree: document settings and units, named views, the origin, bodies, sketches, construction planes, canvases, joints and components. The eye shows or hides an item, a component's radio button makes it the active component, and right-clicking any - row gives that item's menu. Rows drag into groups and other components. + row gives that item's menu. Right-click the design or a component and choose **Expand All** or + **Collapse All** to open or close every folder under that row (the design row stays visible + when the whole tree is collapsed). Rows drag into groups and other components. - **Viewport.** Click to select, Shift or Ctrl to add (Preferences › Selection), drag for a window or crossing box. While sketching, Ctrl/Cmd or Alt/Option suppress auto-snap by default; Shift prefers a midpoint. To reach something under something else (two lines drawn on top of each other, coincident points, an edge in front of a face, overlapping bodies), hold the left button still for half a second diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 63800ba8f..46f2085e0 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -249,6 +249,8 @@ labels; `prefs:measure_axis_distances` identifies the checkbox. | `ui.window` | `action`: minimize, maximize, restore, toggle, close | what the title bar's caption buttons do (on Windows and Linux the application bar is the title bar); close asks about unsaved designs first | | `ui.agent_cursor` | `show` (bool), `speed`: a number from 1 to 5 (times the normal speed) or `"instant"` (no animation: the command runs at once and the pointer jumps to where it acted), `follow_camera` (bool); all optional | the settings. While the cursor is shown, `engine.execute` first glides to the command's toolbar button and to each pick, then runs and replies; later requests wait their turn. It also follows the pointer input sent with `ui.move`, `ui.click`, `ui.drag` and `ui.scroll`, as each event reaches the app, and a press leaves a ripple. `"animate": false` on a call skips it | | `engine.execute` → `view.layout` | `mode`: `floating` or `compact` | Apply and save the workspace layout without opening a dialog, changing the design, resetting the camera or cancelling its active tool. General preferences expose the same choice; `ui.prefs {"layout":"compact"}` also saves it. | +| `engine.execute` → `browser.expand_all` | `path?`: occurrence ids; `component?`: id; omit both for the whole tree | Open every Browser row under that scope, including folders that start closed (Origin, Named Views, Features). Display only: not saved in the design, not an undo step. | +| `engine.execute` → `browser.collapse_all` | same | Close those rows. The design row stays open when the whole tree is collapsed. | | `engine.execute` → `view.history_layout` | `width?`, `dock?`: `bottom`, `left`, `under_browser`, `collapsed?` | Resize/dock the history without opening a dialog or changing the design. Contents respond to measured width; browser-stacked history shares its width and splits height equally. One folded header gives the expanded card the rest; two folded headers stay at the top. | | `ui.agent_chat` | `features?`, `toolbar_button?`, `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp`, `api` or `anthropic` (`api` is OpenAI-compatible, `anthropic` Anthropic-compatible), `command` or `base_url` + `model`}; no keys), `add_dialog?` (`installed`, `custom`, `api`, `anthropic`, or `false` to close), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `model?` (one of its models), `open?`, `side?` (`left`, `right`), `minimized?`, `popped?` (in its own window), `width?`, `picker?`, `refresh?`, `connect?`, `stop?`, `attach?`: a file's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once), `remove_file?` (index of a file on the next message), `send?`: text (files alone make a message too), `attach_view?`, `attach_selection?`, `pick?` (true: open the context picker), `permission?`: an option id or `"cancel"` (the newest question of the agent's own), `approve?`: true, false or `"always"` (the oldest request held for Allow/Deny), `cancel?` (Stop: the queue stays), `send_now?` (stop the running step, then send the queued messages), `remove_pending?` (index), `new_chat?` (clear the chat, new session), `undo?` (the last message's changes) | the chat's state: `features`, `agents` (found and added), `currentAgent`, `state` (off, starting, ready, busy, auth, exited), `popped`, `window` (its place and size), `agent`, `modes`, `mode`, `models`, `model`, `authMethods`, `toolsPort`, `pid`, `waiting`, `turn`, `pending` (queued messages, with their `files`), `attachments` (the files on the next message, by name), `loading` (pictures still being read for it, by name), `stopped`, `detection` and the conversation (`items`). With `features` off only the settings apply. Desktop only; see [Agent chat](agent-chat.md) | | `ui.resize` | `width`, `height` | |