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