From 71598c0354b18205cb8fc5d252ac5bf2cbf88918 Mon Sep 17 00:00:00 2001 From: froglemonade2 <64703083+froglemonade2@users.noreply.github.com> Date: Thu, 5 Nov 2026 02:35:55 +0000 Subject: [PATCH] Agent control: `ui.menu` refuses items the design doesn't have, reports the History bar's right-click menu, and gives Edit Joint Limits its own id (#10745) (#10746) * claim: #10745 Co-Authored-By: Claude Opus 5.5 * Control channel: ui.menu refuses missing targets, reports the History item menu, and tells the joint menu items apart (#10745) - ui.menu looks a target up and refuses one the design doesn't have ("no body `NoSuchBody`"). - The History bar's feature menu is the shared context menu (Target::Timeline), so ui.menu reports it, ui.menuPick runs its items and {"type":"timeline","feature":id} opens it. Its Show All toggle moves to TreeState so the menu can list Delete after the marker. - Edit Joint Limits is ui.editJointLimits and opens Edit Joint with Limits expanded. Co-Authored-By: Claude Opus 5.5 * Icon audit: open the section and canvas menus on a real section and canvas; a hidden section has a menu too Co-Authored-By: Claude Opus 5.5 * ui.menu: check a group's or folder's scope and folder name; Delete after the marker gets its own id A group or folder target is refused unless its scope is a row of its component (`c` or a placement of it) and the folder is bodies, sketches or construction. The History item menu's delete of everything after the marker is ui.deleteAfterMarker, so ui.menuPick can tell it from Delete (review on #10746). Co-Authored-By: Claude Opus 5.5 * ui.menu: a component's own c scope is the design root's only; test that Delete after the marker deletes The browser draws a part's folders and groups under its placements (o:), so a c scope for any component but the root names a row that isn't there (review on #10746). The History test now picks ui.deleteAfterMarker and checks the features are gone. Co-Authored-By: Claude Opus 5.5 * ui.menu: a placement scope must be spelt as the browser keys it o:012 parses to placement 12 but isn't the row's key (o:12), so Show/Hide would store a key no row reads (review on #10746). Co-Authored-By: Claude Opus 5.5 * History item menu: no Delete after the marker when nothing shown is after it A timeline target for a feature the bar's component filter leaves out listed no features, so the item did nothing (review on #10746). Co-Authored-By: Claude Opus 5.5 * ui.menu: a plane target must be construction geometry The plane menu's Show/Hide keys the feature's name as an origin item, so any other feature got a menu whose actions don't fit it (review on #10746). Co-Authored-By: Claude Opus 5.5 * ui.menu: accept the view navigator's and selection filter's menus, which main added Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/browser.rs | 14 +++ crates/ui-egui/src/context_menu.rs | 103 ++++++++++++++++- crates/ui-egui/src/control.rs | 4 + crates/ui-egui/src/dialogs_assembly.rs | 18 ++- crates/ui-egui/src/edit_clipboard.rs | 2 +- crates/ui-egui/src/i18n_menu_tests.rs | 1 + crates/ui-egui/src/joint_browser_tests.rs | 22 ++++ crates/ui-egui/src/menu_tests.rs | 115 +++++++++++++++++++ crates/ui-egui/src/timeline.rs | 133 +++++++++++++--------- crates/ui-egui/tests/icon_audit.rs | 14 ++- docs/control-protocol.md | 2 +- 11 files changed, 365 insertions(+), 63 deletions(-) diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index c1d5da0f7..1f0c07089 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -211,6 +211,9 @@ pub struct TreeState { /// Show components marked out of the History bar anyway (#10393). Held by the session, like /// the bar's Show All toggle; the History controls' menu carries the switch. pub history_show_hidden: bool, + /// The History bar's Show All toggle: every component's features, not only the active or + /// picked one's (#2880). + pub history_show_all: bool, /// The feature of the face or edge last picked in the view, so a new pick scrolls the /// history to it once. pub view_pick: Option, @@ -477,6 +480,17 @@ fn scope_path(scope: &str) -> Vec { scope.strip_prefix("o:").map(|ids| ids.split('/').filter_map(|id| id.parse().ok()).collect()).unwrap_or_default() } +/// Whether a folder or group's scope key is a row the browser draws for `component`: the design's +/// own (`c0`, the root only), or a placement of it, spelt as the browser keys it (`o:12/3`, not +/// `o:012/3`: the rows' state is kept by that key). +pub(crate) fn scope_shows(app: &SolveApp, scope: &str, component: u64) -> bool { + if component == 0 && scope == "c0" { + return true; + } + let path = scope_path(scope); + is_placement_key(scope) && occurrence_key(&path) == scope && app.session.occurrence_placement(&path).is_ok_and(|p| p.component == component) +} + /// Paste on a Bodies or Sketches folder or group: copied (or cut) bodies, or copied sketches and /// features, go into its component (that placement), and into the group. fn paste_item(app: &SolveApp, component: u64, scope: &str, folder: &str, group: Option) -> Item { diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 5235cfc29..e378ebce2 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -88,6 +88,10 @@ pub enum Target { Toolbar, /// The History controls (first, previous, next, last, and Play when shown). HistoryControls, + /// A feature in the History bar. + Timeline { + feature: u64, + }, /// The workspace switcher. Workspace, /// The view gizmo (axes, cube or a custom body) at the viewport's corner. @@ -416,6 +420,7 @@ pub fn items(app: &SolveApp, target: &Target) -> Vec { Target::ToolbarCommand { id } => crate::toolbar_custom::command_items(app, id), Target::Toolbar => crate::toolbar_custom::toolbar_items(app), Target::HistoryControls => crate::timeline::transport_items(app), + Target::Timeline { feature } => crate::timeline::feature_items(app, *feature), Target::Workspace => { let rendering = crate::render_workspace::active(app); let mut v = vec![ @@ -928,7 +933,7 @@ fn joint_items(app: &SolveApp, id: u64) -> Vec { let hidden = !joints.iter().any(|j| app.session.joint_visible(*j)); vec![ act("ui.editJoint", "Edit Joint", "joint").with(json!({ "joint": id })), - act("ui.editJoint", "Edit Joint Limits", "joint").with(json!({ "joint": id })).on(!rigid), + act("ui.editJointLimits", "Edit Joint Limits", "joint").with(json!({ "joint": id })).on(!rigid), act("ui.driveJoint", "Drive Joint", "drive").with(json!({ "joint": id })).on(!rigid), act("ui.animateJoint", "Animate Joint", "play").with(json!({ "joint": id })).on(!rigid && !j.suppressed), act("ui.findJoint", "Find in Window", "fit").with(json!({ "joint": id })), @@ -1588,6 +1593,13 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { let what = if let Some(b) = p.get("body").and_then(Value::as_str) { RenameWhat::Body(b.to_string()) } else if let Some(f) = id_of(&p, "feature") { + // The History bar renames in a dialog. + if p.get("dialog").and_then(Value::as_bool) == Some(true) { + if let Some(name) = app.session.doc.feature(f).map(|f| f.name.clone()) { + app.dialog = Some(crate::dialogs::Dialog::rename(f, &name)); + } + return; + } RenameWhat::Feature(f) } else if let Some(c) = id_of(&p, "component") { RenameWhat::Component(c) @@ -1641,6 +1653,19 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { // Selected first: the rows above the body stay marked until the selection changes. let _ = app.run("select.set", json!({"items": [{"type": "body", "name": b}]})); crate::browser::reveal_body(app, b); + } else if let Some(f) = id_of(&p, "feature") { + crate::timeline::find_in_browser(app, f); + } + } + "ui.copyMessage" => { + if let Some(text) = id_of(&p, "feature").and_then(|f| crate::timeline::feature_message(app, f)) { + crate::edit_clipboard::leave_text(app, text); + } + } + "ui.deleteFeatures" | "ui.deleteAfterMarker" => { + let ids: Vec = p.get("features").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).collect(); + if !ids.is_empty() { + crate::timeline::delete_features(app, ids); } } "ui.findTimeline" => { @@ -1793,10 +1818,11 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { crate::dialogs_assembly::find_joint(app, id); } } - "ui.editJoint" | "ui.driveJoint" | "ui.animateJoint" => { + "ui.editJoint" | "ui.editJointLimits" | "ui.driveJoint" | "ui.animateJoint" => { if let Some(id) = id_of(&p, "joint") { let d = match item.id.as_str() { "ui.editJoint" => crate::dialogs_assembly::edit_joint(app, id), + "ui.editJointLimits" => crate::dialogs_assembly::edit_joint_limits(app, id), "ui.animateJoint" => crate::dialogs_assembly::animate_joint(app, id), _ => crate::dialogs_assembly::drive_joint(app, id), }; @@ -2255,6 +2281,79 @@ pub fn request_open(app: &mut SolveApp, at: Pos2, target: Target) { app.menu.pending = Some((at, target)); } +/// What a right-click can open a menu on is there (for `ui.menu`'s `target`): a body, feature, +/// component, joint… that the design doesn't have has no menu. +pub fn check_target(app: &SolveApp, target: &Target) -> Result<(), String> { + let doc = &app.session.doc; + let feature = |id: u64| doc.feature(id).is_some(); + let component = |id: u64| id == 0 || doc.components.iter().any(|c| c.id == id); + let found = match target { + Target::Viewport + | Target::Origin + | Target::Units + | Target::InsertDesign + | Target::EditSketch + | Target::VisualStyle + | Target::ViewTool + | Target::SelectionFilter + | Target::Navigation + | Target::Toolbar + | Target::HistoryControls + | Target::Workspace + | Target::NamedViews + | Target::ViewGizmo => true, + Target::Body { name } => crate::open_meshing::session_world(&app.session).body(name).is_some(), + Target::Sketch { id } => doc.feature(*id).is_some_and(|f| matches!(f.kind, FeatureKind::Sketch { .. })), + // Construction geometry, as the browser's Construction folder lists it. + Target::Plane { id } => doc.feature(*id).is_some_and(|f| { + matches!(f.kind, FeatureKind::ConstructionPlane { .. } | FeatureKind::ConstructionAxis { .. } | FeatureKind::ConstructionPoint { .. }) + }), + Target::Feature { id } => feature(*id), + Target::Timeline { feature: id } => feature(*id), + Target::OriginPlane { name } => crate::prefs::OriginPlaneNames::PLANES.contains(&name.as_str()), + Target::OriginAxis { name } => ["X", "Y", "Z"].contains(&name.as_str()), + Target::Component { id } => component(*id), + Target::Occurrence { path } => app.session.occurrence_placement(path).is_ok(), + // The scope is the row it is under: the component's own, or one of its placements. + Target::Group { id, scope } => doc.browser_groups.iter().any(|g| g.id == *id && crate::browser::scope_shows(app, scope, g.component)), + Target::Folder { component: id, folder, scope } => { + component(*id) && ["bodies", "sketches", "construction"].contains(&folder.as_str()) && crate::browser::scope_shows(app, scope, *id) + } + Target::Joint { id } => doc.assembly.joints.iter().any(|j| j.id == *id), + Target::ToolbarCommand { id } => solidcraft_engine::find_command(id).is_some(), + Target::NamedView { name } => { + doc.named_views.iter().any(|v| v.name == *name) || crate::browser::STANDARD_VIEWS.iter().any(|(label, _)| label == name) + } + Target::Canvas { id } => doc.canvases.iter().any(|c| c.id == *id), + Target::PointCloud { id } => doc.point_clouds.iter().any(|c| c.id == *id), + // Shown or hidden, the browser lists it. + Target::Section => app.session.section.is_some() || app.tree.hidden_section.is_some(), + }; + if found { + return Ok(()); + } + // A folder or group is found by more than one field: name them all. + match target { + Target::Folder { component, folder, scope } => return Err(format!("no `{folder}` folder of component {component} under `{scope}`")), + Target::Group { id, scope } => return Err(format!("no group {id} under `{scope}`")), + _ => {} + } + let what = serde_json::to_value(target).ok(); + // A History item is a feature. + let kind = match target { + Target::Timeline { .. } => "feature".to_string(), + _ => what.as_ref().and_then(|v| v.get("type")).and_then(Value::as_str).unwrap_or("target").replace('_', " "), + }; + let key = what + .as_ref() + .and_then(Value::as_object) + .and_then(|o| o.iter().find(|(k, _)| *k != "type").map(|(_, v)| v.as_str().map_or_else(|| v.to_string(), str::to_string))); + Err(match key { + Some(key) => format!("no {kind} `{key}`"), + None => format!("no {kind}"), + }) +} + /// The open menu as JSON (for `ui.menu`). pub fn describe(app: &SolveApp) -> Value { let Some(at) = app.viewport.context_menu else { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 5fb0c577c..172257a92 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1336,6 +1336,10 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> }, None => crate::context_menu::Target::Viewport, }; + // A right-click opens a menu only on something that is there. + if let Err(e) = crate::context_menu::check_target(app, &target) { + return err(e); + } crate::context_menu::request_open(app, egui::pos2(x as f32, y as f32), target); return ok(json!({"pending": true})); } diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 2656a14c0..f7c67d92d 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -202,6 +202,8 @@ pub struct JointForm { pub found_note: Option, /// The design and the joint (as the dialog had it) the found limits are for. pub searched: Option, + /// Edit Joint Limits: open the Limits section when the dialog first draws. + pub show_limits: bool, pub animate: bool, /// Animation phase, 0…1. pub phase: f64, @@ -224,6 +226,7 @@ impl JointForm { found: Vec::new(), found_note: None, searched: None, + show_limits: false, animate: false, phase: 0.0, hover: None, @@ -522,7 +525,15 @@ pub fn edit_joint(app: &SolveApp, id: u64) -> Option { Some(Dialog::new(Kind::Assembly(Asm::Joint(Box::new(f))), inputs)) } -/// The Drive Joints dialog on a joint (by id). +/// Edit Joint with its Limits section open (the browser's Edit Joint Limits). +pub fn edit_joint_limits(app: &SolveApp, id: u64) -> Option { + let mut d = edit_joint(app, id)?; + if let Kind::Assembly(Asm::Joint(f)) = &mut d.kind { + f.show_limits = true; + } + Some(d) +} + /// Edit Joint with its motion playing (the browser's Animate Joint). pub fn animate_joint(app: &SolveApp, id: u64) -> Option { let mut d = edit_joint(app, id)?; @@ -560,6 +571,7 @@ pub fn occurrence_bounds(s: &Session, occs: &[u64]) -> Aabb3 { bb } +/// The Drive Joints dialog on a joint (by id). pub fn drive_joint(app: &SolveApp, id: u64) -> Option { let joint = app.session.doc.assembly.joints.iter().position(|j| j.id == id)?; Some(Dialog::new(Kind::Assembly(Asm::Drive { joint, values: current_values(&app.session, joint), focus: true }), vec![])) @@ -811,6 +823,10 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se f.animate = !f.animate; } }); + if std::mem::take(&mut f.show_limits) { + let id = ui.make_persistent_id("joint_limits"); + ui.ctx().data_mut(|d| d.insert_persisted(id, true)); + } crate::ui_kit::section(ui, "joint_limits", "Limits", false, |ui| { let found = f.found.clone(); for (i, (on, lo, hi)) in f.limits.iter_mut().enumerate() { diff --git a/crates/ui-egui/src/edit_clipboard.rs b/crates/ui-egui/src/edit_clipboard.rs index 680d4ea6c..8f9d5c687 100644 --- a/crates/ui-egui/src/edit_clipboard.rs +++ b/crates/ui-egui/src/edit_clipboard.rs @@ -56,7 +56,7 @@ pub fn body_is_cut(app: &SolveApp, name: &str) -> bool { } /// Leave text for the system clipboard: this app's next frame writes it ([`flush`]). -fn leave_text(app: &mut SolveApp, text: String) { +pub(crate) fn leave_text(app: &mut SolveApp, text: String) { app.clipboard_text = Some(text); } diff --git a/crates/ui-egui/src/i18n_menu_tests.rs b/crates/ui-egui/src/i18n_menu_tests.rs index b6dc5c1ba..7e9c2b204 100644 --- a/crates/ui-egui/src/i18n_menu_tests.rs +++ b/crates/ui-egui/src/i18n_menu_tests.rs @@ -57,6 +57,7 @@ fn take(app: &SolveApp, out: &mut BTreeSet) { for id in &features { take_items(out, &context_menu::items(app, &Target::Sketch { id: *id })); take_items(out, &context_menu::items(app, &Target::Plane { id: *id })); + take_items(out, &context_menu::items(app, &Target::Timeline { feature: *id })); } for id in &components { take_items(out, &context_menu::items(app, &Target::Component { id: *id })); diff --git a/crates/ui-egui/src/joint_browser_tests.rs b/crates/ui-egui/src/joint_browser_tests.rs index e20bf1fbf..8669ba34f 100644 --- a/crates/ui-egui/src/joint_browser_tests.rs +++ b/crates/ui-egui/src/joint_browser_tests.rs @@ -403,3 +403,25 @@ mod delete { assert_eq!(h.app.session.doc.assembly.joints.len(), 2); } } + +/// Edit Joint Limits has its own id, so `ui.menuPick` tells it from Edit Joint, and it opens the +/// joint's dialog on its Limits (#10745). +#[test] +fn edit_joint_limits_opens_the_limits_and_has_its_own_id() { + let mut h = harness(); + let hinge = id(&h, "Hinge"); + let items = context_menu::items(&h.app, &Target::Joint { id: hinge }); + let ids = |label: &str| items.iter().filter(|i| i.label == label).map(|i| i.id.clone()).collect::>(); + assert_eq!(ids("Edit Joint"), ["ui.editJoint"]); + assert_eq!(ids("Edit Joint Limits"), ["ui.editJointLimits"]); + + for (item, limits) in [("ui.editJoint", false), ("ui.editJointLimits", true)] { + crate::dialogs::cancel(&mut h.app); + h.frames(2); + h.call("ui.menu", json!({"x": 150, "y": 400, "target": {"type": "joint", "id": hinge}})); + assert_eq!(h.call("ui.menuPick", json!({"item": item}))["ok"], true, "{item}"); + h.frames(3); + assert!(h.app.dialog.is_some(), "{item} opens the joint's dialog"); + assert_eq!(h.widget("Angle limits").is_some(), limits, "{item}: the Limits section open"); + } +} diff --git a/crates/ui-egui/src/menu_tests.rs b/crates/ui-egui/src/menu_tests.rs index 1884dcdc4..08dc5f618 100644 --- a/crates/ui-egui/src/menu_tests.rs +++ b/crates/ui-egui/src/menu_tests.rs @@ -1636,6 +1636,7 @@ fn every_context_target_has_identified_icon_rows_including_submenus() { Target::Canvas { id: 1 }, Target::Section, Target::Folder { component: 0, folder: "bodies".into(), scope: "c0".into() }, + Target::Timeline { feature }, ] { let rows = context_menu::items(&app, &target); assert!(!rows.is_empty(), "unexercised target: {target:?}"); @@ -2195,3 +2196,117 @@ fn insert_design_offers_the_other_open_designs_then_browse() { h.frames(3); assert_eq!(linked(&h.app, "plate.solidcraft"), 2); } + +/// `ui.menu` opens a menu only on something the design has, as a right-click can (#10745). +#[test] +fn ui_menu_refuses_a_target_the_design_does_not_have() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length": 20, "width": 20, "height": 20, "body_name": "Blk"})).unwrap(); + let group = h.app.run("browser.group", json!({"component": 0, "folder": "bodies", "items": ["Blk"]})).unwrap()["group"].as_u64().unwrap(); + let bad_group = format!("no group {group} under `c7`"); + // A plane menu is for construction geometry only, not the box. + let block = h.app.session.doc.features[0].id; + let bad_plane = format!("no plane `{block}`"); + // A part's folders are drawn under its placement, never under a `c` row of its own. + let part = h.app.run("component.create", json!({"name": "Part"})).unwrap()["component"].as_u64().unwrap(); + let placement = h.app.session.doc.occurrence_of(part).unwrap().id; + h.app.run("component.activate", json!({"component": "root"})).unwrap(); + let bad_part = format!("no `bodies` folder of component {part} under `c{part}`"); + // A placement spelt another way (`o:012` for `o:12`) isn't the row's key either. + let bad_alias = format!("no `bodies` folder of component {part} under `o:0{placement}`"); + h.frames(2); + for (target, error) in [ + (json!({"type": "body", "name": "NoSuchBody"}), "no body `NoSuchBody`"), + (json!({"type": "component", "id": 999}), "no component `999`"), + (json!({"type": "joint", "id": 7}), "no joint `7`"), + (json!({"type": "timeline", "feature": 999}), "no feature `999`"), + (json!({"type": "section"}), "no section"), + (json!({"type": "folder", "component": 0, "folder": "drawings", "scope": "c0"}), "no `drawings` folder of component 0 under `c0`"), + (json!({"type": "folder", "component": 0, "folder": "bodies", "scope": "o:999"}), "no `bodies` folder of component 0 under `o:999`"), + (json!({"type": "group", "id": group, "scope": "c7"}), bad_group.as_str()), + (json!({"type": "plane", "id": block}), bad_plane.as_str()), + (json!({"type": "folder", "component": part, "folder": "bodies", "scope": format!("c{part}")}), bad_part.as_str()), + (json!({"type": "folder", "component": part, "folder": "bodies", "scope": format!("o:0{placement}")}), bad_alias.as_str()), + ] { + let reply = h.call("ui.menu", json!({"x": 150, "y": 400, "target": target})); + assert_eq!(reply["error"], error, "{target}"); + assert_eq!(h.call("ui.menu", json!({}))["result"], json!({"open": false, "pending": false}), "{target}"); + } + for target in [ + json!({"type": "body", "name": "Blk"}), + json!({"type": "folder", "component": 0, "folder": "bodies", "scope": "c0"}), + json!({"type": "group", "id": group, "scope": "c0"}), + json!({"type": "folder", "component": part, "folder": "bodies", "scope": format!("o:{placement}")}), + ] { + assert_eq!(h.call("ui.menu", json!({"x": 150, "y": 400, "target": target}))["ok"], true, "{target}"); + assert_eq!(h.call("ui.menu", json!({}))["result"]["open"], true, "{target}"); + h.call("ui.menu", json!({"close": true})); + } +} + +/// The History bar's feature menu is the shared context menu: `ui.menu` reports it after a +/// right-click, `ui.menuPick` runs its items, and a `timeline` target opens it (#10745). +#[test] +fn the_history_bar_feature_menu_is_reported_and_picked() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length": 20, "width": 20, "height": 20, "body_name": "Blk"})).unwrap(); + h.frames(3); + let (id, name) = (h.app.session.doc.features[0].id, h.app.session.doc.features[0].name.clone()); + let labels = |menu: &serde_json::Value| -> Vec { + menu["items"].as_array().into_iter().flatten().filter_map(|i| i["label"].as_str()).map(str::to_string).collect() + }; + let settle = |h: &mut crate::scenario::Harness| { + for _ in 0..500 { + if h.app.deferred.is_none() && h.app.deferred_queue.is_empty() { + break; + } + h.frames(1); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + h.frames(1); + }; + + h.step(&json!({"click": {"handle": format!("timeline:{name}")}, "button": "right"})).unwrap(); + let menu = h.call("ui.menu", json!({}))["result"].clone(); + assert_eq!(menu["target"], json!({"type": "timeline", "feature": id}), "{menu}"); + let shown = labels(&menu); + for label in ["Edit Feature", "Rename", "Suppress Features", "Roll History Marker Here", "Find in Browser", "Copy", "Paste", "Delete"] { + assert!(shown.iter().any(|l| l == label), "no `{label}` in {shown:?}"); + } + assert_eq!(h.call("ui.menuPick", json!({"item": "Suppress Features"}))["ok"], true); + settle(&mut h); + assert!(h.app.session.doc.feature(id).unwrap().suppressed, "Suppress Features suppressed it"); + + // A target opens the same menu, as the right-click did. + h.call("ui.menu", json!({"x": 400, "y": 900, "target": {"type": "timeline", "feature": id}})); + let menu = h.call("ui.menu", json!({}))["result"].clone(); + assert!(labels(&menu).iter().any(|l| l == "Unsuppress Features"), "{menu}"); + assert_eq!(h.call("ui.menuPick", json!({"item": "Unsuppress Features"}))["ok"], true); + settle(&mut h); + assert!(!h.app.session.doc.feature(id).unwrap().suppressed); + h.call("ui.menu", json!({"x": 400, "y": 900, "target": {"type": "timeline", "feature": id}})); + assert_eq!(h.call("ui.menuPick", json!({"item": "Find in Browser"}))["ok"], true); + assert_eq!(h.app.session.selection, vec![solidcraft_engine::Sel::Body { name: "Blk".into() }]); + + // After the history marker, Delete and the delete of everything after the marker are two + // items with their own ids, so each can be picked. + h.app.run("timeline.roll_to", json!({"position": 0})).unwrap(); + settle(&mut h); + h.call("ui.menu", json!({"x": 400, "y": 900, "target": {"type": "timeline", "feature": id}})); + let menu = h.call("ui.menu", json!({}))["result"].clone(); + let ids: Vec<&str> = menu["items"].as_array().into_iter().flatten().filter_map(|i| i["id"].as_str()).collect(); + assert_eq!(ids.iter().filter(|i| **i == "ui.deleteFeatures").count(), 1, "{ids:?}"); + assert_eq!(ids.iter().filter(|i| **i == "ui.deleteAfterMarker").count(), 1, "{ids:?}"); + assert_eq!(h.call("ui.menuPick", json!({"item": "ui.deleteAfterMarker"}))["ok"], true); + for _ in 0..500 { + if h.app.delete_check.is_none() && h.app.deferred.is_none() && h.app.deferred_queue.is_empty() { + break; + } + h.frames(1); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + h.frames(2); + assert!(h.app.session.doc.feature(id).is_none(), "the features after the marker are deleted"); +} diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index 6db319a75..f26a99c87 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -13,6 +13,7 @@ use solidcraft_engine::doc::{ use solidcraft_engine::schema::edit::PlaybackAction; use crate::SolveApp; +use crate::context_menu::Item; use crate::theme::Tokens; /// Apply transport actions from the current marker; endpoints stay bounded, including an @@ -348,15 +349,19 @@ pub(crate) fn menu_targets(app: &SolveApp, id: u64) -> Vec { if selected.contains(&id) { selected } else { vec![id] } } +/// Delete's label in a feature's menu: how many features it deletes when that is more than one. +fn delete_label(count: usize) -> String { + match count { + 1 => crate::i18n::tr_label("Delete").to_string(), + n => crate::i18n::format("timeline.delete_many", &[("count", &n.to_string())]), + } +} + /// Delete in a feature's menu, in both timelines: the selected features when the right-clicked /// one is among them, labelled with how many, else that feature alone (#5005). pub(crate) fn delete_button(app: &mut SolveApp, ui: &mut egui::Ui, id: u64) { let targets = menu_targets(app, id); - let label = match targets.len() { - 1 => crate::i18n::tr_label("Delete").to_string(), - n => crate::i18n::format("timeline.delete_many", &[("count", &n.to_string())]), - }; - if crate::context_menu::button(ui, &label, "delete").clicked() { + if crate::context_menu::button(ui, &delete_label(targets.len()), "delete").clicked() { delete_features(app, targets); ui.close(); } @@ -370,24 +375,76 @@ fn features_from(app: &SolveApp, from: usize, shown: Option<&[usize]>) -> Vec) { +/// `index`, `marker` a design position too): every feature after the marker, only the `shown` +/// ones when the timeline is filtered to a component, with the entry's label, for one delete +/// through [`delete_features`] so the confirmation still lists what would fail. Not offered +/// before the marker, nor when the menu acts on several selected features: an entry that acts +/// partly on the selection and partly beyond it is hard to read. +fn after_marker(app: &SolveApp, id: u64, index: usize, marker: usize, shown: Option<&[usize]>) -> Option<(String, Vec)> { if index < marker || menu_targets(app, id).len() > 1 { - return; + return None; } let ids = features_from(app, marker, shown); + // A feature the bar's filter leaves out has nothing shown after the marker to delete. + if ids.is_empty() { + return None; + } let key = if ids.len() == 1 { "timeline.delete_after_marker_one" } else { "timeline.delete_after_marker_other" }; - let label = crate::i18n::format(key, &[("count", &ids.len().to_string())]); + Some((crate::i18n::format(key, &[("count", &ids.len().to_string())]), ids)) +} + +/// The [`after_marker`] entry as a button. +pub(crate) fn delete_after_marker_button(app: &mut SolveApp, ui: &mut egui::Ui, id: u64, index: usize, marker: usize, shown: Option<&[usize]>) { + let Some((label, ids)) = after_marker(app, id, index, marker, shown) else { return }; if crate::context_menu::button(ui, &label, "delete").clicked() { delete_features(app, ids); ui.close(); } } +/// A History bar feature's menu (`Target::Timeline`): edit, rename, suppress, roll back, find, +/// the clipboard and delete. +pub(crate) fn feature_items(app: &SolveApp, id: u64) -> Vec { + let doc = &app.session.doc; + let (Some(feature), Some(index)) = (doc.feature(id), doc.feature_index(id)) else { return Vec::new() }; + let mut v = vec![Item::action("ui.editFeature", "Edit Feature", "edit").with(json!({ "feature": id }))]; + if matches!(feature.kind, FeatureKind::Sketch { .. }) { + v.extend( + crate::context_menu::items(app, &crate::context_menu::Target::Sketch { id }).into_iter().filter(|item| item.id == "ui.redefineSketch"), + ); + } + if let Some(sketch) = TimelineKind::of(&feature.kind).profile_sketch() { + v.push(Item::action("ui.editSketch", "Edit Profile Sketch", "sketch").with(json!({ "sketch": sketch.0 }))); + } + // Its own message, not a literal: no catalog held the literal, so the item stayed English + // in every language (#8301). + let suppress = if feature.suppressed { "timeline.unsuppress_features" } else { "timeline.suppress_features" }; + v.extend([ + Item::action("ui.rename", "Rename", "rename").with(json!({ "feature": id, "dialog": true })), + Item::action("timeline.suppress", crate::i18n::tr(suppress), "suppress").with(json!({ "feature": id })), + Item::action("timeline.roll_to", "Roll History Marker Here", "rollback").with(json!({ "feature": id })), + Item::action("ui.findBrowser", "Find in Browser", "list").with(json!({ "feature": id })), + Item::sep(), + Item::action("timeline.copy", "Copy", "copy").with(json!({ "features": menu_targets(app, id) })), + Item::action("timeline.paste", "Paste", "paste").with(json!({})).on_if(!app.session.clipboard.is_empty()), + ]); + if feature_message(app, id).is_some() { + let failed = app.session.model.result(id).is_some_and(|r| r.error.is_some()); + let label = if failed { "Copy Error Message" } else { "Copy Warning Message" }; + v.push(Item::action("ui.copyMessage", label, "copy").with(json!({ "feature": id }))); + } + let targets = menu_targets(app, id); + v.push(Item::sep()); + v.push(Item::action("ui.deleteFeatures", &delete_label(targets.len()), "delete").with(json!({ "features": targets }))); + let marker = doc.marker.unwrap_or(doc.features.len()); + let shown = shown_feature_indices(doc, timeline_component(app, app.tree.history_show_all), app.tree.history_show_hidden); + if let Some((label, ids)) = after_marker(app, id, index, marker, Some(&shown)) { + // Its own id, so `ui.menuPick` can tell it from Delete. + v.push(Item::action("ui.deleteAfterMarker", &label, "delete").with(json!({ "features": ids }))); + } + v +} + /// The timeline anchor of a feature: the last one clicked, where a Shift+click range starts. pub(crate) fn anchor_key(id: u64) -> String { format!("f:{id}") @@ -957,8 +1014,7 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { let mut x = ui.max_rect().left(); let origin = x; // In an assembly, only the active (or picked) component's features (#2880). - let show_all_id = ui.id().with("tl_show_all"); - let show_all = ui.data(|d| d.get_temp::(show_all_id)).unwrap_or(false); + let show_all = app.tree.history_show_all; let only = timeline_component(app, show_all); let filtering = only.is_some() || show_all; let shown = shown_feature_indices(&app.session.doc, only, app.tree.history_show_hidden); @@ -982,11 +1038,10 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { "Activate or pick a component in the browser to show only its features" }; if resp.backing_on_hover_text(tip).clicked() && (only.is_some() || show_all) { - ui.data_mut(|d| d.insert_temp(show_all_id, !show_all)); + app.tree.history_show_all = !show_all; } x = br.right() + 8.0; } - let design_marker = marker; let marker = shown.iter().position(|i| *i >= marker).unwrap_or(shown.len()); let feats: Vec<_> = shown .iter() @@ -1151,45 +1206,11 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { if resp.double_clicked() { edit = Some(*id); } - let sketch_of = kind.profile_sketch(); - crate::ui_kit::Menu::context(&resp, |ui| { - if crate::context_menu::button(ui, crate::i18n::tr_label("Edit Feature"), "edit").clicked() { - edit = Some(*id); - ui.close(); - } - sketch_plane_button(app, ui, *id); - if let Some(sk) = sketch_of - && crate::context_menu::button(ui, crate::i18n::tr_label("Edit Profile Sketch"), "sketch").clicked() - { - app.edit_sketch(sk.0); - ui.close(); - } - if crate::context_menu::button(ui, crate::i18n::tr_label("Rename"), "rename").clicked() { - app.dialog = Some(crate::dialogs::Dialog::rename(*id, name)); - ui.close(); - } - // Its own message, not a literal: no catalog held the literal, so the item - // stayed English in every language (#8301). - let suppress = if *suppressed { "timeline.unsuppress_features" } else { "timeline.suppress_features" }; - if crate::context_menu::button(ui, crate::i18n::tr(suppress), "suppress").clicked() { - let _ = app.run_heavy("timeline.suppress", json!({"feature": id})); - ui.close(); - } - if crate::context_menu::button(ui, crate::i18n::tr_label("Roll History Marker Here"), "rollback").clicked() { - let _ = app.run_heavy("timeline.roll_to", json!({ "feature": id })); - ui.close(); - } - if crate::context_menu::button(ui, crate::i18n::tr_label("Find in Browser"), "list").clicked() { - find_in_browser(app, *id); - ui.close(); - } - ui.separator(); - clipboard_buttons(app, ui, *id); - message_button(app, ui, *id); - ui.separator(); - delete_button(app, ui, *id); - delete_after_marker_button(app, ui, *id, design_position(&shown, i, n), design_marker, Some(&shown)); - }); + // The same menu as the browser's, so the control channel reports it (#10745). + if resp.secondary_clicked() { + let at = resp.interact_pointer_pos().unwrap_or(br.center()); + crate::context_menu::open_for(app, at, crate::context_menu::Target::Timeline { feature: *id }); + } x += 32.0; } let mut previous = origin; diff --git a/crates/ui-egui/tests/icon_audit.rs b/crates/ui-egui/tests/icon_audit.rs index 66fd764c6..f9c44243e 100644 --- a/crates/ui-egui/tests/icon_audit.rs +++ b/crates/ui-egui/tests/icon_audit.rs @@ -271,11 +271,21 @@ fn requested_menu_icons_have_artwork_and_match_manifest() { json!({"type":"folder","component":0,"scope":"c0","folder":"bodies"}), json!({"type":"folder","component":0,"scope":"c0","folder":"sketches"}), json!({"type":"folder","component":0,"scope":"c0","folder":"construction"}), - json!({"type":"section"}), - json!({"type":"canvas","id":1}), ] { menu(&mut h, target.clone(), &target.to_string(), &mut requested); } + // The Section Analysis and a canvas have a menu only while they are there (#10745). + h.app.run("inspect.section", json!({"plane": "YZ"})).unwrap(); + menu(&mut h, json!({"type":"section"}), "section", &mut requested); + h.app.run("inspect.section", json!({"clear": true})).unwrap(); + let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec(); + png.extend(400u32.to_be_bytes()); + png.extend(200u32.to_be_bytes()); + png.extend([8, 6, 0, 0, 0, 0, 0, 0, 0]); + let data = solidcraft_engine::doc::canvas::base64_encode(&png); + let canvas = h.app.run("canvas.insert", json!({"data": data, "plane": "XY", "width": 80})).unwrap()["canvas"].clone(); + menu(&mut h, json!({"type":"canvas","id":canvas}), "canvas", &mut requested); + h.app.run("selection.delete", json!({"canvases": [canvas]})).unwrap(); for selection in [ json!({"type":"face","body":body,"index":0,"point":[0,0,0]}), json!({"type":"edge","body":body,"index":0,"point":[0,0,0]}), diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 80f47756f..3a0c28ad5 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -619,7 +619,7 @@ no box selection. | `ui.click` | `x`, `y` (screen points), `button?`: left/right/middle, `shift?`, `ctrl?`, `double?` | real pointer input | | `ui.move` | `x`, `y`, `shift?`, `alt?`, `ctrl?`, `cmd?` | pointer movement without a button; modifiers apply until the next synthetic move/click; a move with omitted modifiers releases them. With `nav: "touchpad"`, Shift pans and Alt/Option orbits. | | `ui.drag` | `x0`, `y0`, `x1`, `y1`, `via?`, `button?`, `shift?`, `ctrl?`, `steps?`, `hold?`, `hold_end?` | press, move, release; `via` is a list of `[x, y]` points passed through on the way (`steps` moves to each); a left drag on the model is a box selection (left to right: window, right to left: crossing), or with `lassoSelect` on (`ui.set`, the SELECT panel's Lasso) a freehand lasso that takes what is wholly inside it; with OpenSCAD navigation, plain left-drag on empty space orbits, Shift+left-drag box-selects, and drags starting on sketch geometry edit it; `hold` keeps the button down that many frames first (a right press-and-hold opens the marking menu, releasing over a direction picks it), `hold_end` that many frames at the end (a sketch drag shows its snap) | -| `ui.menu` | `x?`, `y?`, `target?`, `close?` | with a point: open a context menu there as a right-click would (the viewport's marking menu, or a browser menu with `target: {"type": "body", "name"} \| {"type": "sketch", "id"} \| {"type": "component", "id"}`); without: the open menu (`radial` and `items`: id, label, shortcut, enabled, icon, placeholder, and `children` for a row that opens a flyout; blank icons on headings/separators have `placeholder: false`) | +| `ui.menu` | `x?`, `y?`, `target?`, `close?` | with a point: open a context menu there as a right-click would (the viewport's marking menu, a browser menu with `target: {"type": "body", "name"} \| {"type": "sketch", "id"} \| {"type": "component", "id"}`, or a History bar feature's with `{"type": "timeline", "feature": id}`); a target the design doesn't have is refused (`no body \`Name\``); without: the open menu (`radial` and `items`: id, label, shortcut, enabled, icon, placeholder, and `children` for a row that opens a flyout; blank icons on headings/separators have `placeholder: false`) | | `ui.icon_audit` | `reset?`, `stop?` | `reset: true` enables collection on the UI thread and clears previous requests; returns `{requested: [{name, master, placeholder}]}` sorted by requested id. Each read drains names collected since the previous read/reset. Collection stays enabled until `stop: true` (which returns pending names before disabling it). Includes aliases, variable/table ids and cached paints. | | `ui.menuPick` | `item`: id or label | runs an item of the open menu or of any of its flyouts, as clicking it does; a row that only opens a flyout is refused | | `ui.selectOther` | `x?`, `y?`, `pick?`, `add?`, `hover?`, `close?` | Select Other: with a point, list compatible hidden and visible geometry near the pointer by default (as holding the left button does; disable `select_other_hidden` for the original visible-only list); the popup fits the available window space and scrolls only for overflow; `pick`: select row `pick` (`add`: as Shift-click; with a dialog open, into its active input); `hover`: light a row up; without: the open list (`open`, `at`, `total`: everything under the cursor, `rows`: label, icon, sel, at most 20 per kind, nearest first) |