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