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