Skip to main content

brep_app/
app.rs

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