Skip to main content

brep_app/workbench/
mod.rs

1//! Per-file WORKBENCH registry — a UI FILTER over feature-CREATION.
2//!
3//! A "workbench" trims the feature-creation UI (the "Add new feature" palette and
4//! the selection context bar) and can gate workbench-specific toolbar buttons /
5//! panels. It NEVER changes what the feature history executes, renders, or lets
6//! the user edit: a document full of sheet-metal features opens and works
7//! identically under Modeling. The ONLY things a workbench touches are the palette
8//! (see [`includes_feature`]) and the context offers.
9//!
10//! Built-in workbenches are extended with one new file here + one
11//! entry in [`WORKBENCHES`]. No enums to edit. Each file exposes a single
12//! `'static` [`Workbench`] that OWNS its own inclusion decision (`includes`), its
13//! extra toolbar buttons (data only), and the ids of existing panels it claims.
14//!
15//! Plugin workbenches use the document-scoped [`OwnedWorkbench`] overlay;
16//! their owned strings and schemas never enter the static built-in registry.
17//!
18//! `"All"` is special: it accepts every feature and its buttons are the DERIVED
19//! union of every other workbench's buttons ([`workbench_buttons`]) — never
20//! hand-maintained — so adding a workbench automatically grows it.
21//!
22//! # Shared buttons: a shell MODE's tools belong to no workbench
23//!
24//! A workbench filters feature CREATION. A shell MODE — sketch editing — is
25//! entered from a surface no workbench filters, so its tools cannot be any one
26//! workbench's without vanishing under the others. [`shared_buttons`] is the
27//! second list every row carries: declared once ([`sketch::BUTTONS`]),
28//! conditional on the mode, appended to every workbench's own buttons. That is
29//! what makes the row the SINGLE home for "this mode's tools" — there is no
30//! strip of its own to keep in step, and switching workbench mid-sketch keeps
31//! the tools.
32
33use brep_render::engine_state::EngineState;
34mod commands;
35pub use commands::*;
36
37pub mod all;
38pub mod assembly;
39pub mod cam;
40pub mod diagram;
41pub mod drawing;
42pub mod ecad;
43pub mod gears;
44pub mod instructions;
45pub mod modeling;
46pub mod pads;
47pub mod pcb;
48pub mod schematic;
49pub mod pmi;
50pub mod sheet_metal;
51pub mod simulation;
52pub mod sketch;
53pub mod sketch3d;
54pub mod symbol;
55pub mod wire_harness;
56pub mod welding;
57
58/// The minimal view of one catalogue entry a workbench predicate consumes: the
59/// feature `type` CODE (e.g. `"E"`, `"S"`, `"SM.F"`), read from the existing
60/// app-side catalogue accessor ([`brep_render::features::feature_catalogue`]).
61/// Each workbench file classifies DIRECTLY off this code (no kernel-stamped
62/// category — the kernel stays untouched). Borrows from the runtime catalogue
63/// JSON, hence the lifetime — the registry itself stays `'static` because the
64/// fn-pointer predicate is higher-ranked over the borrow.
65pub struct FeatureInfo<'a> {
66    pub type_code: &'a str,
67}
68
69/// What a button's predicates read: the document's engine and, for the eCAD
70/// workbenches, the document's eCAD editors.
71///
72/// The editors are not engine state — they are egui widgets the app keeps per
73/// document ([`ecad::Editors`]) — so a predicate that only took the engine
74/// could not say whether eCAD's wire tool is armed, and an eCAD button would
75/// have to be offered unconditionally and refused at dispatch instead: a row
76/// drawing unavailable buttons as available. `ecad` is `None` where a document
77/// has no editors, and then every eCAD button reads NOT offered.
78#[derive(Clone, Copy)]
79pub struct ButtonState<'a> {
80    pub engine: &'a EngineState,
81    pub ecad: Option<&'a ecad::Editors>,
82}
83
84impl<'a> ButtonState<'a> {
85    /// The engine alone: every button but the eCAD workbenches' can answer.
86    pub fn of(engine: &'a EngineState) -> Self {
87        Self { engine, ecad: None }
88    }
89
90    /// The engine and the document's eCAD editors.
91    pub fn with_ecad(engine: &'a EngineState, ecad: &'a ecad::Editors) -> Self {
92        Self { engine, ecad: Some(ecad) }
93    }
94}
95
96/// A workbench-specific toolbar button, DATA ONLY (no egui, no behavior): the
97/// shared toolbar-button helper renders it and a click surfaces `id` out of the
98/// toolbar to the shell, which dispatches on `id`.
99///
100/// A button may be CONDITIONAL on document state ([`Self::when`]) and may read
101/// as PRESSED from it ([`Self::pressed`]). Both are predicates over the
102/// document ([`ButtonState`]) rather than flags the toolbar sets, so the
103/// declaration still owns the whole answer and the row stays a renderer:
104/// Drawing's sheet buttons are offered only while a sheet is OPEN, and the armed
105/// sketch draw tool is the lit button. A `None` predicate is the plain case —
106/// always offered, never pressed — which is most buttons.
107///
108/// Three more readings came with the eCAD editors, whose actions carry them:
109/// an offered button can be DISABLED with a reason ([`Self::disabled`]), its
110/// tooltip can have LIVE detail ([`Self::caption`]), and it can be a MENU of other buttons
111/// ([`Self::menu`]).
112pub struct WorkbenchButton {
113    /// Stable id the shell matches on when the button is clicked.
114    pub id: &'static str,
115    /// The single unicode glyph shown on the square button.
116    pub glyph: &'static str,
117    /// Required tab/group/canonical-label path, validated with the registry.
118    pub ribbon_path: &'static str,
119    /// Ribbon sizing; Classic always uses the compact presentation.
120    pub size: CommandSize,
121    /// Hover tooltip / human label.
122    pub tooltip: &'static str,
123    /// When this button is OFFERED at all. `None` = always.
124    pub when: Option<fn(&ButtonState) -> bool>,
125    /// When this button draws PRESSED (a toggle reflecting live state, the way
126    /// the toolbar's wireframe and projection buttons do). `None` = a plain
127    /// momentary button.
128    pub pressed: Option<fn(&ButtonState) -> bool>,
129    /// Why an OFFERED button cannot act right now, or `None` when it can. A
130    /// disabled button is drawn greyed with the reason on hover, and the
131    /// `workbench_button` command refuses it with the same reason — never a
132    /// silent no-op. `None` = never disabled.
133    ///
134    /// This is eCAD's `enabled`, kept apart from `offered` the way eCAD keeps
135    /// it: Finish wire is on the row whenever the wire tool is, and greyed
136    /// until there is a wire to finish, rather than blinking in and out.
137    pub disabled: Option<fn(&ButtonState) -> Option<&'static str>>,
138    /// Supplementary live tooltip detail for a
139    /// button whose words describe state (`Bend: vertical first`) or depend on
140    /// the document (a copper layer's name). `None` = the tooltip.
141    pub caption: Option<fn(&ButtonState) -> String>,
142    /// A MENU button's entries: clicking it opens a menu of these, each with
143    /// its canonical label, live tooltip detail and pressed state, instead of surfacing its own id.
144    /// The entries are buttons in every other respect — ids the lookup finds
145    /// and the `workbench_button` command presses. A menu is offered while any
146    /// entry is. Empty = an ordinary button.
147    pub menu: &'static [WorkbenchButton],
148}
149
150impl WorkbenchButton {
151    /// Whether `state` offers this button. The ONE reading of [`Self::when`] —
152    /// the toolbar row, the `workbench_button` command and `describe_workbenches`
153    /// all route through it, so a button an agent can call is exactly a button
154    /// the user can see.
155    pub fn offered(&self, state: &ButtonState) -> bool {
156        self.when.is_none_or(|when| when(state))
157            && (self.menu.is_empty() || self.menu.iter().any(|entry| entry.offered(state)))
158    }
159
160    /// Whether this button draws pressed in `state`.
161    pub fn is_pressed(&self, state: &ButtonState) -> bool {
162        self.pressed.is_some_and(|pressed| pressed(state))
163    }
164
165    /// Why this button cannot act in `state`, or `None` when it can.
166    pub fn disabled_reason(&self, state: &ButtonState) -> Option<&'static str> {
167        self.disabled.and_then(|disabled| disabled(state))
168    }
169
170    /// Canonical command label; state-specific wording remains in `detail`.
171    pub fn label(&self, _state: &ButtonState) -> String {
172        self.presentation().label().to_owned()
173    }
174
175    pub fn presentation(&self) -> CommandPresentation<'static> {
176        CommandPresentation { id: self.id, glyph: self.glyph, ribbon_path: self.ribbon_path, size: self.size }
177    }
178
179    pub fn detail(&self, state: &ButtonState) -> String {
180        self.caption.map_or_else(|| self.tooltip.to_owned(), |caption| caption(state))
181    }
182}
183
184/// One workbench: a UI filter + optional toolbar buttons + claimed panels. Fully
185/// `'static` — fn-pointer predicate and `&'static` slices, no `OnceLock`.
186pub struct Workbench {
187    /// Stable id, e.g. `"all"` / `"modeling"` / `"sheetMetal"` — the value stored
188    /// in `RenderSettings.workbench` and published to the verifier.
189    pub id: &'static str,
190    /// Human label for the dropdown, e.g. `"Sheet Metal"`.
191    pub label: &'static str,
192    /// SVG catalog key used by the workbench switcher.
193    pub glyph: &'static str,
194    /// This workbench OWNS its inclusion decision: does a catalogue entry belong
195    /// in this workbench's feature-creation UI?
196    pub includes: fn(&FeatureInfo<'_>) -> bool,
197    /// Extra toolbar buttons this workbench adds (data only). EMPTY in v1.
198    pub buttons: &'static [WorkbenchButton],
199    /// Ids of EXISTING panels this workbench CLAIMS. Claim-based, not hide-based:
200    /// a panel is visible unless it is claimed by ≥1 workbench and the active one
201    /// does not list it (see [`panel_visible`]). EMPTY in v1 (nothing claimed →
202    /// every panel visible everywhere). Phase 2 adds claims here, editing NO other
203    /// file — the same anti-rot property the button union gives.
204    pub panels: &'static [&'static str],
205}
206
207/// The fallback / default workbench id. Boot-read validation is implicit:
208/// [`resolve`] maps any unknown stored id to this, so there is no separate boot
209/// step — every consumer routes through `resolve`.
210pub const DEFAULT_WORKBENCH_ID: &str = "modeling";
211
212/// Every workbench, in DROPDOWN ORDER: All, Modeling, Sheet Metal. The dropdown
213/// iterates THIS — labels are never hardcoded. A new workbench is appended here.
214pub static WORKBENCHES: &[&Workbench] = &[
215    &all::ALL,
216    &modeling::MODELING,
217    &sheet_metal::SHEET_METAL,
218    // Placeholders — established for the dropdown, fleshed out later.
219    &wire_harness::WIRE_HARNESS,
220    &assembly::ASSEMBLY,
221    &welding::WELDING,
222    &drawing::DRAWING,
223    // The eCAD four: their editors are drawn in place of the 3D view.
224    &diagram::DIAGRAM,
225    &pcb::PCB,
226    &symbol::SYMBOL,
227    &pads::PADS,
228    // Manufacturing: setups, tools, operations and toolpaths over the model.
229    &cam::CAM,
230    // Manufacturing instructions: an assembly, step by step.
231    &instructions::INSTRUCTIONS,
232    // Motion studies: an assembly's mates driven over time.
233    &simulation::SIMULATION,
234    // Gear generators: one feature per gear type.
235    &gears::GEARS,
236    // PCB diagram: the schematic of PCB's document, its own workbench since
237    // 2026-11-21 (appended last: MCP scripts read `/workbenches/N`).
238    &schematic::SCHEMATIC,
239];
240
241/// Workbenches DECLARED but not yet in the dropdown — none today. A
242/// workbench whose records and buttons land before anything draws it waits
243/// here, held to every law below, and registering it is a move from this
244/// list to [`WORKBENCHES`], which `every_declared_workbench_is_in_exactly_one_list`
245/// keeps honest in both directions. The eCAD four waited here until their
246/// editors were drawn: a workbench whose buttons act on an editor nobody can
247/// see is worse than one that does nothing.
248pub static UNREGISTERED: &[&Workbench] = &[];
249
250/// Pure lookup by id — `None` if there is no such workbench.
251pub fn workbench_by_id(id: &str) -> Option<&'static Workbench> {
252    WORKBENCHES.iter().copied().find(|w| w.id == id)
253}
254
255/// Resolve a (possibly stale / unknown) stored id to a live workbench, falling
256/// back to the default. This IS the boot/read validation — route ALL consumers
257/// (dropdown display, palette/offer filters, buttons, panels) through here.
258pub fn resolve(id: &str) -> &'static Workbench {
259    workbench_by_id(id).unwrap_or_else(|| {
260        workbench_by_id(DEFAULT_WORKBENCH_ID).expect("default workbench must be registered")
261    })
262}
263
264/// The buttons EVERY workbench carries, whatever the active one is — the tools
265/// of a SHELL MODE. A workbench is a filter over feature CREATION; a shell mode
266/// is entered from a surface no workbench filters (the sketch tools' own
267/// `editSketch`, on a History panel no workbench claims), so no workbench owns
268/// its tools and every row has to offer them. Declared ONCE — [`sketch::BUTTONS`]
269/// and conditional on the mode, so out of it the rows are exactly what each
270/// workbench declares.
271///
272/// The PMI command set's buttons ([`pmi::BUTTONS`]) ride the same list: PMI is
273/// no workbench, so no workbench owns Capture view, and it is conditional on
274/// the PMI panel being shown ([`pmi::offered`]) the way a sketch tool is
275/// conditional on its mode.
276///
277/// This is the ONE reading: [`workbench_buttons`] appends it and
278/// [`button_by_id`] searches it, so the row, `describe_workbenches` and the
279/// `workbench_button` command agree about what exists.
280pub fn shared_buttons() -> &'static [WorkbenchButton] {
281    /// The shared sets in one slice, built once: the planar sketch's tools,
282    /// the 3D sketch's, then the PMI set's. Each sketch set is conditional on
283    /// its own mode, so a row never shows both.
284    static SHARED: std::sync::LazyLock<Vec<WorkbenchButton>> = std::sync::LazyLock::new(|| {
285        sketch::BUTTONS
286            .iter()
287            .chain(sketch3d::BUTTONS.iter())
288            .chain(pmi::BUTTONS.iter())
289            .map(|b| WorkbenchButton {
290                id: b.id,
291                glyph: b.glyph,
292                ribbon_path: b.ribbon_path,
293                size: b.size,
294                tooltip: b.tooltip,
295                when: b.when,
296                pressed: b.pressed,
297                disabled: b.disabled,
298                caption: b.caption,
299                menu: b.menu,
300            })
301            .collect()
302    });
303    &SHARED
304}
305
306/// Buttons one workbench LENDS to another: `(borrower id, the lent buttons)`.
307/// The borrower's row shows the lender's own declaration — the same id, the
308/// same picture, the same tooltip, dispatched by the same shell arm — so the
309/// two rows cannot drift apart the way two declarations would.
310///
311/// A lent button is NOT one of the borrower's own: it is declared once, by its
312/// owner, which is what keeps every law above intact. The prefix law
313/// ([`button_prefix`]) reads a workbench's OWN buttons, so PCB showing
314/// `assembly.add_component` breaks nothing; the artwork law sees one button
315/// with one picture; [`button_by_id`] finds the one declaration; and All's
316/// deduped union is built from OWN lists, so a lent button is in it exactly
317/// once — via its owner. What a borrow changes is only [`workbench_buttons`]:
318/// the borrower's row, and therefore [`offered_buttons`], `describe_workbenches`
319/// and what `workbench_button` will press while it is active.
320///
321/// PCB diagram and PCB borrow Assembly's ADD COMPONENT because a board is an assembly of
322/// placed parts and the user asked for "the same one": inserting a component
323/// is one action wherever it is reached from, and a second declaration would
324/// be two ids for it.
325pub static BORROWED: &[(&str, &[&WorkbenchButton])] =
326    &[("schematic", &[assembly::ADD_COMPONENT]), ("pcb", &[assembly::ADD_COMPONENT])];
327
328/// The buttons workbench `id` BORROWS ([`BORROWED`]) — empty for a workbench
329/// that borrows none, and for `"all"`, whose union already carries every
330/// lender's own declaration.
331pub fn borrowed_buttons(id: &str) -> &'static [&'static WorkbenchButton] {
332    BORROWED
333        .iter()
334        .find(|(borrower, _)| *borrower == id)
335        .map_or(&[], |(_, buttons)| *buttons)
336}
337
338/// The active workbench's toolbar buttons: its OWN declared buttons — for
339/// `"all"` the DEDUPED UNION of every workbench's, so "All" shows every icon
340/// without a hand-maintained list — then the ones it BORROWS ([`BORROWED`]),
341/// then the [`shared_buttons`] every workbench carries. The borrowed ones trail
342/// the workbench's own, exactly as the shared tail trails both, so a row's own
343/// declared order (eCAD's toolbar order, in PCB's case) is untouched by a
344/// borrow.
345pub fn workbench_buttons(id: &str) -> Vec<&'static WorkbenchButton> {
346    let wb = resolve(id);
347    let own = if wb.id == "all" {
348        union_in(WORKBENCHES)
349    } else {
350        wb.buttons.iter().collect::<Vec<_>>()
351    };
352    own.into_iter()
353        .chain(borrowed_buttons(wb.id).iter().copied())
354        .chain(shared_buttons())
355        .collect()
356}
357
358/// The active workbench's buttons that `state` actually OFFERS — [`workbench_buttons`]
359/// filtered by each button's [`WorkbenchButton::when`]. This is what the toolbar row
360/// draws and what `describe_workbenches` reports as active, so the two can never
361/// disagree about which buttons exist right now.
362pub fn offered_buttons(id: &str, state: &ButtonState) -> Vec<&'static WorkbenchButton> {
363    if owned_workbenches(state.engine).iter().any(|w| w.id == id) {
364        return shared_buttons().iter().filter(|b| b.offered(state)).collect();
365    }
366    workbench_buttons(id).into_iter().filter(|button| button.offered(state)).collect()
367}
368
369/// Look one button up by id across every workbench AND the shared list — the
370/// dispatch side, which must answer for a button the active workbench does not
371/// carry (the `workbench_button` command names an id, not a workbench) and for
372/// one no workbench declares at all (the sketch tools).
373pub fn button_by_id(id: &str) -> Option<&'static WorkbenchButton> {
374    button_in(WORKBENCHES, id)
375}
376
377/// What every one of a workbench's OWN button ids leads with: its id,
378/// lowercased, and a dot — `drawing.dim.radius`, `sheetmetal.flat_pattern`.
379///
380/// A button id is all the toolbar's return path and the `workbench_button`
381/// command carry, so it must name ONE button across every workbench: with an
382/// id declared twice, [`button_by_id`] returns the first declaration and asks
383/// ITS `when`, and All's union keeps the first and drops the rest. The prefix
384/// makes two workbenches' ids disjoint. It matters where two workbenches
385/// take their buttons from one table: eCAD's editor actions (`view.*`,
386/// `edit.*`, `sheet.*`, `board.*`) are Diagram's and PCB's alike, so each
387/// leads them with its own — `diagram.sheet.tool.wire`,
388/// `schematic.sheet.tool.wire` — while the symbol and pads editors' ids already
389/// lead with `symbol.` and `pads.` and need nothing added. The shared sketch
390/// tools belong to no workbench and lead with none of theirs (`sketch.`).
391pub fn button_prefix(wb: &Workbench) -> String {
392    format!("{}.", wb.id.to_ascii_lowercase())
393}
394
395/// [`button_by_id`] over any registry.
396fn button_in(registry: &[&'static Workbench], id: &str) -> Option<&'static WorkbenchButton> {
397    every_button_in(registry).find(|button| button.id == id)
398}
399
400/// Why the `workbench_button` command must NOT press `id` in `state`, or
401/// `None` when it may. The command's whole gate, here rather than in the
402/// command so it is tested against every kind of button: an unknown id, one
403/// the row is not offering, a MENU (its entries are pressed, not it), and an
404/// offered button that is DISABLED, which is refused with its reason — never
405/// run as a silent no-op.
406pub fn press_refusal(id: &str, state: &ButtonState) -> Option<String> {
407    press_refusal_in(WORKBENCHES, id, state)
408}
409
410/// [`press_refusal`] over any registry.
411fn press_refusal_in(registry: &[&'static Workbench], id: &str, state: &ButtonState) -> Option<String> {
412    let Some(button) = button_in(registry, id) else {
413        return Some(format!("no workbench button `{id}` (see describe_workbenches)"));
414    };
415    if !button.offered(state) {
416        return Some(format!(
417            "the `{id}` button is not offered right now (see describe_workbenches `activeButtons`)"
418        ));
419    }
420    if !button.menu.is_empty() {
421        let entries: Vec<&str> =
422            button.menu.iter().filter(|e| e.offered(state)).map(|e| e.id).collect();
423        return Some(format!("`{id}` opens a menu; press one of its entries: {}", entries.join(", ")));
424    }
425    button
426        .disabled_reason(state)
427        .map(|why| format!("the `{id}` button is disabled right now: {why}"))
428}
429
430/// Buttons that draw ONE picture although their ids differ, because they are
431/// one user-facing action in different places — each group with the reason.
432/// The artwork law (`every_button_draws_catalogued_artwork_shared_only_by_one_action`)
433/// lets two buttons share a picture only when they are the same action behind
434/// their workbench prefixes (Diagram's and PCB's Rotate) or are listed here.
435/// A share between unrelated buttons still fails, which is what the law is for;
436/// a deliberate reuse is a reviewable line here instead of a duplicated icon.
437///
438/// Two reuses were REFUSED rather than listed, because the picture already
439/// means something else in this app: U+21BB ↻ is the BOM's outdated-vs-source
440/// badge (`panels::assembly_components::OUTDATED_GLYPH`), not "rotate", and
441/// U+2713 ✓ is a status tick (a resolved annotation, the switcher's active
442/// entry), not "finish". Rotate and finish have pictures of their own.
443pub const SYNONYMS: &[(&[&str], &str)] = &[
444    (&["sketch.tool.text", "symbol.tool.text", "pads.tool.text", "pcb.board.tool.text"], "places text in the active editor"),
445    (
446        &[
447            "sketch.tool.select",
448            "sketch3d.tool.select",
449            "diagram.sheet.tool.select",
450            "schematic.sheet.tool.select",
451            "pcb.board.tool.select",
452            "symbol.tool.select",
453            "pads.tool.select",
454        ],
455        "select and drag, in every editor",
456    ),
457    (&["sketch.tool.line", "sketch3d.tool.line", "symbol.tool.line", "pads.tool.line", "pcb.board.tool.draw"], "draws a straight line (on the board, corner by corner)"),
458    (&["sketch.tool.point", "sketch3d.tool.point"], "places a point"),
459    (&["sketch.tool.arc", "sketch3d.tool.arc", "pads.tool.arc"], "draws an arc (a sketch's from centre, start and end; the Pads editor's along a chord)"),
460    (&["sketch.tool.bezier", "sketch3d.tool.bezier"], "draws a cubic bezier"),
461    (&["sketch.tool.pickEdges", "sketch3d.tool.pickRef"], "links model geometry into the sketch as a fixed reference"),
462    (&["sketch.tool.rect", "symbol.tool.rectangle", "pads.tool.rectangle"], "draws a rectangle"),
463    (&["sketch.tool.circle", "symbol.tool.circle", "pads.tool.circle"], "draws a circle"),
464    (&["schematic.sheet.wire.finish", "pcb.board.route.finish", "pcb.board.draw.finish"], "ends the path being drawn"),
465    (&["pcb.board.zone.finish", "pcb.board.cutout.finish"], "closes the outline being drawn"),
466];
467
468/// Every DECLARED workbench: the dropdown's ([`WORKBENCHES`]), then the ones
469/// not in it yet ([`UNREGISTERED`]). What the laws hold, so a workbench is
470/// covered before it is offered.
471pub fn declared_workbenches() -> Vec<&'static Workbench> {
472    WORKBENCHES.iter().chain(UNREGISTERED).copied().collect()
473}
474
475/// [`button_by_id`] over every DECLARED workbench, registered or not — for the
476/// eCAD module, whose buttons exist before their workbenches are offered.
477pub(crate) fn button_by_declared_id(id: &str) -> Option<&'static WorkbenchButton> {
478    button_in(&declared_workbenches(), id)
479}
480
481/// Every DECLARED button in the app: each workbench's own, then the shared
482/// ones. The lookup + audit side ([`button_by_id`], the artwork and distinctness
483/// tests) — NOT what any row draws, which is [`offered_buttons`].
484pub fn every_button() -> impl Iterator<Item = &'static WorkbenchButton> {
485    every_button_in(WORKBENCHES)
486}
487
488/// [`every_button`] over any registry.
489///
490/// A MENU button's entries are buttons too — the command presses them by id —
491/// so each follows the menu that holds it.
492fn every_button_in<'r>(
493    registry: &'r [&'static Workbench],
494) -> impl Iterator<Item = &'static WorkbenchButton> + 'r {
495    registry
496        .iter()
497        .flat_map(|w| w.buttons.iter())
498        .chain(shared_buttons())
499        .flat_map(|button| std::iter::once(button).chain(button.menu.iter()))
500}
501
502/// All's own buttons over any registry: the union of every workbench's.
503fn union_in(registry: &[&'static Workbench]) -> Vec<&'static WorkbenchButton> {
504    dedupe_buttons(registry.iter().map(|w| w.buttons))
505}
506
507/// Collect buttons across lists, keeping FIRST occurrence per `id` and preserving
508/// order. The union logic behind [`workbench_buttons`] for `"all"`.
509fn dedupe_buttons<'a>(
510    lists: impl Iterator<Item = &'a [WorkbenchButton]>,
511) -> Vec<&'a WorkbenchButton> {
512    let mut seen = std::collections::HashSet::new();
513    let mut out = Vec::new();
514    for list in lists {
515        for button in list {
516            if seen.insert(button.id) {
517                out.push(button);
518            }
519        }
520    }
521    out
522}
523
524/// Whether a catalogue entry belongs in workbench `active_id`'s feature-creation
525/// UI. The ONE entry point the palette + context-offer filters call: builds a
526/// [`FeatureInfo`] from the feature `type_code` and runs the resolved workbench's
527/// predicate (each workbench file owns its classification off the code).
528pub fn includes_feature(active_id: &str, type_code: &str) -> bool {
529    let info = FeatureInfo { type_code };
530    (resolve(active_id).includes)(&info)
531}
532
533/// The Qualify pane's registration id: a part's declared connection points —
534/// its port groups, their purpose, and the consistency reports the model
535/// already produces.
536///
537/// Claimed by NO workbench, and deliberately: a connection point is part DATA
538/// and belongs to whichever surface the user is on — the schematic symbol, the
539/// pads, or the 3D model — so a claim list would have to name most of the
540/// registry and would still hide the pane from the one workbench it was
541/// forgotten in. What gates it is the DOCUMENT ([`PANEL_CONDITIONS`]), which is
542/// the honest condition: a part that declares no connection points has nothing
543/// to qualify.
544pub const QUALIFY_PANEL_ID: &str = "qualify";
545
546/// A panel whose visibility ALSO depends on the document, beside the claim.
547///
548/// The claim system answers "which workbench is this panel's". It cannot answer
549/// "does this document have anything for it", because a [`Workbench`]'s
550/// `panels` is a list of ids with no room for a predicate. This is that second
551/// half, in the shape [`WorkbenchButton::when`] already uses — a predicate over
552/// [`ButtonState`], which carries the whole engine — so a conditional PANEL is
553/// declared exactly like a conditional BUTTON and read in exactly one place
554/// ([`panel_visible`]).
555///
556/// Keyed by PANEL rather than by workbench because the condition is the
557/// panel's own: Qualify wants a part with connection points wherever it is
558/// drawn, not a different answer per workbench.
559pub struct PanelCondition {
560    pub panel: &'static str,
561    /// Whether the document has anything for this panel. `false` hides it
562    /// exactly as an unclaimed workbench does — in place, keeping its position.
563    pub when: fn(&ButtonState) -> bool,
564}
565
566/// Every conditional panel.
567pub static PANEL_CONDITIONS: &[PanelCondition] = &[
568    PanelCondition { panel: QUALIFY_PANEL_ID, when: declares_connection_points },
569    PanelCondition { panel: FAMILY_TABLE_PANEL_ID, when: is_family_document },
570    PanelCondition { panel: PLM_PANEL_ID, when: crate::panels::plm_host::in_plm_session },
571];
572
573/// The PLM pane's registration id (`panels::plm_host`): every PLM panel, as
574/// sections of one pane. Claimed by no workbench; on screen exactly while the
575/// session's store is a PLM.
576pub const PLM_PANEL_ID: &str = "plm";
577
578/// The Family table pane's registration id: a family seed's member table
579/// (`panels::family_table_editor`). Claimed by no workbench. It is on screen
580/// exactly while the document being edited is a family seed (`.fbrep`),
581/// whatever workbench the user is in.
582pub const FAMILY_TABLE_PANEL_ID: &str = "familyTable";
583
584/// Whether the active document is a family seed: its own `documentClass`
585/// field, so a family that has never been saved answers too.
586pub fn is_family_document(state: &ButtonState) -> bool {
587    crate::document_class::is_family(state.engine)
588}
589
590/// Whether the document declares any connection point: a `ports` block with at
591/// least one group in it. An EMPTY block reads as none — the block is omitted
592/// on re-serialize when empty, so an empty array is a transient the panel's own
593/// "remove the last group" leaves behind, and it must not keep the pane up.
594pub fn declares_connection_points(state: &ButtonState) -> bool {
595    state
596        .engine
597        .history
598        .ports_block()
599        .and_then(serde_json::Value::as_array)
600        .is_some_and(|groups| !groups.is_empty())
601}
602
603/// Whether panel `panel_id` is visible in workbench `active_id`, for document
604/// `state`. TWO halves, and this is the one reading of both.
605///
606/// Claim-based: a panel is visible UNLESS it is claimed by ≥1 workbench and the
607/// active workbench does not list it. `"all"` sees every panel (mirrors the
608/// button union).
609///
610/// Then CONDITIONAL: a panel [`PANEL_CONDITIONS`] names is visible only while
611/// its predicate holds for this document. A panel with no condition — every one
612/// but Qualify — is unaffected, so `state` costs the other callers nothing but
613/// the argument.
614pub fn panel_visible(active_id: &str, panel_id: &str, state: &ButtonState) -> bool {
615    if !PANEL_CONDITIONS
616        .iter()
617        .filter(|condition| condition.panel == panel_id)
618        .all(|condition| (condition.when)(state))
619    {
620        return false;
621    }
622    let dynamic = owned_workbenches(state.engine);
623    let plugin = dynamic.iter().find(|w| w.id == active_id);
624    let claimed = WORKBENCHES.iter().any(|w| w.panels.contains(&panel_id))
625        || dynamic.iter().any(|w| w.panels.iter().any(|p| p == panel_id));
626    if let Some(wb) = plugin {
627        return !claimed || wb.panels.iter().any(|p| p == panel_id);
628    }
629    if !claimed {
630        return true;
631    }
632    let wb = resolve(active_id);
633    if wb.id == "all" {
634        return true;
635    }
636    wb.panels.contains(&panel_id)
637}
638
639/// The workbench list as `{id, label}` JSON plus the resolved current id — the
640/// `__brepWorkbench` logical-state global the headed verifier reads to drive the
641/// dropdown and confirm the active workbench. `current` is the RESOLVED id (an
642/// unknown stored id reads back as the default).
643pub fn workbench_state_json(current_stored: &str) -> String {
644    let available: Vec<serde_json::Value> = WORKBENCHES
645        .iter()
646        .map(|w| serde_json::json!({ "id": w.id, "label": w.label }))
647        .collect();
648    serde_json::json!({
649        "current": resolve(current_stored).id,
650        "available": available,
651    })
652    .to_string()
653}
654
655
656/// Document-scoped, owned overlay. Static built-ins retain their predicates and callbacks.
657#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
658#[serde(rename_all = "camelCase")]
659pub struct OwnedWorkbench {
660    pub id: String,
661    pub label: String,
662    #[serde(default)] pub feature_types: Vec<String>,
663    #[serde(default)] pub actions: Vec<String>,
664    #[serde(default)] pub panels: Vec<String>,
665}
666
667pub fn owned_workbenches(engine: &EngineState) -> Vec<OwnedWorkbench> {
668    serde_json::from_value(engine.plugin_workbenches()).unwrap_or_default()
669}
670
671pub fn resolved_id(engine: &EngineState, id: &str) -> String {
672    if workbench_by_id(id).is_some() || owned_workbenches(engine).iter().any(|w| w.id == id) {
673        id.to_owned()
674    } else { DEFAULT_WORKBENCH_ID.to_owned() }
675}
676
677pub fn includes_feature_scoped(engine: &EngineState, active: &str, ty: &str) -> bool {
678    if let Some(wb) = owned_workbenches(engine).iter().find(|w| w.id == active) {
679        wb.feature_types.iter().any(|f| f == ty)
680    } else { includes_feature(active, ty) }
681}
682
683pub fn plugin_actions(engine: &EngineState, active: &str) -> Vec<serde_json::Value> {
684    let workbenches = owned_workbenches(engine);
685    let ids = workbenches.iter().find(|w| w.id == active).map(|w| &w.actions);
686    engine.plugin_catalogue()["actions"].as_array().into_iter().flatten()
687        .filter(|a| active == "all" || ids.is_some_and(|ids| a["id"].as_str().is_some_and(|id| ids.iter().any(|i| i == id))))
688        .cloned().collect()
689}
690
691
692pub fn workbench_state_scoped(engine: &EngineState) -> serde_json::Value {
693    let mut state: serde_json::Value = serde_json::from_str(&workbench_state_json(&engine.settings.workbench)).unwrap();
694    state["saved"] = serde_json::json!(engine.settings.workbench);
695    state["current"] = serde_json::json!(resolved_id(engine, &engine.settings.workbench));
696    if let Some(available) = state["available"].as_array_mut() {
697        available.extend(owned_workbenches(engine).iter().map(|w| serde_json::json!({"id":w.id,"label":w.label})));
698    }
699    state
700}
701
702/// Declarative panels claimed by the active document's workbench.
703pub fn plugin_panels(engine: &EngineState, active: &str) -> Vec<serde_json::Value> {
704    let workbenches = owned_workbenches(engine);
705    let ids = workbenches.iter().find(|w| w.id == active).map(|w| &w.panels);
706    engine.plugin_catalogue()["panels"].as_array().into_iter().flatten()
707        .filter(|p| active == "all" || ids.is_some_and(|ids| p["id"].as_str().is_some_and(|id| ids.iter().any(|i| i == id))))
708        .cloned().collect()
709}