Skip to main content

brep_app/panels/
context_bar.rs

1//! Context action toolbar — the **selection-driven** action bar (the engine-
2//! native successor to the old app's floating selection action bar,
3//! `SelectionFilter._syncSelectionActions` + `_getHistoryContextActionSpecs`).
4//!
5//! It is shown ONLY while something is selected (hidden otherwise) and its
6//! buttons depend on the CURRENT selection (kinds + count read from
7//! `selection_json`):
8//!
9//! * **Generic actions** (mirror the old selection action bar):
10//!   - **Clear** — `clear_selection`.
11//!   - **Hide** — `hide_selected` (toggles the visibility of EXACTLY what is
12//!     selected: a selected face/edge/vertex hides just that sub-entity, a
13//!     selected solid the whole solid; a second click shows it again).
14//!   - **Edit owning feature** — for a SINGLE selected entity with a known
15//!     producer, `creating_feature(name)` resolves the feature that built it;
16//!     clicking rolls the model to that step (`roll_to`) and asks the shell to
17//!     EXPAND that feature's inline dialog in the history tree. A wire-harness
18//!     BUNDLE solid's producer is the harness tail, which is not a history
19//!     feature: the button stays in place but DISABLED, its tooltip naming the
20//!     spline the bundle follows and the Wire Harness panel as the things to
21//!     edit instead (`Selection::harness_bundle`).
22//! * **Feature-from-selection** — WHICH features a selection offers is answered
23//!   by the KERNEL, per feature: each feature module defines `context_applicable`
24//!   (aggregated in `feature_pipeline::context_offer`), a predicate over the
25//!   [`SelectionProbe`] kind-counts this bar builds each frame. That is where
26//!   nuance lives — e.g. Revolve wants a profile AND an axis edge, so a lone
27//!   face no longer offers it. The pre-fill stays schema-derived: an offered
28//!   feature's `References`-group `reference_selection` fields are filled from
29//!   the selection in schema order under a CONSUMED set (each selected name
30//!   lands in at most ONE field — face+edge → Revolve fills `profile` and
31//!   `axis`). Clicking creates the feature (`add_feature`) with those fields
32//!   pre-filled, then asks the shell to expand the new node for tweaking.
33//! * **Constraint-from-selection** — the assembly-constraint mirror of the
34//!   feature offers, shown when the Assembly Constraints panel is available in
35//!   the active workbench (claim-based visibility). Each constraint type's
36//!   `applicable` predicate ([`brep_kernel::ConstraintTypeDef`]) runs against
37//!   the same probe: all-component selections only (the kernel rejects anything
38//!   else), ONE component's solid(s) for Fixed, a two-element pair across TWO
39//!   distinct components for the pairing types. Clicking adds the constraint
40//!   with `elements` pre-seeded from the selection (the constraints panel's
41//!   seeding helper) and opens its row in the panel.
42//!
43//! Like the other panels this owns NO model state — the selection + history live
44//! in [`EngineState`], borrowed in; it only holds the per-frame `hits` map (widget
45//! screen rects) + the last-drawn action ids the headed verifier reads.
46
47use crate::automation::hit_keys::HitKeyDoc;
48use super::action_rail::{action_rail, ActionItem};
49use super::component_actions::{run_component_action, ComponentAction, ComponentActionRequest};
50use crate::form;
51use brep_render::brep_kernel::{self, SelectionProbe};
52use brep_render::engine_state::EngineState;
53use brep_render::features;
54use brep_render::style::FieldKind;
55use eframe::egui;
56use serde_json::Value;
57use std::collections::{HashMap, HashSet};
58
59/// A request bubbled back to the shell after a context action ran: EXPAND (open
60/// the inline dialog of) the feature with this id in the history tree. The
61/// context bar mutates the engine directly but cannot reach the history panel's
62/// private "expanded" state, so it returns the id for the shell to focus.
63pub type FocusRequest = Option<String>;
64
65/// What a context-bar frame hands back to the shell. The bar mutates the engine
66/// directly, but two effects it cannot reach itself:
67/// * `focus` — the history feature to EXPAND after a create / edit-owning action
68///   (the history panel's expand state is private to it); and
69/// * `info_targets` — the entity names to open PINNED Info windows for after the
70///   Info action (the Info-window manager is shell-owned). One name per selected
71///   entity, so a multi-select opens one window each.
72#[derive(Default)]
73pub struct ContextOutcome {
74    pub focus: FocusRequest,
75    pub info_targets: Vec<String>,
76    /// A COMPONENT document-level flow the shell must run (Edit in place /
77    /// Open Part) — set when the matching component action was clicked; the
78    /// engine-mutating component actions (Move / Fix-Unfix / Delete) already
79    /// applied inside the bar.
80    pub component: Option<ComponentActionRequest>,
81    pub plugin_action: Option<String>,
82}
83
84/// The context bar's transient UI state (the model lives in the engine).
85#[derive(Default)]
86pub struct ContextBarPanel {
87    /// Per-frame widget screen rects, published for the headed verifier. Rebuilt
88    /// each frame (there is no DOM — egui draws on the canvas).
89    hits: HashMap<String, egui::Rect>,
90    /// The generic action ids drawn THIS frame (`clear` / `hide` / `edit-owning`)
91    /// — published so the verifier can assert WHICH actions the selection offered.
92    shown_actions: Vec<String>,
93    /// The feature TYPE CODES offered THIS frame (`E`, `F`, `CH`, …).
94    shown_features: Vec<String>,
95    /// The constraint TYPE ids offered THIS frame (`fixed`, `distance`, …).
96    shown_constraints: Vec<String>,
97    /// The PMI annotation type ids offered THIS frame (`linear`, `datum`, …).
98    shown_pmi: Vec<String>,
99    /// The COMPONENT action ids offered THIS frame (`move`, `open-part`, …)
100    /// — non-empty exactly when the selection is a single component's members.
101    shown_component_actions: Vec<String>,
102    /// The single component the actions target this frame (its ACOMP id).
103    shown_component_target: Option<String>,
104    /// Every component the offered actions act on this frame: the single
105    /// target, or the occurrences a face / multi-component selection moves.
106    shown_component_targets: Vec<String>,
107    /// The tallest the card may draw, in points, set by the shell each frame:
108    /// down to the ViewCube's top, so a long rail scrolls instead of covering
109    /// the cube (lane U audit item 2: at 1280x800 a face selection's 22 rows
110    /// hid it). `None` = unbounded.
111    pub max_height: Option<f32>,
112}
113
114impl ContextBarPanel {
115    pub(crate) fn clear_view(&mut self) {
116        self.hits.clear();
117        self.shown_actions.clear(); self.shown_features.clear();
118        self.shown_constraints.clear(); self.shown_pmi.clear();
119        self.shown_component_actions.clear(); self.shown_component_target = None;
120        self.shown_component_targets.clear();
121    }
122    pub fn new() -> Self {
123        Self::default()
124    }
125
126    /// Draw the context bar as a FLOATING panel over the viewport (nothing when
127    /// nothing is selected — like the old app's floating selection action bar).
128    /// Drawn at ctx level (not inside the scrollable side panel) so its buttons
129    /// are always reachable regardless of side-panel scroll. Returns a
130    /// [`ContextOutcome`] — the feature id the shell should expand in the history
131    /// tree (after a create-from-selection or edit-owning action) plus any entity
132    /// names the shell should open pinned Info windows for (after the Info action).
133    pub fn card(&mut self, ui: &mut egui::Ui, state: &mut EngineState) -> ContextOutcome {
134        self.hits.clear();
135        self.shown_actions.clear();
136        self.shown_features.clear();
137        self.shown_constraints.clear();
138        self.shown_pmi.clear();
139        self.shown_component_actions.clear();
140        self.shown_component_target = None;
141        self.shown_component_targets.clear();
142
143        // Modeling context actions ONLY. Hidden with no selection (geometry OR a
144        // label-selected constraint), and never during reference-selection (the
145        // picker owns the selection), in sketch mode (the sketch context rail
146        // replaces this one) or over an eCAD editor (below). Rendered through the SHARED single-column rail —
147        // see [`super::action_rail`] — so it and the sketch context bar stay
148        // identical. The constraint selection only counts (and only offers its
149        // Delete action) in a workbench that shows the constraints panel — the
150        // same claim gate as the constraint offers.
151        let has_geometry = state.has_selection();
152        let constraint_target = state.selected_constraint().filter(|_| {
153            crate::workbench::panel_visible(
154                &state.settings.workbench,
155                crate::workbench::assembly::CONSTRAINTS_PANEL_ID,
156                &crate::workbench::ButtonState::of(state),
157            )
158        });
159        // Nor while an eCAD editor owns the central tile (Diagram, PCB,
160        // Symbol, Pads): the card is anchored to that tile's corner and its
161        // actions are all 3D ones, so a 3D selection carried across a workbench
162        // switch — the Qualify panel's jump from a picked point, or a face picked
163        // in Modeling — would otherwise stay drawn over the editor, beside the
164        // editor's own tool card. The selection itself is kept for the return.
165        if (!has_geometry && constraint_target.is_none())
166            || state.ref_select_active()
167            || state.any_sketch_mode()
168            || crate::workbench::ecad::Target::of_workbench(&state.settings.workbench).is_some()
169        {
170            return ContextOutcome::default();
171        }
172
173        let sel = Selection::read(state);
174        let comp = component_selection(&sel, state);
175        let probe = selection_probe(&sel, &comp, all_on_sheet_metal(&sel, state));
176        // Welds consume component seams without editing the source part.
177        let mut offers = feature_offers_scoped(&probe, &sel, &state.settings.workbench, Some(state));
178        if comp.suppress_features() {
179            offers.retain(|offer| crate::workbench::welding::is_weld_type(&offer.type_code));
180        }
181        let constraint_types =
182            constraint_offers(&probe, &state.settings.workbench, &crate::workbench::ButtonState::of(state));
183        // PMI annotation offers: the third applicability family — each type's
184        // own predicate on the probe, plain and component geometry alike —
185        // gated on the PMI panel's workbench visibility AND an active view
186        // (creation is gated on a view to annotate).
187        let pmi_types = pmi_offers(
188            &probe,
189            &state.settings.workbench,
190            state.pmi_active_view().is_some(),
191            &crate::workbench::ButtonState::of(state),
192        );
193        // A single component's member solid(s) selected → the COMPONENT action
194        // set replaces the feature-creation offers — but ONLY in a workbench
195        // that shows the assembly structure panel (claim-based: Assembly +
196        // All). The component actions are that panel's row actions, so they
197        // follow its visibility and never bleed into Modeling / Sheet Metal;
198        // the STANDARD actions (Clear / Hide / Info / Edit owning) still apply
199        // to a component selection in every workbench.
200        let component_target = component_action_target(
201            &comp,
202            &state.settings.workbench,
203            &crate::workbench::ButtonState::of(state),
204        )
205        // A Pattern Component instance is not a component of its own: its
206        // actions are the pattern's (suppress it, go to its seed), below.
207        .filter(|id| brep_kernel::pattern_component_instance(id).is_none())
208        .map(|id| {
209            let fixed = state.component_info(id).map(|info| info.fixed).unwrap_or(false);
210            (id.to_string(), fixed)
211        });
212        // The seed of a selected instance: "Select seed" goes there.
213        let instance_seed = comp
214            .sole_target()
215            .and_then(brep_kernel::pattern_component_instance)
216            .map(|(_, seed, _)| seed);
217        // Any OTHER all-component selection — a face, edge or vertex of one
218        // component, or geometry of several — offers Move alone, aimed at the
219        // owning top-level occurrences (several move together on one gizmo).
220        let move_targets = if component_target.is_some() {
221            Vec::new()
222        } else {
223            // Moving an instance moves what it follows: its seed.
224            let mut targets: Vec<String> = Vec::new();
225            for id in component_move_targets(&comp, &state.settings.workbench, &crate::workbench::ButtonState::of(state)) {
226                let id = brep_kernel::pattern_component_instance(&id).map_or(id, |(_, seed, _)| seed);
227                if !targets.contains(&id) {
228                    targets.push(id);
229                }
230            }
231            targets
232        };
233
234        // Build the action items: the generic actions, then feature-from-selection.
235        // Info (🕵 U+1F575, the previous app's "Inspector, Metadata & Mass Properties"
236        // glyph, from the bundled Noto Sans Symbols 2 font) opens one PINNED Info
237        // window per selected entity — unlike the other actions it drives no engine
238        // mutation; the shell opens the windows from the returned targets.
239        let mut items = vec![ActionItem::new(
240            "action:clear",
241            "\u{2716} Clear",
242            "Clear the selection",
243        )];
244        self.shown_actions.push("clear".into());
245        // Hide + Info act on selected GEOMETRY — with only a constraint
246        // selected they would be no-ops, so they are not offered.
247        // A single component's own menu (below) carries its Hide/Show, Info
248        // and Edit feature: the standard ones would repeat them.
249        if has_geometry && component_target.is_none() {
250            items.push(ActionItem::new("action:hide", "\u{1f441} Hide", "Hide/Show selection"));
251            items.push(ActionItem::new(
252                "action:info",
253                "\u{1f575} Info",
254                "Open a pinned Info window per selected entity",
255            ));
256            self.shown_actions.push("hide".into());
257            self.shown_actions.push("info".into());
258        }
259        // The label-selected CONSTRAINT's action: delete it (the panel's row ✕,
260        // reachable from the viewport).
261        if let Some(cid) = &constraint_target {
262            items.push(ActionItem::new(
263                "action:delete-constraint",
264                "\u{2715} Delete constraint",
265                format!("Delete constraint {cid}"),
266            ));
267            self.shown_actions.push("delete-constraint".into());
268        }
269        // A feature selected from its tree row: Delete it (the row ✕), the
270        // same command the Delete key runs ([`crate::delete_selection`]).
271        let feature_target = match crate::delete_selection::model_target(state) {
272            Some(crate::delete_selection::DeleteTarget::Feature(id)) => Some(id),
273            _ => None,
274        };
275        if let Some(id) = &feature_target {
276            items.push(ActionItem::new(
277                "action:delete-feature",
278                "\u{2715} Delete feature",
279                format!("Delete feature {id} (Delete key; one undo step)"),
280            ));
281            self.shown_actions.push("delete-feature".into());
282        }
283        if let Some(item) = edit_owning_item(&sel).filter(|_| component_target.is_none()) {
284            items.push(item);
285            self.shown_actions.push("edit-owning".into());
286        }
287        if let Some(seed) = &instance_seed {
288            items.push(ActionItem::new(
289                "action:select-seed",
290                format!("Select seed {seed}"),
291                "Select the component this instance follows: move, mate or edit it, and every instance follows",
292            ));
293            self.shown_actions.push("select-seed".into());
294        }
295        // A pattern instance (a part Pattern copy or a Pattern Component
296        // instance): suppress it, and while any instance of that pattern is
297        // suppressed, bring them all back.
298        let pattern_instance = sel.single.as_deref().and_then(|name| state.pattern_instance_of(name));
299        if let Some((pattern, number)) = &pattern_instance {
300            items.push(ActionItem::new(
301                "action:suppress-instance",
302                format!("Suppress instance {number}"),
303                format!("Make instance {number} of {pattern} produce no geometry (one undo step)"),
304            ));
305            self.shown_actions.push("suppress-instance".into());
306            let suppressed = state.pattern_suppressed(pattern).len();
307            if suppressed > 0 {
308                items.push(ActionItem::new(
309                    "action:unsuppress-instances",
310                    format!("Unsuppress instances ({suppressed})"),
311                    format!("Bring back every suppressed instance of {pattern}"),
312                ));
313                self.shown_actions.push("unsuppress-instances".into());
314            }
315        }
316        // Component actions: shown INSTEAD of the feature offers when the
317        // selection is exactly one component's member solid(s). THE shared
318        // component menu, the viewport right-click's and the BOM row's too:
319        // same entries, availability and reasons.
320        if let Some((target, _)) = &component_target {
321            let subject = super::component_actions::MenuSubject::of(state, std::slice::from_ref(target));
322            for entry in super::component_actions::component_menu(&subject) {
323                items.push(
324                    ActionItem::new(format!("component:{}", entry.id), entry.label, entry.tooltip)
325                        .enabled(entry.enabled),
326                );
327                self.shown_component_actions.push(entry.id);
328            }
329            self.shown_component_target = Some(target.clone());
330            self.shown_component_targets = vec![target.clone()];
331        }
332        if !move_targets.is_empty() {
333            let action = ComponentAction::Move;
334            let tooltip = if move_targets.len() == 1 {
335                "Move the component that owns the selection (move/rotate gizmo on-off)"
336            } else {
337                "Move the selected components together with one move/rotate gizmo"
338            };
339            items.push(ActionItem::new(
340                format!("component:{}", action.id()),
341                action.label(false),
342                tooltip,
343            ));
344            self.shown_component_actions.push(action.id().to_string());
345            self.shown_component_targets = move_targets.clone();
346        }
347        // A prompt, not a block: when the targets include FIXED components,
348        // offer to unfix them and move them with the rest (one undo step).
349        // (A single component's menu has its own Unfix and Move.)
350        let unfix_targets = if component_target.is_some() {
351            Vec::new()
352        } else {
353            unfix_move_targets(state, &self.shown_component_targets)
354        };
355        if !unfix_targets.is_empty() {
356            items.push(ActionItem::new(
357                format!("component:{UNFIX_MOVE}"),
358                "\u{1F513} Unfix and Move",
359                "Unfix the fixed components in the selection and move them with the rest \
360                 (unfixed only when you drag; one undo step)",
361            ));
362            self.shown_component_actions.push(UNFIX_MOVE.to_string());
363        }
364        // Constraint offers (all-component selections in a workbench that shows
365        // the constraints panel): one button per applicable constraint type.
366        for def in &constraint_types {
367            items.push(ActionItem::new(
368                format!("constraint:{}", def.type_id),
369                def.long_name,
370                format!("Add a {} constraint from the selection", def.label),
371            ));
372            self.shown_constraints.push(def.type_id.to_string());
373        }
374        for offer in &offers {
375            items.push(ActionItem::new(
376                format!("feature:{}", offer.type_code),
377                offer.label.clone(),
378                format!("Create {} from the selection", offer.label),
379            ));
380            self.shown_features.push(offer.type_code.clone());
381        }
382        for def in &pmi_types {
383            items.push(ActionItem::new(
384                format!("pmi:{}", def.type_id),
385                def.long_name,
386                format!("Add a {} to the active PMI view from the selection", def.label),
387            ));
388            self.shown_pmi.push(def.type_id.to_string());
389        }
390
391        // With only a constraint selected the geometry summary would read all
392        // zeros — name the constraint instead.
393        let summary = match (&constraint_target, has_geometry) {
394            (Some(cid), false) => format!("Selected: constraint {cid}"),
395            _ => sel.summary(),
396        };
397        for action in crate::workbench::plugin_actions(state, &state.settings.workbench) {
398            if let Some(id) = action["id"].as_str() {
399                items.push(ActionItem::new(format!("plugin:{id}"), action["ribbonPath"].as_str().and_then(|p| p.rsplit('/').next()).or(action["label"].as_str()).unwrap_or(id), "Open plugin action form"));
400            }
401        }
402        let max_height = self.max_height;
403        let clicked = if crate::viewport::touch::compact(ui.ctx()) {
404            action_rail(ui, Some("Selection actions"), Some(&summary), &items, &mut self.hits)
405        } else {
406            egui::Frame::popup(ui.style())
407            .show(ui, |ui| {
408                let Some(limit) = max_height else {
409                    return action_rail(ui, Some("Selection actions"), Some(&summary), &items, &mut self.hits);
410                };
411                // The frame's own margins come off the limit; a rail that fits
412                // draws exactly as it does unbounded (the scroll area adds no
413                // offset), and one that does not scrolls, publishing its visible
414                // region as `panel:clip`.
415                let limit = (limit - ui.style().spacing.menu_margin.sum().y).max(4.0 * ui.spacing().interact_size.y);
416                let scroll = egui::ScrollArea::vertical()
417                    .id_salt("context-bar-rail")
418                    .max_height(limit)
419                    // An Area's ui is only as tall as last frame's content, which
420                    // would leave a scrolling rail at egui's 64-pt minimum.
421                    .min_scrolled_height(limit)
422                    .show(ui, |ui| action_rail(ui, Some("Selection actions"), Some(&summary), &items, &mut self.hits));
423                if scroll.content_size.y > scroll.inner_rect.height() + 0.5 {
424                    self.hits.insert("panel:clip".into(), scroll.inner_rect);
425                }
426                scroll.inner
427            })
428            .inner
429        };
430
431        // --- apply the intent (one engine mutation per frame) -----------------
432        let mut outcome = ContextOutcome::default();
433        match clicked.as_deref() {
434            Some(key) if key.starts_with("plugin:") => { outcome.plugin_action = Some(key[7..].to_owned()); }
435            Some("action:clear") => {
436                // Also drops a label-selected constraint (clear_selection folds
437                // the constraint selection in).
438                state.clear_selection();
439            }
440            Some("action:delete-constraint") => {
441                if let Some(cid) = &constraint_target {
442                    let target = crate::delete_selection::DeleteTarget::Constraint(cid.clone());
443                    if let Err(error) = crate::delete_selection::apply_engine(state, &target) {
444                        state.push_notice(error);
445                    }
446                }
447            }
448            Some("action:delete-feature") => {
449                if let Some(id) = &feature_target {
450                    let target = crate::delete_selection::DeleteTarget::Feature(id.clone());
451                    if let Err(error) = crate::delete_selection::apply_engine(state, &target) {
452                        state.push_notice(error);
453                    }
454                }
455            }
456            Some("action:hide") => {
457                state.hide_selected();
458            }
459            Some("action:select-seed") => {
460                if let Some(seed) = &instance_seed {
461                    state.select_component(seed);
462                }
463            }
464            Some("action:suppress-instance") => {
465                if let Some((pattern, number)) = &pattern_instance {
466                    match state.pattern_set_suppressed(pattern, Some(*number), true) {
467                        Ok(()) => {
468                            state.clear_selection();
469                        }
470                        Err(error) => state.push_notice(error),
471                    }
472                }
473            }
474            Some("action:unsuppress-instances") => {
475                if let Some((pattern, _)) = &pattern_instance {
476                    if let Err(error) = state.pattern_set_suppressed(pattern, None, false) {
477                        state.push_notice(error);
478                    }
479                }
480            }
481            Some("action:info") => {
482                // No engine mutation — hand the shell one target per selected entity
483                // so it opens (or, on dedup, keeps) a pinned Info window for each.
484                outcome.info_targets = sel.all_names();
485            }
486            Some("action:edit-owning") => {
487                // A bundle's button is disabled; a scripted click by key lands
488                // here anyway and gets the same answer as the tooltip.
489                if let Some(spline) = sel.harness_bundle() {
490                    state.push_notice(bundle_edit_hint(&spline));
491                } else if let Some(fid) = sel.owning_feature.clone() {
492                    if let Some(index) = feature_index(state, &fid) {
493                        state.roll_to(index);
494                    }
495                    outcome.focus = Some(fid);
496                }
497            }
498            Some(key) if key.starts_with("component:") => {
499                if let Some((target, _)) = &component_target {
500                    if let Some(action) = ComponentAction::from_id(&key["component:".len()..]) {
501                        outcome.component = run_component_action(state, action, target);
502                    }
503                    // The shared menu's Info and Edit feature report the way
504                    // the bar's own did.
505                    match outcome.component.take() {
506                        Some(ComponentActionRequest::Info { targets }) => outcome.info_targets = targets,
507                        Some(ComponentActionRequest::EditFeature { feature_id }) => outcome.focus = Some(feature_id),
508                        other => outcome.component = other,
509                    }
510                } else if key == "component:move" && !move_targets.is_empty() {
511                    state.component_move_group_toggle(&move_targets);
512                }
513                if key == format!("component:{UNFIX_MOVE}") && !unfix_targets.is_empty() {
514                    state.component_move_unfix_toggle(&unfix_targets);
515                }
516            }
517            Some(key) if key.starts_with("constraint:") => {
518                let type_id = &key["constraint:".len()..];
519                if constraint_types.iter().any(|def| def.type_id == type_id) {
520                    if let Err(error) = add_constraint_from_selection(state, type_id) {
521                        state.push_notice(format!("Add constraint: {error}"));
522                    }
523                }
524            }
525            Some(key) if key.starts_with("feature:") => {
526                let code = &key["feature:".len()..];
527                if let Some(offer) = offers.iter().find(|o| o.type_code == code) {
528                    outcome.focus = create_feature_from_selection(state, offer, &sel);
529                }
530            }
531            Some(key) if key.starts_with("pmi:") => {
532                let type_id = &key["pmi:".len()..];
533                if pmi_types.iter().any(|def| def.type_id == type_id) {
534                    // The add leaves the new annotation OPEN, so the dock's
535                    // dialog door surfaces the PMI pane; there is nothing for
536                    // this outcome to carry.
537                    if let Err(error) = add_pmi_from_selection(state, type_id) {
538                        state.push_notice(format!("Add PMI: {error}"));
539                    }
540                }
541            }
542            _ => {}
543        }
544        outcome
545    }
546
547    /// The published widget hit-rects (egui points) for the headed verifier —
548    /// `action:clear|action:hide|action:edit-owning` + `feature:<TYPE>`.
549    pub fn hits_json(&self) -> String {
550        crate::automation::hit_rects::hits_json(&self.hits)
551    }
552
553    /// The bar's LOGICAL state for the verifier: whether it is shown + which
554    /// generic actions, feature type-codes, and component actions it offered
555    /// this frame (and the single component the latter target).
556    pub fn state_json(&self) -> String {
557        serde_json::json!({
558            "shown": !self.hits.is_empty(),
559            "actions": self.shown_actions,
560            "features": self.shown_features,
561            "constraints": self.shown_constraints,
562            "pmi": self.shown_pmi,
563            "componentActions": self.shown_component_actions,
564            "componentTarget": self.shown_component_target,
565            "componentTargets": self.shown_component_targets,
566        })
567        .to_string()
568    }
569}
570
571/// The COMPONENT view of the current selection: which ACOMP instances own the
572/// selected entities, and whether the selection qualifies for the component
573/// action set / the feature-offer fence.
574struct ComponentSelection {
575    /// Unique owning ACOMP ids across every selected NAMED entity, selection
576    /// order.
577    ids: Vec<String>,
578    /// Whether EVERY selected entity is component-owned (and at least one is
579    /// selected; a vertex counts through its owning solid).
580    all_component: bool,
581    /// Whether the selection is member SOLIDS only (the shape a viewport
582    /// component click produces).
583    solids_only: bool,
584}
585
586impl ComponentSelection {
587    /// The feature FENCE: suppress modeling-feature creation offers when the
588    /// whole selection is component geometry.
589    fn suppress_features(&self) -> bool {
590        self.all_component && !self.ids.is_empty()
591    }
592
593    /// The single component the ACTION SET targets: exactly one owning
594    /// component, selected via its member solid(s) alone.
595    fn sole_target(&self) -> Option<&str> {
596        (self.suppress_features() && self.solids_only && self.ids.len() == 1)
597            .then(|| self.ids[0].as_str())
598    }
599
600    /// The occurrences a Move on this selection moves: every owning component
601    /// of an all-component selection (empty otherwise).
602    fn move_targets(&self) -> Vec<String> {
603        if self.suppress_features() {
604            self.ids.clone()
605        } else {
606            Vec::new()
607        }
608    }
609}
610
611/// Resolve the selection's component ownership through the engine's namespace
612/// parse (`component_of_solid` accepts any namespaced entity name — solid,
613/// face, or edge).
614fn component_selection(sel: &Selection, state: &EngineState) -> ComponentSelection {
615    let mut ids: Vec<String> = Vec::new();
616    let mut all = true;
617    let mut any = false;
618    for name in sel.all_names() {
619        any = true;
620        match state.component_of_solid(&name) {
621            Some(id) => {
622                if !ids.contains(&id) {
623                    ids.push(id);
624                }
625            }
626            None => all = false,
627        }
628    }
629    // Vertices carry no names: the engine resolves their owning solids.
630    if sel.vertices > 0 {
631        any = true;
632        match state.selected_vertex_components() {
633            Some(owners) => {
634                for id in owners {
635                    if !ids.contains(&id) {
636                        ids.push(id);
637                    }
638                }
639            }
640            None => all = false,
641        }
642    }
643    ComponentSelection {
644        ids,
645        all_component: all && any,
646        solids_only: !sel.solids.is_empty()
647            && sel.sketches.is_empty()
648            && sel.faces.is_empty()
649            && sel.edges.is_empty()
650            && sel.vertices == 0,
651    }
652}
653
654/// The **Edit owning feature** button for `sel`, if the selection has an owning
655/// feature: enabled and rolling to the producer, or — for a wire-harness bundle
656/// solid, whose producer is the harness tail and not a history feature —
657/// disabled with the tooltip saying what to edit instead.
658fn edit_owning_item(sel: &Selection) -> Option<ActionItem> {
659    sel.owning_feature.as_ref()?;
660    let item = match sel.harness_bundle() {
661        Some(spline) => ActionItem::new(
662            "action:edit-owning",
663            "Edit owning feature",
664            bundle_edit_hint(&spline),
665        )
666        .enabled(false),
667        None => ActionItem::new(
668            "action:edit-owning",
669            "Edit owning feature",
670            "Roll to and edit the feature that created this",
671        ),
672    };
673    Some(item)
674}
675
676/// What to edit instead of a bundle solid's (non-existent) owning feature.
677fn bundle_edit_hint(spline: &str) -> String {
678    format!(
679        "This bundle is built by the wire harness, not by a feature. \
680         Edit spline {spline} (the path it follows) or the wires in the Wire Harness panel instead"
681    )
682}
683
684/// The current selection, resolved once per frame from `selection_json`, plus the
685/// single-selection owning feature (for **Edit owning feature**).
686struct Selection {
687    solids: Vec<String>,
688    /// Selected COMMITTED SKETCHES. A committed sketch presents in the scene as a
689    /// solid (`is_sketch`), so it arrives in `selection_json`'s `solids` array; we
690    /// partition it out here because its reference KIND is `SKETCH`, not `SOLID`
691    /// (it must satisfy a `["FACE","SKETCH"]` profile field, and must NOT satisfy a
692    /// `["SOLID"]` field like SM Cutout's `sheet`).
693    sketches: Vec<String>,
694    faces: Vec<String>,
695    edges: Vec<String>,
696    /// Selected construction PLANES / DATUM planes (their scene FRAME names, from
697    /// `selection_json`'s `datums` array). Kept a SEPARATE bucket from `faces`:
698    /// only [`kinds_present`](Self::kinds_present) / [`names_for_filter`](Self::
699    /// names_for_filter) / the probe read it — NEVER the scene-solid consumers
700    /// (`all_names`, Info, Hide, `component_selection`), which cannot resolve a
701    /// datum frame name. A datum plane seats a sketch's `sketchPlane` exactly like
702    /// a planar face (the kernel resolves either).
703    planes: Vec<String>,
704    vertices: usize,
705    /// The producer feature id of a SINGLE-entity selection with a known producer.
706    owning_feature: Option<String>,
707    /// The name of a SINGLE-entity selection.
708    single: Option<String>,
709}
710
711impl Selection {
712    /// When the single selected entity is (or belongs to) a wire-harness BUNDLE
713    /// solid — its producer is the harness tail, never a history feature — the
714    /// id of the spline the bundle follows (`WireHarness:SP1` → `SP1`). `None`
715    /// for every other selection.
716    fn harness_bundle(&self) -> Option<String> {
717        if self.owning_feature.as_deref() != Some(brep_kernel::WIRE_HARNESS_FEATURE_ID) {
718            return None;
719        }
720        let name = self
721            .solids
722            .first()
723            .or_else(|| self.faces.first())
724            .or_else(|| self.edges.first())?;
725        // A face of the bundle is `WireHarness:SP1:Wall0`; the spline is the
726        // segment between the prefix and the next colon.
727        let rest = name.strip_prefix(brep_kernel::BUNDLE_SOLID_PREFIX)?;
728        let spline = rest.split(':').next().filter(|id| !id.is_empty())?;
729        Some(spline.to_string())
730    }
731
732    fn read(state: &EngineState) -> Self {
733        let v: Value = serde_json::from_str(&state.selection_json()).unwrap_or(Value::Null);
734        let names = |key: &str| -> Vec<String> {
735            v[key]
736                .as_array()
737                .map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect())
738                .unwrap_or_default()
739        };
740        // Partition the selected `solids` into REAL solids vs committed sketches: a
741        // selected solid is a sketch iff its name is a committed sketch (the
742        // sketch's selectable name is its id; visibility is irrelevant here).
743        let sketch_ids: std::collections::HashSet<String> = state
744            .committed_sketches()
745            .into_iter()
746            .map(|(id, _visible)| id)
747            .collect();
748        let (sketches, solids): (Vec<String>, Vec<String>) = names("solids")
749            .into_iter()
750            .partition(|name| sketch_ids.contains(name));
751        let faces = names("faces");
752        let edges = names("edges");
753        // Construction planes / datum planes arrive under `datums` — a SEPARATE
754        // bucket (never merged into `faces`): the scene-solid consumers cannot
755        // resolve a datum frame name (see the `planes` field doc).
756        let planes = names("datums");
757        let vertices = v["vertices"].as_u64().unwrap_or(0) as usize;
758
759        // A single selected entity → its owning feature (the old app's
760        // Edit-owning-feature, generalized from FACE/PLANE to any single entity —
761        // a lone selected sketch rolls to its `S` feature, a lone datum/plane to
762        // its `D`/`P` feature). Datum planes count toward the single-selection
763        // total too, else picking one shows no Edit-owning-feature button.
764        let total = solids.len() + sketches.len() + faces.len() + edges.len() + planes.len();
765        let single = if total == 1 && vertices == 0 {
766            faces
767                .first()
768                .or_else(|| edges.first())
769                .or_else(|| solids.first())
770                .or_else(|| sketches.first())
771                .or_else(|| planes.first())
772                .cloned()
773        } else {
774            None
775        };
776        let owning_feature = single
777            .as_deref()
778            .and_then(|name| state.creating_feature(name))
779            .map(|(id, _ty)| id);
780
781        Self {
782            solids,
783            sketches,
784            faces,
785            edges,
786            planes,
787            vertices,
788            owning_feature,
789            single,
790        }
791    }
792
793    /// The selectable KINDS currently present (vertices carry no names, and no
794    /// primary reference is vertex-only, so they never drive feature actions).
795    fn kinds_present(&self) -> Vec<&'static str> {
796        let mut kinds = Vec::new();
797        if !self.solids.is_empty() {
798            kinds.push("SOLID");
799        }
800        if !self.sketches.is_empty() {
801            kinds.push("SKETCH");
802        }
803        if !self.faces.is_empty() {
804            kinds.push("FACE");
805        }
806        if !self.edges.is_empty() {
807            kinds.push("EDGE");
808        }
809        // Datum planes and `P` planes both present as ONE kind, `PLANE` — the
810        // schema filters spell it `["PLANE","FACE"]`, and both resolve as frames.
811        if !self.planes.is_empty() {
812            kinds.push("PLANE");
813        }
814        kinds
815    }
816
817    /// The selected names whose kind the reference `filter` accepts (de-duplicated,
818    /// in solid→face→edge order). `PLANE`/`DATUM` map to selected datum/plane
819    /// frames, `COMPONENT` to selected solids (the picker never yields a bare
820    /// component here).
821    fn names_for_filter(&self, filter: &[String]) -> Vec<String> {
822        let mut out: Vec<String> = Vec::new();
823        let push = |src: &[String], out: &mut Vec<String>| {
824            for name in src {
825                if !out.iter().any(|n| n == name) {
826                    out.push(name.clone());
827                }
828            }
829        };
830        for f in filter {
831            match f.as_str() {
832                "SOLID" | "COMPONENT" => push(&self.solids, &mut out),
833                "SKETCH" => push(&self.sketches, &mut out),
834                "FACE" => push(&self.faces, &mut out),
835                // A `["PLANE","FACE"]` field prefills from EITHER a selected face
836                // (via the FACE arm) or a selected datum/plane frame here; `DATUM`
837                // is an alias for the same planes bucket.
838                "PLANE" | "DATUM" => push(&self.planes, &mut out),
839                "EDGE" => push(&self.edges, &mut out),
840                _ => {}
841            }
842        }
843        out
844    }
845
846    /// Every NAMED selected entity (solids → faces → edges), de-duplicated — one per
847    /// pinned Info window the Info action opens. Vertices carry no name, and datum
848    /// PLANES are deliberately EXCLUDED: this list feeds the scene-solid consumers
849    /// (Info, Hide via `hide_selected`, `component_selection` via
850    /// `component_of_solid`), none of which can resolve a datum frame name. A datum
851    /// plane can be selected (`has_selection` now counts it, so the bar shows and
852    /// offers Sketch), but it only reaches `kinds_present` / `names_for_filter` /
853    /// the probe — never this list.
854    fn all_names(&self) -> Vec<String> {
855        let mut out: Vec<String> = Vec::new();
856        for src in [&self.solids, &self.sketches, &self.faces, &self.edges] {
857            for name in src {
858                if !name.is_empty() && !out.iter().any(|n| n == name) {
859                    out.push(name.clone());
860                }
861            }
862        }
863        out
864    }
865
866    /// "Selected: 2 faces, 1 edge" — the kinds that ARE selected, in the
867    /// bar's own order, each counted in the singular or the plural. It used to
868    /// list every kind with its zero ("0 solid, 0 sketch, 1 face, 0 edge,
869    /// 0 plane, 0 vertex"), six numbers to find the one that was not 0
870    /// (ui-polish-2026-10-28 row 3).
871    fn summary(&self) -> String {
872        let count = crate::panels::count;
873        let parts: Vec<String> = [
874            (self.solids.len(), "solid", "solids"),
875            (self.sketches.len(), "sketch", "sketches"),
876            (self.faces.len(), "face", "faces"),
877            (self.edges.len(), "edge", "edges"),
878            (self.planes.len(), "plane", "planes"),
879            (self.vertices, "vertex", "vertices"),
880        ]
881        .into_iter()
882        .filter(|(n, _, _)| *n > 0)
883        .map(|(n, one, many)| count(n, one, many))
884        .collect();
885        if parts.is_empty() {
886            "Selected: nothing".to_string()
887        } else {
888            format!("Selected: {}", parts.join(", "))
889        }
890    }
891}
892
893/// One reference field of an offered feature, in schema order — the pre-fill
894/// targets [`prefill_references`] consumes the selection into.
895struct OfferField {
896    /// The JSON path of the `References`-group field.
897    path: Vec<String>,
898    /// That field's `selectionFilter` (which selected kinds map into it).
899    filter: Vec<String>,
900    /// Whether automatic prefill writes a list (vs a single name).
901    multiple: bool,
902}
903
904/// One offered feature action.
905struct Offer {
906    /// The feature TYPE CODE (e.g. `E`, `F`, `CH`).
907    type_code: String,
908    /// The button label (the feature's long name).
909    label: String,
910    /// Every `References`-group field whose filter accepts a selected kind
911    /// (schema order) — the create pre-fills them under a consumed set.
912    fields: Vec<OfferField>,
913}
914
915/// Build the [`SelectionProbe`] the kernel applicability predicates run on:
916/// the selection's kind counts, its component view, and whether it sits entirely
917/// on sheet metal ([`all_on_sheet_metal`], the gate for the SM edit features).
918fn selection_probe(
919    sel: &Selection,
920    comp: &ComponentSelection,
921    all_sheet_metal: bool,
922) -> SelectionProbe {
923    SelectionProbe {
924        solids: sel.solids.len(),
925        sketches: sel.sketches.len(),
926        faces: sel.faces.len(),
927        edges: sel.edges.len(),
928        planes: sel.planes.len(),
929        vertices: sel.vertices,
930        components: comp.ids.len(),
931        all_component: comp.all_component,
932        all_sheet_metal,
933    }
934}
935
936/// Whether the selection sits ENTIRELY on sheet-metal bodies (and names at least
937/// one entity) — the gate the SM edit features (Flange / Fillet / Chamfer) key
938/// on. Mirrors [`component_selection`]'s all-or-nothing rule, including its
939/// vertex convention: a vertex carries no name to resolve, so any vertex in the
940/// selection disqualifies it.
941fn all_on_sheet_metal(sel: &Selection, state: &EngineState) -> bool {
942    let names = sel.all_names();
943    !names.is_empty()
944        && sel.vertices == 0
945        && names.iter().all(|name| state.is_sheet_metal_object(name))
946}
947
948/// The feature actions to offer: every catalogue feature whose OWN
949/// `context_applicable` predicate (kernel-defined, next to its schema —
950/// `feature_pipeline::context_offer`) accepts the current selection probe. The
951/// `workbench` argument only FURTHER RESTRICTS that set to the features the
952/// active workbench includes; like the palette filter it is a pure UI trim over
953/// CREATION and never affects the existing history / execution.
954///
955/// The pre-fill stays schema-derived: each offer carries EVERY
956/// `References`-group `reference_selection` field whose `selectionFilter`
957/// intersects a selected kind (schema order), and the create consumes the
958/// selection into them ([`prefill_references`]).
959
960fn feature_offers_scoped(probe: &SelectionProbe, sel: &Selection, workbench: &str, engine: Option<&EngineState>) -> Vec<Offer> {
961    let kinds = sel.kinds_present();
962    if kinds.is_empty() {
963        return Vec::new();
964    }
965    let catalogue = engine.map_or_else(features::feature_catalogue, |e| e.feature_catalogue());
966    let mut out = Vec::new();
967    if let Some(list) = catalogue.get("features").and_then(Value::as_array) {
968        for feature in list {
969            let Some(ty) = feature.get("type").and_then(Value::as_str) else {
970                continue;
971            };
972            if ty.is_empty() {
973                continue;
974            }
975            // Workbench UI filter: skip features this workbench does not include
976            // (classified off the type code).
977            if !engine.map_or_else(|| crate::workbench::includes_feature(workbench, ty), |e| crate::workbench::includes_feature_scoped(e, workbench, ty)) {
978                continue;
979            }
980            // The feature's own answer to "does this selection make me
981            // meaningful?" — nuance (Revolve wants profile AND axis) lives in
982            // the kernel predicate, not here.
983            if !ty.contains('/') && !brep_kernel::feature_context_applicable(ty, probe) {
984                continue;
985            }
986            // The pre-fill targets: every `References`-group reference field
987            // accepting a selected kind. Primitives only carry the boolean-op
988            // `targets` Reference (group `Boolean`), so they never collect any
989            // (their predicates return false anyway).
990            let fields = offer_fields(engine, ty, &kinds);
991            if ty.contains('/') && fields.is_empty() { continue; }
992            out.push(Offer {
993                type_code: ty.to_string(),
994                label: crate::workbench::feature_command_label(feature),
995                fields,
996            });
997        }
998    }
999    out
1000}
1001
1002/// Every `References`-group reference field of feature `ty` whose
1003/// `selectionFilter` accepts one of the selected `kinds`, in schema order:
1004/// the pre-fill targets [`prefill_references`] consumes the selection into.
1005fn offer_fields(engine: Option<&EngineState>, ty: &str, kinds: &[&str]) -> Vec<OfferField> {
1006    engine
1007        .map_or_else(|| features::feature_form_fields(ty), |e| e.feature_form_fields(ty))
1008        .iter()
1009        .filter(|field| field.group == "References")
1010        .filter_map(|field| {
1011            let FieldKind::Reference { filter, multiple } = &field.kind else {
1012                return None;
1013            };
1014            let mut filter = filter.clone();
1015            // Auto-seed a weld's seam as before; a mating face on another part
1016            // is not an owner constraint. Optional scopes are added in the form.
1017            if ty == "WELD" && field.path == ["seam"] {
1018                filter.retain(|kind| matches!(kind.as_str(), "EDGE" | "SKETCH"));
1019            }
1020            filter
1021                .iter()
1022                .any(|f| kinds.iter().any(|k| *k == f.as_str()))
1023                .then(|| OfferField {
1024                    path: field.path.clone(),
1025                    filter: filter.clone(),
1026                    multiple: *multiple,
1027                })
1028        })
1029        .collect()
1030}
1031
1032/// Seed a NEW feature's reference fields from the current selection, exactly
1033/// as the context bar's feature buttons do: the toolbar icons (Classic strip
1034/// and Ribbon Home) and the Add-feature palette create through
1035/// [`crate::panels::history::HistoryPanel::add_feature_of_type`], which calls
1036/// this on the fresh `inputParams` before appending. The same consumed-set
1037/// pre-fill ([`prefill_references`]) and the same component fence apply: a
1038/// selection made entirely of component geometry seeds nothing (the kernel
1039/// rejects component references). Returns the number of fields seeded.
1040pub(crate) fn prefill_from_selection(state: &EngineState, type_code: &str, params: &mut Value) -> usize {
1041    if state.any_sketch_mode() || state.ref_select_active() {
1042        return 0;
1043    }
1044    let sel = Selection::read(state);
1045    let kinds = sel.kinds_present();
1046    if kinds.is_empty() || (!crate::workbench::welding::is_weld_type(type_code) && component_selection(&sel, state).suppress_features()) {
1047        return 0;
1048    }
1049    let writes = prefill_references(&offer_fields(Some(state), type_code, &kinds), &sel);
1050    let count = writes.len();
1051    for (path, value) in writes {
1052        form::set_at(params, &path, value);
1053    }
1054    count
1055}
1056
1057/// The single component the context bar's COMPONENT action set targets, or
1058/// `None` when the selection shape doesn't qualify ([`ComponentSelection::
1059/// sole_target`]) OR the active workbench hides the assembly structure panel
1060/// (claim-based visibility, [`crate::workbench::panel_visible`]: Assembly +
1061/// All). The workbench gate is what keeps the Move / Edit-in-place / Open-Part
1062/// / Fix / Delete buttons — assembly UI — out of the Modeling context bar; the
1063/// feature FENCE (`suppress_features`) is intentionally NOT gated, since the
1064/// kernel rejects component references in every workbench.
1065/// The one component the bar's component actions (and the Delete key, via
1066/// [`crate::delete_selection`]) target for the current selection: the bar's
1067/// own rule, with a Pattern Component instance excluded (its actions are the
1068/// pattern's). A small shared hook so the Delete key and the bar never disagree.
1069pub(crate) fn component_action_target_of(state: &EngineState) -> Option<String> {
1070    let sel = Selection::read(state);
1071    let comp = component_selection(&sel, state);
1072    component_action_target(&comp, &state.settings.workbench, &crate::workbench::ButtonState::of(state))
1073        .filter(|id| brep_kernel::pattern_component_instance(id).is_none())
1074        .map(str::to_string)
1075}
1076
1077fn component_action_target<'a>(
1078    comp: &'a ComponentSelection,
1079    workbench: &str,
1080    panels: &crate::workbench::ButtonState,
1081) -> Option<&'a str> {
1082    // The BOM is the assembly workbench's component list (it absorbed the
1083    // Structure panel): component actions target a selection only where that
1084    // list is on screen.
1085    let list_shown = crate::workbench::panel_visible(
1086        workbench,
1087        crate::workbench::assembly::BOM_PANEL_ID,
1088        panels,
1089    );
1090    list_shown.then(|| comp.sole_target()).flatten()
1091}
1092
1093/// The context bar's "Unfix and Move" action id (`component:unfix-move`) —
1094/// a bar-only action, not one of the BOM row menu's [`ComponentAction`]s.
1095const UNFIX_MOVE: &str = "unfix-move";
1096
1097/// The components "Unfix and Move" acts on: all of `targets` when at least
1098/// one of them is fixed, else none (plain Move already covers them).
1099fn unfix_move_targets(state: &EngineState, targets: &[String]) -> Vec<String> {
1100    let any_fixed = targets
1101        .iter()
1102        .any(|id| state.component_info(id).is_some_and(|info| info.fixed));
1103    if any_fixed {
1104        targets.to_vec()
1105    } else {
1106        Vec::new()
1107    }
1108}
1109
1110/// The occurrences the lone Move action targets for a selection that is not
1111/// the single-component action shape — under the same BOM-visibility gate as
1112/// [`component_action_target`].
1113fn component_move_targets(
1114    comp: &ComponentSelection,
1115    workbench: &str,
1116    panels: &crate::workbench::ButtonState,
1117) -> Vec<String> {
1118    let list_shown = crate::workbench::panel_visible(
1119        workbench,
1120        crate::workbench::assembly::BOM_PANEL_ID,
1121        panels,
1122    );
1123    if list_shown && comp.sole_target().is_none() {
1124        comp.move_targets()
1125    } else {
1126        Vec::new()
1127    }
1128}
1129
1130/// The PMI annotation actions to offer: every type whose `applicable`
1131/// predicate ([`brep_kernel::PMI_TYPES`]) accepts the probe — gated on the PMI
1132/// panel being available in the active workbench (Modeling, Sheet Metal, Assembly, All) and on an active
1133/// view (no view ⇒ no offers).
1134fn pmi_offers(
1135    probe: &SelectionProbe,
1136    workbench: &str,
1137    view_active: bool,
1138    panels: &crate::workbench::ButtonState,
1139) -> Vec<&'static brep_kernel::PmiTypeDef> {
1140    if !view_active
1141        || !crate::workbench::panel_visible(workbench, crate::workbench::pmi::PANEL_ID, panels)
1142    {
1143        return Vec::new();
1144    }
1145    brep_kernel::PMI_TYPES
1146        .iter()
1147        .filter(|def| (def.applicable)(probe))
1148        .collect()
1149}
1150
1151/// Add a PMI annotation of `type_id` to the active view, its reference
1152/// fields pre-seeded from the selection by the schema's `selectionFilter`s
1153/// (faces / edges / datum planes / solids by name, vertices as `{solid}@x,y,z`
1154/// world refs). The annotation plane is never seeded — a selected face is
1155/// the geometry being annotated; the plane is picked in the form. The new
1156/// annotation's form opens (the engine sets the open annotation).
1157pub(crate) fn add_pmi_from_selection(state: &mut EngineState, type_id: &str) -> Result<String, String> {
1158    let catalogue = brep_render::pmi_weld_symbol::pmi_schema_catalogue();
1159    let schema = catalogue
1160        .as_array()
1161        .and_then(|entries| entries.iter().find(|e| e.get("type").and_then(Value::as_str) == Some(type_id)))
1162        .cloned()
1163        .ok_or_else(|| format!("no schema for PMI type '{type_id}'"))?;
1164    let selection: Value = serde_json::from_str(&state.selection_json()).unwrap_or(Value::Null);
1165    let names = |key: &str| -> Vec<String> {
1166        selection[key]
1167            .as_array()
1168            .map(|items| items.iter().filter_map(|item| item.as_str().map(String::from)).collect())
1169            .unwrap_or_default()
1170    };
1171    let vertices: Vec<String> = state
1172        .emphasis
1173        .selected_vertices
1174        .iter()
1175        .map(|vertex| brep_render::engine_state::world_vertex_ref(&vertex.solid, vertex.position))
1176        .collect();
1177    let mut seeded = serde_json::Map::new();
1178    let mut consumed: Vec<String> = Vec::new();
1179    if let Some(fields) = schema.get("inputParamsSchema").and_then(Value::as_object) {
1180        for (key, spec) in fields {
1181            if spec.get("type").and_then(Value::as_str) != Some("reference_selection") || key == "plane" {
1182                continue;
1183            }
1184            let filter: Vec<String> = spec
1185                .get("selectionFilter")
1186                .and_then(Value::as_array)
1187                .map(|kinds| kinds.iter().filter_map(|k| k.as_str().map(String::from)).collect())
1188                .unwrap_or_default();
1189            let multiple = spec.get("multiple").and_then(Value::as_bool).unwrap_or(false);
1190            let cap = spec.get("maxSelections").and_then(Value::as_u64).unwrap_or(if multiple { 64 } else { 1 }) as usize;
1191            let mut picked: Vec<String> = Vec::new();
1192            for kind in &filter {
1193                let source: Vec<String> = match kind.to_ascii_uppercase().as_str() {
1194                    "FACE" => names("faces"),
1195                    "EDGE" => names("edges"),
1196                    "PLANE" | "DATUM" => names("datums"),
1197                    "SOLID" | "COMPONENT" => names("solids"),
1198                    "VERTEX" => vertices.clone(),
1199                    _ => Vec::new(),
1200                };
1201                for name in source {
1202                    if picked.len() < cap && !picked.contains(&name) && !consumed.contains(&name) {
1203                        picked.push(name);
1204                    }
1205                }
1206            }
1207            if picked.is_empty() {
1208                continue;
1209            }
1210            consumed.extend(picked.iter().cloned());
1211            let value = if multiple {
1212                Value::Array(picked.into_iter().map(Value::String).collect())
1213            } else {
1214                Value::String(picked.remove(0))
1215            };
1216            seeded.insert(key.clone(), value);
1217        }
1218    }
1219    state.pmi_add_annotation(None, type_id, &Value::Object(seeded).to_string())
1220}
1221
1222/// The constraint actions to offer: every constraint type whose `applicable`
1223/// predicate ([`brep_kernel::CONSTRAINT_TYPES`], defined with the type table)
1224/// accepts the probe — gated on the Assembly Constraints panel being available
1225/// in the active workbench (claim-based visibility: Assembly + All).
1226fn constraint_offers(
1227    probe: &SelectionProbe,
1228    workbench: &str,
1229    panels: &crate::workbench::ButtonState,
1230) -> Vec<&'static brep_kernel::ConstraintTypeDef> {
1231    if !crate::workbench::panel_visible(
1232        workbench,
1233        crate::workbench::assembly::CONSTRAINTS_PANEL_ID,
1234        panels,
1235    ) {
1236        return Vec::new();
1237    }
1238    brep_kernel::CONSTRAINT_TYPES
1239        .iter()
1240        .filter(|def| (def.applicable)(probe))
1241        .collect()
1242}
1243
1244/// Add a constraint of `type_id` from the selection: `elements` pre-seeded
1245/// through the constraints panel's seeding helper (filtered + capped by the
1246/// type's own schema), then the new row opened so the panel shows its dialog.
1247/// The engine's mutation path handles auto-solve exactly like a panel add.
1248pub(crate) fn add_constraint_from_selection(
1249    state: &mut EngineState,
1250    type_id: &str,
1251) -> Result<String, String> {
1252    let catalogue = brep_kernel::constraint_schema_catalogue();
1253    let schemas: Vec<Value> = catalogue.as_array().cloned().unwrap_or_default();
1254    let seed = super::assembly_constraints::seeded_elements(state, &schemas, type_id);
1255    let id = state.assembly_add_constraint(type_id, &seed.to_string())?;
1256    let _ = state.assembly_set_constraint_open(&id, true);
1257    Ok(id)
1258}
1259
1260/// Consume the selection into an offer's reference fields, schema order: each
1261/// field takes the selected names its filter accepts that NO EARLIER field
1262/// consumed (first name for a single field, all remaining for a multiple) — so
1263/// face+edge → Revolve fills `profile` with the face and `axis` with the edge,
1264/// and Pattern's edge lands in `directionRef` without echoing into `axisRef`.
1265/// Returns `(path, value)` writes for [`form::set_at`].
1266fn prefill_references(fields: &[OfferField], sel: &Selection) -> Vec<(Vec<String>, Value)> {
1267    let mut consumed: HashSet<String> = HashSet::new();
1268    let mut writes = Vec::new();
1269    for field in fields {
1270        let names: Vec<String> = sel
1271            .names_for_filter(&field.filter)
1272            .into_iter()
1273            .filter(|name| !consumed.contains(name))
1274            .collect();
1275        if names.is_empty() {
1276            continue;
1277        }
1278        let value = if field.multiple {
1279            consumed.extend(names.iter().cloned());
1280            Value::Array(names.into_iter().map(Value::String).collect())
1281        } else {
1282            let name = names.into_iter().next().unwrap_or_default();
1283            consumed.insert(name.clone());
1284            Value::String(name)
1285        };
1286        writes.push((field.path.clone(), value));
1287    }
1288    writes
1289}
1290
1291/// Create a feature of `offer.type_code` referencing the selection: build a
1292/// fresh descriptor whose `inputParams` are the schema defaults with an
1293/// engine-unique `id` and the matched reference fields pre-filled
1294/// ([`prefill_references`]), then append it (`add_feature`, which rolls to it).
1295/// Returns the new feature id (for the shell to expand its node).
1296fn create_feature_from_selection(
1297    state: &mut EngineState,
1298    offer: &Offer,
1299    sel: &Selection,
1300) -> Option<String> {
1301    let short = state.feature_schema(&offer.type_code).and_then(|s| s["shortName"].as_str().filter(|s| !s.is_empty()).map(str::to_owned)).unwrap_or_else(|| features::feature_short_name(&offer.type_code));
1302    let id = state.next_feature_id(&short);
1303    let mut params = state.feature_default_params(&offer.type_code);
1304    if let Value::Object(map) = &mut params {
1305        map.insert("id".into(), Value::String(id.clone()));
1306    }
1307
1308    for (path, value) in prefill_references(&offer.fields, sel) {
1309        form::set_at(&mut params, &path, value);
1310    }
1311
1312    let feature = serde_json::json!({
1313        "type": offer.type_code,
1314        "inputParams": params,
1315        "persistentData": {},
1316    });
1317    if state.add_feature(&feature.to_string()).is_ok() {
1318        Some(id)
1319    } else {
1320        None
1321    }
1322}
1323
1324/// The feature index carrying id `id` (the engine exposes index→id, so we scan).
1325fn feature_index(state: &EngineState, id: &str) -> Option<usize> {
1326    (0..state.history_len()).find(|&i| state.feature_id_at(i).as_deref() == Some(id))
1327}
1328
1329
1330/// The hit keys this panel publishes (see `automation::hit_keys`).
1331pub static HIT_KEYS: &[HitKeyDoc] = &[
1332    HitKeyDoc { panel: "context", prefix: "panel:clip", meaning: "the action rail's visible region, published only while the rail is taller than the room above the ViewCube and scrolls", command: None },
1333    HitKeyDoc { panel: "context", prefix: "plugin:", meaning: "open a plugin action form for current selection", command: Some("plugin_action") },
1334    // The generic actions were published from the day the bar was built and
1335    // documented by nobody, so `hit_keys_check` reported four undocumented keys
1336    // the moment a script left something selected while the bar was up — which
1337    // no script had done before the verifier migration.
1338    HitKeyDoc { panel: "context", prefix: "action:clear", meaning: "clear the selection", command: Some("select_clear") },
1339    HitKeyDoc { panel: "context", prefix: "action:hide", meaning: "hide or show the selected geometry", command: Some("set_visible") },
1340    HitKeyDoc { panel: "context", prefix: "action:info", meaning: "open one pinned Info window per selected entity (mass properties, topology, metadata)", command: None },
1341    HitKeyDoc { panel: "context", prefix: "action:delete-feature", meaning: "delete the feature selected from its history-tree row (the Delete key's command)", command: Some("selection_delete") },
1342    HitKeyDoc { panel: "context", prefix: "action:delete-constraint", meaning: "delete the assembly constraint whose viewport label is selected", command: Some("assembly_remove_constraint") },
1343    HitKeyDoc { panel: "context", prefix: "action:suppress-instance", meaning: "suppress the selected pattern instance (a part Pattern copy makes no geometry; a Pattern Component instance places nothing)", command: None },
1344    HitKeyDoc { panel: "context", prefix: "action:select-seed", meaning: "select the seed component a Pattern Component instance follows", command: None },
1345    HitKeyDoc { panel: "context", prefix: "action:unsuppress-instances", meaning: "bring back every suppressed instance of the selected instance's Pattern", command: None },
1346    HitKeyDoc { panel: "context", prefix: "action:edit-owning", meaning: "roll to and edit the feature that created the selection (disabled for a wire-harness bundle solid, which no history feature owns)", command: None },
1347    HitKeyDoc { panel: "context", prefix: "feature:", meaning: "add the offered feature from the selection (feature:type)", command: None },
1348    HitKeyDoc { panel: "context", prefix: "component:", meaning: "a component action", command: None },
1349    HitKeyDoc { panel: "context", prefix: "constraint:", meaning: "add the offered assembly constraint", command: None },
1350    HitKeyDoc { panel: "context", prefix: "pmi:", meaning: "add the offered PMI annotation (pmi:type)", command: None },
1351    HitKeyDoc { panel: "context", prefix: "Selected:", meaning: "the selection summary chip", command: None },
1352];