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