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