Skip to main content

brep_app/workbench/
ecad.rs

1//! The eCAD editors, and their actions as workbench buttons.
2//!
3//! Five workbenches host eCAD (`brep_ecad_egui`): **Harness diagram** runs its
4//! sheet [`Editor`] on a wiring document; **PCB diagram** and **PCB** run ONE
5//! sheet-and-board editor on a schematic document, each pinned to one of its two
6//! views (the schematic, the board: [`BENCHES`]); **Symbol** and **Pads** run its
7//! [`SymbolEditor`] and [`FootprintEditor`]. eCAD keeps every toolbar command as data
8//! ([`brep_ecad_egui::Action`]), with predicates over the editor saying whether it is
9//! offered, enabled and pressed, and what its button says. The workbench
10//! buttons here are those actions: each button asks eCAD's own predicate about
11//! the editor it names ([`offered`], [`pressed`], [`disabled`], [`caption`]),
12//! and a press runs eCAD's own action ([`dispatch`]). BREP decides only which
13//! actions reach a row and what they look like.
14//!
15//! # Ids
16//!
17//! A button id leads with its workbench ([`super::button_prefix`]). Harness
18//! diagram, PCB diagram and PCB take their buttons from ONE eCAD table, whose ids
19//! lead with a group (`sheet.`, `board.`), so each puts its own workbench in
20//! front — `diagram.sheet.tool.select`, `schematic.sheet.tool.select`,
21//! `pcb.board.tool.select` — and [`split`] takes it off again. The symbol and pads editors' ids already lead with `symbol.`
22//! and `pads.`, which ARE their workbenches' ids, so their buttons are eCAD's
23//! ids verbatim. Two workbenches sharing a table is what made the prefix law
24//! necessary: see `a_duplicate_id_names_the_first_workbench_s_button_everywhere`.
25//!
26//! # Which actions reach a row
27//!
28//! eCAD groups its actions ([`brep_ecad_egui::ActionGroup`]). The rows carry View,
29//! Tool, Layer and Context. History (undo, redo) and Zoom (in, out, fit) are
30//! not here: BREP's main toolbar owns Undo, Redo and Zoom to fit, as the
31//! Drawing workbench's sheet already relies on. Selection is keyboard-only in
32//! eCAD's own toolbars too. Of Context, the six actions that only put the tool
33//! down ([`PUT_DOWN`]) are not here: the row's Select and Escape do that, and
34//! BREP's sketch row already teaches "press the lit tool to put it down". The
35//! six copper-layer actions are one MENU button ([`LAYER_MENU_ID`]), because a
36//! layer's name depends on the board's layer count and no fixed picture can say
37//! it.
38//!
39//! # When they are offered
40//!
41//! An eCAD button is offered only while the document HAS editors, its own
42//! workbench is the active one, no sketch is being edited, and eCAD offers the
43//! action ([`active_target`]). The active-workbench condition keeps them out
44//! of All's row: All draws the 3D view, so no editor is on screen under it, and
45//! Diagram's and PCB's copies of one action would stand side by side there —
46//! the duplicate-id collision in another form. The sketch condition is the same
47//! thought for the shared sketch tools: a sketch takes the viewport over, and
48//! its Select beside an editor's Select would be two identical hands.
49
50use super::ButtonState;
51use brep_ecad_egui::{Action, Editor, FootprintEditor, SymbolEditor};
52
53/// One document's eCAD editors: what every eCAD button reads and every press
54/// runs on. The app keeps one per document, beside its engine, so each tab has
55/// its own diagram and board and a tab switch keeps them.
56pub struct Editors {
57    /// The Diagram workbench's editor, on a wiring document.
58    pub diagram: Editor,
59    /// The PCB workbench's editor, on a schematic document with its board.
60    pub pcb: Editor,
61    /// The Symbol workbench's editor: the part's schematic symbol.
62    pub symbol: SymbolEditor,
63    /// The Pads workbench's editor: the part's footprint pads.
64    pub pads: FootprintEditor,
65    /// A selection a HOST asked an editor to make, held until that editor is
66    /// next drawn: `(which editor, the pin or pad NUMBER)`.
67    ///
68    /// Deferred, not set at the moment of asking, because the ask crosses a
69    /// workbench switch. The editor is re-handed its block on the frame it is
70    /// drawn (`viewport::ecad`'s pull), and a load CLEARS the selection — so a
71    /// selection made now would be wiped by the very switch that was supposed
72    /// to show it. [`Self::apply_focus`] runs after the pull instead, which is
73    /// where `set_pins` already runs for the same reason.
74    focus: Option<(Target, String)>,
75}
76
77impl Editors {
78    /// Empty editors: a blank wiring diagram, a blank schematic, a new symbol
79    /// and an empty footprint. The Diagram and PCB libraries offer the parts the
80    /// document's assembly places (`panels::ecad_parts`); no symbols ship with
81    /// the editors.
82    pub fn new() -> Self {
83        let mut diagram = Editor::default();
84        diagram.set_document(brep_ecad_core::Document::new(brep_ecad_core::DocumentKind::Wiring));
85        let mut pcb = Editor::default();
86        pcb.set_document(brep_ecad_core::Document::new(brep_ecad_core::DocumentKind::Schematic));
87        Self {
88            diagram,
89            pcb,
90            symbol: SymbolEditor::blank(),
91            pads: FootprintEditor::new(Default::default(), None, Vec::new()),
92            focus: None,
93        }
94    }
95
96    /// Hold the sheet-and-board editor in the view the active workbench `id`
97    /// shows: the schematic on PCB diagram, the board on PCB. Run every frame
98    /// before the row is drawn, since the workbench also changes by a settings
99    /// write, an open and a restored session, not only by the switcher; a view
100    /// already held costs nothing (`Editor::set_view` returns at once). An
101    /// autorouter run survives the switch: `set_view` puts down only the
102    /// gesture in hand, and the run goes on whenever the board is drawn again.
103    pub fn pin_view(&mut self, id: &str) {
104        let Some(Bench { target, view: Some(view), .. }) = bench(id).copied() else { return };
105        match target {
106            Target::Diagram => self.diagram.set_view(view),
107            Target::Pcb => self.pcb.set_view(view),
108            Target::Symbol | Target::Pads => {}
109        }
110    }
111
112    /// Ask `target`'s editor to select the pin or pad numbered `number` the
113    /// next time it draws. The Qualify panel's jump: a connection point, its
114    /// pin and its pad all carry ONE name, so the number is the whole ask.
115    pub fn focus(&mut self, target: Target, number: String) {
116        self.focus = Some((target, number));
117    }
118
119    /// Make the selection [`Self::focus`] asked for, if it was asked of
120    /// `target`. Called by the host AFTER the pull, once per frame the editor
121    /// is drawn; returns whether anything was selected. A number the editor
122    /// does not have clears the ask all the same — a pin the symbol has not
123    /// got yet is not a standing request.
124    pub fn apply_focus(&mut self, target: Target) -> bool {
125        match self.focus.take_if(|(asked, _)| *asked == target) {
126            Some((Target::Symbol, number)) => self.symbol.select_pin(&number),
127            Some((Target::Pads, number)) => self.pads.select_pad(&number),
128            // Diagram and PCB select components, not pins; nothing asks yet.
129            _ => false,
130        }
131    }
132
133    /// Route selection keys to the visible editor even when the pointer is in a dock.
134    pub fn selection_key(&mut self, target: Target, delete: bool) {
135        match target {
136            Target::Diagram | Target::Pcb => {
137                let editor = if target == Target::Diagram { &mut self.diagram } else { &mut self.pcb };
138                let action = match (editor.view, delete) {
139                    (brep_ecad_egui::View::Board, true) => "board.delete",
140                    (brep_ecad_egui::View::Board, false) => "board.cancel",
141                    (_, true) => "sheet.delete",
142                    (_, false) => "sheet.cancel",
143                };
144                editor.run_action(action);
145            }
146            Target::Symbol => { self.symbol.run_action(if delete { "symbol.delete" } else { "symbol.tool.select" }); }
147            Target::Pads => { self.pads.run_action(if delete { "pads.delete" } else { "pads.tool.select" }); }
148        }
149    }
150
151}
152
153impl Default for Editors {
154    fn default() -> Self {
155        Self::new()
156    }
157}
158
159/// Which of the four editors a button acts on. Each is one editor over one
160/// document block; a workbench reaches one through [`BENCHES`], and two
161/// workbenches (PCB diagram and PCB) reach the same one.
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163pub enum Target {
164    Diagram,
165    Pcb,
166    Symbol,
167    Pads,
168}
169
170impl Target {
171    pub const ALL: [Target; 4] = [Target::Diagram, Target::Pcb, Target::Symbol, Target::Pads];
172
173    /// The key of the document block this editor's document is kept in
174    /// (`diagram`, `pcb`, `symbol`, `pads`), which is also the workbench a jump
175    /// to this editor opens. The pcb block has two workbenches; this names the
176    /// board's. Where the ACTIVE workbench is what is meant — a button id's
177    /// prefix, the target `ecad_state` reports — read the workbench id itself.
178    pub fn workbench_id(self) -> &'static str {
179        match self {
180            Target::Diagram => "diagram",
181            Target::Pcb => "pcb",
182            Target::Symbol => "symbol",
183            Target::Pads => "pads",
184        }
185    }
186
187    /// The editor a workbench id drives, or `None` for a workbench that is not
188    /// one of the four. A plain mapping — unlike [`active_target`] it asks
189    /// nothing about editors or sketch mode, so the host can ask it at the
190    /// moment it must END a sketch because an eCAD workbench became active.
191    pub fn of_workbench(id: &str) -> Option<Target> {
192        bench(id).map(|bench| bench.target)
193    }
194}
195
196/// One eCAD workbench: the editor it draws and, for the sheet-and-board editor,
197/// the view it holds that editor in ([`Editors::pin_view`]).
198#[derive(Clone, Copy, Debug, PartialEq, Eq)]
199pub struct Bench {
200    pub workbench: &'static str,
201    pub target: Target,
202    pub view: Option<brep_ecad_egui::View>,
203}
204
205/// Every eCAD workbench. PCB diagram (`schematic`) and PCB (`pcb`) are the one
206/// schematic document's two views, each its own workbench: the schematic's
207/// tools on one row, the board's on the other.
208pub const BENCHES: [Bench; 5] = [
209    Bench { workbench: "diagram", target: Target::Diagram, view: None },
210    Bench { workbench: "schematic", target: Target::Pcb, view: Some(brep_ecad_egui::View::Schematic) },
211    Bench { workbench: "pcb", target: Target::Pcb, view: Some(brep_ecad_egui::View::Board) },
212    Bench { workbench: "symbol", target: Target::Symbol, view: None },
213    Bench { workbench: "pads", target: Target::Pads, view: None },
214];
215
216/// The eCAD workbench `id` names, or `None` for any other workbench.
217pub fn bench(id: &str) -> Option<&'static Bench> {
218    BENCHES.iter().find(|bench| bench.workbench == id)
219}
220
221/// The dock pane that draws the active editor's parts library
222/// (`Editor::library_panel`): the sheet-and-board editor's workbenches'.
223pub const LIBRARY_PANEL_ID: &str = "ecadLibrary";
224
225/// The dock pane that draws the active editor's inspector — `Editor::inspector`
226/// for Diagram and PCB, `properties` for the symbol and pads editors. One pane
227/// for all four, as the assembly panes serve both Assembly and Wire harness.
228pub const INSPECTOR_PANEL_ID: &str = "ecadInspector";
229
230/// The editor a button id acts on and the eCAD action id it runs there, or
231/// `None` for an id that is no eCAD button's. The inverse of how the tables
232/// spell their ids: `diagram.`, `schematic.` and `pcb.` come off, `symbol.*`
233/// and `pads.*` are eCAD's own.
234pub fn split(id: &str) -> Option<(Target, &str)> {
235    if let Some(action) = id.strip_prefix("diagram.") {
236        Some((Target::Diagram, action))
237    } else if let Some(action) = id.strip_prefix("schematic.") {
238        Some((Target::Pcb, action))
239    } else if let Some(action) = id.strip_prefix("pcb.") {
240        Some((Target::Pcb, action))
241    } else if id.starts_with("symbol.") {
242        Some((Target::Symbol, id))
243    } else if id.starts_with("pads.") {
244        Some((Target::Pads, id))
245    } else {
246        None
247    }
248}
249
250/// The buttons an eCAD workbench carries that are BREP's OWN, not eCAD actions —
251/// dispatched by the shell's own arms, never by [`dispatch`]. None today. Listed
252/// rather than inferred, so an eCAD button whose id is misspelt fails
253/// `every_ecad_workbench_button_is_an_ecad_action_or_brep_s_own` instead of
254/// passing quietly as one of BREP's.
255pub const BREP_OWN: &[&str] = &[];
256
257/// The editor and eCAD action a button id runs, only when the id IS an action in
258/// that editor's own table: [`split`] reads the prefix, this also asks eCAD.
259pub fn ecad_action(id: &str) -> Option<(Target, &str)> {
260    let (target, action) = split(id)?;
261    let known = match target {
262        Target::Diagram | Target::Pcb => brep_ecad_egui::actions().any(|a| a.id == action),
263        Target::Symbol => brep_ecad_egui::symbol_actions().iter().any(|a| a.id == action),
264        Target::Pads => brep_ecad_egui::pad_actions().iter().any(|a| a.id == action),
265    };
266    known.then_some((target, action))
267}
268
269/// The copper-layer MENU button's id. Not an eCAD action: its entries are
270/// (`board.layer.1` .. `board.layer.6`).
271pub const LAYER_MENU_ID: &str = "pcb.board.layer";
272
273/// The six Context actions that only abandon the gesture in progress and
274/// return to Select — five run `Editor::cancel`, the route one drops the draft
275/// and selects `BoardTool::Select`. The row's Select button and Escape
276/// (`sheet.cancel`, `board.cancel`) already do that, so they are not buttons.
277pub const PUT_DOWN: &[&str] = &[
278    "sheet.place.done",
279    "sheet.wire.done",
280    "sheet.label.done",
281    "sheet.move.cancel",
282    "sheet.junction.done",
283    "board.route.done",
284];
285
286/// Why eCAD disables an action it offers, for the few that it ever does. eCAD
287/// answers `enabled` with a bare bool, so the words are BREP's, one per action,
288/// read from the predicate it declares.
289const DISABLED_BECAUSE: &[(&str, &str)] = &[
290    ("sheet.wire.finish", "no wire is being drawn"),
291    ("board.route.via", "a via needs a track being drawn on a board with more than one copper layer"),
292    ("board.route.finish", "no track is being drawn"),
293    ("board.zone.finish", "a zone needs three corners before it can be closed"),
294    ("board.zones.fill", "the board has no zones"),
295];
296
297/// The words for an action eCAD disables with no entry in
298/// [`DISABLED_BECAUSE`] — a table gap, which `every_disabled_action_says_why`
299/// fails on rather than letting this reach a user.
300const DISABLED_UNEXPLAINED: &str = "the editor does not allow it right now";
301
302/// The editor the active workbench draws, if it is one of the four and
303/// something could draw it: the document has editors and no sketch is being
304/// edited (a sketch takes the viewport over). See the module doc for why each
305/// condition is there.
306///
307/// The stored workbench id is read directly, not through `resolve`: `resolve`
308/// answers only for a workbench in the dropdown, and these four are declared
309/// before they are registered ([`super::UNREGISTERED`]). The two readings
310/// agree on every registered id.
311pub fn active_target(state: &ButtonState) -> Option<Target> {
312    state.ecad?;
313    if state.engine.any_sketch_mode() {
314        return None;
315    }
316    Target::of_workbench(&state.engine.settings.workbench)
317}
318
319/// What eCAD says about one of its actions on one of its editors.
320struct Reading {
321    offered: bool,
322    enabled: bool,
323    pressed: Option<bool>,
324    caption: String,
325}
326
327fn read_in<T: 'static>(
328    mut table: impl Iterator<Item = &'static Action<T>>,
329    editor: &T,
330    action: &str,
331) -> Option<Reading> {
332    let action = table.find(|a| a.id == action)?;
333    Some(Reading {
334        offered: action.offered(editor),
335        enabled: action.enabled(editor),
336        pressed: action.pressed(editor),
337        caption: action.caption(editor),
338    })
339}
340
341/// eCAD's reading of `action` on `target`'s editor in `editors`.
342fn read(editors: &Editors, target: Target, action: &str) -> Option<Reading> {
343    match target {
344        Target::Diagram => read_in(brep_ecad_egui::actions(), &editors.diagram, action),
345        Target::Pcb => read_in(brep_ecad_egui::actions(), &editors.pcb, action),
346        Target::Symbol => read_in(brep_ecad_egui::symbol_actions().iter(), &editors.symbol, action),
347        Target::Pads => read_in(brep_ecad_egui::pad_actions().iter(), &editors.pads, action),
348    }
349}
350
351/// eCAD's reading of the action button `id` names, but only while that
352/// button's editor is the one on screen ([`active_target`]) and its OWN
353/// workbench is the active one: PCB diagram and PCB draw one editor, and each
354/// offers only its own row.
355fn reading(state: &ButtonState, id: &str) -> Option<Reading> {
356    let (target, action) = split(id)?;
357    if active_target(state) != Some(target) || id.split('.').next() != Some(state.engine.settings.workbench.as_str()) {
358        return None;
359    }
360    read(state.ecad?, target, action)
361}
362
363/// Whether the eCAD button `id` is offered: its editor is on screen and eCAD
364/// offers the action.
365pub fn offered(state: &ButtonState, id: &str) -> bool {
366    reading(state, id).is_some_and(|r| r.offered)
367}
368
369/// Whether the eCAD button `id` draws pressed: eCAD's own toggle state.
370pub fn pressed(state: &ButtonState, id: &str) -> bool {
371    reading(state, id).is_some_and(|r| r.pressed == Some(true))
372}
373
374/// Why the eCAD button `id` cannot act now, or `None` when eCAD enables it.
375pub fn disabled(state: &ButtonState, id: &str) -> Option<&'static str> {
376    let reading = reading(state, id)?;
377    if reading.enabled {
378        return None;
379    }
380    let action = split(id)?.1;
381    Some(
382        DISABLED_BECAUSE
383            .iter()
384            .find(|(known, _)| *known == action)
385            .map_or(DISABLED_UNEXPLAINED, |(_, why)| *why),
386    )
387}
388
389/// The eCAD button `id`'s live caption: eCAD's own button text, which for some
390/// actions describes state (`Bend: vertical first`, a layer's `B.Cu`).
391pub fn caption(state: &ButtonState, id: &str) -> String {
392    reading(state, id).map_or_else(
393        || super::button_by_declared_id(id).map_or_else(String::new, |b| b.tooltip.to_string()),
394        |r| r.caption,
395    )
396}
397
398/// The layer menu's live caption: the menu's own words and the layer it has
399/// on, so the closed menu still says where a track will go.
400pub fn layer_menu_caption(state: &ButtonState) -> String {
401    let on = super::pcb::LAYERS
402        .iter()
403        .find(|entry| entry.offered(state) && entry.is_pressed(state))
404        .map(|entry| entry.detail(state));
405    match on {
406        Some(layer) => format!("Copper layer: {layer}"),
407        None => "Copper layer".to_string(),
408    }
409}
410
411/// Run the eCAD action the button `id` names on its editor, as a click on
412/// eCAD's own button does. `None` when `id` is no declared button that IS an
413/// eCAD action — a menu is not one (its entries are), and neither is a button
414/// of BREP's own on an eCAD workbench ([`BREP_OWN`]), which the shell's own
415/// arms run. Without that, such a button would reach eCAD's `run_action`,
416/// read `false`, and be reported handled: a press that vanishes. Otherwise
417/// eCAD's answer, `false` when the action is not offered or not enabled now.
418pub fn dispatch(editors: &mut Editors, id: &str) -> Option<bool> {
419    dispatch_in(&super::declared_workbenches(), editors, id)
420}
421
422/// [`dispatch`] over any registry.
423fn dispatch_in(registry: &[&'static super::Workbench], editors: &mut Editors, id: &str) -> Option<bool> {
424    let button = super::button_in(registry, id)?;
425    if !button.menu.is_empty() {
426        return None;
427    }
428    let (target, action) = ecad_action(id)?;
429    Some(match target {
430        Target::Diagram => editors.diagram.run_action(action),
431        Target::Pcb => editors.pcb.run_action(action),
432        Target::Symbol => editors.symbol.run_action(action),
433        Target::Pads => editors.pads.run_action(action),
434    })
435}
436
437/// One eCAD action as a workbench button. `$id` is the BUTTON id — eCAD's
438/// action id behind its workbench's prefix, see [`split`] — and every
439/// predicate is eCAD's own, asked through this module. `toggle` is an action
440/// eCAD reports a pressed state for (a tool, a view, a layer); `command` one it
441/// does not. The tooltip is eCAD's label, word for word — the tests hold it.
442macro_rules! ecad_button {
443    ($id:literal, $glyph:literal, $tooltip:literal, $path:literal, toggle) => {
444        $crate::workbench::WorkbenchButton {
445            id: $id,
446            glyph: $glyph,
447            tooltip: $tooltip,
448            ribbon_path: $path,
449            size: $crate::workbench::CommandSize::Compact,
450            when: Some(|s| $crate::workbench::ecad::offered(s, $id)),
451            pressed: Some(|s| $crate::workbench::ecad::pressed(s, $id)),
452            disabled: Some(|s| $crate::workbench::ecad::disabled(s, $id)),
453            caption: Some(|s| $crate::workbench::ecad::caption(s, $id)),
454            menu: &[],
455        }
456    };
457    ($id:literal, $glyph:literal, $tooltip:literal, $path:literal, command) => {
458        $crate::workbench::WorkbenchButton {
459            id: $id,
460            glyph: $glyph,
461            tooltip: $tooltip,
462            ribbon_path: $path,
463            size: $crate::workbench::CommandSize::Compact,
464            when: Some(|s| $crate::workbench::ecad::offered(s, $id)),
465            pressed: None,
466            disabled: Some(|s| $crate::workbench::ecad::disabled(s, $id)),
467            caption: Some(|s| $crate::workbench::ecad::caption(s, $id)),
468            menu: &[],
469        }
470    };
471}
472pub(crate) use ecad_button;
473
474/// A workbench whose feature filter offers no features: eCAD's documents are
475/// not history features, as PMI's annotations and Drawing's sheets are not.
476pub(crate) fn no_features(_feature: &super::FeatureInfo<'_>) -> bool {
477    false
478}
479