brep_app/app.rs
1//! `BrepApp` — the THIN shell of the engine-native UI.
2//!
3//! One eframe [`App`](eframe::App) that hosts the EXISTING `brep-render` engine and lays out
4//! the panels. The heavy lifting lives in focused modules; this file only owns
5//! the shell:
6//!
7//! * [`Documents`] (`crate::document`) holds the OPEN MODELS — one
8//! [`EngineState`] per document plus its identity, exactly one active. Panels
9//! borrow the active engine through `self.docs.engine_mut()`, which borrows
10//! only that FIELD and so still composes with the disjoint panel borrows
11//! beside it. [`EngineState`] (`brep-render`) is still the single
12//! windowing-agnostic BRAIN per document (scene / camera / controls / settings
13//! / widgets + pointer/wheel/viewcube/pick); we do NOT fork it.
14//! * [`crate::viewport::Viewport`] draws + drives the central 3D viewport (the
15//! offscreen texture, the `egui_wgpu` blit callback, input routing).
16//! * [`crate::panels`] — one module per left-panel section, each a small state
17//! struct + a `show(&mut self, ui, state, …)` method. Adding a panel = add
18//! `panels/<name>.rs`, one field here, one `self.<name>.show(…)` call in
19//! [`eframe::App::ui`] below (see `README.md` → "Adding a panel").
20//!
21//! Native (`run_native`) and wasm (`WebRunner`) run this SAME code.
22
23use crate::document::{Documents, EngineFactory};
24use crate::panels::assembly_constraints::AssemblyConstraintsPanel;
25use crate::panels::bug_report::BugReportPanel;
26use crate::panels::wire_harness::WireHarnessPanel;
27use crate::panels::component_actions::ComponentActionRequest;
28use crate::panels::context_bar::ContextBarPanel;
29use crate::panels::mode_bar::ModeBar;
30use crate::panels::expressions::ExpressionsPanel;
31use crate::panels::file::{FileAction, FileDialog};
32use crate::panels::history::HistoryPanel;
33use crate::panels::info_windows::InfoWindows;
34use crate::panels::scene::ScenePanel;
35use crate::panels::selection::SelectionPanel;
36use crate::panels::sketch::SketchPanel;
37use crate::panels::sketch3d::Sketch3dPanel;
38use crate::panels::part_properties::PartPropertiesPanel;
39use crate::panels::settings::SettingsPanel;
40use crate::panels::toasts::Toasts;
41use crate::panels::toolbar::ToolbarPanel;
42use crate::panels::workbench_toolbar::WorkbenchToolbarPanel;
43use crate::panels::update_components::UpdateComponents;
44use crate::panels::bom::BomPanel;
45use crate::panels::dock::{DockContext, DockState, PaneKind};
46use crate::panels::document_tabs;
47use crate::store::{default_model_store, ModelStore, SETTINGS_KEY};
48use crate::viewport::Viewport;
49use brep_render::engine_state::EngineState;
50use brep_render::style::ThemeMode;
51use eframe::egui;
52
53/// A measured camera spin: an orbit drag the app steps ITSELF, one pointer move
54/// per frame, from `perf_spin`. See `BrepApp::spin` for why it is not driven
55/// from outside.
56///
57/// The steps run through the same `EngineState::pointer_down/move/up` the
58/// viewport's real drag uses (see `viewport::interaction`), so a spin costs
59/// exactly what dragging the mouse costs — no shortcut past the controls.
60#[cfg(feature = "automation")]
61pub struct Spin {
62 /// Pointer steps still to make; the drag ends (pointer_up) on the last one.
63 pub left: u32,
64 /// Where the drag started, in viewport-local logical px.
65 pub origin: (f64, f64),
66 /// Pointer step, in viewport-local logical px per frame.
67 pub step: (f64, f64),
68 /// Steps already made — the drag is a straight sweep from `origin`, and
69 /// reversing at the halfway mark keeps it inside the viewport however many
70 /// frames are asked for.
71 pub made: u32,
72 /// False until the first frame has pressed the button.
73 pub pressed: bool,
74}
75
76pub struct BrepApp {
77 /// Every OPEN MODEL and which one is active. Each document owns a full
78 /// `EngineState` (the shared viewer brain `desktop.rs` / the wasm shell
79 /// wrap) plus its file identity; panels borrow the active one.
80 pub(crate) docs: Documents,
81 /// The central 3D viewport: engine render core + offscreen texture + blit +
82 /// input routing.
83 pub(crate) viewport: Viewport,
84 /// The single persistence seam for settings, layout, and model documents
85 /// (native filesystem / wasm IndexedDB + download/upload).
86 pub(crate) model_store: Box<dyn ModelStore>,
87
88 // --- one small state value per panel --------------------------------------
89 /// Top toolbar: undo/redo, wireframe toggle, zoom-to-fit + standard views,
90 /// and the File-actions seam (owned by the concurrent file panel).
91 pub(crate) toolbar: ToolbarPanel,
92 /// New / Open / Save / Save As of the model document (the `.nbrep`
93 /// recipe) — a reusable modal file dialog opened from the toolbar.
94 file: FileDialog,
95 stl_import: Option<crate::panels::stl_import::StlImportPreview>,
96 /// The "Submit Bug" flow: on the toolbar bug button it screenshots the app
97 /// (UI + 3D model) BEFORE its own dialog opens, then collects a description
98 /// (+ optional email) and POSTs the model + screenshot to the public reports
99 /// endpoint. Native + wasm, one path.
100 bug_report: BugReportPanel,
101 /// The Info window: the licences and this session's diagnostics, toggled
102 /// from the toolbar's info button.
103 info: crate::panels::info::InfoPanel,
104 /// What this session is running on — captured ONCE, from the adapter eframe
105 /// actually gave us (never re-probed), and read by BOTH the Info window and
106 /// the problem report so the two cannot disagree. See
107 /// [`crate::diagnostics`].
108 diagnostics: crate::diagnostics::Diagnostics,
109 /// Workbench actions toolbar: the second top strip under the primary
110 /// toolbar — one button per feature the active workbench offers, plus the
111 /// constraint types where the Constraints panel is shown. Gated by the
112 /// `showWorkbenchToolbar` setting and hidden in the special modes. A click
113 /// flows out as the type to add; the shell adds it through the SAME paths
114 /// the palette / context bar use.
115 workbench_toolbar: WorkbenchToolbarPanel,
116 /// Display-settings + per-solid color panel (Phase 1): a FLOATING window
117 /// (movable + resizable, toggled from the toolbar gear button), no longer a
118 /// left-panel section.
119 settings: SettingsPanel,
120 pub(crate) plugins: crate::plugins::PluginsPanel,
121 pub(crate) javascript: crate::javascript::JavaScriptEditor,
122 /// The active document's OWN BOM attributes (Part Number, Material, Mass,
123 /// …) as a floating window, toggled from the toolbar's Properties button.
124 /// Document-level, not selection-level: entity inspection is the context
125 /// bar's `info_windows`.
126 part_properties: PartPropertiesPanel,
127 /// The Replace component chooser + result summary.
128 replace_dialog: crate::panels::replace_component::ReplaceDialog,
129 /// History feature-tree + schema-driven feature dialog panel (Phase 2).
130 /// NOTE: the editable history is NOT owned here — it lives in the engine core
131 /// (`EngineState.history`), the single source of truth; this panel only reads
132 /// it back to draw and calls the engine's `history_*` methods to mutate.
133 history: HistoryPanel,
134 /// Scene tree ("Scene Manager"): the display scene as a file-tree — per-solid
135 /// visibility + Faces/Edges/Vertices with two-way selection sync. Reads the
136 /// engine scene/emphasis; owns only transient expand + hit state.
137 scene: ScenePanel,
138 /// Assembly Structure tree (claimed by the Assembly workbench): a VIEW over
139 /// the scene's component records — per-instance fixed/visibility/status
140 /// adornments, actions routed to the owning ACOMP feature.
141 /// The BOM panel (claimed by the Assembly workbench): the parts list on
142 /// the shared column-tree widget, with the editable part/occurrence
143 /// attribute columns the Settings "Assemblies" section configures.
144 bom: BomPanel,
145 /// Assembly Constraints panel (claimed by the Assembly workbench): the
146 /// schema-driven constraint collection widget + Solve/auto-solve/DOF header.
147 assembly_constraints: AssemblyConstraintsPanel,
148 /// The wire-harness connection list (a Wire harness workbench pane): add /
149 /// edit / remove wires, read their routed length + status, hover to
150 /// highlight. Document data lives in the engine; this holds the widget's
151 /// transient state.
152 wire_harness: WireHarnessPanel,
153 /// The PMI view tree + annotation forms (the PMI workbench's pane).
154 pmi: crate::panels::pmi::PmiPanel,
155 /// The CAM browser tree (the CAM workbench's pane): setups and their
156 /// operations, NC programs and the tool library over the document's
157 /// `cam` block.
158 pub(crate) cam: crate::panels::cam::CamPanel,
159 pub(crate) instructions: crate::panels::instructions::InstructionsPanel,
160 pub(crate) instructions_player: crate::panels::instructions_player::InstructionsPlayerPanel,
161 /// The Simulation workbench's pane: the studies and the active timeline.
162 pub(crate) simulation: crate::panels::simulation::SimulationPanel,
163 /// The drawing sheets + their forms (the Drawing workbench's pane).
164 sheets: crate::panels::sheets::SheetsPanel,
165 /// Update-components checker: compares each parts-library entry's
166 /// `sourceSignature` against the model store's current content. Kept
167 /// current once per frame (cheap generation key: applied run + store
168 /// save); the constraints header reads the count + runs the batch refresh,
169 /// the structure tree reads per-part badges.
170 update_components: UpdateComponents,
171 /// Expressions / parameters panel: the variable sheet (engine-owned history
172 /// `expressions`) feature params reference. Owns only its editor buffer.
173 expressions: ExpressionsPanel,
174 /// Qualify: the part's declared CONNECTION POINTS, on whichever surface is
175 /// on screen (symbol, pads or 3D). Holds only the selected address; the
176 /// block and both consistency reports come from the engine.
177 qualify: crate::panels::qualify::QualifyPanel,
178 /// The family table editor: a `.fbrep` family seed's member table. Holds
179 /// the selection, the cell being typed and the last Generate report; the
180 /// table itself is the document's `familyTable` block.
181 family_table: crate::panels::family_table_editor::FamilyTableEditor,
182 /// Every PLM panel (`panels::plm_host`): empty in a file-based session.
183 pub(crate) plm: crate::panels::plm_host::PlmHost,
184 /// Info windows: MULTIPLE pinned per-entity inspector windows opened from the
185 /// selection-driven context bar's Info action. Each floating (movable +
186 /// resizable) window is PINNED to one object name at open time — a Metadata
187 /// (editable attribute) tab + a read-only Info (measurements + provenance) tab —
188 /// and keeps showing that entity regardless of later selection changes. Replaces
189 /// the old single Properties window.
190 info_windows: InfoWindows,
191 /// Interference results window: opened by the Assembly workbench's `∩`
192 /// toolbar button, which runs the engine's pairwise-intersect check; a
193 /// floating window like the Info windows with a row per interfering pair
194 /// (click = select both components), a green all-clear pass line, and a
195 /// Re-run button.
196 interference: crate::panels::interference::InterferenceWindow,
197 /// Auto Constraints window (Assembly workbench): opened by the `⚿` toolbar
198 /// button, it lists the constraint types the kernel's inference lane can
199 /// read out of the components' current placement, with what a scan found
200 /// for each, and creates the whole accepted set as one undo step.
201 auto_constraints: crate::panels::auto_constraints::AutoConstraintsWindow,
202 /// step.parts online model library browser (Assembly workbench): a ctx-level
203 /// window (opened by the library toolbar button) that searches the public
204 /// step.parts v1 API, shows results with thumbnails, and imports a chosen
205 /// STEP model as a new part document + adds it to the assembly as an ACOMP.
206 step_parts: crate::panels::step_parts::StepPartsPanel,
207 /// Selection panel: the pickable-kinds filter (which entity kinds a viewport
208 /// click may select — honored by the engine's `select_top_at`). The filter +
209 /// selection live in `EngineState`; this panel only reads/writes them.
210 selection: SelectionPanel,
211 /// Context action toolbar: the selection-driven action bar (Clear / Hide /
212 /// Edit-owning-feature + the feature-from-selection actions whose primary
213 /// reference accepts the selected kind). Shown only while something is
214 /// selected; drives the engine directly and returns a feature id for the shell
215 /// to expand in the history tree.
216 context_bar: ContextBarPanel,
217 /// Sketch (S0): a seeded, read-only sketch preview — pushes a solved rectangle
218 /// + circle to the `set_overlay` channel colored by solver mobility, and shows
219 /// the DOF status readout. The engine-native sketcher's foundation surface.
220 sketch: SketchPanel,
221 sketch3d: Sketch3dPanel,
222 /// Special-mode EXIT controls (Finish/Cancel), always pinned to the top-right
223 /// corner — a card-based reference pick, sketch mode, and any future
224 /// special mode. A form field's pick draws no card: its field is the UI.
225 mode_bar: ModeBar,
226 pick_bar: crate::panels::pick_bar::PickBar,
227 /// Transient toast overlay: drains the engine's queued notices each frame
228 /// (e.g. a sketch solve that failed after an edit) and shows each briefly.
229 pub(crate) toasts: Toasts,
230 /// The status bar's app-wide working indicator (`panels::busy`): what is
231 /// in flight, collected from every source each frame.
232 busy: crate::panels::busy::BusyIndicator,
233 /// Dockable / tabbed side-panel layout (egui_tiles): the shared, persisted
234 /// tree that hosts every side-panel section AND the 3D viewport as tiles the
235 /// user can split, tab, resize, and drag-rearrange. Owns the layout; borrows
236 /// each panel + the engine per frame through [`DockContext`]. Drawn in normal
237 /// modeling mode; sketch / ref-select mode bypasses it (viewport drawn direct).
238 dock: DockState,
239
240 /// Whether the ONE-SHOT first-model framing has fired. The seed run is async
241 /// under a background runner (native thread / wasm worker), so the boot
242 /// `zoom_to_fit` can run before the first solids exist → an unframed first
243 /// model. Once the seed run has landed (`has_solids() && !run_pending()`), the
244 /// `ui` loop frames it once and sets this. Under the synchronous Inline runner
245 /// (tests) the scene is already populated, so this fires on the very first frame.
246 first_run_framed: bool,
247
248 /// A model fetch kicked off at boot from a `?loadModel=<url>` query param
249 /// (wasm only). When the fetch lands it REPLACES the seed model. `None` on
250 /// native and once applied.
251 pending_boot_load: Option<std::sync::mpsc::Receiver<Result<String, String>>>,
252
253 /// "Open in CAD" from the PLM's page: the `?open=part/…/rev/…` this page
254 /// was started with (wasm only), driven once a frame until it settles.
255 plm_launch: Option<crate::panels::plm_launch::Launch>,
256
257 /// The document handle the shared panels were last reset for. Compared to
258 /// `docs.view_id()` at the top of every frame: ONE check catches a switch
259 /// from any source (a tab click, a close, New, Open, Edit Part, a Work
260 /// part entered or left in place) instead of a hook per call site, and it
261 /// runs BEFORE any panel draws this frame.
262 active_document: u64,
263 /// The TAB the panels were last drawn for. A Work part entered or left in
264 /// place changes the view but not the tab, and the BOM — the assembly's
265 /// product structure in both — keeps its packed/expanded state.
266 active_tab: u64,
267
268 /// Whether the active workbench showed the Sheets pane LAST frame — the
269 /// edge the paper is closed on. Closing is a transition, not a condition:
270 /// a sheet opened while another workbench is active (a command, a script)
271 /// stays open until the Drawing workbench is LEFT, exactly as PMI's view
272 /// deactivates on leaving rather than on every frame outside it.
273 sheets_pane_shown: bool,
274
275 /// The DOCUMENT TAB STRIP's per-tab hit-rects from the last dock frame,
276 /// published for the headed verifier. The strip is drawn inside the dock's
277 /// viewport pane, so its rects have to ride back out through the outcome.
278 document_tab_hits: Vec<(String, egui::Rect)>,
279
280 /// The `__brepParams` blob and the document state it was built from:
281 /// `(document, rolled-to step, history revision, json)`.
282 ///
283 /// The blob is the rolled-to feature's whole `inputParams`, and for an
284 /// `IMPORT3D` those params carry the embedded model text — 681 KB on the
285 /// heaviest corpus model. It was rebuilt EVERY frame, which on the browser
286 /// build (where the state registry is always on) also transcoded it into a
287 /// fresh JS string every frame, on the one thread that also has to answer
288 /// the pointer. Nothing reads it per frame; it only has to be correct when
289 /// someone asks. The revision is a mutation counter the document hands out
290 /// (`EngineState::history_revision`), so this cannot go stale without the
291 /// borrow checker having let a mutation past the door that bumps it.
292 params_blob: (u64, usize, u64, String),
293
294 /// A measured camera spin in flight (`perf_spin`): the orbit drag the app
295 /// drives ITSELF, one pointer step per frame, so the frames run back to back.
296 /// Driving it from a host instead would put a round trip between every pair
297 /// of frames, and `dt` — the frame period, the number a user feels as a
298 /// freeze — would measure the host's latency rather than the app's.
299 #[cfg(feature = "automation")]
300 spin: Option<Spin>,
301
302 /// The debounced autosave of every dirty document (`crate::recovery`), and
303 /// the boot-time **Recover unsaved work?** prompt its blob feeds. The
304 /// autosave is held while the prompt is open: the clean seed tab would
305 /// otherwise remove the very blob being offered.
306 autosave: crate::recovery::Autosave,
307 /// Closing (the window's close button, or `app_close`): when it was asked
308 /// (egui clock). The close waits until the store's writes have landed.
309 closing: Option<f64>,
310 /// A close the automation layer asked for, taken by the next frame.
311 pub(crate) close_asked: bool,
312 /// The app let the window close: nothing was left on its way.
313 closed: bool,
314 /// Where a close stands once the store's writes have settled: `0` not
315 /// yet, `1` one frame given to the failure drain (a write that failed
316 /// makes its tab unsaved), `2` the recovery blob written again.
317 close_stage: u8,
318 recovery: crate::recovery::RecoveryPanel,
319 /// The desktop update check and its notice. Inert until the desktop
320 /// binary's `main` starts it, so a harness or a test never checks.
321 #[cfg(not(target_arch = "wasm32"))]
322 updater: crate::update::Updater,
323 /// The reports this user submitted, checked for resolution
324 /// (`crate::report_followup`). Inert until the entry point starts it.
325 report_followup: crate::report_followup::ReportFollowup,
326
327 /// The UI zoom scale CURRENTLY applied to the egui context. Tracks
328 /// `settings.ui_scale` but is only synced to it while the pointer is up, so
329 /// dragging the Settings "UI scale" slider doesn't rescale the whole UI under
330 /// the cursor mid-drag — the settled value is committed on release. See the
331 /// zoom-apply block in `ui`.
332 applied_ui_scale: f32,
333 /// The automation channel (hosts submit commands; the frame drains them at
334 /// three fixed points — see `automation::queue`).
335 #[cfg(feature = "automation")]
336 pub(crate) automation: std::sync::Arc<crate::automation::queue::AutomationQueue>,
337}
338
339/// The caption text size, points (egui's own `Small` is 9). See `app_style`.
340pub const SMALL_TEXT_SIZE: f32 = 10.5;
341
342/// The app's tweaks over egui's style, applied to both themes at startup.
343pub(crate) fn app_style(style: &mut egui::Style) {
344 // Keep overflow discoverable without hovering or scrolling first, in
345 // both themes and every child UI (including eCAD and plugin panels).
346 // ScrollArea's default VisibleWhenNeeded still hides bars that aren't needed.
347 style.spacing.scroll = egui::style::ScrollStyle::solid();
348 // Captions (`ui.small`, `RichText::small`): egui's 9 pt was too small to
349 // read beside 12.5 pt body text in the Info window, the eCAD inspectors and
350 // the Selection actions summary (lane U audit item 9). 10.5 keeps them
351 // visibly secondary. The toolbar/Ribbon group captions stay at 9
352 // (`ribbon::CHROME_CAPTION_SIZE`) so the chrome keeps its height.
353 style.text_styles.insert(egui::TextStyle::Small, egui::FontId::new(SMALL_TEXT_SIZE, egui::FontFamily::Proportional));
354}
355
356
357/// How long a close waits for writes still on their way to the store (a PLM
358/// server that stopped answering must not keep the app open forever).
359const CLOSE_WAIT_SECS: f64 = 30.0;
360
361impl BrepApp {
362 /// Closing the window. What is unsaved is written for recovery at once
363 /// (the next start offers it, as after a crash), and the window stays open
364 /// until every write the store issued (a Save, that recovery blob) has
365 /// landed: a write-behind store would otherwise lose a Save made just
366 /// before. After [`CLOSE_WAIT_SECS`] it closes anyway.
367 fn close_when_written(&mut self, ctx: &egui::Context) {
368 let asked = ctx.input(|i| i.viewport().close_requested()) || std::mem::take(&mut self.close_asked);
369 if self.closed {
370 return;
371 }
372 let now = ctx.input(|i| i.time);
373 if asked && self.closing.is_none() {
374 if !self.recovery.is_open() {
375 self.autosave.flush(&self.docs, self.model_store.as_ref());
376 }
377 self.closing = Some(now);
378 }
379 let Some(since) = self.closing else { return };
380 let pending = self.model_store.pending_writes();
381 let timed_out = now - since > CLOSE_WAIT_SECS;
382 if pending == 0 || timed_out {
383 match self.close_stage {
384 // The writes settled. A failed one (the server down) makes its
385 // tab unsaved when the failures are drained, later in this
386 // frame: give that a frame…
387 0 => self.close_stage = 1,
388 // …then write the recovery blob again, so a Save that never
389 // reached the server is offered at the next start.
390 1 => {
391 if !self.recovery.is_open() {
392 self.autosave.flush(&self.docs, self.model_store.as_ref());
393 }
394 self.close_stage = 2;
395 }
396 _ if self.model_store.pending_writes() == 0 || timed_out => {
397 self.closed = true;
398 ctx.send_viewport_cmd(egui::ViewportCommand::Close);
399 return;
400 }
401 _ => {}
402 }
403 ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
404 ctx.request_repaint();
405 return;
406 }
407 ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
408 egui::Area::new(egui::Id::new("brep-closing"))
409 .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
410 .order(egui::Order::Foreground)
411 .show(ctx, |ui| {
412 egui::Frame::popup(ui.style()).show(ui, |ui| {
413 ui.horizontal(|ui| {
414 ui.spinner();
415 ui.label(format!("Finishing {pending} save(s) before closing…"));
416 });
417 });
418 });
419 ctx.request_repaint_after(std::time::Duration::from_millis(50));
420 }
421
422 /// The close state, for automation (`__brepClosing`).
423 pub(crate) fn closing_json(&self) -> String {
424 serde_json::json!({
425 "closing": self.closing.is_some(),
426 "closed": self.closed,
427 "pending": self.model_store.pending_writes(),
428 })
429 .to_string()
430 }
431
432 /// The automation queue a host submits commands to.
433 #[cfg(feature = "automation")]
434 pub fn automation(&self) -> &std::sync::Arc<crate::automation::queue::AutomationQueue> {
435 &self.automation
436 }
437
438 /// Open a `.nbrep` file named on the command line — `brep-app model.nbrep`,
439 /// which is also what a desktop file association hands us (`Exec=… %f`).
440 ///
441 /// The path goes through the same `FileDialog::open_document` door as
442 /// File>Open, so the document keeps the full path as its identity and a
443 /// later plain Save writes back to the file the user double-clicked, rather
444 /// than to a copy in the app's own models directory. A path that does not
445 /// parse leaves the status line saying so and the seed document in place —
446 /// a bad argument must not cost the user a window.
447 ///
448 /// Native only: called once, before the first frame.
449 #[cfg(not(target_arch = "wasm32"))]
450 pub fn open_path_from_command_line(&mut self, path: &std::path::Path) {
451 // Absolute, so the store resolves it as a real file rather than as a
452 // name inside the models directory (`store::resolve` routes anything
453 // with a separator straight to the filesystem).
454 let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
455 let Some(name) = path.to_str() else {
456 log::warn!("brep-app: {} is not valid UTF-8; not opening it", path.display());
457 return;
458 };
459 // Field-by-field, because `open_document` borrows the documents and the
460 // store while `self.file` is borrowed mutably.
461 let Self { file, docs, model_store, .. } = self;
462 file.open_document(docs, model_store.as_ref(), name);
463 }
464
465 /// The 3D viewport rect of the last frame, in egui points.
466 pub fn view_rect(&self) -> Option<egui::Rect> {
467 self.viewport.last_rect()
468 }
469
470 /// The session's store, read-only (the automation layer's `frame_info`
471 /// counts its writes still on their way).
472 pub(crate) fn model_store(&self) -> &dyn ModelStore {
473 self.model_store.as_ref()
474 }
475
476 /// Why this session cannot switch stores live, or `None` when it can: every
477 /// open document untitled and clean, the state a fresh start has. A named
478 /// document's identity belongs to the store it came from, and a dirty one's
479 /// work has nowhere to go in a new store.
480 pub(crate) fn reconnect_blocker(&self) -> Option<String> {
481 self.reconnect_blocker_with(crate::document::Document::is_dirty)
482 }
483
484 fn reconnect_blocker_with(&self, is_dirty: impl Fn(&crate::document::Document) -> bool) -> Option<String> {
485 let named = self.docs.iter().filter(|d| d.name().is_some()).count();
486 let dirty = self.docs.iter().filter(|d| is_dirty(d)).count();
487 match (named, dirty) {
488 (0, 0) => None,
489 (_, 0) => Some(format!("{named} document(s) from this store are open: close them, then Connect now (or restart)")),
490 _ => Some(format!("{dirty} document(s) have unsaved work: save or close them, then Connect now (or restart)")),
491 }
492 }
493
494 /// Switch this session to the PLM configured at `root`, live (S1's named
495 /// limit): the native boot S2 runs at start, then everything the app read
496 /// from the store when it was built is read again from the new one. Only
497 /// while [`Self::reconnect_blocker`] is `None`. A refused boot changes
498 /// nothing and says why.
499 #[cfg(not(target_arch = "wasm32"))]
500 pub(crate) fn reconnect_plm(&mut self, root: std::path::PathBuf) -> Result<String, String> {
501 use crate::plm::connection::Status;
502 if let Some(why) = self.reconnect_blocker() {
503 return Err(why);
504 }
505 let config = crate::plm::config::resolve(&root, &|_| None, &Default::default())?
506 .ok_or_else(|| format!("no PLM is configured in {}", root.display()))?;
507 let store = crate::store::boot_native_store(root, config);
508 let Some(Status::Connected { url, username }) = store.plm_session().map(|s| s.status) else {
509 let why = store.take_persistence_errors().join("; ");
510 return Err(if why.is_empty() { "the PLM did not take this session".into() } else { why });
511 };
512 self.model_store = store;
513 self.docs.set_canonicalizer(self.model_store.canonicalizer());
514 // Settings: every open engine, and every later tab, starts from the
515 // defaults with the new store's settings over them, as a fresh boot
516 // would; nothing of the old store's carries over.
517 let saved = self.model_store.read(SETTINGS_KEY);
518 let fresh = move |mut state: EngineState| {
519 state.settings = brep_render::style::RenderSettings::default();
520 let defaults = state.settings.to_json();
521 let _ = state.apply_settings_json(&defaults);
522 if let Some(saved) = &saved {
523 let _ = state.apply_settings_json(saved);
524 }
525 state
526 };
527 for doc in self.docs.iter_mut() {
528 let engine = std::mem::replace(&mut doc.engine, EngineState::new());
529 doc.engine = fresh(engine);
530 }
531 self.docs.wrap_engine_factory(fresh);
532 self.dock = DockState::new(self.model_store.as_ref());
533 self.recovery.arm_from_store(
534 self.model_store.as_ref(),
535 self.docs.engine().settings.disable_recovery_prompt,
536 );
537 self.file = FileDialog::new();
538 self.update_components = UpdateComponents::new();
539 Ok(format!("connected to {url} as {username}"))
540 }
541
542 /// Keep automation waits active until the File dialog has delivered the PDF.
543 pub(crate) fn instructions_pdf_pending(&self) -> bool {
544 self.file.instructions_pdf_pending()
545 }
546
547 /// The file dialog, the documents and the store together — for the
548 /// automation commands that drive a document-class flow (Generate, a
549 /// store read-back) exactly as the panels do.
550 pub(crate) fn file_docs_store(&mut self) -> (&mut FileDialog, &mut Documents, &dyn ModelStore) {
551 (&mut self.file, &mut self.docs, self.model_store.as_ref())
552 }
553
554 /// The active document's engine.
555 pub fn docs_engine(&self) -> &EngineState {
556 self.docs.engine()
557 }
558
559 /// Open the mesh import preview for the file `name` (`.stl` or `.3mf`)
560 /// against the active document — what activating it in the Import explorer
561 /// does. The preview replaces the shell until it is accepted or cancelled.
562 pub fn open_mesh_preview(&mut self, name: String, bytes: Vec<u8>) -> Result<(), String> {
563 use brep_render::runner::MeshImportFormat;
564 let format = match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {
565 Some("stl") => MeshImportFormat::Stl,
566 Some("3mf") => MeshImportFormat::ThreeMf,
567 _ => return Err(format!("{name} is not an STL or 3MF file")),
568 };
569 self.start_mesh_preview(format, name, bytes);
570 Ok(())
571 }
572
573 fn start_mesh_preview(&mut self, format: brep_render::runner::MeshImportFormat, name: String, bytes: Vec<u8>) {
574 self.stl_import = Some(crate::panels::stl_import::StlImportPreview::new(
575 self.docs.active_id(), format, name, bytes, self.docs.spawn_engine(),
576 ));
577 self.viewport.forget_document();
578 }
579
580 /// Whether the mesh import preview is open.
581 pub fn mesh_preview_open(&self) -> bool {
582 self.stl_import.is_some()
583 }
584
585 /// The engine the 3D viewport is drawing: the mesh import preview's own
586 /// while it is open (it replaces the shell), else the active document's.
587 /// What a pointer script's `locate` must project through.
588 pub fn viewport_engine(&self) -> &EngineState {
589 match &self.stl_import {
590 Some(preview) => &preview.engine,
591 None => self.docs.engine(),
592 }
593 }
594
595 pub fn new(cc: &eframe::CreationContext<'_>) -> Result<Self, String> {
596 Self::new_with(cc, crate::automation::AppOptions::default())
597 }
598
599 /// Build the app with host-supplied options: an isolated store (a host
600 /// MUST pass one) and whether to start on the seed model.
601 pub fn new_with(cc: &eframe::CreationContext<'_>, opts: crate::automation::AppOptions) -> Result<Self, String> {
602 // Solid scroll bars and readable captions, in both themes.
603 cc.egui_ctx.all_styles_mut(app_style);
604 // The action registry's view of each pass (`activate_widget`).
605 #[cfg(feature = "automation")]
606 crate::automation::actions::install(&cc.egui_ctx);
607 let crate::automation::AppOptions { store: opt_store, seed } = opts;
608 let render_state = cc
609 .wgpu_render_state
610 .as_ref()
611 .ok_or_else(|| "eframe was not created with a wgpu render state".to_string())?;
612
613 // The viewport owns the render core + blit pipeline, built from eframe's
614 // SHARED device/queue/format.
615 let viewport = Viewport::new(render_state);
616
617 // The session's diagnostics, taken from that same render state: the
618 // adapter about to draw every frame is the one a report must name. The
619 // WebGPU-vs-WebGL2 decision has already been made by the time we get
620 // here (eframe drops `BROWSER_WEBGPU` from the backend set when the
621 // browser offers no WebGPU adapter), so this READS the outcome — asking
622 // again later would be a second question with its own answer.
623 let diagnostics = crate::diagnostics::Diagnostics::from_render_state(render_state);
624
625 // --- storage seam: load the persisted settings ------------------------
626 let model_store = opt_store.unwrap_or_else(default_model_store);
627 // wasm: hand the store the egui context so an async file-upload load
628 // callback can wake the reactive frame loop (see `store::set_repaint_ctx`).
629 #[cfg(target_arch = "wasm32")]
630 crate::store::set_repaint_ctx(cc.egui_ctx.clone());
631 let saved_settings = model_store.read(SETTINGS_KEY);
632
633 // --- how a document's engine is built --------------------------------
634 // Every tab gets its OWN engine, and therefore its own history runner —
635 // a runner owns the resident kernel state of the document it executes,
636 // so one shared between documents would apply a background run against
637 // the wrong registry. See `crate::document`.
638 let plugins = crate::plugins::PluginsPanel::new(model_store.as_ref());
639 let javascript = crate::javascript::JavaScriptEditor::new(model_store.as_ref());
640 let plugin_packages = plugins.packages.clone();
641 let engine_factory: EngineFactory = Box::new(move || {
642 let mut state = EngineState::new();
643 // Native: run the whole history — and per-object measurement queries — on a
644 // persistent background thread so the UI never freezes during a run or a
645 // selection (M2b). Installed BEFORE anything loads so it builds through it.
646 #[cfg(not(target_arch = "wasm32"))]
647 state.set_runner(Box::new(brep_render::runner::ThreadRunner::new()));
648 // wasm: the browser-thread analogue — a dedicated web worker (M3b) so the
649 // single-threaded wasm UI stays responsive during a run. Same seam. Tests
650 // (which never hit this wasm path) keep the default synchronous InlineRunner.
651 #[cfg(target_arch = "wasm32")]
652 state.set_runner(Box::new(crate::worker::WorkerRunner::new()));
653 if !plugin_packages.borrow().is_empty() {
654 if let Err(error) = crate::plugins::restore(&mut state, &plugin_packages.borrow()) {
655 log::error!("Plugin restore failed: {error}");
656 }
657 }
658 state.set_viewcube_enabled(true);
659 // Partial-override apply: unknown/absent keys keep their defaults.
660 if let Some(saved) = &saved_settings {
661 let _ = state.apply_settings_json(saved);
662 }
663 state
664 });
665
666 // Start with the seed model on every launch (7626103c2). Reopening the
667 // previous session can immediately rerun a problematic document and
668 // prevent the user from recovering by restarting the app, so which
669 // documents were open is not persisted at all: saved models come back
670 // through the file dialog, and work that was never saved comes back as
671 // the crash-recovery OFFER below — a prompt, never an automatic load.
672 let mut docs = Documents::new(engine_factory);
673 docs.set_canonicalizer(model_store.canonicalizer());
674 if starts_on_seed_model(seed, &docs.engine().settings) {
675 let _ = docs.engine_mut().set_history_json(&seed_history_json());
676 }
677 docs.engine_mut().zoom_to_fit();
678 docs.active_mut().mark_clean();
679
680 // The autosave blob from a session that ended with unsaved work: offer
681 // it back (a prompt, never an automatic restore — see `crate::recovery`).
682 let mut recovery = crate::recovery::RecoveryPanel::new();
683 recovery.arm_from_store(model_store.as_ref(), docs.engine().settings.disable_recovery_prompt);
684
685 // The settings panel seeds its working JSON from the (post-load) engine
686 // settings so the widgets reflect the persisted state on first paint.
687 let settings = SettingsPanel::new();
688 let part_properties = PartPropertiesPanel::new();
689
690 // New / Open / Save / Save As. Holds no document identity — that lives
691 // on each `Document`.
692 let file = FileDialog::new();
693
694 // Boot at the saved UI scale.
695 let applied_ui_scale = docs.engine().settings.ui_scale;
696 let active_document = docs.active_id();
697
698 // The dock layout (loads the persisted tree, or the default). Built before
699 // `model_store` is moved into `Self`.
700 let dock = DockState::new(model_store.as_ref());
701
702 // Boot-load: if the page URL carries `?loadModel=<url>` (wasm only), start
703 // fetching that model NOW; the seed still loads this frame and the fetched
704 // model REPLACES it when it lands (drained in `ui`). See the drain block.
705 crate::offsite::prefetch();
706 #[cfg(target_arch = "wasm32")]
707 let pending_boot_load = web_sys::window()
708 .and_then(|w| w.location().search().ok())
709 .and_then(|search| web_sys::UrlSearchParams::new_with_str(&search).ok())
710 .and_then(|params| params.get("loadModel"))
711 .filter(|url| !url.is_empty())
712 .map(|url| crate::offsite::fetch_text(&cc.egui_ctx, "Opening a model from a link", url));
713 #[cfg(not(target_arch = "wasm32"))]
714 let pending_boot_load: Option<std::sync::mpsc::Receiver<Result<String, String>>> = None;
715 #[cfg(target_arch = "wasm32")]
716 let plm_launch = crate::panels::plm_launch::Launch::from_page();
717 #[cfg(not(target_arch = "wasm32"))]
718 let plm_launch = None;
719
720 Ok(Self {
721 docs,
722 viewport,
723 toolbar: ToolbarPanel::new(),
724 workbench_toolbar: WorkbenchToolbarPanel::new(),
725 model_store,
726 file,
727 stl_import: None,
728 bug_report: BugReportPanel::new(),
729 info: crate::panels::info::InfoPanel::new(),
730 diagnostics,
731 settings,
732 plugins,
733 javascript,
734 part_properties,
735 replace_dialog: Default::default(),
736 history: HistoryPanel::new(),
737 scene: ScenePanel::new(),
738 bom: BomPanel::new(),
739 assembly_constraints: AssemblyConstraintsPanel::new(),
740 wire_harness: WireHarnessPanel::new(),
741 pmi: crate::panels::pmi::PmiPanel::new(),
742 cam: crate::panels::cam::CamPanel::new(),
743 instructions: crate::panels::instructions::InstructionsPanel::new(),
744 instructions_player: crate::panels::instructions_player::InstructionsPlayerPanel::new(),
745 simulation: crate::panels::simulation::SimulationPanel::new(),
746 sheets: crate::panels::sheets::SheetsPanel::new(),
747 update_components: UpdateComponents::new(),
748 expressions: ExpressionsPanel::new(),
749 qualify: crate::panels::qualify::QualifyPanel::new(),
750 family_table: crate::panels::family_table_editor::FamilyTableEditor::new(),
751 plm: crate::panels::plm_host::PlmHost::new(),
752 info_windows: InfoWindows::new(),
753 interference: crate::panels::interference::InterferenceWindow::new(),
754 auto_constraints: crate::panels::auto_constraints::AutoConstraintsWindow::new(),
755 step_parts: crate::panels::step_parts::StepPartsPanel::new(),
756 selection: SelectionPanel::new(),
757 context_bar: ContextBarPanel::new(),
758 sketch: SketchPanel::new(),
759 sketch3d: Sketch3dPanel::new(),
760 mode_bar: ModeBar::new(),
761 pick_bar: crate::panels::pick_bar::PickBar::new(),
762 toasts: Toasts::new(),
763 busy: crate::panels::busy::BusyIndicator::new(),
764 dock,
765 first_run_framed: false,
766 pending_boot_load,
767 plm_launch,
768 active_document,
769 active_tab: active_document,
770 sheets_pane_shown: false,
771 document_tab_hits: Vec::new(),
772 params_blob: (u64::MAX, usize::MAX, u64::MAX, String::new()),
773 #[cfg(feature = "automation")]
774 spin: None,
775 autosave: crate::recovery::Autosave::new(),
776 closing: None,
777 close_asked: false,
778 closed: false,
779 close_stage: 0,
780 recovery,
781 #[cfg(not(target_arch = "wasm32"))]
782 updater: crate::update::Updater::inert(),
783 report_followup: crate::report_followup::ReportFollowup::new(),
784 applied_ui_scale,
785 #[cfg(feature = "automation")]
786 automation: {
787 let q = crate::automation::queue::AutomationQueue::new();
788 q.attach(&cc.egui_ctx);
789 q
790 },
791 })
792 }
793
794 /// Start the desktop update check (`crate::update`). Called by the
795 /// desktop binary's `main` only.
796 #[cfg(not(target_arch = "wasm32"))]
797 pub fn start_update_check(&mut self, ctx: &egui::Context) {
798 self.updater = crate::update::Updater::start(ctx);
799 }
800
801 /// Remember submitted problem reports and check them for resolution
802 /// (`crate::report_followup`). Called by the desktop `main` and the web
803 /// entry point only.
804 pub fn start_report_followup(&mut self, ctx: &egui::Context) {
805 self.report_followup.start(ctx);
806 }
807
808 /// Arm a measured camera spin: `frames` pointer steps of `step` logical px
809 /// each, starting at the centre of the 3D viewport. Replaces any spin in
810 /// flight. See [`Spin`].
811 #[cfg(feature = "automation")]
812 pub fn start_spin(&mut self, frames: u32, step: (f64, f64)) {
813 let rect = self.viewport.last_rect();
814 let origin = rect
815 .map(|r| (r.width() as f64 * 0.5, r.height() as f64 * 0.5))
816 .unwrap_or((320.0, 240.0));
817 self.spin = Some(Spin { left: frames.max(1), origin, step, made: 0, pressed: false });
818 }
819
820 /// Is a measured spin still running?
821 #[cfg(feature = "automation")]
822 pub fn spinning(&self) -> bool {
823 self.spin.is_some()
824 }
825
826 /// Advance an in-flight spin by ONE pointer step and keep the frame loop
827 /// awake. The drag sweeps out and back over a fixed span so it never leaves
828 /// the viewport however many frames are asked for; the camera keeps turning
829 /// either way, which is all the measurement needs.
830 #[cfg(feature = "automation")]
831 fn step_spin(&mut self, ctx: &egui::Context) {
832 let Some(mut spin) = self.spin.take() else { return };
833 {
834 let state = self.docs.engine_mut();
835 if !spin.pressed {
836 state.pointer_down(spin.origin.0, spin.origin.1, brep_render::controls::BUTTON_LEFT);
837 spin.pressed = true;
838 }
839 const SPAN: f64 = 60.0;
840 let phase = f64::from(spin.made % (2 * SPAN as u32));
841 let t = if phase <= SPAN { phase } else { 2.0 * SPAN - phase };
842 state.pointer_move(spin.origin.0 + spin.step.0 * t, spin.origin.1 + spin.step.1 * t);
843 spin.made += 1;
844 spin.left -= 1;
845 if spin.left == 0 {
846 state.pointer_up();
847 }
848 }
849 if spin.left > 0 {
850 self.spin = Some(spin);
851 }
852 ctx.request_repaint();
853 }
854
855 /// The `__brepParams` JSON, rebuilt only when the document it describes can
856 /// have changed. The `params_blob` FIELD carries the reason this is not
857 /// simply built afresh each frame.
858 fn params_blob(&mut self) -> &str {
859 let key = (
860 self.docs.active_id(),
861 self.docs.engine().history_rollback(),
862 self.docs.engine().history_revision(),
863 );
864 if (self.params_blob.0, self.params_blob.1, self.params_blob.2) != key {
865 self.params_blob = (
866 key.0,
867 key.1,
868 key.2,
869 self.docs.engine().feature_params_json(key.1),
870 );
871 }
872 &self.params_blob.3
873 }
874
875 /// Global keyboard shortcuts (egui input): **Ctrl/Cmd+Z** undo,
876 /// **Ctrl/Cmd+Shift+Z** or **Ctrl/Cmd+Y** redo, **Esc** clears the selection
877 /// — unless a popup or menu is up, which the Escape closes instead.
878 ///
879 /// `Modifiers::COMMAND` is Ctrl on Windows/Linux and ⌘ on macOS, so one map
880 /// covers both. Skipped entirely while an egui TEXT edit is focused so typing
881 /// (and text-field Ctrl+Z / Esc-to-defocus) is never hijacked. Redo is
882 /// consumed BEFORE undo because egui's `consume_key` matches modifiers
883 /// logically (a plain `COMMAND+Z` pattern would also swallow `COMMAND+Shift+Z`).
884 fn handle_shortcuts(&mut self, ctx: &egui::Context) {
885 // A modal owns every key: its Escape closes it, and nothing under it —
886 // undo, a Delete, the selection — is the key's to change.
887 if ctx.text_edit_focused() || crate::viewport::modal_open_last_pass(ctx) {
888 return;
889 }
890 use egui::{Key, Modifiers};
891 // A popup or menu that was up last frame owns this Escape: it closes on
892 // `key_pressed(Escape)`, which a consumed key never is, so the key is
893 // left in the input for it and nothing below acts on it — not the
894 // sketch tool, not a pick, and not the selection its menu is about.
895 let popup_open = crate::viewport::popup_open_last_pass(ctx);
896 // On an eCAD workbench, Delete and Escape are the editor's keys, and
897 // whether they reach it is the editors' ONE rule, `keys_reach_editor`
898 // (a text field, a menu or combo box, a modal), not a copy of it here.
899 // The watch above is the host's own addition: egui's popup memory does
900 // not see the host's `open_bool` menus (a tree row's), and those own
901 // their Escape on every workbench.
902 let ecad_target = crate::workbench::ecad::Target::of_workbench(&self.docs.engine().settings.workbench);
903 let keys_free = match ecad_target {
904 Some(_) => !popup_open && brep_ecad_egui::keys_reach_editor(ctx),
905 None => !popup_open,
906 };
907 if crate::javascript::JavaScriptEditor::editing_source(ctx) {
908 return;
909 }
910 let sketching_3d = self.docs.engine().sketch3d_mode();
911 let (redo, undo, esc, tab) = ctx.input_mut(|i| {
912 let redo = i.consume_key(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z)
913 || i.consume_key(Modifiers::COMMAND, Key::Y);
914 let undo = i.consume_key(Modifiers::COMMAND, Key::Z);
915 let esc = keys_free && i.consume_key(Modifiers::NONE, Key::Escape);
916 // Tab cycles the 3D sketch's working plane; outside that mode it
917 // stays egui's focus key.
918 let tab = sketching_3d && keys_free && i.consume_key(Modifiers::NONE, Key::Tab);
919 (redo, undo, esc, tab)
920 });
921 // Delete / Backspace: THE delete-selection command
922 // (`crate::delete_selection`), whatever the selection is — sketch,
923 // 3D sketch, eCAD, sheet object, PMI annotation, constraint, component
924 // or feature — before the sketch modes return below.
925 if keys_free {
926 self.delete_selection_key(ctx);
927 }
928 // The 3D sketch editor: the same per-session undo routing as the
929 // planar one; Esc drops the armed tool's pending clicks first and the
930 // tool itself second.
931 if sketching_3d {
932 if redo {
933 self.docs.engine_mut().sketch3d_redo();
934 }
935 if undo {
936 self.docs.engine_mut().sketch3d_undo();
937 }
938 if esc {
939 let engine = self.docs.engine_mut();
940 if engine.sketch3d_pending_len() > 0 {
941 engine.sketch3d_tool_cancel();
942 } else {
943 let _ = engine.sketch3d_set_tool(Some("select"));
944 }
945 }
946 if tab {
947 self.docs.engine_mut().sketch3d_cycle_work_plane();
948 }
949 return;
950 }
951 // While editing a sketch, Ctrl+Z / Ctrl+Shift+Z drive the PER-SESSION sketch
952 // history (S6a), not the model-level undo — this global router consumes the
953 // keys first (before the viewport), so it must intercept here. Esc drops the
954 // active draw/trim/pick tool back to Select/drag (clearing any in-progress
955 // placement): this is the ONLY reliable capture point, since `consume_key`
956 // above already swallowed the Escape before the viewport can see it.
957 if self.docs.engine().sketch_mode() {
958 if redo {
959 self.docs.engine_mut().sketch_redo();
960 }
961 if undo {
962 self.docs.engine_mut().sketch_undo();
963 }
964 if esc {
965 self.docs.engine_mut().sketch_set_tool(Some("select"));
966 }
967 return;
968 }
969 if redo {
970 self.docs.engine_mut().redo();
971 }
972 if undo {
973 self.docs.engine_mut().undo();
974 }
975 if esc {
976 // An open pick-list popup owns the first Escape: close it WITHOUT
977 // clearing the selection (a popup-built multi-selection must survive
978 // dismissing the list); the next Escape clears as before.
979 if self.viewport.close_candidate_popup() {
980 return;
981 }
982 // An open Replace component chooser closes on Escape (its own
983 // keys never see it: this handler takes Escape first). A repair
984 // pick in its result window is cancelled the same way.
985 if self.replace_dialog.escape() {
986 return;
987 }
988 // A REFERENCE PICK owns the next one — a 3D pick or anchors on a
989 // drawing sheet alike — and Escape has to CANCEL it
990 // rather than merely clear the selection. Beginning a pick ROLLS THE
991 // MODEL BACK to the step before the edited feature so the picker sees
992 // the geometry that feature is about to consume; Finish and Cancel
993 // both restore that roll through `end_ref_select`. Escape used to do
994 // neither: it cleared the selection, left the picker open and left the
995 // history PARKED before the feature, so the feature stopped running
996 // and the viewport quietly showed the model without it. Measured on
997 // the retired `rotate-face.json`, which read the seed volume back at its
998 // closed-form step with the feature never re-run.
999 if self.docs.engine().ref_select_active() {
1000 self.docs.engine_mut().cancel_ref_select();
1001 return;
1002 }
1003 // A family-row preview owns the next one: Escape leaves the
1004 // preview (the family's own values again) and keeps the selection.
1005 if self.family_table.escape_preview(self.docs.engine_mut()) {
1006 return;
1007 }
1008 // The global router owns Escape before the viewport runs its keys.
1009 if let Some(target) = ecad_target {
1010 self.docs.active_mut().ecad.selection_key(target, false);
1011 return;
1012 }
1013 self.docs.engine_mut().clear_selection();
1014 }
1015 }
1016
1017 /// A FORM FIELD's reference pick, settled at the end of the frame (after
1018 /// the dock has drawn every pane, the viewport's click included):
1019 ///
1020 /// * a SINGLE-valued field finishes on its first pick — there is nothing
1021 /// left to wait for, and the feature's result appears at once;
1022 /// * a form that asked for the pick to end (`ref_select_request_finish`:
1023 /// an edit elsewhere on a feature's form) gets it now, after the frame's
1024 /// viewport click has landed in the pick;
1025 /// * a pick NO form claimed this frame (`ref_select_claim`) is finished:
1026 /// its pane was tabbed away, closed, or its subject is gone, and a pick
1027 /// with no field on screen has nothing to end it.
1028 ///
1029 /// Card-based picks are not this method's: their card is always on screen.
1030 fn settle_form_pick(&mut self) {
1031 let engine = self.docs.engine_mut();
1032 let Some(field) = engine.ref_select_field() else {
1033 return;
1034 };
1035 if !engine.ref_select_in_form() {
1036 return;
1037 }
1038 let claimed = engine.ref_select_take_claim();
1039 let single_done = !field.multiple && field.picks > 0;
1040 if single_done || engine.ref_select_finish_requested() || !claimed {
1041 engine.finish_ref_select();
1042 }
1043 }
1044
1045 /// DELETE (or Backspace) runs THE delete-selection command
1046 /// ([`crate::delete_selection`]) on whatever is selected: the same call as
1047 /// that object's row ✕ / menu Delete, so the key and the menu do the same
1048 /// thing (one undo step, no extra confirmation). The key is consumed only
1049 /// when there IS something to delete, and left to the family-table grid
1050 /// when it owns the keyboard. Never a SHEET, PMI VIEW or study: each takes
1051 /// everything placed on it with it and stays behind its menu's Delete.
1052 /// Called after the text-edit / modal / popup guards, so a Backspace typed
1053 /// into a field never gets here.
1054 fn delete_selection_key(&mut self, ctx: &egui::Context) {
1055 use egui::{Key, Modifiers};
1056 if self.family_table.owns_delete_key(ctx) {
1057 return;
1058 }
1059 let Some(target) = crate::delete_selection::target(&self.docs) else {
1060 return;
1061 };
1062 let pressed = ctx.input_mut(|i| {
1063 i.consume_key(Modifiers::NONE, Key::Delete) || i.consume_key(Modifiers::NONE, Key::Backspace)
1064 });
1065 if !pressed {
1066 return;
1067 }
1068 if let Err(error) = crate::delete_selection::apply(&mut self.docs, &target) {
1069 self.docs.engine_mut().push_notice(format!("Delete: {error}"));
1070 }
1071 }
1072
1073 /// Open the component source, offering to recover a missing file from the
1074 /// assembly's embedded part definition.
1075 /// Open the Replace component chooser on `component_id` (the component
1076 /// menus' Replace…).
1077 pub(crate) fn open_replace(&mut self, component_id: &str) {
1078 if let Err(error) = crate::panels::replace_component::finish_work_part_for_replace(&mut self.docs) {
1079 self.docs.engine_mut().push_notice(format!("Replace: {error}"));
1080 return;
1081 }
1082 let document = self.docs.active().name().map(str::to_string);
1083 self.replace_dialog.open(self.docs.engine(), self.model_store.as_ref(), component_id, document.as_deref());
1084 }
1085
1086 /// Open the Replace summary alone, for mates an earlier replace holds.
1087 pub(crate) fn review_replace(&mut self) {
1088 self.replace_dialog.review();
1089 }
1090
1091 /// A component menu's document-level flow (`component_actions`): every
1092 /// menu — the context bar, the viewport's right-click, the BOM row — hands
1093 /// its request here, so each flow has one implementation.
1094 fn run_component_request(&mut self, request: ComponentActionRequest, compact: bool) {
1095 match request {
1096 ComponentActionRequest::SavePartAs { component_id } => self.edit_part(&component_id),
1097 ComponentActionRequest::Replace { component_id } => self.open_replace(&component_id),
1098 ComponentActionRequest::WorkPart { component_path, in_place } => {
1099 let mode = if in_place {
1100 crate::document::work_part::WorkPartMode::InPlace
1101 } else {
1102 crate::document::work_part::WorkPartMode::NewTab
1103 };
1104 if let Err(error) = self.docs.begin_work_part_as(&component_path, mode) {
1105 self.docs.engine_mut().push_notice(format!("Work part: {error}"));
1106 }
1107 }
1108 ComponentActionRequest::Info { targets } => {
1109 self.info_windows.open_for(&targets, self.viewport.last_rect());
1110 }
1111 ComponentActionRequest::EditFeature { feature_id } => {
1112 self.history.focus_feature(feature_id);
1113 if compact {
1114 self.dock.show_pane(PaneKind::History);
1115 }
1116 }
1117 }
1118 }
1119
1120 fn edit_part(&mut self, component_id: &str) {
1121 self.file.edit_component_part(
1122 &mut self.docs,
1123 self.model_store.as_ref(),
1124 component_id,
1125 );
1126 }
1127
1128 /// Draw an isolated preview while the destination document remains untouched.
1129 /// Hand the working indicator this frame's work, most important first:
1130 /// the active document's runner queues, a boot load, the STEP parts
1131 /// library's downloads, then every background document's queues.
1132 fn collect_busy(&mut self, ctx: &egui::Context) {
1133 use crate::panels::busy::{engine_activities, Activity};
1134 let active = self.docs.active_index();
1135 let mut activities = engine_activities(self.docs.engine(), self.docs.active_id(), None);
1136 if self.pending_boot_load.is_some() {
1137 activities.push(Activity::new("boot", "boot", "Loading document"));
1138 }
1139 activities.extend(self.step_parts.busy_activities());
1140 activities.extend(self.file.busy_activities());
1141 // A write-behind store (the browser's IndexedDB) still settling saves.
1142 let saving = self.model_store.pending_writes();
1143 if saving > 0 {
1144 let label = match saving {
1145 1 => "Saving to browser storage".to_string(),
1146 n => format!("Saving to browser storage ({n} writes)"),
1147 };
1148 activities.push(Activity::new("storeWrite", "storeWrite", label));
1149 }
1150 for (index, doc) in self.docs.iter().enumerate() {
1151 if index != active {
1152 activities.extend(engine_activities(&doc.engine, doc.id(), Some(&doc.title())));
1153 }
1154 }
1155 self.busy.update(activities, ctx.input(|i| i.time));
1156 self.busy.request_repaint(ctx);
1157 }
1158
1159 fn show_stl_preview(&mut self, ui: &mut egui::Ui) -> bool {
1160 use crate::panels::stl_import::PreviewAction;
1161 let Some(preview) = self.stl_import.as_mut() else {
1162 return false;
1163 };
1164 let action = if preview.destination != self.docs.active_id() {
1165 PreviewAction::Cancel
1166 } else {
1167 preview.show(ui, &mut self.viewport)
1168 };
1169 if crate::automation::registry::enabled() {
1170 let _publish_span = crate::perf::span(crate::perf::Phase::Publish);
1171 crate::automation::registry::publish("__brepImportPreview", "STL/OBJ import preview state (tolerances, counts, accept readiness); null when no preview is open", &preview.state_json());
1172 crate::automation::registry::publish("__brepImportRegions", "interactive mesh import: phase, region list (proposed kind, status, residual, refits), selected region and its form; null when no preview is open", &preview.regions_json());
1173 crate::automation::registry::publish("__brepImportPreviewHit", "import preview dialog widget rects", &preview.hits_json());
1174 crate::automation::registry::publish("__brepCamera", "camera state: kind, eye, target, up, near/far, projection block, worldPerPixel", &preview.engine.camera_state_json());
1175 crate::automation::registry::publish("__brepPpp", "pixels per point of the surface", &format!("{}", ui.ctx().pixels_per_point()));
1176 crate::automation::registry::publish("__brepHistory", "history listing {step, features:[{index,type,id}]}", &self.docs.engine().history_listing_json());
1177 crate::automation::registry::publish("__brepDocuments", "open document tabs {active, tabs:[{title,name,dirty}]}", &document_tabs::state_json(&self.docs));
1178 }
1179 let close = match action {
1180 PreviewAction::Accept => {
1181 match preview.accept_into(self.docs.active_id(), self.docs.engine_mut()) {
1182 Ok(()) => true,
1183 Err(error) => {
1184 self.docs.engine_mut().push_notice(error);
1185 false
1186 }
1187 }
1188 }
1189 PreviewAction::Cancel => true,
1190 PreviewAction::None => false,
1191 };
1192 if close {
1193 self.stl_import = None;
1194 self.viewport.forget_document();
1195 ui.ctx().request_repaint();
1196 }
1197 true
1198 }
1199
1200 /// Phase 3 of the automation frame (§4.4): read-only commands answer from
1201 /// THIS frame's registry and layout. A method rather than a block at the
1202 /// end of `ui` because the import preview returns from that function early
1203 /// and still owes the frame its reads.
1204 #[cfg(feature = "automation")]
1205 fn drain_reads(&mut self, ctx: &egui::Context) {
1206 let _t = crate::perf::trace("drain reads + publish_view");
1207 let queue = self.automation.clone();
1208 let frame = ctx.cumulative_frame_nr();
1209 queue.drain_app(
1210 crate::automation::command::Phase::Read,
1211 &mut crate::automation::command::Ctx { app: self, egui: ctx },
1212 frame,
1213 );
1214 // The frame drawn now shows this document: a capture landing next
1215 // frame is of it.
1216 let view = self.docs.view();
1217 queue.publish_view(view.handle(), view.committed_revision());
1218 // This pass's layout is the current one for a layout read that comes
1219 // before anything changes it (`automation::queue::Need::Layout`).
1220 queue.note_pass();
1221 }
1222
1223 /// Every notice raised since the last gather — the engine's, storage
1224 /// failures found after a write returned, refused edits — mirrored to the
1225 /// automation queue's `notices` drain. Called by the frame (which then
1226 /// shows them as toasts) and by the frame-free service step, so a hidden
1227 /// window still reports what the user would have seen.
1228 fn gather_notices(&mut self) -> Vec<(brep_render::engine_state::NoticeSeverity, String)> {
1229 use brep_render::engine_state::NoticeSeverity;
1230 let mut raised = self.docs.engine_mut().take_graded_notices();
1231 // Same lane for STORAGE failures the store could only discover after its
1232 // synchronous `write` returned `Ok` (the browser backend writes behind an
1233 // in-memory mirror). A save that did not persist must never be silent.
1234 let errors = self.model_store.take_persistence_errors().into_iter().chain(self.autosave.take_errors());
1235 let failures: Vec<String> = errors.filter_map(|text| crate::panels::plm_host::plain_write_failure(&text)).collect();
1236 if let Some(last) = failures.last() {
1237 // The status line said "saved …" when the write was issued.
1238 self.file.status = last.clone();
1239 }
1240 if failures.iter().any(|text| text.contains("the PLM server is not reachable")) {
1241 self.plm.note_unreachable();
1242 }
1243 raised.extend(failures.into_iter().map(|text| (NoticeSeverity::Error, text)));
1244 // ...and the tab whose Save that was is unsaved again: it was marked
1245 // clean when the write was issued, and a clean tab closes without a
1246 // question.
1247 let failed = self.model_store.take_failed_writes();
1248 for name in &failed {
1249 self.docs.mark_write_failed(self.model_store.as_ref(), name);
1250 }
1251 // A part an open assembly holds a copy of (saved with it): the copy
1252 // keeps the change, marked, so the next Save writes it again.
1253 for name in &failed {
1254 self.docs.mark_failed_copies(self.model_store.as_ref(), name);
1255 }
1256 // An edit a read-only document refused (a PLM revision not checked out,
1257 // or released): its history kept the saved bytes, and this says why.
1258 for doc in self.docs.iter_mut() {
1259 if let Some(text) = doc.take_refused() {
1260 raised.push((NoticeSeverity::Warning, text));
1261 }
1262 }
1263 // The automation channel's `notices` drain: what the user would have SEEN.
1264 // Without this the drain has no producers at all and every script's
1265 // `{"notices": []}` asserts nothing.
1266 #[cfg(feature = "automation")]
1267 for (_, text) in &raised {
1268 self.automation.push_notice(
1269 crate::automation::command::NoticeKind::Toast,
1270 text.clone(),
1271 );
1272 }
1273 raised
1274 }
1275
1276 /// Application-command dispatch without a frame (the desktop loop's
1277 /// service step; see `automation::queue`): the PLM/store tasks that
1278 /// answered, the queue's frame-free head, the background runs it started,
1279 /// and the notices they raised. Draws nothing. Returns whether work it
1280 /// must keep servicing is still in flight.
1281 #[cfg(feature = "automation")]
1282 pub fn service_automation(&mut self, ctx: &egui::Context) -> bool {
1283 #[cfg(not(target_arch = "wasm32"))]
1284 crate::plm::native::run_pending();
1285 let queue = self.automation.clone();
1286 let polled = queue.drain_frameless(&mut crate::automation::command::Ctx { app: self, egui: ctx });
1287 let running = self.docs.pump_all();
1288 let raised = self.gather_notices();
1289 if polled || running || !raised.is_empty() {
1290 // Work in flight or landing moves what a pass would show.
1291 queue.mark_layout_dirty();
1292 }
1293 if !raised.is_empty() {
1294 let now = ctx.input(|i| i.time);
1295 self.toasts.extend(raised, now);
1296 }
1297 // A window that IS drawn shows the effect on its next frame.
1298 ctx.request_repaint();
1299 polled || running || queue.has_frameless_work()
1300 }
1301
1302 /// Reset everything the shared panels and the viewport hold ABOUT ONE
1303 /// DOCUMENT, run at the top of the first frame that sees a different active
1304 /// document.
1305 ///
1306 /// Panel state is deliberately NOT per-document (one History panel, one
1307 /// Scene tree, …): a second copy per tab would double every panel's state
1308 /// for a benefit — remembering which feature form was open in a background
1309 /// tab — nobody asked for. The price is that the transient state has to be
1310 /// dropped on a switch, because every bit of it (expansion sets, hit maps,
1311 /// an open feature form, a pinned Info window's object name) refers to the
1312 /// document that just went away.
1313 fn reset_document_scoped_state(&mut self) {
1314 self.history = HistoryPanel::new();
1315 self.scene = ScenePanel::new();
1316 self.bom = BomPanel::new();
1317 self.assembly_constraints = AssemblyConstraintsPanel::new();
1318 self.wire_harness = WireHarnessPanel::new();
1319 self.pmi = crate::panels::pmi::PmiPanel::new();
1320 self.cam = crate::panels::cam::CamPanel::new();
1321 self.sheets = crate::panels::sheets::SheetsPanel::new();
1322 self.expressions = ExpressionsPanel::new();
1323 self.qualify = crate::panels::qualify::QualifyPanel::new();
1324 self.family_table = crate::panels::family_table_editor::FamilyTableEditor::new();
1325 // A family-row preview left on in a document the user comes back to
1326 // would have no pane state to show or end it: switching ends it.
1327 self.docs.engine_mut().set_expression_preview(None);
1328 // Pinned to object NAMES of the old document ("Box" exists in most of
1329 // them), so these would silently retarget rather than go blank.
1330 self.info_windows = InfoWindows::new();
1331 self.interference = crate::panels::interference::InterferenceWindow::new();
1332 self.auto_constraints = crate::panels::auto_constraints::AutoConstraintsWindow::new();
1333 // The outdated-parts cache keys on `(applied_generation, save_generation)`,
1334 // and two documents' generations are unrelated — a switch can land on the
1335 // same key with an entirely different parts library.
1336 self.update_components.invalidate();
1337 self.viewport.forget_document();
1338 }
1339
1340 /// Publish every plain-state blob ([`state_blobs::STATE_BLOBS`]) from its
1341 /// producer. The frame calls this; `state_get` asks
1342 /// [`state_blob_json`](Self::state_blob_json) itself, so a read of one of
1343 /// these never waits for a frame.
1344 ///
1345 /// [`state_blobs::STATE_BLOBS`]: crate::automation::state_blobs::STATE_BLOBS
1346 fn publish_state_blobs(&mut self, ctx: &egui::Context) {
1347 for (name, doc) in crate::automation::state_blobs::STATE_BLOBS {
1348 if let Some(json) = self.state_blob_json(name, ctx) {
1349 crate::automation::registry::publish(name, doc, &json);
1350 }
1351 }
1352 }
1353
1354 /// One plain-state blob by name, built from the app's data now. `None`
1355 /// for a name that is not one of [`STATE_BLOBS`] (a layout blob, which
1356 /// only a drawn pass publishes).
1357 ///
1358 /// [`STATE_BLOBS`]: crate::automation::state_blobs::STATE_BLOBS
1359 pub fn state_blob_json(&mut self, name: &str, ctx: &egui::Context) -> Option<String> {
1360 if name == "__brepSelectionInspection" {
1361 let document = self.docs.active_id();
1362 return Some(self.selection.inspection_json(self.docs.engine_mut(), document));
1363 }
1364 let engine = self.docs.engine();
1365 Some(match name {
1366 // The import preview draws its own engine while it is open.
1367 "__brepCamera" => match &self.stl_import {
1368 Some(preview) => preview.engine.camera_state_json(),
1369 None => engine.camera_state_json(),
1370 },
1371 "__brepImportPreview" => self.stl_import.as_ref().map_or_else(|| "null".to_string(), |p| p.state_json()),
1372 "__brepImportRegions" => self.stl_import.as_ref().map_or_else(|| "null".to_string(), |p| p.regions_json()),
1373 "__brepPpp" => format!("{}", ctx.pixels_per_point()),
1374 "__brepSettings" => engine.settings_json(),
1375 "__brepSolidColors" => engine.solid_color_overrides_json(),
1376 "__brepHistory" => engine.history_listing_json(),
1377 "__brepGizmo" => engine.gizmo_state_json(),
1378 "__brepFile" => self.file.file_state_json(&self.docs, self.model_store.as_ref()),
1379 "__brepModel" => self.model_signature_json(),
1380 "__brepReport" => engine.history_report_json(),
1381 // The in-flight run: whether one is pending, the feature the runner
1382 // says it is executing, and the feature a cancelled run was stuck on.
1383 "__brepRun" => serde_json::json!({
1384 "pending": engine.run_pending(),
1385 "progress": engine.run_progress().map(|p| serde_json::json!({
1386 "generation": p.generation,
1387 "index": p.index,
1388 "total": p.total,
1389 "featureId": p.feature_id,
1390 "featureType": p.feature_type,
1391 })),
1392 "cancelled": engine.cancelled_run(),
1393 })
1394 .to_string(),
1395 "__brepBusy" => self.busy.state_json(),
1396 "__brepExpr" => serde_json::json!({
1397 "expressions": engine.expressions_json(),
1398 "variables": serde_json::from_str::<serde_json::Value>(&engine.expression_variables_json())
1399 .unwrap_or(serde_json::Value::Null),
1400 "configurator": serde_json::from_str::<serde_json::Value>(&engine.configurator_json())
1401 .unwrap_or(serde_json::Value::Null),
1402 })
1403 .to_string(),
1404 "__brepPlmDoc" => self.plm.state_json(&self.docs),
1405 // The queued toast texts — the only trace of a refusal the app shows
1406 // as a transient card (e.g. a constraint the strip could not add).
1407 "__brepNotices" => self.toasts.texts_json(),
1408 "__brepToasts" => self.toasts.state_json(),
1409 "__brepBug" => self.bug_report.state_json(),
1410 "__brepDiagnostics" => self.diagnostics.json().to_string(),
1411 // Where the last ~120 frames' milliseconds went. `__brepDiagnostics`
1412 // says WHICH renderer is drawing; this says what it costs, in the
1413 // same split the Info window's Performance rows show.
1414 "__brepPerf" => crate::perf::json(),
1415 "__brepWireHarness" => engine.wire_harness_state_json(),
1416 "__brepCam" => {
1417 self.cam.refresh_geometry(self.docs.engine());
1418 crate::panels::cam::cam_state_json(self.docs.engine(), &self.cam)
1419 }
1420 "__brepInstructions" => self.instructions.state_json(),
1421 "__brepInstructionsPlayer" => self.instructions_player.state_json(engine),
1422 "__brepSimulation" => crate::panels::simulation::state_json(engine, &self.simulation),
1423 "__brepCamSim" => self.cam.sim.state_json().to_string(),
1424 "__brepPorts" => engine.ports_state_json(),
1425 "__brepQualify" => self.qualify.state_json(),
1426 "__brepFamily" => self.family_table.state_json(),
1427 "__brepPmi" => engine.pmi_state_json(),
1428 "__brepSheets" => self.docs.engine_mut().sheet_state_json(),
1429 // The workbench logical state (resolved current id + available
1430 // ids); the dropdown's rects ride in `__brepToolbar`.
1431 "__brepWorkbench" => crate::workbench::workbench_state_scoped(engine).to_string(),
1432 "__brepSelection" => engine.selection_json(),
1433 "__brepInfoWindows" => self.info_windows.published_json(self.docs.engine_mut()),
1434 "__brepInterference" => self.interference.state_json_in(engine),
1435 "__brepAutoConstraints" => self.auto_constraints.state_json(),
1436 "__brepStepParts" => self.step_parts.state_json(),
1437 "__brepSelectionFilter" => engine.selection_filter_json(),
1438 "__brepFilterButton" => self.selection.button_json(),
1439 "__brepContext" => self.context_bar.state_json(),
1440 "__brepPickBar" => self.pick_bar.state_json(),
1441 "__brepDocuments" => document_tabs::state_json(&self.docs),
1442 "__brepRecovery" => self.recovery.state_json(),
1443 "__brepClosing" => self.closing_json(),
1444 "__brepComponentMove" => engine.component_move_json(),
1445 "__brepSketch" => self.sketch.published_json(engine),
1446 "__brepSketch3d" => self.sketch3d.published_json(engine),
1447 "__brepWireframe" => format!("{}", engine.settings.wireframe),
1448 // The pick's `subject` and `path` name the FORM FIELD it runs in
1449 // (`<panel>/field:<path>#activate` is that field's button, Done
1450 // while the pick runs); `inForm` is false for the card-based
1451 // picks, whose controls are `modebar/refsel:*`.
1452 "__brepRefSelect" => {
1453 let field = engine.ref_select_field();
1454 serde_json::json!({
1455 "active": engine.ref_select_active(),
1456 "prompt": engine.ref_select_prompt(),
1457 "names": engine.ref_select_names(),
1458 "subject": field.as_ref().map(|f| f.subject.clone()),
1459 "path": field.as_ref().map(|f| f.path.join(".")),
1460 "multiple": field.as_ref().map(|f| f.multiple),
1461 "picks": field.as_ref().map(|f| f.picks),
1462 "inForm": engine.ref_select_in_form(),
1463 "ghostsLit": engine.ref_select_ghosts_lit(),
1464 })
1465 .to_string()
1466 }
1467 "__brepStep" => format!("{}", engine.history_rollback()),
1468 "__brepParams" => self.params_blob().to_string(),
1469 _ => return None,
1470 })
1471 }
1472
1473 /// A signature of the CURRENT rendered model (rolled-to step) — solid count,
1474 /// per-solid triangle count + bbox, and total triangles. Published to JS so
1475 /// the headed verifier can prove each roll / edit produced different geometry
1476 /// (names alone don't: a SUBTRACT reuses the target's name).
1477 #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
1478 pub(crate) fn model_signature_json(&self) -> String {
1479 let solids: Vec<serde_json::Value> = self
1480 .docs
1481 .engine()
1482 .scene
1483 .solids()
1484 .iter()
1485 .map(|s| {
1486 serde_json::json!({
1487 "name": s.name,
1488 "tris": s.mesh.indices.len() / 3,
1489 "min": s.bbox.min,
1490 "max": s.bbox.max,
1491 })
1492 })
1493 .collect();
1494 let total_tris: usize = self
1495 .docs
1496 .engine()
1497 .scene
1498 .solids()
1499 .iter()
1500 .map(|s| s.mesh.indices.len() / 3)
1501 .sum();
1502 serde_json::json!({
1503 "step": self.docs.engine().history_rollback(),
1504 "solidCount": solids.len(),
1505 "totalTris": total_tris,
1506 "solids": solids,
1507 })
1508 .to_string()
1509 }
1510
1511 /// Open or close the floating Settings window — the toolbar gear's flag,
1512 /// reachable from the automation layer (`settings_window`).
1513 pub fn set_settings_window_open(&mut self, open: bool) {
1514 self.settings.open = open;
1515 }
1516
1517 /// Open or close the floating Part Properties window — the toolbar tag
1518 /// button's flag, reachable from the automation layer
1519 /// (`part_properties_window`).
1520 pub fn set_part_properties_window_open(&mut self, open: bool) {
1521 self.part_properties.open = open;
1522 }
1523
1524 /// Open or close the floating Info window — the toolbar info button's flag,
1525 /// reachable from the automation layer (`info_window`).
1526 pub fn set_info_window_open(&mut self, open: bool) {
1527 self.info.open = open;
1528 }
1529
1530 /// What this session is running on. The app's ONE record of it: the Info
1531 /// window draws it, a problem report carries it, the `diagnostics` command
1532 /// returns it and the MCP banner names its adapter — all from here.
1533 /// Where the JavaScript editor's Run sends a program (a host's own
1534 /// script runner; the desktop app installs its server's on its own).
1535 pub fn set_script_host(&mut self, host: Box<dyn crate::javascript::ScriptHost>) {
1536 self.javascript.host = Some(host);
1537 }
1538
1539 pub fn diagnostics(&self) -> &crate::diagnostics::Diagnostics {
1540 &self.diagnostics
1541 }
1542
1543 /// Begin the in-app problem report: the same call the Submit Bug button
1544 /// makes, and for the same reason it makes it THIS frame — `request`
1545 /// captures the current frame before its own dialog exists.
1546 pub fn begin_bug_report(&mut self, ctx: &egui::Context) {
1547 self.bug_report.request(ctx, self.docs.engine(), &self.diagnostics);
1548 }
1549
1550 /// Activate an available declarative panel using its stable package ID.
1551 pub(crate) fn show_plugin_panel(&mut self, id: &str) -> Result<(), String> {
1552 self.dock.show_plugin_panel(self.docs.engine(), id)
1553 }
1554
1555 /// Bring a built-in dock pane to the front (`show_pane`).
1556 pub fn show_pane(&mut self, kind: PaneKind) {
1557 self.dock.show_pane(kind);
1558 }
1559
1560 /// Shared document activation / unsaved-close handling for both presentations.
1561 fn apply_document_actions(&mut self, activate: Option<usize>, close: Option<usize>) {
1562 if (activate.is_some() || close.is_some()) && self.docs.engine().ref_select_in_form() {
1563 self.docs.engine_mut().finish_ref_select();
1564 }
1565 if let Some(index) = activate { self.docs.activate(index); }
1566 if let Some(index) = close { self.file.request_close(&mut self.docs, index); }
1567 }
1568
1569 /// The parts-library staleness check and its refresh — the Constraints
1570 /// header's "Update components (N)" button, reachable as the
1571 /// `component_update` command. Returns `(outdated, missing, refreshed)`;
1572 /// `run` is skipped when nothing is outdated.
1573 pub fn update_components(&mut self, run: bool) -> Result<(usize, Vec<String>, usize), String> {
1574 let store = self.model_store.as_ref();
1575 let synced = self.docs.synced_signatures();
1576 self.update_components.ensure_current(self.docs.engine_mut(), store, self.file.save_generation(), &synced);
1577 let outdated = self.update_components.outdated_count();
1578 let missing = self.update_components.missing().to_vec();
1579 let refreshed = if run { self.update_components.run(self.docs.engine_mut(), store)? } else { 0 };
1580 Ok((outdated, missing, refreshed))
1581 }
1582
1583 /// Frame what the central tile is actually DRAWING: the OPEN SHEET's paper
1584 /// when a sheet is open, the 3D scene otherwise.
1585 ///
1586 /// This is where the fit branch lives, and it is here rather than in the
1587 /// toolbar because the two halves sit in different places — the 3D fit is an
1588 /// engine camera op (`EngineState::zoom_to_fit`) while the sheet's pan/zoom
1589 /// is viewport-transient state, refitted by clearing the marker the sheet
1590 /// paint compares against. One method, so the toolbar's Zoom-to-fit button
1591 /// and the `zoom_to_fit` command can never mean different things — and so
1592 /// the paper needs no Fit button of its own.
1593 ///
1594 /// The toolbar draws BEFORE the dock in `ui`, so a fit requested from the
1595 /// button lands on this very frame.
1596 pub fn zoom_to_fit(&mut self) {
1597 if self.docs.engine().sheet_open().is_some() {
1598 self.viewport.request_sheet_fit();
1599 } else {
1600 self.docs.engine_mut().zoom_to_fit();
1601 }
1602 }
1603
1604 /// Run what a WORKBENCH TOOLBAR button does, by its `WorkbenchButton::id`.
1605 ///
1606 /// Split out of `ui` so a toolbar click and the `workbench_button` command
1607 /// run the SAME arms: the workbench registry declares a button, this
1608 /// dispatches it, and the automation surface owns no second copy of the
1609 /// list. Returns whether the id was known.
1610 pub fn dispatch_workbench_button(&mut self, id: &str) -> bool {
1611 // The eCAD workbenches' buttons (Diagram, PCB, Symbol, Pads) are
1612 // eCAD's own actions: run on the active document's editors with
1613 // eCAD's `run_action`, so a press does exactly what eCAD's toolbar
1614 // button does. `None` is any other id, which falls through to the
1615 // arms below.
1616 if crate::workbench::ecad::dispatch(&mut self.docs.active_mut().ecad, id).is_some() {
1617 return true;
1618 }
1619 // The SHEET's constructions are the Drawing workbench's two tables plus
1620 // the section and the detail, and each press is the PMI annotation
1621 // buttons' workflow: the object is created on the open sheet with
1622 // nothing picked yet, and its dialog opens (through the dialog door,
1623 // which surfaces the Sheets pane) — where its reference rows are picked
1624 // on the paper with the reference picker.
1625 if let Some((kind, alignment)) = crate::workbench::drawing::dim_tool(id) {
1626 let engine = self.docs.engine_mut();
1627 if let Err(error) = engine.sheet_add_dimension(None, kind, Some(alignment), Vec::new()) {
1628 engine.push_notice(format!("Sheet dimension: {error}"));
1629 }
1630 return true;
1631 }
1632 if let Some(axis) = crate::workbench::drawing::ord_tool(id) {
1633 let engine = self.docs.engine_mut();
1634 if let Err(error) = engine.sheet_add_ordinate(None, axis, None, Vec::new()) {
1635 engine.push_notice(format!("Ordinate set: {error}"));
1636 }
1637 return true;
1638 }
1639 if id == crate::workbench::drawing::BOM_BUTTON_ID {
1640 let engine = self.docs.engine_mut();
1641 if let Err(error) = engine.sheet_insert_bom() { engine.push_notice(format!("BOM table: {error}")); }
1642 return true;
1643 }
1644 if id == crate::workbench::drawing::SECTION_BUTTON_ID {
1645 let engine = self.docs.engine_mut();
1646 if let Err(error) = engine.sheet_new_section(None) {
1647 engine.push_notice(format!("Section view: {error}"));
1648 }
1649 return true;
1650 }
1651 if id == crate::workbench::drawing::DETAIL_BUTTON_ID {
1652 let engine = self.docs.engine_mut();
1653 if let Err(error) = engine.sheet_new_detail(None) {
1654 engine.push_notice(format!("Detail view: {error}"));
1655 }
1656 return true;
1657 }
1658 // The SKETCH mode's draw tools are one table too, and they are SHARED —
1659 // every workbench's row carries them while a sketch is being edited, so
1660 // this arm answers for all of them whatever workbench is active.
1661 // Pressing the LIT tool puts it down (back to Select), matching the
1662 // sheet constructions above; pressing the lit Select is already Select.
1663 if let Some(tool) = crate::workbench::sketch::draw_tool(id) {
1664 let engine = self.docs.engine_mut();
1665 let armed = engine.sketch_active_tool().unwrap_or("select") == tool;
1666 engine.sketch_set_tool(Some(if armed { "select" } else { tool }));
1667 return true;
1668 }
1669 // The 3D sketch's tools and working-plane radio, shared the same way.
1670 if let Some(tool) = crate::workbench::sketch3d::draw_tool(id) {
1671 let engine = self.docs.engine_mut();
1672 let armed = engine.sketch3d_active_tool().unwrap_or("select") == tool;
1673 let _ = engine.sketch3d_set_tool(Some(if armed { "select" } else { tool }));
1674 return true;
1675 }
1676 if let Some(plane) = crate::workbench::sketch3d::work_plane(id) {
1677 let _ = self.docs.engine_mut().sketch3d_set_work_plane(plane);
1678 return true;
1679 }
1680 match id {
1681 // The sketch strip's one-shot action, now the row's: infer the
1682 // constraints the rough-in geometry already implies.
1683 crate::workbench::sketch::AUTOCONSTRAIN_BUTTON_ID => {
1684 self.docs.engine_mut().sketch_auto_constrain();
1685 }
1686 // Sheet Metal's flat pattern: open the export modal in its DXF /
1687 // SVG mode; the engine reports "no sheet-metal body in the part"
1688 // as a toast on export.
1689 "sheetmetal.flat_pattern" => {
1690 self.file.dispatch(FileAction::ExportFlatPattern, &mut self.docs, self.model_store.as_ref());
1691 }
1692 // Assembly's Add Component: open the insert-component modal (the
1693 // same flow as the ACOMP palette pick). ONE arm for both rows that
1694 // carry it — PCB BORROWS this very button (`workbench::BORROWED`)
1695 // rather than declaring a second id for the same action.
1696 crate::workbench::assembly::ADD_COMPONENT_BUTTON_ID => {
1697 self.file.dispatch(FileAction::InsertComponent, &mut self.docs, self.model_store.as_ref());
1698 }
1699 // Assembly's interference check: run the engine's pairwise
1700 // intersect sweep NOW and open the results window.
1701 "assembly.interference" => {
1702 self.interference.open_and_run(self.docs.engine_mut());
1703 }
1704 // Assembly's Auto Constraints: open the inference window and scan
1705 // the current placement NOW, so it opens showing real counts.
1706 "assembly.auto_constrain" => {
1707 self.auto_constraints.open_and_scan(self.docs.engine_mut());
1708 }
1709 // Assembly's step.parts library: open the online-library browser
1710 // (search → thumbnails → import a STEP part → add as an ACOMP).
1711 "assembly.step_parts_library" => {
1712 self.step_parts.open();
1713 }
1714 // Wire harness's Declare connection point: the part's FIRST port
1715 // group, with one point at the origin. It exists because the
1716 // Qualify pane is on screen only while the part declares some — so
1717 // without it a 3D-only part could never get its first one from the
1718 // UI at all. The pane is surfaced by the dock's own ports door on
1719 // the next frame, once the visibility pass has let it back in.
1720 crate::workbench::wire_harness::DECLARE_POINT_BUTTON_ID => {
1721 let engine = self.docs.engine_mut();
1722 engine.history.set_ports_block(
1723 Some(serde_json::json!([{
1724 "name": crate::workbench::wire_harness::FIRST_GROUP,
1725 "purpose": crate::workbench::wire_harness::FIRST_PURPOSE,
1726 "points": [{
1727 "name": crate::workbench::wire_harness::FIRST_POINT,
1728 "transform": {
1729 "position": [0.0, 0.0, 0.0],
1730 "rotationEuler": [0.0, 0.0, 0.0],
1731 },
1732 }],
1733 }])),
1734 None,
1735 );
1736 }
1737 // CAM's four actions: each hands the CAM pane its request and
1738 // surfaces the pane, which performs it on the frame it draws (the
1739 // pane owns the selection the action reads — which setup an
1740 // operation goes into — so the pane performs it, not the shell).
1741 crate::workbench::cam::NEW_SETUP_BUTTON_ID => {
1742 self.cam.request(crate::panels::cam::CamRequest::NewSetup);
1743 self.show_pane(PaneKind::Cam);
1744 }
1745 crate::workbench::cam::NEW_TOOL_BUTTON_ID => {
1746 self.cam.request(crate::panels::cam::CamRequest::NewTool);
1747 self.show_pane(PaneKind::Cam);
1748 }
1749 crate::workbench::cam::NEW_OPERATION_BUTTON_ID => {
1750 self.cam.request(crate::panels::cam::CamRequest::NewOperation);
1751 self.show_pane(PaneKind::Cam);
1752 }
1753 crate::workbench::cam::GENERATE_BUTTON_ID => {
1754 self.cam.request(crate::panels::cam::CamRequest::Generate);
1755 self.show_pane(PaneKind::Cam);
1756 }
1757 // Instructions: New from assembly opens the instructions in a new
1758 // tab (the open assembly, saved, is the target); the wizard and a
1759 // new step go to the pane, which owns the selected step.
1760 crate::workbench::instructions::NEW_BUTTON_ID => {
1761 let (_, docs, store) = self.file_docs_store();
1762 match crate::instructions::new_instructions(docs, store, crate::instructions::Source::Active, true) {
1763 Ok(_) => self.show_pane(PaneKind::Instructions),
1764 Err(error) => self.docs.engine_mut().push_notice(format!("New instructions: {error}")),
1765 }
1766 }
1767 crate::workbench::instructions::WIZARD_BUTTON_ID => {
1768 self.instructions.request(crate::panels::instructions::InstructionsRequest::Wizard);
1769 self.show_pane(PaneKind::Instructions);
1770 }
1771 crate::workbench::instructions::NEW_STEP_BUTTON_ID => {
1772 self.instructions.request(crate::panels::instructions::InstructionsRequest::NewStep);
1773 self.show_pane(PaneKind::Instructions);
1774 }
1775 // Play starts at the first step, or plays the shown one again.
1776 crate::workbench::instructions::PLAY_BUTTON_ID => {
1777 let shown = self.docs.engine().instructions_shown_step().is_some();
1778 self.instructions_player.request(if shown { brep_render::engine_state::PlayTo::Replay } else { brep_render::engine_state::PlayTo::First });
1779 self.show_pane(PaneKind::InstructionsPlayer);
1780 }
1781 // Simulation: the pane performs them (it draws the timeline the
1782 // new study or motor lands on).
1783 crate::workbench::simulation::NEW_STUDY_BUTTON_ID => {
1784 self.simulation.request(crate::panels::simulation::SimulationRequest::NewStudy);
1785 self.show_pane(PaneKind::Simulation);
1786 }
1787 crate::workbench::simulation::ADD_MOTOR_BUTTON_ID => {
1788 self.simulation.request(crate::panels::simulation::SimulationRequest::AddMotor);
1789 self.show_pane(PaneKind::Simulation);
1790 }
1791 // PMI's Capture view: snapshot the camera + visibility into a new
1792 // active view and surface the PMI pane so its row is seen.
1793 crate::workbench::pmi::CAPTURE_BUTTON_ID => {
1794 self.docs.engine_mut().pmi_capture_view(None);
1795 self.dock.show_pane(PaneKind::Pmi);
1796 }
1797 // Drawing's Back to 3D: leave the open sheet. The paper's own
1798 // widgets go with it, and the sheet keeps its contents — the same
1799 // edit the Sheets pane's Close sheet makes.
1800 crate::workbench::drawing::SHEET_CLOSE_BUTTON_ID => {
1801 let _ = self.docs.engine_mut().sheet_set_open(None);
1802 self.viewport.forget_sheet();
1803 }
1804 // Drawing's Add sheet: a new sheet, opened on the paper, and the
1805 // Sheets pane brought forward so its row is seen.
1806 crate::workbench::drawing::ADD_SHEET_BUTTON_ID => {
1807 self.docs.engine_mut().sheet_add(None);
1808 self.dock.show_pane(PaneKind::Sheets);
1809 }
1810 // Drawing's Place view: the first saved PMI view on the open sheet;
1811 // the placement's form opens (the door surfaces the pane), and its
1812 // `view` field is where a different view is chosen.
1813 crate::workbench::drawing::PLACE_VIEW_BUTTON_ID => {
1814 let engine = self.docs.engine_mut();
1815 let placed = match engine.sheet_pmi_view_ids().first().cloned() {
1816 Some(view) => engine.sheet_place_view(None, &view, None, None).map(|_| ()),
1817 None => Err("capture a PMI view in the PMI workbench first".to_string()),
1818 };
1819 if let Err(error) = placed {
1820 engine.push_notice(format!("Place view: {error}"));
1821 }
1822 }
1823 _ => return false,
1824 }
1825 true
1826 }
1827
1828}
1829
1830impl eframe::App for BrepApp {
1831 /// The browser's automation pump reaches the app between frames through
1832 /// eframe's runner (`WebRunner::app_mut`, `web_pump`). A web-only method.
1833 #[cfg(target_arch = "wasm32")]
1834 fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
1835 Some(self)
1836 }
1837
1838 /// Phase 1 of the automation frame (§4.4): queued input commands become
1839 /// egui events; a screenshot that landed completes its reply. Called by
1840 /// every eframe runner before `ui`; the headless host calls it itself.
1841 #[cfg(feature = "automation")]
1842 fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
1843 let view = self.viewport.last_rect();
1844 // eframe runs a pass without `ui` when the window is not visible (a
1845 // hidden tab's timer frames, an occluded or minimised window): input
1846 // given to it reaches no widget. Automation input waits for a pass
1847 // that draws (the loop's or the page pump's own, `on_demand`, which
1848 // mark theirs visible), and `activate_widget` keeps the widgets of
1849 // the last pass that drew. egui hit-tests pointer input against the
1850 // PREVIOUS pass's widgets, so the pass right after one that did not
1851 // draw only lays out again, and input waits for the one after it.
1852 //
1853 // A hidden TAB with a WebMCP host attached draws every pass instead:
1854 // eframe runs its timer passes right after the page pump's (each
1855 // repaint request schedules one), and a pass that skips `ui` between
1856 // a press and its release makes egui forget the press. eframe reads
1857 // the root viewport's visibility after this hook, so marking it
1858 // visible here is what has it run `ui`.
1859 #[cfg(target_arch = "wasm32")]
1860 if crate::automation::registry::enabled() {
1861 let root = raw_input.viewports.entry(egui::ViewportId::ROOT).or_default();
1862 if root.occluded == Some(true) {
1863 root.occluded = Some(false);
1864 }
1865 }
1866 let draws = raw_input.viewports.get(&egui::ViewportId::ROOT).and_then(|v| v.visible()).unwrap_or(true);
1867 let drew = crate::automation::actions::note_pass(ctx, draws);
1868 if !draws || !drew {
1869 return;
1870 }
1871 self.automation.drain_input(raw_input, ctx.cumulative_frame_nr(), ctx.pixels_per_point(), view, ctx);
1872 }
1873
1874
1875 fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
1876 // Open this frame's timing window (banks the previous frame's phase
1877 // totals and its period) and bracket the whole body. See `perf`: on a
1878 // single-threaded shell a long frame IS a frozen UI, so what the frame
1879 // spends is the whole diagnosis.
1880 crate::perf::tick();
1881 let _ui_span = crate::perf::span(crate::perf::Phase::Ui);
1882 let _frame_trace = crate::perf::trace("frame");
1883
1884 // The native store and PLM queue (`plm::native`): every task whose I/O
1885 // answered since the last frame finishes here, on this thread, FIRST —
1886 // before any early return below (the mesh preview's replaces the whole
1887 // shell) can skip it. The browser drains its microtasks between events
1888 // the same way, whatever the page is showing.
1889 #[cfg(not(target_arch = "wasm32"))]
1890 crate::plm::native::run_pending();
1891 // A PLM save made mid-rebuild is pictured once its run lands.
1892 crate::plm::thumbnail::tick(|id| self.docs.iter().find(|d| d.id() == id).map(|d| &d.engine));
1893 // Its player data too (instructions), and a refused upload is said.
1894 crate::plm::player_data::tick(|id| self.docs.iter().find(|d| d.id() == id).map(|d| &d.engine));
1895 if let Some(notice) = crate::plm::player_data::take_notice() {
1896 self.docs.engine_mut().push_notice_as(brep_render::engine_state::NoticeSeverity::Warning, notice);
1897 }
1898 // The File menu's recent-file pictures that finished since last frame.
1899 crate::plm::thumbnail::persist_recent(self.model_store.as_ref());
1900
1901 // --- global keyboard shortcuts (undo/redo/clear-selection) ------------
1902 // Handled before any panel draws so a Ctrl+Z etc. this frame takes effect
1903 // this frame. `ctx` is a cheap Arc clone (avoids borrowing `ui` across the
1904 // `&mut self` call).
1905 let ctx = ui.ctx().clone();
1906
1907 self.plugins.finish_installations(&mut self.docs, self.model_store.as_ref());
1908 self.plugins.sync_documents(&mut self.docs);
1909 self.javascript.poll(&ctx, &mut self.docs, self.model_store.as_ref());
1910 self.plugins.poll(&ctx, self.docs.engine_mut(), self.model_store.as_ref());
1911
1912 // Phase 2 of the automation frame (§4.4): mutations run before any
1913 // panel draws, so this frame shows their effect.
1914 #[cfg(feature = "automation")]
1915 {
1916 let queue = self.automation.clone();
1917 let frame = ctx.cumulative_frame_nr();
1918 let _t = crate::perf::trace("drain mutate");
1919 queue.drain_app(
1920 crate::automation::command::Phase::Mutate,
1921 &mut crate::automation::command::Ctx { app: self, egui: &ctx },
1922 frame,
1923 );
1924 }
1925
1926 // A measured spin (`perf_spin`) advances one pointer step per frame, here
1927 // — after the mutation drain that may have armed it, so the spin starts
1928 // on the frame it was asked for.
1929 #[cfg(feature = "automation")]
1930 self.step_spin(&ctx);
1931
1932 // --- a different document is active than the panels were drawn for ----
1933 // Checked FIRST, before anything draws: the switch itself happened late
1934 // in some earlier frame (a tab click, a close, an Open), and every
1935 // shared panel is still holding the previous document's transient state.
1936 if self.active_document != self.docs.view_id() {
1937 if !self.javascript.running_in(self.active_document) {
1938 for doc in self.docs.iter_mut() { if doc.id() == self.active_document { doc.engine.cancel_plugin_action(); } }
1939 }
1940 // The Interference window is reset below, but its overlay lives in
1941 // the document being left: take it down there, or switching back
1942 // shows the volumes with no window to clear them.
1943 for doc in self.docs.iter_mut() {
1944 if doc.id() == self.active_document {
1945 doc.engine.clear_interference_overlay();
1946 }
1947 }
1948 self.plugins.close_action();
1949 self.active_document = self.docs.view_id();
1950 let same_tab = self.active_tab == self.docs.active_id();
1951 self.active_tab = self.docs.active_id();
1952 let bom = same_tab.then(|| std::mem::take(&mut self.bom));
1953 self.reset_document_scoped_state();
1954 if let Some(bom) = bom {
1955 self.bom = bom;
1956 }
1957 }
1958
1959 // --- the workbench decides whether placed parts show their ports -------
1960 // A workbench that shows the Wire Harness panel (Wire harness, All)
1961 // draws the ports components carry; the others — Modeling included,
1962 // though it offers the Port feature — keep the assembly clean. A no-op
1963 // when nothing changed.
1964 {
1965 // The document's name lives in the SHELL (the tab, the file), and a
1966 // drawing sheet's title block prints it. Told to the engine here,
1967 // every frame, because that is where the active tab is known; a
1968 // no-op when it has not changed. It is the DISPLAY name, the one the
1969 // tab shows: a stamp reading `bracket.nbrep` would be naming our
1970 // file format rather than the drawing.
1971 let name = self
1972 .docs
1973 .active()
1974 .name()
1975 .map(crate::store::model_display_name)
1976 .unwrap_or_default();
1977 let engine = self.docs.engine_mut();
1978 engine.set_document_name(&name);
1979 let show = crate::workbench::panel_visible(
1980 &engine.settings.workbench,
1981 crate::workbench::wire_harness::PANEL_ID,
1982 &crate::workbench::ButtonState::of(engine),
1983 );
1984 engine.set_component_ports_visible(show);
1985 // The PMI workbench IS the PMI editing mode: a workbench that shows
1986 // the PMI panel (PMI, All) enters it — the modeling camera /
1987 // visibility / wireframe are remembered — and one that hides it
1988 // leaves it, deactivating the view and restoring them.
1989 let pmi_shown = crate::workbench::panel_visible(
1990 &engine.settings.workbench,
1991 crate::workbench::pmi::PANEL_ID,
1992 &crate::workbench::ButtonState::of(engine),
1993 );
1994 // An exploded view is shown from the Assembly workbench's Constraints
1995 // pane without entering PMI (a capture still remembers the modeling
1996 // state), so that pane counts as an exploded view's home too. With
1997 // neither on screen (nor the paper), the view is put away, so no one
1998 // models on exploded displays.
1999 let exploded_shown = crate::workbench::panel_visible(
2000 &engine.settings.workbench,
2001 crate::workbench::assembly::CONSTRAINTS_PANEL_ID,
2002 &crate::workbench::ButtonState::of(engine),
2003 ) && engine
2004 .pmi_active_view()
2005 .is_some_and(|id| engine.is_exploded_view(id));
2006 let paper_shown = crate::workbench::panel_visible(
2007 &engine.settings.workbench,
2008 crate::workbench::drawing::SHEETS_PANEL_ID,
2009 &crate::workbench::ButtonState::of(engine),
2010 );
2011 // A step of the instructions shows through its view, so the
2012 // Instructions and Player panes are a view's home too.
2013 let instructions_shown = [crate::workbench::instructions::PANEL_ID, crate::workbench::instructions::PLAYER_PANEL_ID]
2014 .into_iter()
2015 .any(|panel| crate::workbench::panel_visible(&engine.settings.workbench, panel, &crate::workbench::ButtonState::of(engine)));
2016 if pmi_shown && !engine.pmi_workbench_entered() {
2017 engine.pmi_enter_workbench();
2018 } else if !pmi_shown && !exploded_shown && !instructions_shown && engine.pmi_workbench_entered() {
2019 engine.pmi_leave_workbench();
2020 }
2021 if !pmi_shown && !exploded_shown && !paper_shown && !instructions_shown && engine.pmi_active_view().is_some() {
2022 engine.pmi_deactivate_view();
2023 }
2024 // The DRAWING workbench owns the paper: LEAVING it for a workbench
2025 // that hides the Sheets pane closes an open sheet, so the central
2026 // tile is not left drawing paper whose tools, pane and way back are
2027 // all hidden. It is a MODE change — the sheets and their contents
2028 // are untouched — and an edge, see `sheets_pane_shown`.
2029 let sheets_shown = crate::workbench::panel_visible(
2030 &engine.settings.workbench,
2031 crate::workbench::drawing::SHEETS_PANEL_ID,
2032 &crate::workbench::ButtonState::of(engine),
2033 );
2034 if self.sheets_pane_shown && !sheets_shown && engine.sheet_open().is_some() {
2035 let _ = engine.sheet_set_open(None);
2036 self.viewport.forget_sheet();
2037 }
2038 self.sheets_pane_shown = sheets_shown;
2039 }
2040
2041 // --- GUI chrome theme -------------------------------------------------
2042 // Apply the user's theme preference to the egui chrome every frame
2043 // (idempotent: `set_theme` just stores the preference). Auto follows the
2044 // OS/system theme (prefers-color-scheme on web); egui falls back to dark
2045 // when no OS signal is available. This controls panels/windows/toolbar/
2046 // text only — the 3D viewport `background` is a separate setting.
2047 ctx.set_theme(match self.docs.engine().settings.theme {
2048 ThemeMode::Auto => egui::ThemePreference::System,
2049 ThemeMode::Light => egui::ThemePreference::Light,
2050 ThemeMode::Dark => egui::ThemePreference::Dark,
2051 });
2052
2053 // --- global UI size scale --------------------------------------------
2054 // Apply the user's "UI scale" to the whole egui chrome every frame. This
2055 // is idempotent when unchanged (`set_zoom_factor` only repaints on an
2056 // actual change) and composes with the native device pixel ratio
2057 // (pixels_per_point = zoom_factor * native_pixels_per_point).
2058 //
2059 // Defer live UI rescale while the user drags the Settings "UI scale" slider:
2060 // the slider value updates continuously, but only commit it to the actual egui
2061 // zoom once the pointer is released, so the whole UI doesn't rescale under the
2062 // cursor mid-drag.
2063 let pointer_down = ctx.input(|i| i.pointer.any_down());
2064 if !pointer_down {
2065 self.applied_ui_scale = self.docs.engine().settings.ui_scale;
2066 }
2067 ctx.set_zoom_factor(self.applied_ui_scale);
2068 crate::viewport::touch::prepare_browser_input(ui);
2069
2070 // --- history-runner pump ---------------------------------------------
2071 // Apply any completed background history run BEFORE panels read the scene.
2072 // For the synchronous InlineRunner this is a no-op (`rerun_history` already
2073 // pumped its own submit), so nothing changes today; it is the seam a future
2074 // native-thread / wasm-worker runner lands its reply through. While a run is
2075 // still in flight, keep the frame loop alive so its reply gets pumped — for
2076 // Inline `run_pending()` is always false, so this never fires.
2077 //
2078 // EVERY open document is pumped, not just the active one — see
2079 // `Documents::pump_all`, which also keeps the active document's parts
2080 // library in the kernel's store when a background tab's run lands.
2081 let work_in_flight = {
2082 let _t = crate::perf::trace("pump_all");
2083 self.docs.pump_all()
2084 };
2085 if work_in_flight {
2086 ctx.request_repaint();
2087 }
2088 // The CAM simulation player, whether or not its pane is drawn.
2089 let dt = ctx.input(|i| i.stable_dt as f64).clamp(0.0, 0.25);
2090 if self.cam.sim.pump(self.docs.engine_mut(), dt) {
2091 ctx.request_repaint();
2092 }
2093 // An exploded view's Explode / Collapse animation.
2094 if self.docs.engine_mut().exploded_tick(dt) {
2095 ctx.request_repaint();
2096 }
2097 // A motion study: its bake (a few frames per tick) and its playhead,
2098 // driven only while the workbench offers the Simulation pane
2099 // (Simulation, All); the frame that leaves it puts every posed part
2100 // and the camera back, and a document edit made in another workbench
2101 // never wakes the study there (`SimulationPanel::drive_playback`).
2102 let simulation_shown = {
2103 let engine = self.docs.engine();
2104 crate::workbench::panel_visible(
2105 &engine.settings.workbench,
2106 crate::workbench::simulation::PANEL_ID,
2107 &crate::workbench::ButtonState::of(engine),
2108 )
2109 };
2110 if self.simulation.drive_playback(self.docs.engine_mut(), simulation_shown, dt) {
2111 ctx.request_repaint();
2112 }
2113 // The pane's Export button: the app owns the viewport's render core.
2114 if let Some(request) = self.simulation.take_export() {
2115 #[cfg(not(target_arch = "wasm32"))]
2116 let result = {
2117 let spec = crate::simulation_export::ExportSpec {
2118 study: Some(request.study.clone()),
2119 format: request.format.clone(),
2120 width: request.width,
2121 height: request.height,
2122 fps: Some(request.fps),
2123 path: Some(request.path.clone()),
2124 };
2125 crate::simulation_export::export(self, &spec).map(|(report, _)| report.summary())
2126 };
2127 #[cfg(target_arch = "wasm32")]
2128 let result = Err::<String, String>(format!("video export is native only (asked for {})", request.format));
2129 self.simulation.report(result);
2130 ctx.request_repaint();
2131 }
2132 // An instructions step's parts coming home along their arrows.
2133 if self.docs.engine_mut().instructions_insertion_tick(dt) {
2134 ctx.request_repaint();
2135 }
2136 self.docs.show_work_part_bar(ui, self.model_store.as_ref());
2137 if self.show_stl_preview(ui) {
2138 // The preview REPLACES the shell for the frame, and this early
2139 // return used to take the frame's READ drain with it: while a
2140 // preview was open every read-only automation command — `ping`,
2141 // `state_get`, `hit_rects`, a screenshot — went unanswered until
2142 // the host gave up on it, so no script could observe the preview it
2143 // had just opened. The preview publishes its own state and rects
2144 // above; this answers the reads that ask for them.
2145 #[cfg(feature = "automation")]
2146 self.drain_reads(&ctx);
2147 return;
2148 }
2149 if crate::automation::registry::enabled() {
2150 let _publish_span = crate::perf::span(crate::perf::Phase::Publish);
2151 for name in ["__brepImportPreview", "__brepImportRegions"] {
2152 crate::automation::registry::publish(name, crate::automation::state_blobs::doc(name), "null");
2153 }
2154 }
2155
2156 // The tab strip's dirty dots, refreshed once per frame (cheap — see
2157 // `Document::refresh_dirty_marker`).
2158 {
2159 let _t = crate::perf::trace("refresh_dirty_markers");
2160 self.docs.refresh_dirty_markers();
2161 }
2162
2163 // --- boot-load (?loadModel=): apply the fetched model once it lands ----
2164 // Replaces the seed with the URL-specified document (armed in `new`). The
2165 // ehttp callback wakes the frame loop, so a plain per-frame drain suffices.
2166 // `load_model_and_fit` arms deferred framing; the pump above reframes it
2167 // next frame. `mark_clean` opens it as a non-dirty document.
2168 if self.pending_boot_load.is_some() {
2169 let received = self
2170 .pending_boot_load
2171 .as_ref()
2172 .and_then(|rx| rx.try_recv().ok());
2173 if let Some(result) = received {
2174 self.pending_boot_load = None;
2175 match result {
2176 Ok(json) => {
2177 // REPLACES the seed in place rather than adding a tab.
2178 // It lands on the document that is already active,
2179 // whatever the session restored.
2180 let _ = self.docs.engine_mut().load_model_and_fit(&json);
2181 self.docs.active_mut().mark_clean();
2182 }
2183 Err(e) => self
2184 .docs
2185 .engine_mut()
2186 .push_notice(format!("Could not load model from URL: {e}")),
2187 }
2188 }
2189 }
2190
2191 // --- "Open in CAD" (?open=part/…/rev/…) --------------------------------
2192 if let Some(launch) = self.plm_launch.as_mut() {
2193 use crate::panels::plm_launch::Step;
2194 let step = launch.step(self.model_store.as_ref(), &mut self.docs, &mut self.file);
2195 match &step {
2196 Step::SignIn(sentence) => {
2197 self.settings.show_plm_tab();
2198 self.docs.engine_mut().push_notice(sentence.clone());
2199 }
2200 Step::Refused(sentence) => self.docs.engine_mut().push_notice(sentence.clone()),
2201 _ => {}
2202 }
2203 if step.settles() {
2204 crate::panels::plm_launch::forget_query();
2205 }
2206 if launch.is_done() {
2207 self.plm_launch = None;
2208 } else {
2209 ui.ctx().request_repaint();
2210 }
2211 }
2212
2213 crate::panels::ecad_parts::sync(self.docs.active_mut());
2214 // A sheet's Duplicate past the last offered occurrence: another assembly component.
2215 crate::panels::ecad_parts::answer_duplicate_requests(self.docs.active_mut());
2216 let requests = crate::panels::ecad_parts::take_open_requests(self.docs.active_mut());
2217 for key in requests {
2218 self.file.open_document(&mut self.docs, self.model_store.as_ref(), &key);
2219 }
2220 // The parts pane's Add part button presses Assembly's Add Component: one arm.
2221 if crate::panels::ecad_parts::take_add_part_request(self.docs.active_mut()) {
2222 self.dispatch_workbench_button(crate::workbench::assembly::ADD_COMPONENT_BUTTON_ID);
2223 }
2224 // The eCAD host's Update parts button is Constraints' Update components.
2225 if std::mem::take(&mut self.docs.active_mut().ecad_update_requested) {
2226 if let Err(error) = self.update_components.run(self.docs.engine_mut(), self.model_store.as_ref()) {
2227 self.docs.engine_mut().push_notice(format!("Update components: {error}"));
2228 }
2229 }
2230
2231 // --- update-components badge freshness ---------------------------------
2232 // Keep the outdated-parts checker current BEFORE any assembly panel draws
2233 // (the structure tree renders per-node badges ahead of the constraints
2234 // header). Cheap: a real recompute happens only when an applied run or a
2235 // successful store save moved the generation key.
2236 let synced = self.docs.synced_signatures();
2237 self.update_components.ensure_current(
2238 self.docs.engine_mut(),
2239 self.model_store.as_ref(),
2240 self.file.save_generation(),
2241 &synced,
2242 );
2243 // …and the eCAD host marks the components placed from those parts.
2244 self.docs.active_mut().ecad_outdated = self.update_components.outdated().to_vec();
2245 // An Update that would discard an edit made here asks first.
2246 self.update_components.show_conflict(ui.ctx(), self.docs.engine_mut(), self.model_store.as_ref());
2247
2248 // --- async-safe first-model framing -----------------------------------
2249 // The seed run is async under a background runner (native thread / wasm
2250 // worker), so the boot `zoom_to_fit` may have run before any solid existed.
2251 // Frame the model ONCE, the first frame the seed run has fully landed (solids
2252 // present AND no run still in flight). Under the synchronous Inline runner
2253 // (tests) both hold on the very first frame, so this is identical to today.
2254 if !self.first_run_framed
2255 && !self.docs.engine().run_pending()
2256 && self.docs.engine().has_solids()
2257 {
2258 self.docs.engine_mut().zoom_to_fit();
2259 self.first_run_framed = true;
2260 }
2261
2262 self.handle_shortcuts(&ctx);
2263
2264 // A form field's reference pick on a touch or narrow window is a
2265 // FOCUSED pick: every piece of chrome — toolbar and ribbon, workbench
2266 // strip, status bar, docks and the dialog in them, the action overlay
2267 // — steps aside and the view fills the window, with the PICK BAR
2268 // (`panels::pick_bar`: what is picked, the picks, the filter button,
2269 // Finish, Cancel) its only control. Finish or Cancel brings all of it
2270 // back as it was. Decided once, here, before any of it is drawn.
2271 let pick_layout = {
2272 let engine = self.docs.engine();
2273 crate::panels::pick_bar::PickLayout::of(
2274 engine.ref_select_active(),
2275 engine.ref_select_in_form(),
2276 crate::viewport::touch::narrow(&ctx),
2277 )
2278 };
2279 let focused_pick = pick_layout == crate::panels::pick_bar::PickLayout::Focused;
2280 crate::viewport::touch::set_chrome_hidden(&ctx, focused_pick);
2281
2282 // --- top toolbar: primary actions, drawn FIRST so its top strip is
2283 // reserved above the left panel + central viewport. A clicked File button
2284 // returns an action the file dialog acts on (open its modal / save / new).
2285 self.toolbar.read_only = !self.docs.active().access().is_editable();
2286 if crate::viewport::touch::compact(&ctx) {
2287 self.toolbar.documents = document_tabs::MenuState::from_documents(&self.docs);
2288 }
2289 let toolbar_outcome = if focused_pick {
2290 self.toolbar.clear_hits();
2291 crate::panels::toolbar::ToolbarOutcome::default()
2292 } else {
2293 let doc = self.docs.view_mut();
2294 self.toolbar.show(
2295 ui,
2296 &mut doc.engine,
2297 Some(&doc.ecad),
2298 self.model_store.as_ref(),
2299 &mut self.settings.open,
2300 &mut self.part_properties.open,
2301 &mut self.info.open,
2302 )
2303 };
2304 crate::panels::set_chrome_bottom(&ctx, ui.available_rect_before_wrap().top());
2305 if toolbar_outcome.toggle_mobile_panels { self.dock.toggle_mobile_drawer(); }
2306 if crate::viewport::touch::compact(&ctx) {
2307 self.apply_document_actions(toolbar_outcome.documents.activate, toolbar_outcome.documents.close);
2308 self.document_tab_hits = toolbar_outcome.documents.hits;
2309 }
2310 if toolbar_outcome.plugins { self.plugins.open = !self.plugins.open; }
2311 if toolbar_outcome.javascript { self.javascript.open = !self.javascript.open; }
2312 if let Some(id) = toolbar_outcome.plugin_action {
2313 if let Err(error) = self.plugins.open_action(self.docs.engine(), &id) { self.plugins.error = Some(error); }
2314 }
2315 self.plugins.active_document = self.docs.active_id();
2316 self.plugins.show(&ctx, self.docs.engine_mut(), self.model_store.as_ref());
2317 // Run goes to the app's own script runner (its server's code mode),
2318 // started on the first run; installed once the window is opened.
2319 #[cfg(all(not(target_arch = "wasm32"), feature = "mcp"))]
2320 if self.javascript.open && self.javascript.host.is_none() {
2321 self.javascript.host = Some(Box::new(crate::mcp::EditorHost::new(self.automation.clone(), self.diagnostics.adapter_line())));
2322 }
2323 // In the browser: the page's Web Worker runner (src/webmcp.rs).
2324 #[cfg(all(target_arch = "wasm32", feature = "mcp", feature = "scripting"))]
2325 if self.javascript.open && self.javascript.host.is_none() {
2326 self.javascript.host = Some(Box::new(crate::webmcp::PageScripts));
2327 }
2328 self.javascript.show(&ctx, &mut self.docs, self.model_store.as_ref());
2329 // The panels' exports (a plugin bundle, the script) leave through the
2330 // file dialog's export door: the Save-file chooser on desktop, a
2331 // download in the browser.
2332 let exports = self.plugins.take_save_requests().into_iter().chain(self.javascript.take_save_requests());
2333 for request in exports {
2334 if let Err(error) = self.file.request_save_file(&mut self.docs, self.model_store.as_ref(), request) {
2335 self.docs.engine_mut().push_notice(error);
2336 }
2337 }
2338 // An inbox row opens its review in the PLM pane.
2339 for event in toolbar_outcome.plm_review {
2340 self.plm.open_review(event);
2341 }
2342 if let Some(name) = toolbar_outcome.recent_document {
2343 self.file
2344 .open_document(&mut self.docs, self.model_store.as_ref(), &name);
2345 }
2346 if let Some(action) = toolbar_outcome.file {
2347 self.file
2348 .dispatch(action, &mut self.docs, self.model_store.as_ref());
2349 }
2350 // Submit Bug: begin the screenshot-capture + report flow. `request`
2351 // grabs the current frame (before its dialog exists) and the model, so
2352 // it must run THIS frame while the shot is still dialog-free.
2353 if toolbar_outcome.bug_report {
2354 self.bug_report.request(&ctx, self.docs.engine(), &self.diagnostics);
2355 }
2356 // A workbench toolbar button click surfaces its id here; the dispatch
2357 // itself is a METHOD so the `workbench_button` command runs the very
2358 // same arms (a button an agent can only reach by clicking is a button
2359 // an agent cannot reach when something covers it).
2360 if let Some(id) = toolbar_outcome.workbench_button {
2361 self.dispatch_workbench_button(id);
2362 }
2363 // Zoom-to-fit: the ONE button frames whatever the tile draws — the open
2364 // sheet's paper, or the 3D scene. See `BrepApp::zoom_to_fit`.
2365 if toolbar_outcome.zoom_to_fit {
2366 self.zoom_to_fit();
2367 }
2368
2369 // --- workbench actions toolbar: a second strip directly UNDER the
2370 // primary toolbar (egui stacks top panels in call order) listing the
2371 // active workbench's creatable features + the constraint types. Off via
2372 // the Settings checkbox, and never in sketch / reference-selection mode
2373 // (the panel decides — see `WorkbenchToolbarPanel::visible`). A feature
2374 // click adds exactly what the palette pick would, so ACOMP still routes
2375 // to the component selector; a constraint click is the context bar's
2376 // constraint offer, seeded from the current selection.
2377 // A read-only document (a PLM revision not checked out, or released)
2378 // draws the strip disabled: every button on it creates something.
2379 self.workbench_toolbar.read_only = !self.docs.active().access().is_editable();
2380 let actions = if self.docs.engine().settings.toolbar_style
2381 == brep_render::style::ToolbarStyle::Classic
2382 {
2383 self.workbench_toolbar.show(ui, self.docs.engine())
2384 } else {
2385 self.workbench_toolbar
2386 .set_ribbon_hits(self.toolbar.home_hits());
2387 toolbar_outcome.creation
2388 };
2389 if let Some(type_code) = actions.feature {
2390 self.history
2391 .add_feature_of_type(self.docs.engine_mut(), &type_code);
2392 // No `show_pane` here: `HistoryPanel::open_form` moved the target and
2393 // the dialog door surfaces History for it (`surface_open_dialogs`
2394 // below). ACOMP opens the component-selector MODAL instead of a
2395 // feature dialog, so it moves no target and surfaces no pane.
2396 if self.history.take_insert_component_request() {
2397 self.file.dispatch(
2398 FileAction::InsertComponent,
2399 &mut self.docs,
2400 self.model_store.as_ref(),
2401 );
2402 }
2403 }
2404 if let Some(type_id) = actions.constraint {
2405 // The strip offers every type regardless of the selection (unlike the
2406 // context bar's gated offers), so a refusal has to be SAID: a toast,
2407 // never a silent no-op. A document with no components has no assembly
2408 // session to add to (the kernel's own message names the session, not
2409 // the cause) — say what is actually missing.
2410 let engine = self.docs.engine_mut();
2411 if !engine.history_has_assembly() {
2412 engine.push_notice(
2413 "Add constraint: the document has no components — insert a component first"
2414 .to_string(),
2415 );
2416 } else {
2417 // The add leaves the new constraint OPEN (the kernel mints it
2418 // that way), so the dialog door surfaces the Constraints pane.
2419 if let Err(error) =
2420 crate::panels::context_bar::add_constraint_from_selection(engine, &type_id)
2421 {
2422 engine.push_notice(format!("Add constraint: {error}"));
2423 }
2424 }
2425 }
2426 if let Some(type_id) = actions.annotation {
2427 // The context bar's annotation offer, from the strip: seeded from
2428 // the selection, and the new annotation's form opens through the
2429 // dialog door. The strip offers every type whatever is selected, so
2430 // a refusal — no active view to add to — is said, not swallowed.
2431 let engine = self.docs.engine_mut();
2432 if let Err(error) = crate::panels::context_bar::add_pmi_from_selection(engine, &type_id) {
2433 engine.push_notice(format!("Add annotation: {error}"));
2434 }
2435 }
2436
2437 // --- sketch mode has NO strip of its own: its draw tools are workbench
2438 // buttons in the row above (`workbench::sketch`), offered while a sketch
2439 // is being edited, so the 3D viewport is the full-width sketching
2440 // surface with nothing between it and the one toolbar.
2441
2442 // --- bottom STATUS BAR: a persistent, full-width strip whose CONTENT is
2443 // chosen by context each frame. Drawn AFTER the top bars but BEFORE the
2444 // left panel(s) so it reserves the FULL bottom width and the left column
2445 // stops above it (egui resolves reserved space by call order). It is a
2446 // HOST: the branch below picks what to draw. A NEW context is added by
2447 // extending this branch (e.g. `else if engine.some_mode() { … }`) and
2448 // routing through the owning panel's `show_status_bar` for DRY styling.
2449 // Its top is the floor the toasts stack up from (`Toasts::show`).
2450 //
2451 // Its RIGHT END is the app-wide working indicator (`panels::busy`),
2452 // whatever the context: collected here from every source, drawn first
2453 // in a right-to-left row so the context content gets what is left of
2454 // the width and never runs under it.
2455 self.collect_busy(&ctx);
2456 let status_bar_top = if focused_pick {
2457 // The pick bar carries the filter button; nothing of the bar
2458 // stays published.
2459 self.busy.clear_hits();
2460 self.selection.clear_hits();
2461 ui.max_rect().bottom()
2462 } else { egui::containers::panel::Panel::bottom("brep-status-bar")
2463 .resizable(false)
2464 .min_size(30.0)
2465 .show(ui, |ui| {
2466 ui.add_space(2.0);
2467 // `Align::Min`, not `Center`: the bar's height is not known
2468 // until its content is laid out, and centring against the
2469 // unbounded space below doubled the bar with the indicator on
2470 // a row of its own.
2471 ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
2472 self.busy.show_status_bar(ui);
2473 ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
2474 if self.docs.engine().sketch_mode() {
2475 // Sketch context: the status row (title / DOF / N selected /
2476 // undo-redo / Lock). The selection-filter row is NOT drawn
2477 // now, so drop its stale hit-rects (the verifier must never
2478 // click a phantom rect for an off-screen widget).
2479 self.selection.clear_hits();
2480 self.sketch.show_status_bar(ui, self.docs.engine_mut());
2481 } else if self.docs.engine().sketch3d_mode() {
2482 // The 3D sketch's status row: DOF, selection, the
2483 // working plane in force and what the last click hit.
2484 self.selection.clear_hits();
2485 self.sketch3d.show_status_bar(ui, self.docs.engine_mut());
2486 } else if crate::workbench::ecad::Target::of_workbench(&self.docs.engine().settings.workbench).is_some() {
2487 // An eCAD editor owns the central tile, and a click there
2488 // picks nothing 3D: the pickable-kinds filter would be a
2489 // row of dead checkboxes. The strip carries the editor's
2490 // own line instead: where the pointer is and what is under it.
2491 self.selection.clear_hits();
2492 self.viewport.show_ecad_status(ui);
2493 } else {
2494 // Modeling context: the selection filter (pickable kinds).
2495 let document = self.docs.active_id();
2496 self.selection.show_status_bar(ui, self.docs.engine_mut(), document);
2497 }
2498 });
2499 });
2500 ui.add_space(2.0);
2501 })
2502 .response
2503 .rect
2504 .top() };
2505 // Cancel on the working indicator: sent to the document whose run it
2506 // named, which a background tab's run need not be the active one.
2507 if let Some(activity) = self.busy.take_cancel() {
2508 if let Some(doc) = self.docs.iter_mut().find(|doc| Some(doc.id()) == activity.document) {
2509 doc.engine.cancel_run();
2510 }
2511 }
2512
2513 // --- central region: the dock tree, OR (special modes) the bare 3D view
2514 // ---------------------------------------------------------------------
2515 // Normal modeling mode: ONE egui_tiles tree fills the whole remaining
2516 // area between the top toolbar and the bottom status bar. Every side-panel
2517 // section AND the 3D viewport are tiles the user can split / tab / resize /
2518 // drag-rearrange, and the layout persists. Which side panes are visible is
2519 // filtered per-workbench inside the dock (`workbench::panel_visible`).
2520 //
2521 // Sketch mode and reference-selection are "special modes" that take over
2522 // the shell: they BYPASS the tree and draw the viewport directly, so the
2523 // modeling side panes don't appear (sketch's own entity-list panel + the
2524 // top-right mode card own those flows). Drawing the viewport HERE — before
2525 // the top-right overlay below — keeps `viewport.last_rect()` current-frame
2526 // so the overlay anchors to the live 3D-view rect with no lag.
2527 let sketch = self.docs.engine().any_sketch_mode();
2528 // Only a CARD-based pick (a connection point's seat, a spline anchor's
2529 // port) takes the shell over. A FORM FIELD's pick — a feature's, a
2530 // constraint's, an annotation's, a sheet object's — keeps the dock: the
2531 // field is drawn focused in its own pane and the picks go to it, the
2532 // way other CAD applications keep the dialog up while you click in the
2533 // view (`EngineState::ref_select_in_form`).
2534 // Except on a touch or narrow window, where the dock and the dialog
2535 // in it would cover the view and leave nothing to pick: there a form
2536 // field's pick takes the shell over too (`focused_pick`, decided
2537 // before the toolbar is drawn).
2538
2539 let compact = crate::viewport::touch::compact(&ctx);
2540 let entity_drawer_id = egui::Id::new("brep-mobile-sketch-entities");
2541 let mut entity_drawer_open = sketch && ctx.data(|d| d.get_temp::<bool>(entity_drawer_id)).unwrap_or(false);
2542 let mut mobile_sketch_hits: std::collections::HashMap<String, egui::Rect> = std::collections::HashMap::new();
2543 if sketch && compact {
2544 egui::containers::panel::Panel::top("brep-mobile-sketch-controls").resizable(false).show(ui, |ui| {
2545 ui.horizontal(|ui| {
2546 self.mode_bar.card(ui, self.docs.engine_mut());
2547 });
2548 });
2549 self.sketch.clear_list_hits();
2550 self.sketch3d.clear_list_hits();
2551 } else if sketch {
2552 // Sketch entity lists (Curves / Points / Constraints) + solver
2553 // settings — a dedicated left panel, drawn BEFORE the viewport so it
2554 // reserves the left and the viewport fills the rest.
2555 egui::containers::panel::Panel::left("sketch-entities")
2556 .resizable(true)
2557 .default_size(300.0)
2558 .size_range(200.0..=560.0)
2559 .show(ui, |ui| {
2560 if self.docs.engine().sketch3d_mode() {
2561 self.sketch3d.show_entity_lists(ui, self.docs.engine_mut());
2562 } else {
2563 self.sketch.show_entity_lists(ui, self.docs.engine_mut());
2564 }
2565 });
2566 }
2567
2568 self.history.sync_palette_display(self.model_store.as_ref());
2569 // The PLM panels (a PLM session only): each PLM document's access from
2570 // its revision, and the revisions the user asked to open.
2571 let plm = self.plm.sync(self.model_store.as_ref(), &mut self.docs, self.file.save_generation());
2572 for name in plm.open {
2573 self.file.open_document(&mut self.docs, self.model_store.as_ref(), &name);
2574 }
2575 for (name, folder) in plm.opened_from {
2576 if let Some(doc) = self.docs.index_of(&name).and_then(|index| self.docs.get_mut(index)) {
2577 doc.set_plm_folder(Some(folder));
2578 }
2579 }
2580 // The CAM pane's chooser and save requests (a tool import, a library
2581 // export) go through the shell's doors like the PLM pane's; the file
2582 // the chooser delivers goes back to the pane.
2583 let cam_requests = self.cam.take_shell_requests();
2584 if let Some((tag, title)) = cam_requests.pick_file {
2585 if let Err(error) = self.file.request_pick_file(self.model_store.as_ref(), &tag, &title) {
2586 self.file.status = error;
2587 }
2588 }
2589 for request in cam_requests.save_files {
2590 if let Err(error) = self.file.request_save_file(&mut self.docs, self.model_store.as_ref(), request) {
2591 self.docs.engine_mut().push_notice(error);
2592 }
2593 }
2594 if let Some(file) = self.file.take_picked_file(crate::panels::cam::IMPORT_TOOLS_TAG) {
2595 self.cam.deliver_picked(self.docs.engine_mut(), &file.name, &file.bytes);
2596 }
2597 // A PLM section asked for a file (Attach a file…, Add file…): the file
2598 // chooser answers, and the file goes back to the section that asked.
2599 if let Some((tag, title)) = plm.pick_file {
2600 if let Err(error) = self.file.request_pick_file(self.model_store.as_ref(), &tag, &title) {
2601 self.file.status = error;
2602 }
2603 }
2604 for tag in self.plm.pick_tags() {
2605 if let Some(file) = self.file.take_picked_file(&tag) {
2606 self.plm.deliver_picked(&tag, file);
2607 }
2608 }
2609 if plm.refresh_inbox {
2610 self.toolbar.refresh_inbox();
2611 }
2612 if let Some(why) = plm.sign_in_again {
2613 self.settings.ask_plm_sign_in(why);
2614 }
2615 // A PLM section's downloads leave through the same export door.
2616 for request in plm.save_files {
2617 if let Err(error) = self.file.request_save_file(&mut self.docs, self.model_store.as_ref(), request) {
2618 self.docs.engine_mut().push_notice(error);
2619 }
2620 }
2621 // Save As → "A new part" (D9): the PLM pane's New part form, shown.
2622 if self.file.take_plm_new_part() {
2623 self.plm.open_new_part();
2624 self.show_pane(PaneKind::Plm);
2625 }
2626 if self.plm.busy() {
2627 ui.ctx().request_repaint();
2628 }
2629 // Following other clients (`panels::plm_follow`): when the feed moved,
2630 // the inbox asks again too; and the next question gets a frame.
2631 if self.plm.take_followed() {
2632 self.toolbar.refresh_inbox();
2633 }
2634 if let Some(next) = self.plm.next_follow_in() {
2635 ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(next.max(0.1)));
2636 }
2637 if sketch || !pick_layout.shows_dock() {
2638 self.viewport.set_chrome_obscured(compact && entity_drawer_open);
2639 // Special mode: the viewport fills the remaining central area; no
2640 // dock, no modeling side panes — and therefore no DOCUMENT TAB
2641 // STRIP either, which is the guard that keeps a live sketch /
2642 // reference-pick session from having its document swapped out from
2643 // under it.
2644 self.viewport.show(ui, self.docs.engine_mut());
2645 // No dock, so no tab strip: its last-drawn rects must not stay
2646 // published (the compact strip is the toolbar's, set above).
2647 if !compact { self.document_tab_hits.clear(); }
2648 if focused_pick {
2649 let view = self.viewport.last_rect().unwrap_or(ui.max_rect());
2650 self.pick_bar.show(&ctx, view, self.docs.engine_mut(), &mut self.selection);
2651 // Settled as the dock's branch settles it: the bar claimed the
2652 // pick, so this finishes a single field on its pick.
2653 self.settle_form_pick();
2654 } else {
2655 self.pick_bar.clear_hits();
2656 }
2657 if compact && sketch {
2658 let view = self.viewport.last_rect().unwrap_or(ui.max_rect());
2659 egui::Area::new(egui::Id::new("brep-mobile-sketch-tab"))
2660 .order(egui::Order::Middle).fixed_pos(view.left_top() + egui::vec2(2.0, 4.0)).movable(false)
2661 .show(&ctx, |ui| {
2662 let tab = crate::panels::dock::mobile_tab(ui, "Entities", entity_drawer_open);
2663 mobile_sketch_hits.insert("toggle".into(), tab.rect);
2664 if entity_drawer_open { mobile_sketch_hits.insert("close".into(), tab.rect); }
2665 if tab.clicked() { entity_drawer_open = !entity_drawer_open; ctx.request_repaint(); }
2666 });
2667 if entity_drawer_open {
2668 let panel = egui::Rect::from_min_size(view.left_top() + egui::vec2(52.0, 4.0),
2669 egui::vec2((view.width() - 60.0).min(400.0).max(100.0), (view.height() - 8.0).max(100.0)));
2670 crate::panels::dock::mobile_panel(&ctx, entity_drawer_id, panel, |ui| {
2671 if self.docs.engine().sketch3d_mode() {
2672 self.sketch3d.show_entity_lists(ui, self.docs.engine_mut());
2673 } else {
2674 self.sketch.show_entity_lists(ui, self.docs.engine_mut());
2675 }
2676 });
2677 }
2678 }
2679 DockState::retract_all(DockContext {
2680 docs: &mut self.docs,
2681 plugins: &mut self.plugins,
2682 viewport: &mut self.viewport,
2683 history: &mut self.history,
2684 bom: &mut self.bom,
2685 assembly_constraints: &mut self.assembly_constraints,
2686 wire_harness: &mut self.wire_harness,
2687 pmi: &mut self.pmi,
2688 sheets: &mut self.sheets,
2689 scene: &mut self.scene,
2690 expressions: &mut self.expressions,
2691 qualify: &mut self.qualify,
2692 family_table: &mut self.family_table,
2693 update_components: &mut self.update_components,
2694 model_store: self.model_store.as_ref(),
2695 plm: &mut self.plm,
2696 cam: &mut self.cam,
2697 instructions: &mut self.instructions,
2698 instructions_player: &mut self.instructions_player,
2699 simulation: &mut self.simulation,
2700 });
2701 } else {
2702 self.pick_bar.clear_hits();
2703 // Normal mode: the dock owns the whole central area (the viewport is a
2704 // pane). Cross-panel requests the panels can't act on while their
2705 // borrows are held bubble OUT via the returned outcome — the SAME
2706 // requests the old left-panel closure produced.
2707 let outcome = self.dock.ui(
2708 ui,
2709 DockContext {
2710 docs: &mut self.docs,
2711 plugins: &mut self.plugins,
2712 viewport: &mut self.viewport,
2713 history: &mut self.history,
2714 bom: &mut self.bom,
2715 assembly_constraints: &mut self.assembly_constraints,
2716 wire_harness: &mut self.wire_harness,
2717 pmi: &mut self.pmi,
2718 sheets: &mut self.sheets,
2719 scene: &mut self.scene,
2720 expressions: &mut self.expressions,
2721 qualify: &mut self.qualify,
2722 family_table: &mut self.family_table,
2723 update_components: &mut self.update_components,
2724 model_store: self.model_store.as_ref(),
2725 plm: &mut self.plm,
2726 cam: &mut self.cam,
2727 instructions: &mut self.instructions,
2728 instructions_player: &mut self.instructions_player,
2729 simulation: &mut self.simulation,
2730 },
2731 );
2732
2733 // A form field's pick, settled for the frame: finished when its
2734 // single field has its one pick, when its form asked (an edit
2735 // elsewhere on it), or when no form drew it.
2736 self.settle_form_pick();
2737
2738 // The ACOMP palette pick must open the COMPONENT SELECTOR, never a
2739 // bare feature dialog — the file dialog is shell-owned.
2740 if outcome.insert_component_requested {
2741 self.file.dispatch(
2742 FileAction::InsertComponent,
2743 &mut self.docs,
2744 self.model_store.as_ref(),
2745 );
2746 }
2747 // The DOCUMENT TAB STRIP inside the viewport tile. Activation is
2748 // immediate; a close routes through the file dialog because a dirty
2749 // document has to be confirmed first, and that prompt lives there.
2750 // A pick runs in ONE document's engine: switching or closing a
2751 // document commits a form field's pick first, so it is never left
2752 // running in a document that is no longer on screen.
2753 self.apply_document_actions(outcome.document_tabs.activate, outcome.document_tabs.close);
2754 if !compact { self.document_tab_hits = outcome.document_tabs.hits; }
2755 // A structure-tree Edit — or a BOM row's action button, which
2756 // reports through the same outcome field so there is one arm and
2757 // not two — expands its feature in the history tree.
2758 if let Some(focus) = outcome.feature_focus {
2759 self.history.focus_feature(focus);
2760 if compact { self.dock.show_pane(PaneKind::History); }
2761 }
2762 // Structure-tree interaction hooks route through the SAME dispatcher
2763 // as the context bar (one truth per action); document-level flows
2764 // (edit-in-place / open-part) come back as requests the shell runs.
2765 // A BOM row menu's document-level flow: its engine-mutating half
2766 // already ran inside the panel, through the same dispatcher.
2767 // Double-clicking empty space leaves the Work part.
2768 if self.viewport.take_empty_double_click() && self.docs.work_part_path().is_some() {
2769 if let Err(error) = self.docs.return_to_assembly() {
2770 self.docs.engine_mut().push_notice(format!("Work part: {error}"));
2771 }
2772 }
2773 if let Some(request) = outcome.component_request.or_else(|| self.viewport.take_component_request()) {
2774 self.run_component_request(request, compact);
2775 }
2776 }
2777
2778 self.history.sync_palette_display(self.model_store.as_ref());
2779
2780 // --- file dialog: a ctx-level modal (like the command palette), drawn
2781 // after the panels so its backdrop dims the whole shell. Idempotent when
2782 // closed; also polls for a completed async import each frame.
2783 self.file
2784 .show(&ctx, &mut self.docs, self.model_store.as_ref());
2785
2786 // --- crash recovery: the boot prompt, then the debounced autosave -----
2787 // Drawn with the same ctx-level modal treatment as the file dialog. The
2788 // autosave ticks only once the prompt has resolved (or never existed).
2789 if self.recovery.is_open() {
2790 if let Some(resolution) =
2791 self.recovery.show(&ctx, &mut self.docs, self.model_store.as_ref())
2792 {
2793 self.autosave.note_cleared();
2794 if let crate::recovery::Resolution::Restored(count) = resolution {
2795 self.docs.engine_mut().push_notice_as(NoticeSeverity::Info, format!(
2796 "Restored {count} unsaved document{}",
2797 if count == 1 { "" } else { "s" }
2798 ));
2799 }
2800 }
2801 } else {
2802 self.recovery.clear_hits();
2803 let now = ctx.input(|i| i.time);
2804 if let Some(due) = self.autosave.tick(&self.docs, self.model_store.as_ref(), now) {
2805 // The frame loop idles between inputs; wake it when the write is due.
2806 ctx.request_repaint_after(std::time::Duration::from_secs_f64(due.max(0.05)));
2807 }
2808 }
2809
2810 // --- desktop update notice: an installed update closes the app through
2811 // the close path below, which keeps unsaved work for recovery.
2812 #[cfg(not(target_arch = "wasm32"))]
2813 if self.updater.show(&ctx) {
2814 self.close_asked = true;
2815 }
2816 self.close_when_written(&ctx);
2817
2818 if let Some((format, name, bytes)) = self.file.take_stl_import() {
2819 self.start_mesh_preview(format, name, bytes);
2820 ctx.request_repaint();
2821 }
2822
2823 // --- Submit Bug: the screenshot-capture state machine + report modal.
2824 // Drawn at ctx level like the file dialog; idempotent while idle. Draws
2825 // NOTHING during capture, so the screenshot it requested never contains
2826 // this dialog.
2827 self.bug_report.show(&ctx, self.docs.engine_mut());
2828 if let Some((id, summary)) = self.bug_report.take_submitted() {
2829 self.report_followup.record(id, summary);
2830 }
2831 self.report_followup.tick(&ctx, self.docs.engine_mut());
2832 self.sketch.show_text_dialog(&ctx, self.docs.engine_mut());
2833
2834 // --- Info: the licences + this session's diagnostics + the MCP start
2835 // button, a floating window toggled from the toolbar's info button.
2836 // Idempotent when closed. The server's state is read here, each frame
2837 // the window is open, and a click is answered here: the shell owns the
2838 // queue the server attaches to and the adapter line its session names.
2839 #[cfg(all(not(target_arch = "wasm32"), feature = "mcp"))]
2840 let mcp_view = if self.info.open { crate::mcp::info_view() } else { crate::panels::info::McpView::Unavailable };
2841 #[cfg(not(all(not(target_arch = "wasm32"), feature = "mcp")))]
2842 let mcp_view = crate::panels::info::McpView::Unavailable;
2843 self.info.show(&ctx, &self.diagnostics, &mcp_view);
2844 #[cfg(all(not(target_arch = "wasm32"), feature = "mcp"))]
2845 if self.info.take_mcp_start() {
2846 // The failure is already in `mcp::status()`, which the window
2847 // shows next frame, and on stderr in the same words.
2848 let _ = crate::mcp::start_from_window(self.automation.clone(), self.diagnostics.adapter_line());
2849 }
2850
2851 // --- Settings: a floating (movable + resizable) window, toggled from the
2852 // toolbar gear button, drawn at ctx level like Properties so it floats
2853 // over the shell. Idempotent when closed. Replaces the old sidebar section.
2854 // This preview runs every frame, including when Settings is closed.
2855 // Exact dirty checks serialize the whole assembly; use the tab's cached
2856 // marker here. reconnect_plm still checks the exact saved bytes before
2857 // switching stores, including metadata edits the marker may not see.
2858 self.settings.reconnect_blocker =
2859 self.reconnect_blocker_with(crate::document::Document::dirty_marker);
2860 self.settings
2861 .show(&ctx, self.docs.engine_mut(), self.model_store.as_ref());
2862 // Signed out here (Forget): the server's refusal that follows is the
2863 // person's own doing, not news to prompt about.
2864 if self.settings.take_plm_signed_out_here() {
2865 self.plm.signed_out_here();
2866 }
2867 // Signed in again after the server refused this session's token: the
2868 // live session takes the new token, for the same user, and goes on with
2869 // its open tabs (no store switch, nothing to close).
2870 if self.settings.plm_signed_out() {
2871 if let (Some((username, token)), Some(client)) = (self.settings.take_fresh_plm_token(), self.model_store.plm_client()) {
2872 if client.me().is_none_or(|me| me.username == username) {
2873 client.replace_token(&token);
2874 self.plm.follow_now();
2875 } else {
2876 self.docs.engine_mut().push_notice(format!(
2877 "Signed in as {username}, not {}: restart the app (or Connect now) to use the PLM as {username}",
2878 client.me().map(|me| me.username).unwrap_or_default()
2879 ));
2880 }
2881 }
2882 }
2883 // The PLM tab's Connect now: switch this session to the PLM live.
2884 #[cfg(not(target_arch = "wasm32"))]
2885 if let Some(root) = self.settings.take_reconnect_request() {
2886 let outcome = self.reconnect_plm(root);
2887 self.settings.reconnected(outcome);
2888 }
2889
2890 // --- Part Properties: the active document's own BOM attribute record,
2891 // in a floating window beside Settings. The title is passed in because
2892 // the panel takes only the engine, and a user with several tabs open
2893 // must be able to see WHICH part they are annotating.
2894 let part_title = self.docs.active().title();
2895 let part_document = self.docs.active().id();
2896 self.part_properties.configure_plm(self.model_store.plm_client(), self.docs.active().name());
2897 self.part_properties
2898 .show(&ctx, self.docs.engine_mut(), &part_title, part_document);
2899 if std::mem::take(&mut self.assembly_constraints.review_replace_requested) {
2900 self.review_replace();
2901 }
2902 self.replace_dialog
2903 .show(&ctx, self.docs.engine_mut(), self.model_store.as_ref());
2904
2905 ctx.data_mut(|d| d.insert_temp(entity_drawer_id, entity_drawer_open));
2906
2907 // --- top-right overlay column: the special-mode EXIT card (Finish/Cancel
2908 // for reference-selection / sketch mode) stacked ABOVE the selection-driven
2909 // CONTEXT ACTION rail. Both cards live in ONE ctx-level Area anchored
2910 // top-right so they never overlap, and the context rail uses the SAME
2911 // renderer whether it is showing modeling actions or sketch actions
2912 // (`panels::action_rail`). A modeling create/edit action returns a feature
2913 // id to expand in the history tree.
2914 #[cfg(all(feature = "automation", target_arch = "wasm32"))]
2915 crate::automation::registry::publish("__brepMobileActions", "compact action menu button rectangle", "{}");
2916 if focused_pick || (compact && (entity_drawer_open || (!sketch && self.dock.mobile_drawer_open()))) {
2917 crate::panels::action_rail::close_mobile_actions(&ctx);
2918 self.mode_bar.clear_hits();
2919 self.sketch.clear_context_hits();
2920 self.sketch3d.clear_context_hits();
2921 self.context_bar.clear_view();
2922 } else {
2923 let mut focus: Option<String> = None;
2924 let mut info_targets: Vec<String> = Vec::new();
2925 let mut plugin_action = None;
2926 let mut component_request: Option<ComponentActionRequest> = None;
2927 // Anchor the overlay to the RIGHT edge of the 3D VIEW (the viewport
2928 // tile), not the window — so it stays glued to the viewport wherever
2929 // docking frames it. The viewport was drawn earlier THIS frame, so its
2930 // rect is current. Before the first draw (`None`) fall back to the
2931 // window's top-right.
2932 let mut overlay = egui::Area::new(egui::Id::new("brep-top-right-overlay"))
2933 .order(egui::Order::Foreground);
2934 overlay = match self.viewport.last_rect() {
2935 Some(rect) => overlay
2936 .fixed_pos(rect.right_top() + egui::vec2(-12.0, 8.0))
2937 .pivot(egui::Align2::RIGHT_TOP),
2938 None => overlay.anchor(egui::Align2::RIGHT_TOP, egui::vec2(-12.0, 56.0)),
2939 };
2940 overlay
2941 .show(&ctx, |ui| {
2942 // 0. The family-row preview's card: which row, and Exit.
2943 self.family_table.preview_card(ui, self.docs.engine_mut());
2944 // 1. Exit controls for whatever special mode is active.
2945 if !(compact && sketch) { self.mode_bar.card(ui, self.docs.engine_mut()); }
2946 // 2. Context actions: sketch actions in sketch mode, else the
2947 // modeling selection actions. Same rail, mode-appropriate items.
2948 let has_actions = if self.docs.engine().sketch_mode() { self.docs.engine().sketch_selection_count() > 0 }
2949 else if self.docs.engine().sketch3d_mode() { self.docs.engine().sketch3d_selection_count() > 0 }
2950 else { self.docs.engine().has_selection() || self.docs.engine().selected_constraint().is_some() };
2951 let mut draw_actions = |ui: &mut egui::Ui| {
2952 if self.docs.engine().sketch_mode() {
2953 self.sketch.context_card(ui, self.docs.engine_mut());
2954 } else if self.docs.engine().sketch3d_mode() {
2955 self.sketch3d.context_card(ui, self.docs.engine_mut());
2956 } else {
2957 // Room down to the ViewCube's top, from wherever the
2958 // cards above left the cursor.
2959 self.context_bar.max_height = if compact { None } else { self.viewport.last_rect().and_then(|view| {
2960 let cube: serde_json::Value =
2961 serde_json::from_str(&self.docs.engine().viewcube_rect_json()).ok()?;
2962 let (top, h) = (cube["y"].as_f64()? as f32, cube["h"].as_f64()? as f32);
2963 (h > 0.0).then(|| view.top() + top - 8.0 - ui.cursor().top())
2964 }) };
2965 let outcome = self.context_bar.card(ui, self.docs.engine_mut());
2966 focus = outcome.focus;
2967 info_targets = outcome.info_targets;
2968 plugin_action = outcome.plugin_action;
2969 component_request = outcome.component;
2970 }
2971 };
2972 if compact {
2973 if has_actions {
2974 ui.set_min_width(110.0);
2975 let button = ui.add_sized([110.0, 44.0], egui::Button::new("Actions"));
2976 if button.clicked() { crate::panels::action_rail::open_mobile_actions(ui.ctx()); }
2977 draw_actions(ui);
2978 #[cfg(all(feature = "automation", target_arch = "wasm32"))]
2979 crate::automation::registry::publish("__brepMobileActions", "shared action chooser and entry rectangles",
2980 &crate::panels::action_rail::mobile_actions_json(ui.ctx(), button.rect));
2981 } else {
2982 crate::panels::action_rail::close_mobile_actions(ui.ctx());
2983 self.sketch.clear_context_hits();
2984 self.sketch3d.clear_context_hits();
2985 self.context_bar.clear_view();
2986 }
2987 } else { draw_actions(ui); }
2988 });
2989 if let Some(focus) = focus {
2990 self.history.focus_feature(focus);
2991 if compact { self.dock.show_pane(PaneKind::History); }
2992 }
2993 // The Info action returns one target per selected entity — open (or, on
2994 // dedup, keep) a pinned Info window for each. Drawn below.
2995 if let Some(id) = plugin_action {
2996 if let Err(e) = self.plugins.open_action(self.docs.engine(), &id) { self.plugins.error = Some(e); }
2997 }
2998 if !info_targets.is_empty() {
2999 self.info_windows.open_for(&info_targets, self.viewport.last_rect());
3000 }
3001 // Component document-level flows (the engine-mutating component
3002 // actions already ran inside the bar).
3003 if let Some(request) = component_request {
3004 self.run_component_request(request, false);
3005 }
3006 }
3007
3008 if compact { crate::panels::action_rail::show_mobile_actions(&ctx); }
3009
3010 // --- THE DIALOG DOOR: every dynamically generated dialog that opened
3011 // this frame makes its host pane's tab current.
3012 //
3013 // ONE call, placed after everything that can open one — the dock's panes
3014 // and viewport, and the context bar's overlay above — so a form opened
3015 // anywhere is surfaced in the same frame, before `__brepDock` publishes
3016 // the active tab below. It watches the TARGETS rather than the callers
3017 // because most of them set the target inside the engine or inside a
3018 // panel's draw, with no dock in reach; `panels::dock::DialogTargets`
3019 // carries that reasoning and the openers it covers.
3020 let targets = crate::panels::dock::DialogTargets::read(
3021 &self.history,
3022 self.docs.engine(),
3023 self.docs.active_id(),
3024 );
3025 self.dock.surface_opened_dialogs(targets);
3026
3027 // --- Info windows: the pinned per-entity inspector windows, drawn at ctx
3028 // level like the file dialog so they float over the shell. Each is pinned to
3029 // its open-time object name (selection changes never retarget them); closed
3030 // windows (their `×`) are pruned here. Drawn AFTER the context bar so a
3031 // window opened THIS frame paints this frame.
3032 self.info_windows.show(&ctx, self.docs.engine_mut());
3033
3034 // --- interference results window: same floating idiom, owned report;
3035 // its Re-run button re-drives the engine check.
3036 self.interference.show(&ctx, self.docs.engine_mut());
3037
3038 // --- auto-constraints window: the inference scan + its Create button.
3039 self.auto_constraints.show(&ctx, self.docs.engine_mut());
3040 self.step_parts
3041 .show(&ctx, self.docs.engine_mut(), self.model_store.as_ref());
3042
3043 // --- transient toasts: drain the engine's queued notices (e.g. a sketch
3044 // solve that failed after an edit) and show each briefly. Drawn last so
3045 // the cards float over the whole shell.
3046 let now = ctx.input(|i| i.time);
3047 // All three sources gathered FIRST, because the automation queue must see
3048 // every one of them: `Toasts::extend` keeps only the last few on screen,
3049 // and a message dropped for space is exactly the one a host wants told.
3050 use brep_render::engine_state::NoticeSeverity;
3051 let raised = self.gather_notices();
3052 self.toasts.extend(raised, now);
3053 // An edit after a card was raised supersedes it (`Toasts::note_document`).
3054 self.toasts
3055 .note_document(self.docs.active_id(), self.docs.engine().history.undo_top(), now);
3056 self.toasts.show(&ctx, self.viewport.last_rect(), status_bar_top);
3057
3058 // The state registry (`automation::registry`): the live app + engine
3059 // state, published by name with a one-line doc so a host can read it
3060 // (and, on wasm, mirrored to `window.__brep*` for the verify scripts).
3061 // Purely additive; no render effect. Published AFTER the panels draw so
3062 // the hit-rects are for THIS frame's layout. Off unless a host enabled it.
3063 if crate::automation::registry::enabled() {
3064 let _publish_span = crate::perf::span(crate::perf::Phase::Publish);
3065 // Every blob that is plain app state, from the one producer
3066 // `state_get` also asks at dispatch time (`state_blob_json`).
3067 self.publish_state_blobs(&ctx);
3068 // Keyboard focus, for a driver typing into a widget by its rect: the
3069 // frame counter says a click has been drawn, `rect` is the widget
3070 // egui gave the focus to (null while nothing has it). A typed
3071 // string lands only in a focused field, so a verifier waits on this
3072 // rather than on time (BREP_app/web/verify_plm_helpers.mjs).
3073 let focused = crate::column_tree::focused_rect(ui.ctx());
3074 // The focused value editor's text, taken (not left) so a frame
3075 // with no focused editor publishes null.
3076 let text: Option<String> = ui.ctx().data_mut(|d| d.remove_temp::<String>(crate::column_tree::focused_text_id())).filter(|_| focused.is_some());
3077 crate::automation::registry::publish("__brepFocus", "keyboard focus {frame, rect:[x,y,w,h]|null (the focused widget), text:string|null (a value editor's in-progress string)}", &serde_json::json!({
3078 "frame": ui.ctx().cumulative_frame_nr(),
3079 "rect": focused.map(|r| [r.min.x, r.min.y, r.width(), r.height()]),
3080 "text": text,
3081 }).to_string());
3082 crate::automation::registry::publish("__brepFileHit", "file dialog widget rects", &self.file.hits_json());
3083 crate::automation::registry::publish("__brepStatusHit", "status bar widget rects: busy, busy:more, busy:cancel (present only while the working indicator shows)", &self.busy.hits_json());
3084 crate::automation::registry::publish("__brepHit", "history panel widget rects: step:i edit:i del:i box:i add:menu form:* field:* panel:clip", &self.history.hits_json());
3085 crate::automation::registry::publish("__brepPaletteHit", "add-feature palette widget rects in screen points: input top item:type display display#mode (empty while closed)", &self.history.palette_hits_json());
3086 crate::automation::registry::publish("__brepExprHit", "expressions panel widget rects", &self.expressions.hits_json());
3087 crate::automation::registry::publish("__brepToolbar", "toolbar rects: shared File menu file:* and workbench:item:<id>; Ribbon tabs/overflow ribbon:* and Home creation wbtb:*; command keys undo redo fit projection wireframe show:* help info bug workbench:btn:<id>. Classic wraps its controls; Ribbon compacts Large commands before whole-group overflow. Keys appear when their widgets are rendered; menu entries appear while open", &self.toolbar.hits_json());
3088 // The workbench actions strip's button rects (`wbtb:feature:<type>` /
3089 // `wbtb:constraint:<type>` / `wbtb:annotation:<type>`); an empty map
3090 // while the strip is hidden.
3091 crate::automation::registry::publish("__brepWorkbenchToolbar", "creation rects: wbtb:* feature:type constraint:type annotation:type, from the Classic workbench strip or Ribbon Home; empty while hidden or another Ribbon tab is selected", &self.workbench_toolbar.hits_json());
3092 // The PLM pane (a PLM session only): its sections' widget rects,
3093 // `plm/section:<id>` and `plm/<section>:<widget>`, and the active
3094 // document's access and revision.
3095 crate::automation::registry::publish("__brepPlmHit", "PLM pane rects: section:lifecycle, lifecycle:revision:<label>, lifecycle:verb:check-out, save:<yes|no|remember>, web:<summary|revisions|attachments|structure|history|parts|workspace|reviews>", &self.plm.hits_json());
3096 crate::automation::registry::publish("__brepToastsHit", "toast card rects (toast:<i> top to bottom, toast:more)", &self.toasts.hits_json());
3097 crate::automation::registry::publish("__brepBugHit", "bug report panel widget rects", &self.bug_report.hits_json());
3098 // The JavaScript editor window: its outer rect against the surface
3099 // it may fill, and its widget rects (`javascript/panel:clip`,
3100 // `javascript/source`, `javascript/output`, the buttons).
3101 crate::automation::registry::publish("__brepJavascript", "JavaScript editor window {open, rect:[x,y,w,h] or null while closed, surface:[w,h], running, output}", &self.javascript.state_json());
3102 crate::automation::registry::publish("__brepJavascriptHit", "JavaScript editor window widget rects (panel:clip, run, cancel, save, open, export, help, example, source, output); empty while the window is closed", &self.javascript.hits_json());
3103 // The wire harness: the document's connections + the last run's
3104 // routing report (engine truth), and the panel's widget rects.
3105 crate::automation::registry::publish("__brepWireHarnessHit", "wire harness panel widget rects", &self.wire_harness.hits_json());
3106 // The CAM block (setups with their operations, tools, operations,
3107 // NC programs) plus the pane's selection and last notice, and the
3108 // pane's rects (`cam:*`).
3109 self.cam.refresh_geometry(self.docs.engine());
3110 crate::automation::registry::publish("__brepCamHit", "CAM pane widget rects (cam:*)", &self.cam.hits_json());
3111 crate::automation::registry::publish("__brepInstructionsHit", "Instructions pane widget rects (instructions:*)", &self.instructions.hits_json());
3112 crate::automation::registry::publish("__brepInstructionsPlayerHit", "Player pane widget rects (player:*)", &self.instructions_player.hits_json());
3113 crate::automation::registry::publish("__brepSimulationHit", "Simulation pane widget rects (simulation:*)", &self.simulation.hits_json());
3114 // The part's declared connection points (the `ports` block) and the
3115 // ports tail's report, beside the Qualify panel's own selection and
3116 // its rects (`qualify:*`).
3117 crate::automation::registry::publish("__brepQualifyHit", "Qualify panel widget rects (qualify:*)", &self.qualify.hits_json());
3118 // The family table as the Family table pane last read it, its
3119 // problems, selection and the last Generate report; and its rects.
3120 crate::automation::registry::publish("__brepFamilyHit", "Family table pane widget rects (family:*)", &self.family_table.hits_json());
3121 // The PMI block + report + active view / open annotation, and the
3122 // PMI panel's rects (`pmi:capture`, `pmi:add`, `pmi:add:<type>`,
3123 // `pmi:row:<id>`, `pmi:cell:<id>:<column>`, `pmi:menu:<id>`, the
3124 // form's `pmi:` keys).
3125 crate::automation::registry::publish("__brepPluginsHit", "Declarative plugin panel action controls", &self.plugins.panel_hits_json());
3126 crate::automation::registry::publish("__brepPmiHit", "PMI panel widget rects (pmi:*)", &self.pmi.hits_json());
3127 // The `sheets` block, which sheet the viewport draws, and the OPEN
3128 // sheet's whole projection — the paper, the visible edge runs and
3129 // the annotations that passed the parallel rule, in millimetres.
3130 // The panel's rects (`sheets:add`, `sheets:place:<view>`,
3131 // `sheets:row:<id>`, the form's `sheets:` keys) ride beside it.
3132 crate::automation::registry::publish("__brepSheetsHit", "Sheets panel widget rects (sheets:*)", &self.sheets.hits_json());
3133 crate::automation::registry::publish("__brepInfoWindowsHit", "info window widget rects", &self.info_windows.hits_json());
3134 crate::automation::registry::publish("__brepInterferenceHit", "interference panel widget rects", &self.interference.hits_json());
3135 crate::automation::registry::publish("__brepAutoConstraintsHit", "auto-constraints widget rects", &self.auto_constraints.hits_json());
3136 crate::automation::registry::publish("__brepStepPartsHit", "STEP parts library widget rects", &self.step_parts.hits_json());
3137 crate::automation::registry::publish("__brepSelectionHit", "selection bar widget rects (filter:kind, clear, hide)", &self.selection.hits_json());
3138 crate::automation::registry::publish("__brepContextHit", "context action bar widget rects", &self.context_bar.hits_json());
3139 crate::automation::registry::publish("__brepPickBarHit", "focused pick bar widget rects (bar, finish, cancel, x<i>)", &self.pick_bar.hits_json());
3140 crate::automation::registry::publish("__brepModeBarHit", "mode bar widget rects (refsel:*, Sketch:*)", &self.mode_bar.hits_json());
3141 // The DOCUMENT TABS: the open models, which one is active, and the
3142 // strip's per-tab hit-rects, so an e2e script can switch and close
3143 // documents the way a user does.
3144 crate::automation::registry::publish(
3145 "__brepDocumentsHit",
3146 "document tab strip widget rects",
3147 &crate::automation::hit_rects::hits_json(
3148 self.document_tab_hits.iter().map(|(key, rect)| (key, rect)),
3149 ),
3150 );
3151 // The boot-time recovery prompt: its entries and its two buttons.
3152 crate::automation::registry::publish("__brepRecoveryHit", "recovery prompt widget rects", &self.recovery.hits_json());
3153 #[cfg(target_arch = "wasm32")]
3154 crate::automation::registry::publish("__brepMobileDock", "compact dock drawer controls", &self.dock.mobile_state_json());
3155 #[cfg(target_arch = "wasm32")]
3156 crate::automation::registry::publish("__brepMobileSketch", "compact sketch entity drawer controls", &serde_json::json!({
3157 "compact": compact, "open": entity_drawer_open,
3158 "rects": serde_json::from_str::<serde_json::Value>(&crate::automation::hit_rects::hits_json(mobile_sketch_hits.iter())).unwrap_or_default(),
3159 }).to_string());
3160 crate::automation::registry::publish("__brepSketchHit", "sketch-mode overlay widget rects: the SKETCH ACTIONS card (constraint:glyph fix construction cleanup delete) \u{2014} empty out of sketch mode. The draw tools are NOT here: they are workbench buttons in the toolbar row (toolbar/workbench:btn:sketch.tool.* and sketch.autoconstrain)", &self.sketch.hits_json(self.docs.engine()));
3161 crate::automation::registry::publish("__brepSketchListHit", "sketch entity-list widget rects: section:* geometry:id point:id constraint:id del:kind:id panel:clip (empty out of sketch mode)", &self.sketch.list_hits_json(self.docs.engine()));
3162 crate::automation::registry::publish("__brepSketch3dHit", "3D sketch-mode overlay widget rects: the 3D SKETCH ACTIONS card (constraint:type fix construction delete) \u{2014} empty out of 3D sketch mode. The draw tools and the working-plane radio are workbench buttons in the toolbar row (toolbar/workbench:btn:sketch3d.tool.* and sketch3d.plane.*)", &self.sketch3d.hits_json(self.docs.engine()));
3163 crate::automation::registry::publish("__brepSketch3dListHit", "3D sketch entity-list widget rects: section:* geometry:id point:id constraint:id del:kind:id reference:name unlink:name panel:clip (empty out of 3D sketch mode)", &self.sketch3d.list_hits_json(self.docs.engine()));
3164 // Viewport origin + projected probe points (viewport-local logical
3165 // px) so the verifier can click precise spots ON the Box and ON the
3166 // Pin during ref-select mode. Index 0 is a Box top-corner clear of the
3167 // pin; indices 1..4 are points on the Pin's cylindrical stub that
3168 // protrudes above the Box top (y=20), on the camera-facing sides — the
3169 // verifier tries them until one picks "Pin".
3170 crate::automation::registry::publish("__brepView", "the 3D viewport rect {x,y,w,h} in egui points", &self.viewport.viewport_rect_json());
3171 // Dock layout snapshot (per-pane visible / rendered) so the verifier
3172 // can see which side panels are on-screen and, once a user tabs panels
3173 // together, activate the right tab before asserting on its widgets.
3174 // `active=false` in sketch / ref-select (the dock is bypassed).
3175 crate::automation::registry::publish("__brepDock", "dock layout in tab-strip order: per-pane visible/activeTab/rendered", &self.dock.state_json(!sketch && pick_layout.shows_dock()));
3176 crate::automation::registry::publish("__brepProbe", "projected seed-model probe points (viewport-local px) for the verifier",
3177 &self
3178 .docs
3179 .engine()
3180 .world_to_screen_json(
3181 "[[2.0,20.0,2.0],[14.243,22.5,14.243],[16.0,22.5,10.0],\
3182 [10.0,22.5,16.0],[10.0,25.0,10.0]]",
3183 )
3184 .unwrap_or_else(|_| "[]".to_string()),
3185 );
3186 }
3187
3188 // The viewport renders only a dirty engine. A panel drawn after it this
3189 // frame may have marked it dirty: draw that on the next frame instead of
3190 // waiting for the next input event.
3191 if self.docs.engine().dirty {
3192 ctx.request_repaint();
3193 }
3194
3195 // Phase 3 of the automation frame (§4.4): reads answer from THIS frame's
3196 // registry and layout.
3197 #[cfg(feature = "automation")]
3198 self.drain_reads(&ctx);
3199
3200 #[cfg(target_arch = "wasm32")]
3201 crate::viewport::touch::publish_editor(&ctx);
3202
3203 // NOTE: the 3D viewport is no longer drawn here — it is a dock tile drawn
3204 // earlier this frame (normal mode) or drawn directly in the sketch /
3205 // ref-select branch above. Drawing it before the top-right overlay is what
3206 // keeps that overlay anchored to the live viewport rect.
3207 }
3208}
3209
3210
3211/// Mirror an engine JSON string to `window.<name>` (wasm/verification only).
3212
3213/// Whether a launch opens on [`seed_history_json`]: the caller asked for the
3214/// seed and the user has not turned it off with the "Start with an empty
3215/// document" setting (`disableStartupModel`).
3216pub(crate) fn starts_on_seed_model(seed: bool, settings: &brep_render::style::RenderSettings) -> bool {
3217 seed && !settings.disable_startup_model
3218}
3219
3220/// The seed model handed to the engine at startup: a 3-feature history so the
3221/// tree / roll / edit are real —
3222/// 0. `P.CU` "Box" — a 20 mm cube at the origin (spans `[0,20]³`).
3223/// 1. `P.CY` "Pin" — a r=6, h=30 cylinder (axis +Y) positioned to pierce the
3224/// cube through its centre in XZ (x=10, z=10) from below (y=-5) to above.
3225/// 2. `B` "Cut" — SUBTRACT: `targetSolid = Box`, tools `[Pin]` → the cube
3226/// with a cylindrical through-hole (the ref-select field is visible for the
3227/// next slice). Roll-to-step shows: cube → cube+cylinder → subtracted cube.
3228///
3229/// This is just the INITIAL document — once handed to `EngineState`, the engine
3230/// OWNS the mutable history; the app keeps no copy.
3231pub(crate) fn seed_history_json() -> String {
3232 serde_json::json!({
3233 "expressions": "",
3234 "configurator": {},
3235 "features": [
3236 {
3237 "type": "P.CU",
3238 "inputParams": {
3239 "id": "Box",
3240 "sizeX": 20.0, "sizeY": 20.0, "sizeZ": 20.0,
3241 "transform": {
3242 "position": [0.0, 0.0, 0.0],
3243 "rotationEuler": [0.0, 0.0, 0.0],
3244 "scale": [1.0, 1.0, 1.0]
3245 },
3246 "boolean": { "targets": [], "operation": "NONE", "mergeCoplanarFaces": true }
3247 },
3248 "persistentData": {}
3249 },
3250 {
3251 "type": "P.CY",
3252 "inputParams": {
3253 "id": "Pin",
3254 "radius": 6.0, "height": 30.0,
3255 "transform": {
3256 "position": [10.0, -5.0, 10.0],
3257 "rotationEuler": [0.0, 0.0, 0.0],
3258 "scale": [1.0, 1.0, 1.0]
3259 },
3260 "boolean": { "targets": [], "operation": "NONE", "mergeCoplanarFaces": true }
3261 },
3262 "persistentData": {}
3263 },
3264 {
3265 "type": "B",
3266 "inputParams": {
3267 "id": "Cut",
3268 "targetSolid": "Box",
3269 "boolean": { "operation": "SUBTRACT", "targets": ["Pin"], "mergeCoplanarFaces": true }
3270 },
3271 "persistentData": {}
3272 }
3273 ]
3274 })
3275 .to_string()
3276}