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