Skip to main content

brep_app/
app.rs

1//! `BrepApp` — the THIN shell of the engine-native UI.
2//!
3//! One 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::part_properties::PartPropertiesPanel;
38use crate::panels::settings::SettingsPanel;
39use crate::panels::toasts::Toasts;
40use crate::panels::toolbar::ToolbarPanel;
41use crate::panels::workbench_toolbar::WorkbenchToolbarPanel;
42use crate::panels::update_components::UpdateComponents;
43use crate::panels::bom::BomPanel;
44use crate::panels::dock::{DockContext, DockState, PaneKind};
45use crate::panels::document_tabs;
46use crate::store::{default_model_store, ModelStore, SETTINGS_KEY};
47use crate::viewport::Viewport;
48use brep_render::engine_state::EngineState;
49use brep_render::style::ThemeMode;
50use eframe::egui;
51
52/// A measured camera spin: an orbit drag the app steps ITSELF, one pointer move
53/// per frame, from `perf_spin`. See [`BrepApp::spin`] for why it is not driven
54/// from outside.
55///
56/// The steps run through the same `EngineState::pointer_down/move/up` the
57/// viewport's real drag uses (see `viewport::interaction`), so a spin costs
58/// exactly what dragging the mouse costs — no shortcut past the controls.
59#[cfg(feature = "automation")]
60pub struct Spin {
61    /// Pointer steps still to make; the drag ends (pointer_up) on the last one.
62    pub left: u32,
63    /// Where the drag started, in viewport-local logical px.
64    pub origin: (f64, f64),
65    /// Pointer step, in viewport-local logical px per frame.
66    pub step: (f64, f64),
67    /// Steps already made — the drag is a straight sweep from `origin`, and
68    /// reversing at the halfway mark keeps it inside the viewport however many
69    /// frames are asked for.
70    pub made: u32,
71    /// False until the first frame has pressed the button.
72    pub pressed: bool,
73}
74
75pub struct BrepApp {
76    /// Every OPEN MODEL and which one is active. Each document owns a full
77    /// `EngineState` (the shared viewer brain `desktop.rs` / the wasm shell
78    /// wrap) plus its file identity; panels borrow the active one.
79    pub(crate) docs: Documents,
80    /// The central 3D viewport: engine render core + offscreen texture + blit +
81    /// input routing.
82    pub(crate) viewport: Viewport,
83    /// The single persistence seam for settings, layout, and model documents
84    /// (native filesystem / wasm IndexedDB + download/upload).
85    pub(crate) model_store: Box<dyn ModelStore>,
86
87    // --- one small state value per panel --------------------------------------
88    /// Top toolbar: undo/redo, wireframe toggle, zoom-to-fit + standard views,
89    /// and the File-actions seam (owned by the concurrent file panel).
90    pub(crate) toolbar: ToolbarPanel,
91    /// New / Open / Save / Save As of the model document (the `.nbrep`
92    /// recipe) — a reusable modal file dialog opened from the toolbar.
93    file: FileDialog,
94    stl_import: Option<crate::panels::stl_import::StlImportPreview>,
95    /// The "Submit Bug" flow: on the toolbar bug button it screenshots the app
96    /// (UI + 3D model) BEFORE its own dialog opens, then collects a description
97    /// (+ optional email) and POSTs the model + screenshot to the public reports
98    /// endpoint. Native + wasm, one path.
99    bug_report: BugReportPanel,
100    /// The Info window: the licences and this session's diagnostics, toggled
101    /// from the toolbar's info button.
102    info: crate::panels::info::InfoPanel,
103    /// What this session is running on — captured ONCE, from the adapter eframe
104    /// actually gave us (never re-probed), and read by BOTH the Info window and
105    /// the problem report so the two cannot disagree. See
106    /// [`crate::diagnostics`].
107    diagnostics: crate::diagnostics::Diagnostics,
108    /// Workbench actions toolbar: the second top strip under the primary
109    /// toolbar — one button per feature the active workbench offers, plus the
110    /// constraint types where the Constraints panel is shown. Gated by the
111    /// `showWorkbenchToolbar` setting and hidden in the special modes. A click
112    /// flows out as the type to add; the shell adds it through the SAME paths
113    /// the palette / context bar use.
114    workbench_toolbar: WorkbenchToolbarPanel,
115    /// Display-settings + per-solid color panel (Phase 1): a FLOATING window
116    /// (movable + resizable, toggled from the toolbar gear button), no longer a
117    /// left-panel section.
118    settings: SettingsPanel,
119    pub(crate) plugins: crate::plugins::PluginsPanel,
120    pub(crate) javascript: crate::javascript::JavaScriptEditor,
121    /// The active document's OWN BOM attributes (Part Number, Material, Mass,
122    /// …) as a floating window, toggled from the toolbar's Properties button.
123    /// Document-level, not selection-level: entity inspection is the context
124    /// bar's `info_windows`.
125    part_properties: PartPropertiesPanel,
126    /// History feature-tree + schema-driven feature dialog panel (Phase 2).
127    /// NOTE: the editable history is NOT owned here — it lives in the engine core
128    /// (`EngineState.history`), the single source of truth; this panel only reads
129    /// it back to draw and calls the engine's `history_*` methods to mutate.
130    history: HistoryPanel,
131    /// Scene tree ("Scene Manager"): the display scene as a file-tree — per-solid
132    /// visibility + Faces/Edges/Vertices with two-way selection sync. Reads the
133    /// engine scene/emphasis; owns only transient expand + hit state.
134    scene: ScenePanel,
135    /// Assembly Structure tree (claimed by the Assembly workbench): a VIEW over
136    /// the scene's component records — per-instance fixed/visibility/status
137    /// adornments, actions routed to the owning ACOMP feature.
138    /// The BOM panel (claimed by the Assembly workbench): the parts list on
139    /// the shared column-tree widget, with the editable part/occurrence
140    /// attribute columns the Settings "Assemblies" section configures.
141    bom: BomPanel,
142    /// Assembly Constraints panel (claimed by the Assembly workbench): the
143    /// schema-driven constraint collection widget + Solve/auto-solve/DOF header.
144    assembly_constraints: AssemblyConstraintsPanel,
145    /// The wire-harness connection list (a Wire harness workbench pane): add /
146    /// edit / remove wires, read their routed length + status, hover to
147    /// highlight. Document data lives in the engine; this holds the widget's
148    /// transient state.
149    wire_harness: WireHarnessPanel,
150    /// The PMI view tree + annotation forms (the PMI workbench's pane).
151    pmi: crate::panels::pmi::PmiPanel,
152    /// The drawing sheets + their forms (the Drawing workbench's pane).
153    sheets: crate::panels::sheets::SheetsPanel,
154    /// Update-components checker: compares each parts-library entry's
155    /// `sourceSignature` against the model store's current content. Kept
156    /// current once per frame (cheap generation key: applied run + store
157    /// save); the constraints header reads the count + runs the batch refresh,
158    /// the structure tree reads per-part badges.
159    update_components: UpdateComponents,
160    /// Expressions / parameters panel: the variable sheet (engine-owned history
161    /// `expressions`) feature params reference. Owns only its editor buffer.
162    expressions: ExpressionsPanel,
163    /// Qualify: the part's declared CONNECTION POINTS, on whichever surface is
164    /// on screen (symbol, pads or 3D). Holds only the selected address; the
165    /// block and both consistency reports come from the engine.
166    qualify: crate::panels::qualify::QualifyPanel,
167    /// The family table editor: a `.fbrep` family seed's member table. Holds
168    /// the selection, the cell being typed and the last Generate report; the
169    /// table itself is the document's `familyTable` block.
170    family_table: crate::panels::family_table_editor::FamilyTableEditor,
171    /// Every PLM panel (`panels::plm_host`): empty in a file-based session.
172    pub(crate) plm: crate::panels::plm_host::PlmHost,
173    /// Info windows: MULTIPLE pinned per-entity inspector windows opened from the
174    /// selection-driven context bar's Info action. Each floating (movable +
175    /// resizable) window is PINNED to one object name at open time — a Metadata
176    /// (editable attribute) tab + a read-only Info (measurements + provenance) tab —
177    /// and keeps showing that entity regardless of later selection changes. Replaces
178    /// the old single Properties window.
179    info_windows: InfoWindows,
180    /// Interference results window: opened by the Assembly workbench's `∩`
181    /// toolbar button, which runs the engine's pairwise-intersect check; a
182    /// floating window like the Info windows with a row per interfering pair
183    /// (click = select both components), a green all-clear pass line, and a
184    /// Re-run button.
185    interference: crate::panels::interference::InterferenceWindow,
186    /// Auto Constraints window (Assembly workbench): opened by the `⚿` toolbar
187    /// button, it lists the constraint types the kernel's inference lane can
188    /// read out of the components' current placement, with what a scan found
189    /// for each, and creates the whole accepted set as one undo step.
190    auto_constraints: crate::panels::auto_constraints::AutoConstraintsWindow,
191    /// step.parts online model library browser (Assembly workbench): a ctx-level
192    /// window (opened by the library toolbar button) that searches the public
193    /// step.parts v1 API, shows results with thumbnails, and imports a chosen
194    /// STEP model as a new part document + adds it to the assembly as an ACOMP.
195    step_parts: crate::panels::step_parts::StepPartsPanel,
196    /// Selection panel: the pickable-kinds filter (which entity kinds a viewport
197    /// click may select — honored by the engine's `select_top_at`). The filter +
198    /// selection live in `EngineState`; this panel only reads/writes them.
199    selection: SelectionPanel,
200    /// Context action toolbar: the selection-driven action bar (Clear / Hide /
201    /// Edit-owning-feature + the feature-from-selection actions whose primary
202    /// reference accepts the selected kind). Shown only while something is
203    /// selected; drives the engine directly and returns a feature id for the shell
204    /// to expand in the history tree.
205    context_bar: ContextBarPanel,
206    /// Sketch (S0): a seeded, read-only sketch preview — pushes a solved rectangle
207    /// + circle to the `set_overlay` channel colored by solver mobility, and shows
208    /// the DOF status readout. The engine-native sketcher's foundation surface.
209    sketch: SketchPanel,
210    /// Special-mode EXIT controls (Finish/Cancel), always pinned to the top-right
211    /// corner — reference-selection, sketch mode, and any future special mode.
212    mode_bar: ModeBar,
213    /// Transient toast overlay: drains the engine's queued notices each frame
214    /// (e.g. a sketch solve that failed after an edit) and shows each briefly.
215    pub(crate) toasts: Toasts,
216    /// The status bar's app-wide working indicator (`panels::busy`): what is
217    /// in flight, collected from every source each frame.
218    busy: crate::panels::busy::BusyIndicator,
219    /// Dockable / tabbed side-panel layout (egui_tiles): the shared, persisted
220    /// tree that hosts every side-panel section AND the 3D viewport as tiles the
221    /// user can split, tab, resize, and drag-rearrange. Owns the layout; borrows
222    /// each panel + the engine per frame through [`DockContext`]. Drawn in normal
223    /// modeling mode; sketch / ref-select mode bypasses it (viewport drawn direct).
224    dock: DockState,
225
226    /// Whether the ONE-SHOT first-model framing has fired. The seed run is async
227    /// under a background runner (native thread / wasm worker), so the boot
228    /// `zoom_to_fit` can run before the first solids exist → an unframed first
229    /// model. Once the seed run has landed (`has_solids() && !run_pending()`), the
230    /// `ui` loop frames it once and sets this. Under the synchronous Inline runner
231    /// (tests) the scene is already populated, so this fires on the very first frame.
232    first_run_framed: bool,
233
234    /// A model fetch kicked off at boot from a `?loadModel=<url>` query param
235    /// (wasm only). When the fetch lands it REPLACES the seed model. `None` on
236    /// native and once applied.
237    pending_boot_load: Option<std::sync::mpsc::Receiver<Result<String, String>>>,
238
239    /// "Open in CAD" from the PLM's page: the `?open=part/…/rev/…` this page
240    /// was started with (wasm only), driven once a frame until it settles.
241    plm_launch: Option<crate::panels::plm_launch::Launch>,
242
243    /// The document handle the shared panels were last reset for. Compared to
244    /// `docs.active_id()` at the top of every frame: ONE check catches a switch
245    /// from any source (a tab click, a close, New, Open, Edit Part) instead of a
246    /// hook per call site, and it runs BEFORE any panel draws this frame.
247    active_document: u64,
248
249    /// Whether the active workbench showed the Sheets pane LAST frame — the
250    /// edge the paper is closed on. Closing is a transition, not a condition:
251    /// a sheet opened while another workbench is active (a command, a script)
252    /// stays open until the Drawing workbench is LEFT, exactly as PMI's view
253    /// deactivates on leaving rather than on every frame outside it.
254    sheets_pane_shown: bool,
255
256    /// The DOCUMENT TAB STRIP's per-tab hit-rects from the last dock frame,
257    /// published for the headed verifier. The strip is drawn inside the dock's
258    /// viewport pane, so its rects have to ride back out through the outcome.
259    document_tab_hits: Vec<(String, egui::Rect)>,
260
261    /// The `__brepParams` blob and the document state it was built from:
262    /// `(document, rolled-to step, history revision, json)`.
263    ///
264    /// The blob is the rolled-to feature's whole `inputParams`, and for an
265    /// `IMPORT3D` those params carry the embedded model text — 681 KB on the
266    /// heaviest corpus model. It was rebuilt EVERY frame, which on the browser
267    /// build (where the state registry is always on) also transcoded it into a
268    /// fresh JS string every frame, on the one thread that also has to answer
269    /// the pointer. Nothing reads it per frame; it only has to be correct when
270    /// someone asks. The revision is a mutation counter the document hands out
271    /// (`EngineState::history_revision`), so this cannot go stale without the
272    /// borrow checker having let a mutation past the door that bumps it.
273    params_blob: (u64, usize, u64, String),
274
275    /// A measured camera spin in flight (`perf_spin`): the orbit drag the app
276    /// drives ITSELF, one pointer step per frame, so the frames run back to back.
277    /// Driving it from a host instead would put a round trip between every pair
278    /// of frames, and `dt` — the frame period, the number a user feels as a
279    /// freeze — would measure the host's latency rather than the app's.
280    #[cfg(feature = "automation")]
281    spin: Option<Spin>,
282
283    /// The debounced autosave of every dirty document (`crate::recovery`), and
284    /// the boot-time **Recover unsaved work?** prompt its blob feeds. The
285    /// autosave is held while the prompt is open: the clean seed tab would
286    /// otherwise remove the very blob being offered.
287    autosave: crate::recovery::Autosave,
288    recovery: crate::recovery::RecoveryPanel,
289
290    /// The UI zoom scale CURRENTLY applied to the egui context. Tracks
291    /// `settings.ui_scale` but is only synced to it while the pointer is up, so
292    /// dragging the Settings "UI scale" slider doesn't rescale the whole UI under
293    /// the cursor mid-drag — the settled value is committed on release. See the
294    /// zoom-apply block in `ui`.
295    applied_ui_scale: f32,
296    /// The automation channel (hosts submit commands; the frame drains them at
297    /// three fixed points — see `automation::queue`).
298    #[cfg(feature = "automation")]
299    pub(crate) automation: std::sync::Arc<crate::automation::queue::AutomationQueue>,
300}
301
302impl BrepApp {
303    /// The automation queue a host submits commands to.
304    #[cfg(feature = "automation")]
305    pub fn automation(&self) -> &std::sync::Arc<crate::automation::queue::AutomationQueue> {
306        &self.automation
307    }
308
309    /// Open a `.nbrep` file named on the command line — `brep-app model.nbrep`,
310    /// which is also what a desktop file association hands us (`Exec=… %f`).
311    ///
312    /// The path goes through the same `FileDialog::open_document` door as
313    /// File>Open, so the document keeps the full path as its identity and a
314    /// later plain Save writes back to the file the user double-clicked, rather
315    /// than to a copy in the app's own models directory. A path that does not
316    /// parse leaves the status line saying so and the seed document in place —
317    /// a bad argument must not cost the user a window.
318    ///
319    /// Native only: called once, before the first frame.
320    #[cfg(not(target_arch = "wasm32"))]
321    pub fn open_path_from_command_line(&mut self, path: &std::path::Path) {
322        // Absolute, so the store resolves it as a real file rather than as a
323        // name inside the models directory (`store::resolve` routes anything
324        // with a separator straight to the filesystem).
325        let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
326        let Some(name) = path.to_str() else {
327            log::warn!("brep-app: {} is not valid UTF-8; not opening it", path.display());
328            return;
329        };
330        // Field-by-field, because `open_document` borrows the documents and the
331        // store while `self.file` is borrowed mutably.
332        let Self { file, docs, model_store, .. } = self;
333        file.open_document(docs, model_store.as_ref(), name);
334    }
335
336    /// The 3D viewport rect of the last frame, in egui points.
337    pub fn view_rect(&self) -> Option<egui::Rect> {
338        self.viewport.last_rect()
339    }
340
341    /// The session's store, read-only (the automation layer's `frame_info`
342    /// counts its writes still on their way).
343    pub(crate) fn model_store(&self) -> &dyn ModelStore {
344        self.model_store.as_ref()
345    }
346
347    /// Why this session cannot switch stores live, or `None` when it can: every
348    /// open document untitled and clean, the state a fresh start has. A named
349    /// document's identity belongs to the store it came from, and a dirty one's
350    /// work has nowhere to go in a new store.
351    pub(crate) fn reconnect_blocker(&self) -> Option<String> {
352        self.reconnect_blocker_with(crate::document::Document::is_dirty)
353    }
354
355    fn reconnect_blocker_with(&self, is_dirty: impl Fn(&crate::document::Document) -> bool) -> Option<String> {
356        let named = self.docs.iter().filter(|d| d.name().is_some()).count();
357        let dirty = self.docs.iter().filter(|d| is_dirty(d)).count();
358        match (named, dirty) {
359            (0, 0) => None,
360            (_, 0) => Some(format!("{named} document(s) from this store are open: close them, then Connect now (or restart)")),
361            _ => Some(format!("{dirty} document(s) have unsaved work: save or close them, then Connect now (or restart)")),
362        }
363    }
364
365    /// Switch this session to the PLM configured at `root`, live (S1's named
366    /// limit): the native boot S2 runs at start, then everything the app read
367    /// from the store when it was built is read again from the new one. Only
368    /// while [`Self::reconnect_blocker`] is `None`. A refused boot changes
369    /// nothing and says why.
370    #[cfg(not(target_arch = "wasm32"))]
371    pub(crate) fn reconnect_plm(&mut self, root: std::path::PathBuf) -> Result<String, String> {
372        use crate::plm::connection::Status;
373        if let Some(why) = self.reconnect_blocker() {
374            return Err(why);
375        }
376        let config = crate::plm::config::resolve(&root, &|_| None, &Default::default())?
377            .ok_or_else(|| format!("no PLM is configured in {}", root.display()))?;
378        let store = crate::store::boot_native_store(root, config);
379        let Some(Status::Connected { url, username }) = store.plm_session().map(|s| s.status) else {
380            let why = store.take_persistence_errors().join("; ");
381            return Err(if why.is_empty() { "the PLM did not take this session".into() } else { why });
382        };
383        self.model_store = store;
384        // Settings: every open engine, and every later tab, starts from the
385        // defaults with the new store's settings over them, as a fresh boot
386        // would; nothing of the old store's carries over.
387        let saved = self.model_store.read(SETTINGS_KEY);
388        let fresh = move |mut state: EngineState| {
389            state.settings = brep_render::style::RenderSettings::default();
390            let defaults = state.settings.to_json();
391            let _ = state.apply_settings_json(&defaults);
392            if let Some(saved) = &saved {
393                let _ = state.apply_settings_json(saved);
394            }
395            state
396        };
397        for doc in self.docs.iter_mut() {
398            let engine = std::mem::replace(&mut doc.engine, EngineState::new());
399            doc.engine = fresh(engine);
400        }
401        self.docs.wrap_engine_factory(fresh);
402        self.dock = DockState::new(self.model_store.as_ref());
403        self.recovery.arm_from_store(
404            self.model_store.as_ref(),
405            self.docs.engine().settings.disable_recovery_prompt,
406        );
407        self.file = FileDialog::new();
408        self.update_components = UpdateComponents::new();
409        Ok(format!("connected to {url} as {username}"))
410    }
411
412    /// The file dialog, the documents and the store together — for the
413    /// automation commands that drive a document-class flow (Generate, a
414    /// store read-back) exactly as the panels do.
415    pub(crate) fn file_docs_store(&mut self) -> (&mut FileDialog, &mut Documents, &dyn ModelStore) {
416        (&mut self.file, &mut self.docs, self.model_store.as_ref())
417    }
418
419    /// The active document's engine.
420    pub fn docs_engine(&self) -> &EngineState {
421        self.docs.engine()
422    }
423
424    /// Open the mesh import preview for the file `name` (`.stl` or `.3mf`)
425    /// against the active document — what activating it in the Import explorer
426    /// does. The preview replaces the shell until it is accepted or cancelled.
427    pub fn open_mesh_preview(&mut self, name: String, bytes: Vec<u8>) -> Result<(), String> {
428        use brep_render::runner::MeshImportFormat;
429        let format = match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {
430            Some("stl") => MeshImportFormat::Stl,
431            Some("3mf") => MeshImportFormat::ThreeMf,
432            _ => return Err(format!("{name} is not an STL or 3MF file")),
433        };
434        self.start_mesh_preview(format, name, bytes);
435        Ok(())
436    }
437
438    fn start_mesh_preview(&mut self, format: brep_render::runner::MeshImportFormat, name: String, bytes: Vec<u8>) {
439        self.stl_import = Some(crate::panels::stl_import::StlImportPreview::new(
440            self.docs.active_id(), format, name, bytes, self.docs.spawn_engine(),
441        ));
442        self.viewport.forget_document();
443    }
444
445    /// Whether the mesh import preview is open.
446    pub fn mesh_preview_open(&self) -> bool {
447        self.stl_import.is_some()
448    }
449
450    pub fn new(cc: &eframe::CreationContext<'_>) -> Result<Self, String> {
451        Self::new_with(cc, crate::automation::AppOptions::default())
452    }
453
454    /// Build the app with host-supplied options: an isolated store (a host
455    /// MUST pass one) and whether to start on the seed model.
456    pub fn new_with(cc: &eframe::CreationContext<'_>, opts: crate::automation::AppOptions) -> Result<Self, String> {
457        // Keep overflow discoverable without hovering or scrolling first, in
458        // both themes and every child UI (including eCAD and plugin panels).
459        // ScrollArea's default VisibleWhenNeeded still hides bars that aren't needed.
460        cc.egui_ctx.all_styles_mut(|style| {
461            style.spacing.scroll = egui::style::ScrollStyle::solid();
462        });
463        let crate::automation::AppOptions { store: opt_store, seed } = opts;
464        let render_state = cc
465            .wgpu_render_state
466            .as_ref()
467            .ok_or_else(|| "eframe was not created with a wgpu render state".to_string())?;
468
469        // The viewport owns the render core + blit pipeline, built from eframe's
470        // SHARED device/queue/format.
471        let viewport = Viewport::new(render_state);
472
473        // The session's diagnostics, taken from that same render state: the
474        // adapter about to draw every frame is the one a report must name. The
475        // WebGPU-vs-WebGL2 decision has already been made by the time we get
476        // here (eframe drops `BROWSER_WEBGPU` from the backend set when the
477        // browser offers no WebGPU adapter), so this READS the outcome — asking
478        // again later would be a second question with its own answer.
479        let diagnostics = crate::diagnostics::Diagnostics::from_render_state(render_state);
480
481        // --- storage seam: load the persisted settings ------------------------
482        let model_store = opt_store.unwrap_or_else(default_model_store);
483        // wasm: hand the store the egui context so an async file-upload load
484        // callback can wake the reactive frame loop (see `store::set_repaint_ctx`).
485        #[cfg(target_arch = "wasm32")]
486        crate::store::set_repaint_ctx(cc.egui_ctx.clone());
487        let saved_settings = model_store.read(SETTINGS_KEY);
488
489        // --- how a document's engine is built --------------------------------
490        // Every tab gets its OWN engine, and therefore its own history runner —
491        // a runner owns the resident kernel state of the document it executes,
492        // so one shared between documents would apply a background run against
493        // the wrong registry. See `crate::document`.
494        let plugins = crate::plugins::PluginsPanel::new(model_store.as_ref());
495        let javascript = crate::javascript::JavaScriptEditor::new(model_store.as_ref());
496        let plugin_packages = plugins.packages.clone();
497        let engine_factory: EngineFactory = Box::new(move || {
498            let mut state = EngineState::new();
499            // Native: run the whole history — and per-object measurement queries — on a
500            // persistent background thread so the UI never freezes during a run or a
501            // selection (M2b). Installed BEFORE anything loads so it builds through it.
502            #[cfg(not(target_arch = "wasm32"))]
503            state.set_runner(Box::new(brep_render::runner::ThreadRunner::new()));
504            // wasm: the browser-thread analogue — a dedicated web worker (M3b) so the
505            // single-threaded wasm UI stays responsive during a run. Same seam. Tests
506            // (which never hit this wasm path) keep the default synchronous InlineRunner.
507            #[cfg(target_arch = "wasm32")]
508            state.set_runner(Box::new(crate::worker::WorkerRunner::new()));
509            if !plugin_packages.borrow().is_empty() {
510                if let Err(error) = crate::plugins::restore(&mut state, &plugin_packages.borrow()) {
511                    log::error!("Plugin restore failed: {error}");
512                }
513            }
514            state.set_viewcube_enabled(true);
515            // Partial-override apply: unknown/absent keys keep their defaults.
516            if let Some(saved) = &saved_settings {
517                let _ = state.apply_settings_json(saved);
518            }
519            state
520        });
521
522        // Start with the seed model on every launch (7626103c2). Reopening the
523        // previous session can immediately rerun a problematic document and
524        // prevent the user from recovering by restarting the app, so which
525        // documents were open is not persisted at all: saved models come back
526        // through the file dialog, and work that was never saved comes back as
527        // the crash-recovery OFFER below — a prompt, never an automatic load.
528        let mut docs = Documents::new(engine_factory);
529        let _ = docs.engine_mut().set_history_json(if seed { seed_history_json() } else { crate::document::EMPTY_DOCUMENT.to_string() }.as_str());
530        docs.engine_mut().zoom_to_fit();
531        docs.active_mut().mark_clean();
532
533        // The autosave blob from a session that ended with unsaved work: offer
534        // it back (a prompt, never an automatic restore — see `crate::recovery`).
535        let mut recovery = crate::recovery::RecoveryPanel::new();
536        recovery.arm_from_store(model_store.as_ref(), docs.engine().settings.disable_recovery_prompt);
537
538        // The settings panel seeds its working JSON from the (post-load) engine
539        // settings so the widgets reflect the persisted state on first paint.
540        let settings = SettingsPanel::new();
541        let part_properties = PartPropertiesPanel::new();
542
543        // New / Open / Save / Save As. Holds no document identity — that lives
544        // on each `Document`.
545        let file = FileDialog::new();
546
547        // Boot at the saved UI scale.
548        let applied_ui_scale = docs.engine().settings.ui_scale;
549        let active_document = docs.active_id();
550
551        // The dock layout (loads the persisted tree, or the default). Built before
552        // `model_store` is moved into `Self`.
553        let dock = DockState::new(model_store.as_ref());
554
555        // Boot-load: if the page URL carries `?loadModel=<url>` (wasm only), start
556        // fetching that model NOW; the seed still loads this frame and the fetched
557        // model REPLACES it when it lands (drained in `ui`). See the drain block.
558        crate::offsite::prefetch();
559        #[cfg(target_arch = "wasm32")]
560        let pending_boot_load = web_sys::window()
561            .and_then(|w| w.location().search().ok())
562            .and_then(|search| web_sys::UrlSearchParams::new_with_str(&search).ok())
563            .and_then(|params| params.get("loadModel"))
564            .filter(|url| !url.is_empty())
565            .map(|url| crate::offsite::fetch_text(&cc.egui_ctx, "Opening a model from a link", url));
566        #[cfg(not(target_arch = "wasm32"))]
567        let pending_boot_load: Option<std::sync::mpsc::Receiver<Result<String, String>>> = None;
568        #[cfg(target_arch = "wasm32")]
569        let plm_launch = crate::panels::plm_launch::Launch::from_page();
570        #[cfg(not(target_arch = "wasm32"))]
571        let plm_launch = None;
572
573        Ok(Self {
574            docs,
575            viewport,
576            toolbar: ToolbarPanel::new(),
577            workbench_toolbar: WorkbenchToolbarPanel::new(),
578            model_store,
579            file,
580            stl_import: None,
581            bug_report: BugReportPanel::new(),
582            info: crate::panels::info::InfoPanel::new(),
583            diagnostics,
584            settings,
585            plugins,
586            javascript,
587            part_properties,
588            history: HistoryPanel::new(),
589            scene: ScenePanel::new(),
590            bom: BomPanel::new(),
591            assembly_constraints: AssemblyConstraintsPanel::new(),
592            wire_harness: WireHarnessPanel::new(),
593            pmi: crate::panels::pmi::PmiPanel::new(),
594            sheets: crate::panels::sheets::SheetsPanel::new(),
595            update_components: UpdateComponents::new(),
596            expressions: ExpressionsPanel::new(),
597            qualify: crate::panels::qualify::QualifyPanel::new(),
598            family_table: crate::panels::family_table_editor::FamilyTableEditor::new(),
599            plm: crate::panels::plm_host::PlmHost::new(),
600            info_windows: InfoWindows::new(),
601            interference: crate::panels::interference::InterferenceWindow::new(),
602            auto_constraints: crate::panels::auto_constraints::AutoConstraintsWindow::new(),
603            step_parts: crate::panels::step_parts::StepPartsPanel::new(),
604            selection: SelectionPanel::new(),
605            context_bar: ContextBarPanel::new(),
606            sketch: SketchPanel::new(),
607            mode_bar: ModeBar::new(),
608            toasts: Toasts::new(),
609            busy: crate::panels::busy::BusyIndicator::new(),
610            dock,
611            first_run_framed: false,
612            pending_boot_load,
613            plm_launch,
614            active_document,
615            sheets_pane_shown: false,
616            document_tab_hits: Vec::new(),
617            params_blob: (u64::MAX, usize::MAX, u64::MAX, String::new()),
618            #[cfg(feature = "automation")]
619            spin: None,
620            autosave: crate::recovery::Autosave::new(),
621            recovery,
622            applied_ui_scale,
623            #[cfg(feature = "automation")]
624            automation: {
625                let q = crate::automation::queue::AutomationQueue::new();
626                q.attach(&cc.egui_ctx);
627                q
628            },
629        })
630    }
631
632    /// Arm a measured camera spin: `frames` pointer steps of `step` logical px
633    /// each, starting at the centre of the 3D viewport. Replaces any spin in
634    /// flight. See [`Spin`].
635    #[cfg(feature = "automation")]
636    pub fn start_spin(&mut self, frames: u32, step: (f64, f64)) {
637        let rect = self.viewport.last_rect();
638        let origin = rect
639            .map(|r| (r.width() as f64 * 0.5, r.height() as f64 * 0.5))
640            .unwrap_or((320.0, 240.0));
641        self.spin = Some(Spin { left: frames.max(1), origin, step, made: 0, pressed: false });
642    }
643
644    /// Is a measured spin still running?
645    #[cfg(feature = "automation")]
646    pub fn spinning(&self) -> bool {
647        self.spin.is_some()
648    }
649
650    /// Advance an in-flight spin by ONE pointer step and keep the frame loop
651    /// awake. The drag sweeps out and back over a fixed span so it never leaves
652    /// the viewport however many frames are asked for; the camera keeps turning
653    /// either way, which is all the measurement needs.
654    #[cfg(feature = "automation")]
655    fn step_spin(&mut self, ctx: &egui::Context) {
656        let Some(mut spin) = self.spin.take() else { return };
657        {
658            let state = self.docs.engine_mut();
659            if !spin.pressed {
660                state.pointer_down(spin.origin.0, spin.origin.1, brep_render::controls::BUTTON_LEFT);
661                spin.pressed = true;
662            }
663            const SPAN: f64 = 60.0;
664            let phase = f64::from(spin.made % (2 * SPAN as u32));
665            let t = if phase <= SPAN { phase } else { 2.0 * SPAN - phase };
666            state.pointer_move(spin.origin.0 + spin.step.0 * t, spin.origin.1 + spin.step.1 * t);
667            spin.made += 1;
668            spin.left -= 1;
669            if spin.left == 0 {
670                state.pointer_up();
671            }
672        }
673        if spin.left > 0 {
674            self.spin = Some(spin);
675        }
676        ctx.request_repaint();
677    }
678
679    /// The `__brepParams` JSON, rebuilt only when the document it describes can
680    /// have changed. The `params_blob` FIELD carries the reason this is not
681    /// simply built afresh each frame.
682    fn params_blob(&mut self) -> &str {
683        let key = (
684            self.docs.active_id(),
685            self.docs.engine().history_rollback(),
686            self.docs.engine().history_revision(),
687        );
688        if (self.params_blob.0, self.params_blob.1, self.params_blob.2) != key {
689            self.params_blob = (
690                key.0,
691                key.1,
692                key.2,
693                self.docs.engine().feature_params_json(key.1),
694            );
695        }
696        &self.params_blob.3
697    }
698
699    /// Global keyboard shortcuts (egui input): **Ctrl/Cmd+Z** undo,
700    /// **Ctrl/Cmd+Shift+Z** or **Ctrl/Cmd+Y** redo, **Esc** clears the selection
701    /// — unless a popup or menu is up, which the Escape closes instead.
702    ///
703    /// `Modifiers::COMMAND` is Ctrl on Windows/Linux and ⌘ on macOS, so one map
704    /// covers both. Skipped entirely while an egui TEXT edit is focused so typing
705    /// (and text-field Ctrl+Z / Esc-to-defocus) is never hijacked. Redo is
706    /// consumed BEFORE undo because egui's `consume_key` matches modifiers
707    /// logically (a plain `COMMAND+Z` pattern would also swallow `COMMAND+Shift+Z`).
708    fn handle_shortcuts(&mut self, ctx: &egui::Context) {
709        // A modal owns every key: its Escape closes it, and nothing under it —
710        // undo, a Delete, the selection — is the key's to change.
711        if ctx.text_edit_focused() || crate::viewport::modal_open_last_pass(ctx) {
712            return;
713        }
714        use egui::{Key, Modifiers};
715        // A popup or menu that was up last frame owns this Escape: it closes on
716        // `key_pressed(Escape)`, which a consumed key never is, so the key is
717        // left in the input for it and nothing below acts on it — not the
718        // sketch tool, not a pick, and not the selection its menu is about.
719        let popup_open = crate::viewport::popup_open_last_pass(ctx);
720        // On an eCAD workbench, Delete and Escape are the editor's keys, and
721        // whether they reach it is the editors' ONE rule, `keys_reach_editor`
722        // (a text field, a menu or combo box, a modal), not a copy of it here.
723        // The watch above is the host's own addition: egui's popup memory does
724        // not see the host's `open_bool` menus (a tree row's), and those own
725        // their Escape on every workbench.
726        let ecad_target = crate::workbench::ecad::Target::of_workbench(&self.docs.engine().settings.workbench);
727        let keys_free = match ecad_target {
728            Some(_) => !popup_open && brep_ecad_egui::keys_reach_editor(ctx),
729            None => !popup_open,
730        };
731        if crate::javascript::JavaScriptEditor::editing_source(ctx) {
732            return;
733        }
734        let (redo, undo, esc) = ctx.input_mut(|i| {
735            let redo = i.consume_key(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z)
736                || i.consume_key(Modifiers::COMMAND, Key::Y);
737            let undo = i.consume_key(Modifiers::COMMAND, Key::Z);
738            let esc = keys_free && i.consume_key(Modifiers::NONE, Key::Escape);
739            (redo, undo, esc)
740        });
741        // While editing a sketch, Ctrl+Z / Ctrl+Shift+Z drive the PER-SESSION sketch
742        // history (S6a), not the model-level undo — this global router consumes the
743        // keys first (before the viewport), so it must intercept here. Esc drops the
744        // active draw/trim/pick tool back to Select/drag (clearing any in-progress
745        // placement): this is the ONLY reliable capture point, since `consume_key`
746        // above already swallowed the Escape before the viewport can see it.
747        if self.docs.engine().sketch_mode() {
748            if redo {
749                self.docs.engine_mut().sketch_redo();
750            }
751            if undo {
752                self.docs.engine_mut().sketch_undo();
753            }
754            if esc {
755                self.docs.engine_mut().sketch_set_tool(Some("select"));
756            }
757            return;
758        }
759        if redo {
760            self.docs.engine_mut().redo();
761        }
762        if undo {
763            self.docs.engine_mut().undo();
764        }
765        if let Some(target) = ecad_target {
766            if keys_free && !self.docs.engine().ref_select_active() {
767                let delete = ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Delete)
768                    || i.consume_key(Modifiers::NONE, Key::Backspace));
769                if delete {
770                    self.docs.active_mut().ecad.selection_key(target, true);
771                }
772            }
773        } else {
774            self.delete_selected_annotation(ctx);
775        }
776        if esc {
777            // An open pick-list popup owns the first Escape: close it WITHOUT
778            // clearing the selection (a popup-built multi-selection must survive
779            // dismissing the list); the next Escape clears as before.
780            if self.viewport.close_candidate_popup() {
781                return;
782            }
783            // A REFERENCE PICK owns the next one — a 3D pick or anchors on a
784            // drawing sheet alike — and Escape has to CANCEL it
785            // rather than merely clear the selection. Beginning a pick ROLLS THE
786            // MODEL BACK to the step before the edited feature so the picker sees
787            // the geometry that feature is about to consume; Finish and Cancel
788            // both restore that roll through `end_ref_select`. Escape used to do
789            // neither: it cleared the selection, left the picker open and left the
790            // history PARKED before the feature, so the feature stopped running
791            // and the viewport quietly showed the model without it. Measured on
792            // the retired `rotate-face.json`, which read the seed volume back at its
793            // closed-form step with the feature never re-run.
794            if self.docs.engine().ref_select_active() {
795                self.docs.engine_mut().cancel_ref_select();
796                return;
797            }
798            // A family-row preview owns the next one: Escape leaves the
799            // preview (the family's own values again) and keeps the selection.
800            if self.family_table.escape_preview(self.docs.engine_mut()) {
801                return;
802            }
803            // The global router owns Escape before the viewport runs its keys.
804            if let Some(target) = ecad_target {
805                self.docs.active_mut().ecad.selection_key(target, false);
806                return;
807            }
808            self.docs.engine_mut().clear_selection();
809        }
810    }
811
812    /// DELETE (or Backspace) removes the selected object of the OPEN drawing
813    /// sheet — a placed view, a sheet dimension or an ordinate set, picked on
814    /// the paper or in the Sheets tree — or, with no sheet open, the selected
815    /// PMI annotation while the PMI workbench is up. Either goes through the
816    /// destructive entry of the object's own row menu, so the key and the menu
817    /// do the same thing (and it is one undo step, like the menu's).
818    ///
819    /// The key is consumed only when there IS something to delete. Never a
820    /// SHEET or a PMI VIEW: each takes everything placed on it with it, and
821    /// both stay behind their menus' Delete. Nothing while a reference pick is
822    /// up — deleting the object whose references are being picked would
823    /// strand the picker. (Called after the text-edit and sketch-mode returns,
824    /// so a Backspace typed into a field, or a sketch's own Delete, never gets
825    /// here.)
826    fn delete_selected_annotation(&mut self, ctx: &egui::Context) {
827        use egui::{Key, Modifiers};
828        let engine = self.docs.engine();
829        if engine.ref_select_active() {
830            return;
831        }
832        let target = if engine.sheet_open().is_some() {
833            engine.sheet_selected_object().map(|id| (true, id.to_string()))
834        } else if engine.pmi_workbench_entered() {
835            engine.pmi_selected_annotation().map(|id| (false, id.to_string()))
836        } else {
837            None
838        };
839        let Some((on_sheet, id)) = target else {
840            return;
841        };
842        let pressed = ctx.input_mut(|i| {
843            i.consume_key(Modifiers::NONE, Key::Delete) || i.consume_key(Modifiers::NONE, Key::Backspace)
844        });
845        if !pressed {
846            return;
847        }
848        let engine = self.docs.engine_mut();
849        let result = if on_sheet {
850            crate::panels::sheets::delete_held_object(engine, &id)
851        } else {
852            crate::panels::pmi::delete_annotation(engine, &id)
853        };
854        if let Err(error) = result {
855            engine.push_notice(format!("{}: {error}", if on_sheet { "Sheets" } else { "PMI" }));
856        }
857    }
858
859    /// Open the component source, offering to recover a missing file from the
860    /// assembly's embedded part definition.
861    fn edit_part(&mut self, component_id: &str) {
862        self.file.edit_component_part(
863            &mut self.docs,
864            self.model_store.as_ref(),
865            component_id,
866        );
867    }
868
869    /// Draw an isolated preview while the destination document remains untouched.
870    /// Hand the working indicator this frame's work, most important first:
871    /// the active document's runner queues, a boot load, the STEP parts
872    /// library's downloads, then every background document's queues.
873    fn collect_busy(&mut self, ctx: &egui::Context) {
874        use crate::panels::busy::{engine_activities, Activity};
875        let active = self.docs.active_index();
876        let mut activities = engine_activities(self.docs.engine(), self.docs.active_id(), None);
877        if self.pending_boot_load.is_some() {
878            activities.push(Activity::new("boot", "boot", "Loading document"));
879        }
880        activities.extend(self.step_parts.busy_activities());
881        activities.extend(self.file.busy_activities());
882        // A write-behind store (the browser's IndexedDB) still settling saves.
883        let saving = self.model_store.pending_writes();
884        if saving > 0 {
885            let label = match saving {
886                1 => "Saving to browser storage".to_string(),
887                n => format!("Saving to browser storage ({n} writes)"),
888            };
889            activities.push(Activity::new("storeWrite", "storeWrite", label));
890        }
891        for (index, doc) in self.docs.iter().enumerate() {
892            if index != active {
893                activities.extend(engine_activities(&doc.engine, doc.id(), Some(&doc.title())));
894            }
895        }
896        self.busy.update(activities, ctx.input(|i| i.time));
897        self.busy.request_repaint(ctx);
898    }
899
900    fn show_stl_preview(&mut self, ui: &mut egui::Ui) -> bool {
901        use crate::panels::stl_import::PreviewAction;
902        let Some(preview) = self.stl_import.as_mut() else {
903            return false;
904        };
905        let action = if preview.destination != self.docs.active_id() {
906            PreviewAction::Cancel
907        } else {
908            preview.show(ui, &mut self.viewport)
909        };
910        if crate::automation::registry::enabled() {
911            let _publish_span = crate::perf::span(crate::perf::Phase::Publish);
912            crate::automation::registry::publish("__brepImportPreview", "STL/OBJ import preview state (tolerances, counts, accept readiness); null when no preview is open", &preview.state_json());
913            crate::automation::registry::publish("__brepImportPreviewHit", "import preview dialog widget rects", &preview.hits_json());
914            crate::automation::registry::publish("__brepCamera", "camera state: kind, eye, target, up, near/far, projection block, worldPerPixel", &preview.engine.camera_state_json());
915            crate::automation::registry::publish("__brepPpp", "pixels per point of the surface", &format!("{}", ui.ctx().pixels_per_point()));
916            crate::automation::registry::publish("__brepHistory", "history listing {step, features:[{index,type,id}]}", &self.docs.engine().history_listing_json());
917            crate::automation::registry::publish("__brepDocuments", "open document tabs {active, tabs:[{title,name,dirty}]}", &document_tabs::state_json(&self.docs));
918        }
919        let close = match action {
920            PreviewAction::Accept => {
921                match preview.accept_into(self.docs.active_id(), self.docs.engine_mut()) {
922                    Ok(()) => true,
923                    Err(error) => {
924                        self.docs.engine_mut().push_notice(error);
925                        false
926                    }
927                }
928            }
929            PreviewAction::Cancel => true,
930            PreviewAction::None => false,
931        };
932        if close {
933            self.stl_import = None;
934            self.viewport.forget_document();
935            ui.ctx().request_repaint();
936        }
937        true
938    }
939
940    /// Phase 3 of the automation frame (§4.4): read-only commands answer from
941    /// THIS frame's registry and layout. A method rather than a block at the
942    /// end of `ui` because the import preview returns from that function early
943    /// and still owes the frame its reads.
944    #[cfg(feature = "automation")]
945    fn drain_reads(&mut self, ctx: &egui::Context) {
946        let queue = self.automation.clone();
947        let frame = ctx.cumulative_frame_nr();
948        queue.drain_app(
949            crate::automation::command::Phase::Read,
950            &mut crate::automation::command::Ctx { app: self, egui: ctx },
951            frame,
952        );
953    }
954
955    /// Reset everything the shared panels and the viewport hold ABOUT ONE
956    /// DOCUMENT, run at the top of the first frame that sees a different active
957    /// document.
958    ///
959    /// Panel state is deliberately NOT per-document (one History panel, one
960    /// Scene tree, …): a second copy per tab would double every panel's state
961    /// for a benefit — remembering which feature form was open in a background
962    /// tab — nobody asked for. The price is that the transient state has to be
963    /// dropped on a switch, because every bit of it (expansion sets, hit maps,
964    /// an open feature form, a pinned Info window's object name) refers to the
965    /// document that just went away.
966    fn reset_document_scoped_state(&mut self) {
967        self.history = HistoryPanel::new();
968        self.scene = ScenePanel::new();
969        self.bom = BomPanel::new();
970        self.assembly_constraints = AssemblyConstraintsPanel::new();
971        self.wire_harness = WireHarnessPanel::new();
972        self.pmi = crate::panels::pmi::PmiPanel::new();
973        self.sheets = crate::panels::sheets::SheetsPanel::new();
974        self.expressions = ExpressionsPanel::new();
975        self.qualify = crate::panels::qualify::QualifyPanel::new();
976        self.family_table = crate::panels::family_table_editor::FamilyTableEditor::new();
977        // A family-row preview left on in a document the user comes back to
978        // would have no pane state to show or end it: switching ends it.
979        self.docs.engine_mut().set_expression_preview(None);
980        // Pinned to object NAMES of the old document ("Box" exists in most of
981        // them), so these would silently retarget rather than go blank.
982        self.info_windows = InfoWindows::new();
983        self.interference = crate::panels::interference::InterferenceWindow::new();
984        self.auto_constraints = crate::panels::auto_constraints::AutoConstraintsWindow::new();
985        // The outdated-parts cache keys on `(applied_generation, save_generation)`,
986        // and two documents' generations are unrelated — a switch can land on the
987        // same key with an entirely different parts library.
988        self.update_components.invalidate();
989        self.viewport.forget_document();
990    }
991
992    /// A signature of the CURRENT rendered model (rolled-to step) — solid count,
993    /// per-solid triangle count + bbox, and total triangles. Published to JS so
994    /// the headed verifier can prove each roll / edit produced different geometry
995    /// (names alone don't: a SUBTRACT reuses the target's name).
996    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
997    fn model_signature_json(&self) -> String {
998        let solids: Vec<serde_json::Value> = self
999            .docs
1000            .engine()
1001            .scene
1002            .solids()
1003            .iter()
1004            .map(|s| {
1005                serde_json::json!({
1006                    "name": s.name,
1007                    "tris": s.mesh.indices.len() / 3,
1008                    "min": s.bbox.min,
1009                    "max": s.bbox.max,
1010                })
1011            })
1012            .collect();
1013        let total_tris: usize = self
1014            .docs
1015            .engine()
1016            .scene
1017            .solids()
1018            .iter()
1019            .map(|s| s.mesh.indices.len() / 3)
1020            .sum();
1021        serde_json::json!({
1022            "step": self.docs.engine().history_rollback(),
1023            "solidCount": solids.len(),
1024            "totalTris": total_tris,
1025            "solids": solids,
1026        })
1027        .to_string()
1028    }
1029
1030    /// Open or close the floating Settings window — the toolbar gear's flag,
1031    /// reachable from the automation layer (`settings_window`).
1032    pub fn set_settings_window_open(&mut self, open: bool) {
1033        self.settings.open = open;
1034    }
1035
1036    /// Open or close the floating Part Properties window — the toolbar tag
1037    /// button's flag, reachable from the automation layer
1038    /// (`part_properties_window`).
1039    pub fn set_part_properties_window_open(&mut self, open: bool) {
1040        self.part_properties.open = open;
1041    }
1042
1043    /// Open or close the floating Info window — the toolbar info button's flag,
1044    /// reachable from the automation layer (`info_window`).
1045    pub fn set_info_window_open(&mut self, open: bool) {
1046        self.info.open = open;
1047    }
1048
1049    /// What this session is running on. The app's ONE record of it: the Info
1050    /// window draws it, a problem report carries it, the `diagnostics` command
1051    /// returns it and the MCP banner names its adapter — all from here.
1052    pub fn diagnostics(&self) -> &crate::diagnostics::Diagnostics {
1053        &self.diagnostics
1054    }
1055
1056    /// Begin the in-app problem report: the same call the Submit Bug button
1057    /// makes, and for the same reason it makes it THIS frame — `request`
1058    /// captures the current frame before its own dialog exists.
1059    pub fn begin_bug_report(&mut self, ctx: &egui::Context) {
1060        self.bug_report.request(ctx, self.docs.engine(), &self.diagnostics);
1061    }
1062
1063    /// Activate an available declarative panel using its stable package ID.
1064    pub(crate) fn show_plugin_panel(&mut self, id: &str) -> Result<(), String> {
1065        self.dock.show_plugin_panel(self.docs.engine(), id)
1066    }
1067
1068    /// Bring a built-in dock pane to the front (`show_pane`).
1069    pub fn show_pane(&mut self, kind: PaneKind) {
1070        self.dock.show_pane(kind);
1071    }
1072
1073    /// The parts-library staleness check and its refresh — the Constraints
1074    /// header's "Update components (N)" button, reachable as the
1075    /// `component_update` command. Returns `(outdated, missing, refreshed)`;
1076    /// `run` is skipped when nothing is outdated.
1077    pub fn update_components(&mut self, run: bool) -> Result<(usize, Vec<String>, usize), String> {
1078        let store = self.model_store.as_ref();
1079        self.update_components.ensure_current(self.docs.engine_mut(), store, self.file.save_generation());
1080        let outdated = self.update_components.outdated_count();
1081        let missing = self.update_components.missing().to_vec();
1082        let refreshed = if run { self.update_components.run(self.docs.engine_mut(), store)? } else { 0 };
1083        Ok((outdated, missing, refreshed))
1084    }
1085
1086    /// Frame what the central tile is actually DRAWING: the OPEN SHEET's paper
1087    /// when a sheet is open, the 3D scene otherwise.
1088    ///
1089    /// This is where the fit branch lives, and it is here rather than in the
1090    /// toolbar because the two halves sit in different places — the 3D fit is an
1091    /// engine camera op (`EngineState::zoom_to_fit`) while the sheet's pan/zoom
1092    /// is viewport-transient state, refitted by clearing the marker the sheet
1093    /// paint compares against. One method, so the toolbar's Zoom-to-fit button
1094    /// and the `zoom_to_fit` command can never mean different things — and so
1095    /// the paper needs no Fit button of its own.
1096    ///
1097    /// The toolbar draws BEFORE the dock in `ui`, so a fit requested from the
1098    /// button lands on this very frame.
1099    pub fn zoom_to_fit(&mut self) {
1100        if self.docs.engine().sheet_open().is_some() {
1101            self.viewport.request_sheet_fit();
1102        } else {
1103            self.docs.engine_mut().zoom_to_fit();
1104        }
1105    }
1106
1107    /// Run what a WORKBENCH TOOLBAR button does, by its `WorkbenchButton::id`.
1108    ///
1109    /// Split out of `ui` so a toolbar click and the `workbench_button` command
1110    /// run the SAME arms: the workbench registry declares a button, this
1111    /// dispatches it, and the automation surface owns no second copy of the
1112    /// list. Returns whether the id was known.
1113    pub fn dispatch_workbench_button(&mut self, id: &str) -> bool {
1114        // The eCAD workbenches' buttons (Diagram, PCB, Symbol, Pads) are
1115        // eCAD's own actions: run on the active document's editors with
1116        // eCAD's `run_action`, so a press does exactly what eCAD's toolbar
1117        // button does. `None` is any other id, which falls through to the
1118        // arms below.
1119        if crate::workbench::ecad::dispatch(&mut self.docs.active_mut().ecad, id).is_some() {
1120            return true;
1121        }
1122        // The SHEET's constructions are the Drawing workbench's two tables plus
1123        // the section and the detail, and each press is the PMI annotation
1124        // buttons' workflow: the object is created on the open sheet with
1125        // nothing picked yet, and its dialog opens (through the dialog door,
1126        // which surfaces the Sheets pane) — where its reference rows are picked
1127        // on the paper with the reference picker.
1128        if let Some((kind, alignment)) = crate::workbench::drawing::dim_tool(id) {
1129            let engine = self.docs.engine_mut();
1130            if let Err(error) = engine.sheet_add_dimension(None, kind, Some(alignment), Vec::new()) {
1131                engine.push_notice(format!("Sheet dimension: {error}"));
1132            }
1133            return true;
1134        }
1135        if let Some(axis) = crate::workbench::drawing::ord_tool(id) {
1136            let engine = self.docs.engine_mut();
1137            if let Err(error) = engine.sheet_add_ordinate(None, axis, None, Vec::new()) {
1138                engine.push_notice(format!("Ordinate set: {error}"));
1139            }
1140            return true;
1141        }
1142        if id == crate::workbench::drawing::BOM_BUTTON_ID {
1143            let engine = self.docs.engine_mut();
1144            if let Err(error) = engine.sheet_insert_bom() { engine.push_notice(format!("BOM table: {error}")); }
1145            return true;
1146        }
1147        if id == crate::workbench::drawing::SECTION_BUTTON_ID {
1148            let engine = self.docs.engine_mut();
1149            if let Err(error) = engine.sheet_new_section(None) {
1150                engine.push_notice(format!("Section view: {error}"));
1151            }
1152            return true;
1153        }
1154        if id == crate::workbench::drawing::DETAIL_BUTTON_ID {
1155            let engine = self.docs.engine_mut();
1156            if let Err(error) = engine.sheet_new_detail(None) {
1157                engine.push_notice(format!("Detail view: {error}"));
1158            }
1159            return true;
1160        }
1161        // The SKETCH mode's draw tools are one table too, and they are SHARED —
1162        // every workbench's row carries them while a sketch is being edited, so
1163        // this arm answers for all of them whatever workbench is active.
1164        // Pressing the LIT tool puts it down (back to Select), matching the
1165        // sheet constructions above; pressing the lit Select is already Select.
1166        if let Some(tool) = crate::workbench::sketch::draw_tool(id) {
1167            let engine = self.docs.engine_mut();
1168            let armed = engine.sketch_active_tool().unwrap_or("select") == tool;
1169            engine.sketch_set_tool(Some(if armed { "select" } else { tool }));
1170            return true;
1171        }
1172        match id {
1173            // The sketch strip's one-shot action, now the row's: infer the
1174            // constraints the rough-in geometry already implies.
1175            crate::workbench::sketch::AUTOCONSTRAIN_BUTTON_ID => {
1176                self.docs.engine_mut().sketch_auto_constrain();
1177            }
1178            // Sheet Metal's flat pattern: open the export modal in its DXF /
1179            // SVG mode; the engine reports "no sheet-metal body in the part"
1180            // as a toast on export.
1181            "sheetmetal.flat_pattern" => {
1182                self.file.dispatch(FileAction::ExportFlatPattern, &mut self.docs, self.model_store.as_ref());
1183            }
1184            // Assembly's Add Component: open the insert-component modal (the
1185            // same flow as the ACOMP palette pick). ONE arm for both rows that
1186            // carry it — PCB BORROWS this very button (`workbench::BORROWED`)
1187            // rather than declaring a second id for the same action.
1188            crate::workbench::assembly::ADD_COMPONENT_BUTTON_ID => {
1189                self.file.dispatch(FileAction::InsertComponent, &mut self.docs, self.model_store.as_ref());
1190            }
1191            // Assembly's interference check: run the engine's pairwise
1192            // intersect sweep NOW and open the results window.
1193            "assembly.interference" => {
1194                self.interference.open_and_run(self.docs.engine_mut());
1195            }
1196            // Assembly's Auto Constraints: open the inference window and scan
1197            // the current placement NOW, so it opens showing real counts.
1198            "assembly.auto_constrain" => {
1199                self.auto_constraints.open_and_scan(self.docs.engine_mut());
1200            }
1201            // Assembly's step.parts library: open the online-library browser
1202            // (search → thumbnails → import a STEP part → add as an ACOMP).
1203            "assembly.step_parts_library" => {
1204                self.step_parts.open();
1205            }
1206            // Wire harness's Declare connection point: the part's FIRST port
1207            // group, with one point at the origin. It exists because the
1208            // Qualify pane is on screen only while the part declares some — so
1209            // without it a 3D-only part could never get its first one from the
1210            // UI at all. The pane is surfaced by the dock's own ports door on
1211            // the next frame, once the visibility pass has let it back in.
1212            crate::workbench::wire_harness::DECLARE_POINT_BUTTON_ID => {
1213                let engine = self.docs.engine_mut();
1214                engine.history.set_ports_block(
1215                    Some(serde_json::json!([{
1216                        "name": crate::workbench::wire_harness::FIRST_GROUP,
1217                        "purpose": crate::workbench::wire_harness::FIRST_PURPOSE,
1218                        "points": [{
1219                            "name": crate::workbench::wire_harness::FIRST_POINT,
1220                            "transform": {
1221                                "position": [0.0, 0.0, 0.0],
1222                                "rotationEuler": [0.0, 0.0, 0.0],
1223                            },
1224                        }],
1225                    }])),
1226                    None,
1227                );
1228            }
1229            // PMI's Capture view: snapshot the camera + visibility into a new
1230            // active view and surface the PMI pane so its row is seen.
1231            crate::workbench::pmi::CAPTURE_BUTTON_ID => {
1232                self.docs.engine_mut().pmi_capture_view(None);
1233                self.dock.show_pane(PaneKind::Pmi);
1234            }
1235            // Drawing's Back to 3D: leave the open sheet. The paper's own
1236            // widgets go with it, and the sheet keeps its contents — the same
1237            // edit the Sheets pane's Close sheet makes.
1238            crate::workbench::drawing::SHEET_CLOSE_BUTTON_ID => {
1239                let _ = self.docs.engine_mut().sheet_set_open(None);
1240                self.viewport.forget_sheet();
1241            }
1242            // Drawing's Add sheet: a new sheet, opened on the paper, and the
1243            // Sheets pane brought forward so its row is seen.
1244            crate::workbench::drawing::ADD_SHEET_BUTTON_ID => {
1245                self.docs.engine_mut().sheet_add(None);
1246                self.dock.show_pane(PaneKind::Sheets);
1247            }
1248            // Drawing's Place view: the first saved PMI view on the open sheet;
1249            // the placement's form opens (the door surfaces the pane), and its
1250            // `view` field is where a different view is chosen.
1251            crate::workbench::drawing::PLACE_VIEW_BUTTON_ID => {
1252                let engine = self.docs.engine_mut();
1253                let placed = match engine.sheet_pmi_view_ids().first().cloned() {
1254                    Some(view) => engine.sheet_place_view(None, &view, None, None).map(|_| ()),
1255                    None => Err("capture a PMI view in the PMI workbench first".to_string()),
1256                };
1257                if let Err(error) = placed {
1258                    engine.push_notice(format!("Place view: {error}"));
1259                }
1260            }
1261            _ => return false,
1262        }
1263        true
1264    }
1265
1266}
1267
1268impl eframe::App for BrepApp {
1269    /// Phase 1 of the automation frame (§4.4): queued input commands become
1270    /// egui events; a screenshot that landed completes its reply. Called by
1271    /// every eframe runner before `ui`; the headless host calls it itself.
1272    #[cfg(feature = "automation")]
1273    fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
1274        let view = self.viewport.last_rect();
1275        self.automation.drain_input(raw_input, ctx.cumulative_frame_nr(), ctx.pixels_per_point(), view, ctx);
1276    }
1277
1278
1279    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
1280        // Open this frame's timing window (banks the previous frame's phase
1281        // totals and its period) and bracket the whole body. See `perf`: on a
1282        // single-threaded shell a long frame IS a frozen UI, so what the frame
1283        // spends is the whole diagnosis.
1284        crate::perf::tick();
1285        let _ui_span = crate::perf::span(crate::perf::Phase::Ui);
1286
1287        // The native store and PLM queue (`plm::native`): every task whose I/O
1288        // answered since the last frame finishes here, on this thread, FIRST —
1289        // before any early return below (the mesh preview's replaces the whole
1290        // shell) can skip it. The browser drains its microtasks between events
1291        // the same way, whatever the page is showing.
1292        #[cfg(not(target_arch = "wasm32"))]
1293        crate::plm::native::run_pending();
1294        // A PLM save made mid-rebuild is pictured once its run lands.
1295        crate::plm::thumbnail::tick(|id| self.docs.iter().find(|d| d.id() == id).map(|d| &d.engine));
1296
1297        // --- global keyboard shortcuts (undo/redo/clear-selection) ------------
1298        // Handled before any panel draws so a Ctrl+Z etc. this frame takes effect
1299        // this frame. `ctx` is a cheap Arc clone (avoids borrowing `ui` across the
1300        // `&mut self` call).
1301        let ctx = ui.ctx().clone();
1302
1303        self.plugins.finish_installations(&mut self.docs, self.model_store.as_ref());
1304        self.plugins.sync_documents(&mut self.docs);
1305        self.javascript.poll(&ctx, &mut self.docs, self.model_store.as_ref());
1306        self.plugins.poll(&ctx, self.docs.engine_mut(), self.model_store.as_ref());
1307
1308        // Phase 2 of the automation frame (§4.4): mutations run before any
1309        // panel draws, so this frame shows their effect.
1310        #[cfg(feature = "automation")]
1311        {
1312            let queue = self.automation.clone();
1313            let frame = ctx.cumulative_frame_nr();
1314            queue.drain_app(
1315                crate::automation::command::Phase::Mutate,
1316                &mut crate::automation::command::Ctx { app: self, egui: &ctx },
1317                frame,
1318            );
1319        }
1320
1321        // A measured spin (`perf_spin`) advances one pointer step per frame, here
1322        // — after the mutation drain that may have armed it, so the spin starts
1323        // on the frame it was asked for.
1324        #[cfg(feature = "automation")]
1325        self.step_spin(&ctx);
1326
1327        // --- a different document is active than the panels were drawn for ----
1328        // Checked FIRST, before anything draws: the switch itself happened late
1329        // in some earlier frame (a tab click, a close, an Open), and every
1330        // shared panel is still holding the previous document's transient state.
1331        if self.active_document != self.docs.active_id() {
1332            if !self.javascript.running_in(self.active_document) {
1333                for doc in self.docs.iter_mut() { if doc.id() == self.active_document { doc.engine.cancel_plugin_action(); } }
1334            }
1335            self.plugins.close_action();
1336            self.active_document = self.docs.active_id();
1337            self.reset_document_scoped_state();
1338        }
1339
1340        // --- the workbench decides whether placed parts show their ports -------
1341        // A workbench that shows the Wire Harness panel (Wire harness, All)
1342        // draws the ports components carry; the others — Modeling included,
1343        // though it offers the Port feature — keep the assembly clean. A no-op
1344        // when nothing changed.
1345        {
1346            // The document's name lives in the SHELL (the tab, the file), and a
1347            // drawing sheet's title block prints it. Told to the engine here,
1348            // every frame, because that is where the active tab is known; a
1349            // no-op when it has not changed. It is the DISPLAY name, the one the
1350            // tab shows: a stamp reading `bracket.nbrep` would be naming our
1351            // file format rather than the drawing.
1352            let name = self
1353                .docs
1354                .active()
1355                .name()
1356                .map(crate::store::model_display_name)
1357                .unwrap_or_default();
1358            let engine = self.docs.engine_mut();
1359            engine.set_document_name(&name);
1360            let show = crate::workbench::panel_visible(
1361                &engine.settings.workbench,
1362                crate::workbench::wire_harness::PANEL_ID,
1363                &crate::workbench::ButtonState::of(engine),
1364            );
1365            engine.set_component_ports_visible(show);
1366            // The PMI workbench IS the PMI editing mode: a workbench that shows
1367            // the PMI panel (PMI, All) enters it — the modeling camera /
1368            // visibility / wireframe are remembered — and one that hides it
1369            // leaves it, deactivating the view and restoring them.
1370            let pmi_shown = crate::workbench::panel_visible(
1371                &engine.settings.workbench,
1372                crate::workbench::pmi::PANEL_ID,
1373                &crate::workbench::ButtonState::of(engine),
1374            );
1375            if pmi_shown && !engine.pmi_workbench_entered() {
1376                engine.pmi_enter_workbench();
1377            } else if !pmi_shown && engine.pmi_workbench_entered() {
1378                engine.pmi_leave_workbench();
1379            }
1380            // The DRAWING workbench owns the paper: LEAVING it for a workbench
1381            // that hides the Sheets pane closes an open sheet, so the central
1382            // tile is not left drawing paper whose tools, pane and way back are
1383            // all hidden. It is a MODE change — the sheets and their contents
1384            // are untouched — and an edge, see `sheets_pane_shown`.
1385            let sheets_shown = crate::workbench::panel_visible(
1386                &engine.settings.workbench,
1387                crate::workbench::drawing::SHEETS_PANEL_ID,
1388                &crate::workbench::ButtonState::of(engine),
1389            );
1390            if self.sheets_pane_shown && !sheets_shown && engine.sheet_open().is_some() {
1391                let _ = engine.sheet_set_open(None);
1392                self.viewport.forget_sheet();
1393            }
1394            self.sheets_pane_shown = sheets_shown;
1395        }
1396
1397        // --- GUI chrome theme -------------------------------------------------
1398        // Apply the user's theme preference to the egui chrome every frame
1399        // (idempotent: `set_theme` just stores the preference). Auto follows the
1400        // OS/system theme (prefers-color-scheme on web); egui falls back to dark
1401        // when no OS signal is available. This controls panels/windows/toolbar/
1402        // text only — the 3D viewport `background` is a separate setting.
1403        ctx.set_theme(match self.docs.engine().settings.theme {
1404            ThemeMode::Auto => egui::ThemePreference::System,
1405            ThemeMode::Light => egui::ThemePreference::Light,
1406            ThemeMode::Dark => egui::ThemePreference::Dark,
1407        });
1408
1409        // --- global UI size scale --------------------------------------------
1410        // Apply the user's "UI scale" to the whole egui chrome every frame. This
1411        // is idempotent when unchanged (`set_zoom_factor` only repaints on an
1412        // actual change) and composes with the native device pixel ratio
1413        // (pixels_per_point = zoom_factor * native_pixels_per_point).
1414        //
1415        // Defer live UI rescale while the user drags the Settings "UI scale" slider:
1416        // the slider value updates continuously, but only commit it to the actual egui
1417        // zoom once the pointer is released, so the whole UI doesn't rescale under the
1418        // cursor mid-drag.
1419        let pointer_down = ctx.input(|i| i.pointer.any_down());
1420        if !pointer_down {
1421            self.applied_ui_scale = self.docs.engine().settings.ui_scale;
1422        }
1423        ctx.set_zoom_factor(self.applied_ui_scale);
1424
1425        // --- history-runner pump ---------------------------------------------
1426        // Apply any completed background history run BEFORE panels read the scene.
1427        // For the synchronous InlineRunner this is a no-op (`rerun_history` already
1428        // pumped its own submit), so nothing changes today; it is the seam a future
1429        // native-thread / wasm-worker runner lands its reply through. While a run is
1430        // still in flight, keep the frame loop alive so its reply gets pumped — for
1431        // Inline `run_pending()` is always false, so this never fires.
1432        //
1433        // EVERY open document is pumped, not just the active one — see
1434        // `Documents::pump_all`, which also keeps the active document's parts
1435        // library in the kernel's store when a background tab's run lands.
1436        let work_in_flight = self.docs.pump_all();
1437        if work_in_flight {
1438            ctx.request_repaint();
1439        }
1440        if self.show_stl_preview(ui) {
1441            // The preview REPLACES the shell for the frame, and this early
1442            // return used to take the frame's READ drain with it: while a
1443            // preview was open every read-only automation command — `ping`,
1444            // `state_get`, `hit_rects`, a screenshot — went unanswered until
1445            // the host gave up on it, so no script could observe the preview it
1446            // had just opened. The preview publishes its own state and rects
1447            // above; this answers the reads that ask for them.
1448            #[cfg(feature = "automation")]
1449            self.drain_reads(&ctx);
1450            return;
1451        }
1452        if crate::automation::registry::enabled() {
1453            let _publish_span = crate::perf::span(crate::perf::Phase::Publish);
1454            crate::automation::registry::publish("__brepImportPreview", "STL/OBJ import preview state (tolerances, counts, accept readiness); null when no preview is open", "null");
1455        }
1456
1457        // The tab strip's dirty dots, refreshed once per frame (cheap — see
1458        // `Document::refresh_dirty_marker`).
1459        self.docs.refresh_dirty_markers();
1460
1461        // --- boot-load (?loadModel=): apply the fetched model once it lands ----
1462        // Replaces the seed with the URL-specified document (armed in `new`). The
1463        // ehttp callback wakes the frame loop, so a plain per-frame drain suffices.
1464        // `load_model_and_fit` arms deferred framing; the pump above reframes it
1465        // next frame. `mark_clean` opens it as a non-dirty document.
1466        if self.pending_boot_load.is_some() {
1467            let received = self
1468                .pending_boot_load
1469                .as_ref()
1470                .and_then(|rx| rx.try_recv().ok());
1471            if let Some(result) = received {
1472                self.pending_boot_load = None;
1473                match result {
1474                    Ok(json) => {
1475                        // REPLACES the seed in place rather than adding a tab.
1476                        // It lands on the document that is already active,
1477                        // whatever the session restored.
1478                        let _ = self.docs.engine_mut().load_model_and_fit(&json);
1479                        self.docs.active_mut().mark_clean();
1480                    }
1481                    Err(e) => self
1482                        .docs
1483                        .engine_mut()
1484                        .push_notice(format!("Could not load model from URL: {e}")),
1485                }
1486            }
1487        }
1488
1489        // --- "Open in CAD" (?open=part/…/rev/…) --------------------------------
1490        if let Some(launch) = self.plm_launch.as_mut() {
1491            use crate::panels::plm_launch::Step;
1492            let step = launch.step(self.model_store.as_ref(), &mut self.docs, &mut self.file);
1493            match &step {
1494                Step::SignIn(sentence) => {
1495                    self.settings.show_plm_tab();
1496                    self.docs.engine_mut().push_notice(sentence.clone());
1497                }
1498                Step::Refused(sentence) => self.docs.engine_mut().push_notice(sentence.clone()),
1499                _ => {}
1500            }
1501            if step.settles() {
1502                crate::panels::plm_launch::forget_query();
1503            }
1504            if launch.is_done() {
1505                self.plm_launch = None;
1506            } else {
1507                ui.ctx().request_repaint();
1508            }
1509        }
1510
1511        crate::panels::ecad_parts::sync(self.docs.active_mut());
1512        let requests = crate::panels::ecad_parts::take_open_requests(self.docs.active_mut());
1513        for key in requests {
1514            self.file.open_document(&mut self.docs, self.model_store.as_ref(), &key);
1515        }
1516        // The parts pane's Add part button presses Assembly's Add Component: one arm.
1517        if crate::panels::ecad_parts::take_add_part_request(self.docs.active_mut()) {
1518            self.dispatch_workbench_button(crate::workbench::assembly::ADD_COMPONENT_BUTTON_ID);
1519        }
1520        // The eCAD host's Update parts button is Constraints' Update components.
1521        if std::mem::take(&mut self.docs.active_mut().ecad_update_requested) {
1522            if let Err(error) = self.update_components.run(self.docs.engine_mut(), self.model_store.as_ref()) {
1523                self.docs.engine_mut().push_notice(format!("Update components: {error}"));
1524            }
1525        }
1526
1527        // --- update-components badge freshness ---------------------------------
1528        // Keep the outdated-parts checker current BEFORE any assembly panel draws
1529        // (the structure tree renders per-node badges ahead of the constraints
1530        // header). Cheap: a real recompute happens only when an applied run or a
1531        // successful store save moved the generation key.
1532        self.update_components.ensure_current(
1533            self.docs.engine_mut(),
1534            self.model_store.as_ref(),
1535            self.file.save_generation(),
1536        );
1537        // …and the eCAD host marks the components placed from those parts.
1538        self.docs.active_mut().ecad_outdated = self.update_components.outdated().to_vec();
1539
1540        // --- async-safe first-model framing -----------------------------------
1541        // The seed run is async under a background runner (native thread / wasm
1542        // worker), so the boot `zoom_to_fit` may have run before any solid existed.
1543        // Frame the model ONCE, the first frame the seed run has fully landed (solids
1544        // present AND no run still in flight). Under the synchronous Inline runner
1545        // (tests) both hold on the very first frame, so this is identical to today.
1546        if !self.first_run_framed
1547            && !self.docs.engine().run_pending()
1548            && self.docs.engine().has_solids()
1549        {
1550            self.docs.engine_mut().zoom_to_fit();
1551            self.first_run_framed = true;
1552        }
1553
1554        self.handle_shortcuts(&ctx);
1555
1556        // --- top toolbar: primary actions, drawn FIRST so its top strip is
1557        // reserved above the left panel + central viewport. A clicked File button
1558        // returns an action the file dialog acts on (open its modal / save / new).
1559        self.toolbar.read_only = !self.docs.active().access().is_editable();
1560        let doc = self.docs.active_mut();
1561        let toolbar_outcome = self.toolbar.show(
1562            ui,
1563            &mut doc.engine,
1564            Some(&doc.ecad),
1565            self.model_store.as_ref(),
1566            &mut self.settings.open,
1567            &mut self.part_properties.open,
1568            &mut self.info.open,
1569        );
1570        if toolbar_outcome.plugins { self.plugins.open = !self.plugins.open; }
1571        if toolbar_outcome.javascript { self.javascript.open = !self.javascript.open; }
1572        if let Some(id) = toolbar_outcome.plugin_action {
1573            if let Err(error) = self.plugins.open_action(self.docs.engine(), &id) { self.plugins.error = Some(error); }
1574        }
1575        self.plugins.active_document = self.docs.active_id();
1576        self.plugins.show(&ctx, self.docs.engine_mut(), self.model_store.as_ref());
1577        self.javascript.show(&ctx, &mut self.docs, self.model_store.as_ref());
1578        // An inbox row opens its review or change order in the PLM pane.
1579        for event in toolbar_outcome.plm_review {
1580            self.plm.open_review(event);
1581        }
1582        if let Some(name) = toolbar_outcome.recent_document {
1583            self.file
1584                .open_document(&mut self.docs, self.model_store.as_ref(), &name);
1585        }
1586        if let Some(action) = toolbar_outcome.file {
1587            self.file
1588                .dispatch(action, &mut self.docs, self.model_store.as_ref());
1589        }
1590        // Submit Bug: begin the screenshot-capture + report flow. `request`
1591        // grabs the current frame (before its dialog exists) and the model, so
1592        // it must run THIS frame while the shot is still dialog-free.
1593        if toolbar_outcome.bug_report {
1594            self.bug_report.request(&ctx, self.docs.engine(), &self.diagnostics);
1595        }
1596        // A workbench toolbar button click surfaces its id here; the dispatch
1597        // itself is a METHOD so the `workbench_button` command runs the very
1598        // same arms (a button an agent can only reach by clicking is a button
1599        // an agent cannot reach when something covers it).
1600        if let Some(id) = toolbar_outcome.workbench_button {
1601            self.dispatch_workbench_button(id);
1602        }
1603        // Zoom-to-fit: the ONE button frames whatever the tile draws — the open
1604        // sheet's paper, or the 3D scene. See `BrepApp::zoom_to_fit`.
1605        if toolbar_outcome.zoom_to_fit {
1606            self.zoom_to_fit();
1607        }
1608
1609        // --- workbench actions toolbar: a second strip directly UNDER the
1610        // primary toolbar (egui stacks top panels in call order) listing the
1611        // active workbench's creatable features + the constraint types. Off via
1612        // the Settings checkbox, and never in sketch / reference-selection mode
1613        // (the panel decides — see `WorkbenchToolbarPanel::visible`). A feature
1614        // click adds exactly what the palette pick would, so ACOMP still routes
1615        // to the component selector; a constraint click is the context bar's
1616        // constraint offer, seeded from the current selection.
1617        // A read-only document (a PLM revision not checked out, or released)
1618        // draws the strip disabled: every button on it creates something.
1619        self.workbench_toolbar.read_only = !self.docs.active().access().is_editable();
1620        let actions = if self.docs.engine().settings.toolbar_style
1621            == brep_render::style::ToolbarStyle::Classic
1622        {
1623            self.workbench_toolbar.show(ui, self.docs.engine())
1624        } else {
1625            self.workbench_toolbar
1626                .set_ribbon_hits(self.toolbar.home_hits());
1627            toolbar_outcome.creation
1628        };
1629        if let Some(type_code) = actions.feature {
1630            self.history
1631                .add_feature_of_type(self.docs.engine_mut(), &type_code);
1632            // No `show_pane` here: `HistoryPanel::open_form` moved the target and
1633            // the dialog door surfaces History for it (`surface_open_dialogs`
1634            // below). ACOMP opens the component-selector MODAL instead of a
1635            // feature dialog, so it moves no target and surfaces no pane.
1636            if self.history.take_insert_component_request() {
1637                self.file.dispatch(
1638                    FileAction::InsertComponent,
1639                    &mut self.docs,
1640                    self.model_store.as_ref(),
1641                );
1642            }
1643        }
1644        if let Some(type_id) = actions.constraint {
1645            // The strip offers every type regardless of the selection (unlike the
1646            // context bar's gated offers), so a refusal has to be SAID: a toast,
1647            // never a silent no-op. A document with no components has no assembly
1648            // session to add to (the kernel's own message names the session, not
1649            // the cause) — say what is actually missing.
1650            let engine = self.docs.engine_mut();
1651            if !engine.history_has_assembly() {
1652                engine.push_notice(
1653                    "Add constraint: the document has no components — insert a component first"
1654                        .to_string(),
1655                );
1656            } else {
1657                // The add leaves the new constraint OPEN (the kernel mints it
1658                // that way), so the dialog door surfaces the Constraints pane.
1659                if let Err(error) =
1660                    crate::panels::context_bar::add_constraint_from_selection(engine, &type_id)
1661                {
1662                    engine.push_notice(format!("Add constraint: {error}"));
1663                }
1664            }
1665        }
1666        if let Some(type_id) = actions.annotation {
1667            // The context bar's annotation offer, from the strip: seeded from
1668            // the selection, and the new annotation's form opens through the
1669            // dialog door. The strip offers every type whatever is selected, so
1670            // a refusal — no active view to add to — is said, not swallowed.
1671            let engine = self.docs.engine_mut();
1672            if let Err(error) = crate::panels::context_bar::add_pmi_from_selection(engine, &type_id) {
1673                engine.push_notice(format!("Add annotation: {error}"));
1674            }
1675        }
1676
1677        // --- sketch mode has NO strip of its own: its draw tools are workbench
1678        // buttons in the row above (`workbench::sketch`), offered while a sketch
1679        // is being edited, so the 3D viewport is the full-width sketching
1680        // surface with nothing between it and the one toolbar.
1681
1682        // --- bottom STATUS BAR: a persistent, full-width strip whose CONTENT is
1683        // chosen by context each frame. Drawn AFTER the top bars but BEFORE the
1684        // left panel(s) so it reserves the FULL bottom width and the left column
1685        // stops above it (egui resolves reserved space by call order). It is a
1686        // HOST: the branch below picks what to draw. A NEW context is added by
1687        // extending this branch (e.g. `else if engine.some_mode() { … }`) and
1688        // routing through the owning panel's `show_status_bar` for DRY styling.
1689        // Its top is the floor the toasts stack up from (`Toasts::show`).
1690        //
1691        // Its RIGHT END is the app-wide working indicator (`panels::busy`),
1692        // whatever the context: collected here from every source, drawn first
1693        // in a right-to-left row so the context content gets what is left of
1694        // the width and never runs under it.
1695        self.collect_busy(&ctx);
1696        let status_bar_top = egui::containers::panel::Panel::bottom("brep-status-bar")
1697            .resizable(false)
1698            .min_size(30.0)
1699            .show(ui, |ui| {
1700                ui.add_space(2.0);
1701                // `Align::Min`, not `Center`: the bar's height is not known
1702                // until its content is laid out, and centring against the
1703                // unbounded space below doubled the bar with the indicator on
1704                // a row of its own.
1705                ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
1706                    self.busy.show(ui);
1707                    ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
1708                        if self.docs.engine().sketch_mode() {
1709                            // Sketch context: the status row (title / DOF / N selected /
1710                            // undo-redo / Lock). The selection-filter row is NOT drawn
1711                            // now, so drop its stale hit-rects (the verifier must never
1712                            // click a phantom rect for an off-screen widget).
1713                            self.selection.clear_hits();
1714                            self.sketch.show_status_bar(ui, self.docs.engine_mut());
1715                        } else if crate::workbench::ecad::Target::of_workbench(&self.docs.engine().settings.workbench).is_some() {
1716                            // An eCAD editor owns the central tile, and a click there
1717                            // picks nothing 3D: the pickable-kinds filter would be a
1718                            // row of dead checkboxes. The strip carries the editor's
1719                            // own line instead: where the pointer is and what is under it.
1720                            self.selection.clear_hits();
1721                            self.viewport.show_ecad_status(ui);
1722                        } else {
1723                            // Modeling context: the selection filter (pickable kinds).
1724                            self.selection.show_status_bar(ui, self.docs.engine_mut());
1725                        }
1726                    });
1727                });
1728                ui.add_space(2.0);
1729            })
1730            .response
1731            .rect
1732            .top();
1733        // Cancel on the working indicator: sent to the document whose run it
1734        // named, which a background tab's run need not be the active one.
1735        if let Some(activity) = self.busy.take_cancel() {
1736            if let Some(doc) = self.docs.iter_mut().find(|doc| Some(doc.id()) == activity.document) {
1737                doc.engine.cancel_run();
1738            }
1739        }
1740
1741        // --- central region: the dock tree, OR (special modes) the bare 3D view
1742        // ---------------------------------------------------------------------
1743        // Normal modeling mode: ONE egui_tiles tree fills the whole remaining
1744        // area between the top toolbar and the bottom status bar. Every side-panel
1745        // section AND the 3D viewport are tiles the user can split / tab / resize /
1746        // drag-rearrange, and the layout persists. Which side panes are visible is
1747        // filtered per-workbench inside the dock (`workbench::panel_visible`).
1748        //
1749        // Sketch mode and reference-selection are "special modes" that take over
1750        // the shell: they BYPASS the tree and draw the viewport directly, so the
1751        // modeling side panes don't appear (sketch's own entity-list panel + the
1752        // top-right mode card own those flows). Drawing the viewport HERE — before
1753        // the top-right overlay below — keeps `viewport.last_rect()` current-frame
1754        // so the overlay anchors to the live 3D-view rect with no lag.
1755        let sketch = self.docs.engine().sketch_mode();
1756        let ref_select = self.docs.engine().ref_select_active();
1757
1758        if sketch {
1759            // Sketch entity lists (Curves / Points / Constraints) + solver
1760            // settings — a dedicated left panel, drawn BEFORE the viewport so it
1761            // reserves the left and the viewport fills the rest.
1762            egui::containers::panel::Panel::left("sketch-entities")
1763                .resizable(true)
1764                .default_size(300.0)
1765                .size_range(200.0..=560.0)
1766                .show(ui, |ui| {
1767                    self.sketch.show_entity_lists(ui, self.docs.engine_mut());
1768                });
1769        }
1770
1771        self.history.sync_palette_display(self.model_store.as_ref());
1772        // The PLM panels (a PLM session only): each PLM document's access from
1773        // its revision, and the revisions the user asked to open.
1774        let plm = self.plm.sync(self.model_store.as_ref(), &mut self.docs, self.file.save_generation());
1775        for name in plm.open {
1776            self.file.open_document(&mut self.docs, self.model_store.as_ref(), &name);
1777        }
1778        // A PLM section asked for a file (Attach a file…, Add file…): the file
1779        // chooser answers, and the file goes back to the section that asked.
1780        if let Some((tag, title)) = plm.pick_file {
1781            if let Err(error) = self.file.request_pick_file(self.model_store.as_ref(), &tag, &title) {
1782                self.file.status = error;
1783            }
1784        }
1785        for tag in self.plm.pick_tags() {
1786            if let Some(file) = self.file.take_picked_file(&tag) {
1787                self.plm.deliver_picked(&tag, file);
1788            }
1789        }
1790        if plm.refresh_inbox {
1791            self.toolbar.refresh_inbox();
1792        }
1793        // Save As → "A new part" (D9): the PLM pane's New part form, shown.
1794        if self.file.take_plm_new_part() {
1795            self.plm.open_new_part();
1796            self.show_pane(PaneKind::Plm);
1797        }
1798        if self.plm.busy() {
1799            ui.ctx().request_repaint();
1800        }
1801        // Following other clients (`panels::plm_follow`): when the feed moved,
1802        // the inbox asks again too; and the next question gets a frame.
1803        if self.plm.take_followed() {
1804            self.toolbar.refresh_inbox();
1805        }
1806        if let Some(next) = self.plm.next_follow_in() {
1807            ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(next.max(0.1)));
1808        }
1809        if sketch || ref_select {
1810            // Special mode: the viewport fills the remaining central area; no
1811            // dock, no modeling side panes — and therefore no DOCUMENT TAB
1812            // STRIP either, which is the guard that keeps a live sketch /
1813            // reference-pick session from having its document swapped out from
1814            // under it.
1815            self.viewport.show(ui, self.docs.engine_mut());
1816            DockState::retract_all(DockContext {
1817                docs: &mut self.docs,
1818                plugins: &mut self.plugins,
1819                viewport: &mut self.viewport,
1820                history: &mut self.history,
1821                bom: &mut self.bom,
1822                assembly_constraints: &mut self.assembly_constraints,
1823                wire_harness: &mut self.wire_harness,
1824                pmi: &mut self.pmi,
1825                sheets: &mut self.sheets,
1826                scene: &mut self.scene,
1827                expressions: &mut self.expressions,
1828                qualify: &mut self.qualify,
1829                family_table: &mut self.family_table,
1830                update_components: &mut self.update_components,
1831                model_store: self.model_store.as_ref(),
1832                plm: &mut self.plm,
1833            });
1834        } else {
1835            // Normal mode: the dock owns the whole central area (the viewport is a
1836            // pane). Cross-panel requests the panels can't act on while their
1837            // borrows are held bubble OUT via the returned outcome — the SAME
1838            // requests the old left-panel closure produced.
1839            let outcome = self.dock.ui(
1840                ui,
1841                DockContext {
1842                    docs: &mut self.docs,
1843                    plugins: &mut self.plugins,
1844                    viewport: &mut self.viewport,
1845                    history: &mut self.history,
1846                    bom: &mut self.bom,
1847                    assembly_constraints: &mut self.assembly_constraints,
1848                    wire_harness: &mut self.wire_harness,
1849                    pmi: &mut self.pmi,
1850                    sheets: &mut self.sheets,
1851                    scene: &mut self.scene,
1852                    expressions: &mut self.expressions,
1853                    qualify: &mut self.qualify,
1854                    family_table: &mut self.family_table,
1855                    update_components: &mut self.update_components,
1856                    model_store: self.model_store.as_ref(),
1857                    plm: &mut self.plm,
1858                },
1859            );
1860
1861            // The ACOMP palette pick must open the COMPONENT SELECTOR, never a
1862            // bare feature dialog — the file dialog is shell-owned.
1863            if outcome.insert_component_requested {
1864                self.file.dispatch(
1865                    FileAction::InsertComponent,
1866                    &mut self.docs,
1867                    self.model_store.as_ref(),
1868                );
1869            }
1870            // The DOCUMENT TAB STRIP inside the viewport tile. Activation is
1871            // immediate; a close routes through the file dialog because a dirty
1872            // document has to be confirmed first, and that prompt lives there.
1873            if let Some(index) = outcome.document_tabs.activate {
1874                self.docs.activate(index);
1875            }
1876            if let Some(index) = outcome.document_tabs.close {
1877                self.file.request_close(&mut self.docs, index);
1878            }
1879            self.document_tab_hits = outcome.document_tabs.hits;
1880            // A structure-tree Edit — or a BOM row's action button, which
1881            // reports through the same outcome field so there is one arm and
1882            // not two — expands its feature in the history tree.
1883            if let Some(focus) = outcome.feature_focus {
1884                self.history.focus_feature(focus);
1885            }
1886            // Structure-tree interaction hooks route through the SAME dispatcher
1887            // as the context bar (one truth per action); document-level flows
1888            // (edit-in-place / open-part) come back as requests the shell runs.
1889            // A BOM row menu's document-level flow: its engine-mutating half
1890            // already ran inside the panel, through the same dispatcher.
1891            match outcome.component_request {
1892                Some(ComponentActionRequest::OpenPart { component_id }) => {
1893                    self.edit_part(&component_id);
1894                }
1895                None => {}
1896            }
1897        }
1898
1899        self.history.sync_palette_display(self.model_store.as_ref());
1900
1901        // --- file dialog: a ctx-level modal (like the command palette), drawn
1902        // after the panels so its backdrop dims the whole shell. Idempotent when
1903        // closed; also polls for a completed async import each frame.
1904        self.file
1905            .show(&ctx, &mut self.docs, self.model_store.as_ref());
1906        self.plm.save_prompt(&ctx, &mut self.docs, &mut self.file, self.model_store.as_ref());
1907
1908        // --- crash recovery: the boot prompt, then the debounced autosave -----
1909        // Drawn with the same ctx-level modal treatment as the file dialog. The
1910        // autosave ticks only once the prompt has resolved (or never existed).
1911        if self.recovery.is_open() {
1912            if let Some(resolution) =
1913                self.recovery.show(&ctx, &mut self.docs, self.model_store.as_ref())
1914            {
1915                self.autosave.note_cleared();
1916                if let crate::recovery::Resolution::Restored(count) = resolution {
1917                    self.docs.engine_mut().push_notice_as(NoticeSeverity::Info, format!(
1918                        "Restored {count} unsaved document{}",
1919                        if count == 1 { "" } else { "s" }
1920                    ));
1921                }
1922            }
1923        } else {
1924            self.recovery.clear_hits();
1925            let now = ctx.input(|i| i.time);
1926            if let Some(due) = self.autosave.tick(&self.docs, self.model_store.as_ref(), now) {
1927                // The frame loop idles between inputs; wake it when the write is due.
1928                ctx.request_repaint_after(std::time::Duration::from_secs_f64(due.max(0.05)));
1929            }
1930        }
1931
1932        if let Some((format, name, bytes)) = self.file.take_stl_import() {
1933            self.start_mesh_preview(format, name, bytes);
1934            ctx.request_repaint();
1935        }
1936
1937        // --- Submit Bug: the screenshot-capture state machine + report modal.
1938        // Drawn at ctx level like the file dialog; idempotent while idle. Draws
1939        // NOTHING during capture, so the screenshot it requested never contains
1940        // this dialog.
1941        self.bug_report.show(&ctx, self.docs.engine_mut());
1942
1943        // --- Info: the licences + this session's diagnostics + the MCP start
1944        // button, a floating window toggled from the toolbar's info button.
1945        // Idempotent when closed. The server's state is read here, each frame
1946        // the window is open, and a click is answered here: the shell owns the
1947        // queue the server attaches to and the adapter line its session names.
1948        #[cfg(all(not(target_arch = "wasm32"), feature = "mcp"))]
1949        let mcp_view = if self.info.open { crate::mcp::info_view() } else { crate::panels::info::McpView::Unavailable };
1950        #[cfg(not(all(not(target_arch = "wasm32"), feature = "mcp")))]
1951        let mcp_view = crate::panels::info::McpView::Unavailable;
1952        self.info.show(&ctx, &self.diagnostics, &mcp_view);
1953        #[cfg(all(not(target_arch = "wasm32"), feature = "mcp"))]
1954        if self.info.take_mcp_start() {
1955            // The failure is already in `mcp::status()`, which the window
1956            // shows next frame, and on stderr in the same words.
1957            let _ = crate::mcp::start_from_window(self.automation.clone(), self.diagnostics.adapter_line());
1958        }
1959
1960        // --- Settings: a floating (movable + resizable) window, toggled from the
1961        // toolbar gear button, drawn at ctx level like Properties so it floats
1962        // over the shell. Idempotent when closed. Replaces the old sidebar section.
1963        // This preview runs every frame, including when Settings is closed.
1964        // Exact dirty checks serialize the whole assembly; use the tab's cached
1965        // marker here. reconnect_plm still checks the exact saved bytes before
1966        // switching stores, including metadata edits the marker may not see.
1967        self.settings.reconnect_blocker =
1968            self.reconnect_blocker_with(crate::document::Document::dirty_marker);
1969        self.settings
1970            .show(&ctx, self.docs.engine_mut(), self.model_store.as_ref());
1971        // The PLM tab's Connect now: switch this session to the PLM live.
1972        #[cfg(not(target_arch = "wasm32"))]
1973        if let Some(root) = self.settings.take_reconnect_request() {
1974            let outcome = self.reconnect_plm(root);
1975            self.settings.reconnected(outcome);
1976        }
1977
1978        // --- Part Properties: the active document's own BOM attribute record,
1979        // in a floating window beside Settings. The title is passed in because
1980        // the panel takes only the engine, and a user with several tabs open
1981        // must be able to see WHICH part they are annotating.
1982        let part_title = self.docs.active().title();
1983        let part_document = self.docs.active().id();
1984        self.part_properties.configure_plm(self.model_store.plm_client(), self.docs.active().name());
1985        self.part_properties
1986            .show(&ctx, self.docs.engine_mut(), &part_title, part_document);
1987
1988        // --- top-right overlay column: the special-mode EXIT card (Finish/Cancel
1989        // for reference-selection / sketch mode) stacked ABOVE the selection-driven
1990        // CONTEXT ACTION rail. Both cards live in ONE ctx-level Area anchored
1991        // top-right so they never overlap, and the context rail uses the SAME
1992        // renderer whether it is showing modeling actions or sketch actions
1993        // (`panels::action_rail`). A modeling create/edit action returns a feature
1994        // id to expand in the history tree.
1995        {
1996            let mut focus: Option<String> = None;
1997            let mut info_targets: Vec<String> = Vec::new();
1998            let mut plugin_action = None;
1999            let mut component_request: Option<ComponentActionRequest> = None;
2000            // Anchor the overlay to the RIGHT edge of the 3D VIEW (the viewport
2001            // tile), not the window — so it stays glued to the viewport wherever
2002            // docking frames it. The viewport was drawn earlier THIS frame, so its
2003            // rect is current. Before the first draw (`None`) fall back to the
2004            // window's top-right.
2005            let mut overlay = egui::Area::new(egui::Id::new("brep-top-right-overlay"))
2006                .order(egui::Order::Foreground);
2007            overlay = match self.viewport.last_rect() {
2008                Some(rect) => overlay
2009                    .fixed_pos(rect.right_top() + egui::vec2(-12.0, 8.0))
2010                    .pivot(egui::Align2::RIGHT_TOP),
2011                None => overlay.anchor(egui::Align2::RIGHT_TOP, egui::vec2(-12.0, 56.0)),
2012            };
2013            overlay
2014                .show(&ctx, |ui| {
2015                    // 0. The family-row preview's card: which row, and Exit.
2016                    self.family_table.preview_card(ui, self.docs.engine_mut());
2017                    // 1. Exit controls for whatever special mode is active.
2018                    self.mode_bar.card(ui, self.docs.engine_mut());
2019                    // 2. Context actions: sketch actions in sketch mode, else the
2020                    // modeling selection actions. Same rail, mode-appropriate items.
2021                    if self.docs.engine().sketch_mode() {
2022                        self.sketch.context_card(ui, self.docs.engine_mut());
2023                    } else {
2024                        let outcome = self.context_bar.card(ui, self.docs.engine_mut());
2025                        focus = outcome.focus;
2026                        info_targets = outcome.info_targets;
2027                        plugin_action = outcome.plugin_action;
2028                        component_request = outcome.component;
2029                    }
2030                });
2031            if let Some(focus) = focus {
2032                self.history.focus_feature(focus);
2033            }
2034            // The Info action returns one target per selected entity — open (or, on
2035            // dedup, keep) a pinned Info window for each. Drawn below.
2036            if let Some(id) = plugin_action {
2037                if let Err(e) = self.plugins.open_action(self.docs.engine(), &id) { self.plugins.error = Some(e); }
2038            }
2039            if !info_targets.is_empty() {
2040                self.info_windows.open_for(&info_targets, self.viewport.last_rect());
2041            }
2042            // Component document-level flows (the engine-mutating component
2043            // actions already ran inside the bar).
2044            match component_request {
2045                Some(ComponentActionRequest::OpenPart { component_id }) => {
2046                    self.edit_part(&component_id);
2047                }
2048                None => {}
2049            }
2050        }
2051
2052        // --- THE DIALOG DOOR: every dynamically generated dialog that opened
2053        // this frame makes its host pane's tab current.
2054        //
2055        // ONE call, placed after everything that can open one — the dock's panes
2056        // and viewport, and the context bar's overlay above — so a form opened
2057        // anywhere is surfaced in the same frame, before `__brepDock` publishes
2058        // the active tab below. It watches the TARGETS rather than the callers
2059        // because most of them set the target inside the engine or inside a
2060        // panel's draw, with no dock in reach; `panels::dock::DialogTargets`
2061        // carries that reasoning and the openers it covers.
2062        let targets = crate::panels::dock::DialogTargets::read(
2063            &self.history,
2064            self.docs.engine(),
2065            self.docs.active_id(),
2066        );
2067        self.dock.surface_opened_dialogs(targets);
2068
2069        // --- Info windows: the pinned per-entity inspector windows, drawn at ctx
2070        // level like the file dialog so they float over the shell. Each is pinned to
2071        // its open-time object name (selection changes never retarget them); closed
2072        // windows (their `×`) are pruned here. Drawn AFTER the context bar so a
2073        // window opened THIS frame paints this frame.
2074        self.info_windows.show(&ctx, self.docs.engine_mut());
2075
2076        // --- interference results window: same floating idiom, owned report;
2077        // its Re-run button re-drives the engine check.
2078        self.interference.show(&ctx, self.docs.engine_mut());
2079
2080        // --- auto-constraints window: the inference scan + its Create button.
2081        self.auto_constraints.show(&ctx, self.docs.engine_mut());
2082        self.step_parts
2083            .show(&ctx, self.docs.engine_mut(), self.model_store.as_ref());
2084
2085        // --- transient toasts: drain the engine's queued notices (e.g. a sketch
2086        // solve that failed after an edit) and show each briefly. Drawn last so
2087        // the cards float over the whole shell.
2088        let now = ctx.input(|i| i.time);
2089        // All three sources gathered FIRST, because the automation queue must see
2090        // every one of them: `Toasts::extend` keeps only the last few on screen,
2091        // and a message dropped for space is exactly the one a host wants told.
2092        use brep_render::engine_state::NoticeSeverity;
2093        let mut raised = self.docs.engine_mut().take_graded_notices();
2094        // Same lane for STORAGE failures the store could only discover after its
2095        // synchronous `write` returned `Ok` (the browser backend writes behind an
2096        // in-memory mirror). A save that did not persist must never be silent.
2097        let errors = self.model_store.take_persistence_errors().into_iter().chain(self.autosave.take_errors());
2098        raised.extend(errors.map(|text| (NoticeSeverity::Error, text)));
2099        // An edit a read-only document refused (a PLM revision not checked out,
2100        // or released): its history kept the saved bytes, and this says why.
2101        for doc in self.docs.iter_mut() {
2102            if let Some(text) = doc.take_refused() {
2103                raised.push((NoticeSeverity::Warning, text));
2104            }
2105        }
2106        // The automation channel's `notices` drain: what the user would have SEEN.
2107        // Without this the drain has no producers at all and every script's
2108        // `{"notices": []}` asserts nothing.
2109        #[cfg(feature = "automation")]
2110        for (_, text) in &raised {
2111            self.automation.push_notice(
2112                crate::automation::command::NoticeKind::Toast,
2113                text.clone(),
2114            );
2115        }
2116        self.toasts.extend(raised, now);
2117        // An edit after a card was raised supersedes it (`Toasts::note_document`).
2118        self.toasts
2119            .note_document(self.docs.active_id(), self.docs.engine().history.undo_top(), now);
2120        self.toasts.show(&ctx, self.viewport.last_rect(), status_bar_top);
2121
2122        // The state registry (`automation::registry`): the live app + engine
2123        // state, published by name with a one-line doc so a host can read it
2124        // (and, on wasm, mirrored to `window.__brep*` for the verify scripts).
2125        // Purely additive; no render effect. Published AFTER the panels draw so
2126        // the hit-rects are for THIS frame's layout. Off unless a host enabled it.
2127        if crate::automation::registry::enabled() {
2128            let _publish_span = crate::perf::span(crate::perf::Phase::Publish);
2129            let ppp = ui.ctx().pixels_per_point();
2130            crate::automation::registry::publish("__brepCamera", "camera state: kind, eye, target, up, near/far, projection block, worldPerPixel", &self.docs.engine().camera_state_json());
2131            crate::automation::registry::publish("__brepSettings", "render and UI settings", &self.docs.engine().settings_json());
2132            crate::automation::registry::publish("__brepSolidColors", "per-solid colour overrides", &self.docs.engine().solid_color_overrides_json());
2133            crate::automation::registry::publish("__brepHistory", "history listing {step, features:[{index,type,id}]}", &self.docs.engine().history_listing_json());
2134            crate::automation::registry::publish("__brepGizmo", "transform gizmo state", &self.docs.engine().gizmo_state_json());
2135            crate::automation::registry::publish("__brepFile", "file dialog state (mode, entries, current name)",
2136                &self.file.file_state_json(&self.docs, self.model_store.as_ref()),
2137            );
2138            crate::automation::registry::publish("__brepFileHit", "file dialog widget rects", &self.file.hits_json());
2139            crate::automation::registry::publish("__brepModel", "model signature: solid count, triangle count, per-solid bounds (change detection)", &self.model_signature_json());
2140            crate::automation::registry::publish("__brepReport", "last run report {featureErrors, featureNotes, featureFulfilment, featureRefusals (only when a feature failed with a typed refusal), featureApproximations (only when a successful feature carries a measured approximation: feature id → [{code, body, measured, bar, volume_bound, edges, message, summary}]), unresolved, displayErrors, featureTimings, featureOutputs}", &self.docs.engine().history_report_json());
2141            // The in-flight run: whether one is pending, the feature the runner
2142            // says it is executing, and the feature a cancelled run was stuck on.
2143            crate::automation::registry::publish("__brepRun", "in-flight run {pending, progress:{generation,index,total,featureId,featureType}|null, cancelled}",
2144                &serde_json::json!({
2145                    "pending": self.docs.engine().run_pending(),
2146                    "progress": self.docs.engine().run_progress().map(|p| serde_json::json!({
2147                        "generation": p.generation,
2148                        "index": p.index,
2149                        "total": p.total,
2150                        "featureId": p.feature_id,
2151                        "featureType": p.feature_type,
2152                    })),
2153                    "cancelled": self.docs.engine().cancelled_run(),
2154                })
2155                .to_string(),
2156            );
2157            crate::automation::registry::publish("__brepBusy", "the status bar's working indicator {shown, activities:[{kind, label, document, cancellable, elapsed}]} — everything in flight, most important first; shown once work has lasted 0.2 s", &self.busy.state_json());
2158            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());
2159            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());
2160            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());
2161            crate::automation::registry::publish("__brepExprHit", "expressions panel widget rects", &self.expressions.hits_json());
2162            crate::automation::registry::publish("__brepExpr", "expressions script, its variables and the configurator",
2163                &serde_json::json!({
2164                    "expressions": self.docs.engine().expressions_json(),
2165                    "variables": serde_json::from_str::<serde_json::Value>(
2166                        &self.docs.engine().expression_variables_json()
2167                    )
2168                    .unwrap_or(serde_json::Value::Null),
2169                    "configurator": serde_json::from_str::<serde_json::Value>(
2170                        &self.docs.engine().configurator_json()
2171                    )
2172                    .unwrap_or(serde_json::Value::Null),
2173                })
2174                .to_string(),
2175            );
2176            crate::automation::registry::publish("__brepToolbar", "toolbar rects: shared File menu file:* and workbench:item:<id>; Ribbon tabs/overflow ribbon:* and Home creation wbtb:*; command keys undo redo fit projection wireframe show:* help info bug workbench:btn:<id>. Classic wraps its controls; Ribbon compacts Large commands before whole-group overflow. Keys appear when their widgets are rendered; menu entries appear while open", &self.toolbar.hits_json());
2177            // The workbench actions strip's button rects (`wbtb:feature:<type>` /
2178            // `wbtb:constraint:<type>` / `wbtb:annotation:<type>`); an empty map
2179            // while the strip is hidden.
2180            crate::automation::registry::publish("__brepWorkbenchToolbar", "creation rects: wbtb:* feature:type constraint:type annotation:type, from the Classic workbench strip or Ribbon Home; empty while hidden or another Ribbon tab is selected", &self.workbench_toolbar.hits_json());
2181            // The PLM pane (a PLM session only): its sections' widget rects,
2182            // `plm/section:<id>` and `plm/<section>:<widget>`, and the active
2183            // document's access and revision.
2184            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|ecos>", &self.plm.hits_json());
2185            crate::automation::registry::publish("__brepPlmDoc", "the active document on the PLM: {access:{editable, reason}, plmDocument, revision:{id,label,lifecycle,lockedBy,lockedByMe}, busy, message, offered:[verb key], files:{staged:{name,mediaType,kind,size,target}, revision:[name], part:[name], problem, notice, status, busy}}; null with no PLM session", &self.plm.state_json(&self.docs));
2186            // The queued toast texts — the only trace of a refusal the app shows
2187            // as a transient card (e.g. a constraint the strip could not add).
2188            crate::automation::registry::publish("__brepNotices", "queued toast texts", &self.toasts.texts_json());
2189            crate::automation::registry::publish("__brepToasts", "toast cards {cards: [{text, severity (error|warning|info), count, shown, superseded}], shown, folded}", &self.toasts.state_json());
2190            crate::automation::registry::publish("__brepToastsHit", "toast card rects (toast:<i> top to bottom, toast:more)", &self.toasts.hits_json());
2191            crate::automation::registry::publish("__brepBug", "bug report panel state", &self.bug_report.state_json());
2192            crate::automation::registry::publish("__brepDiagnostics", "what this session is running on: renderer, adapter, texture ceiling, version, platform", &self.diagnostics.json().to_string());
2193            // Where the last ~120 frames' milliseconds went. `__brepDiagnostics`
2194            // says WHICH renderer is drawing; this says what it costs, in the
2195            // same split the Info window's Performance rows show.
2196            crate::automation::registry::publish("__brepPerf", "rolling per-frame timings in ms {frames, window, dt, ui, publish, sync, fit, overlays, draw} each {avg,p95,max}", &crate::perf::json());
2197            crate::automation::registry::publish("__brepBugHit", "bug report panel widget rects", &self.bug_report.hits_json());
2198            // The JavaScript editor window: its outer rect against the surface
2199            // it may fill, and its widget rects (`javascript/panel:clip`,
2200            // `javascript/source`, `javascript/output`, the buttons).
2201            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());
2202            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());
2203            // The wire harness: the document's connections + the last run's
2204            // routing report (engine truth), and the panel's widget rects.
2205            crate::automation::registry::publish("__brepWireHarness", "wire harness connections and the last routing report", &self.docs.engine().wire_harness_state_json());
2206            crate::automation::registry::publish("__brepWireHarnessHit", "wire harness panel widget rects", &self.wire_harness.hits_json());
2207            // The part's declared connection points (the `ports` block) and the
2208            // ports tail's report, beside the Qualify panel's own selection and
2209            // its rects (`qualify:*`).
2210            crate::automation::registry::publish("__brepPorts", "the part's declared connection points (the `ports` block) and the ports tail's report of the last run", &self.docs.engine().ports_state_json());
2211            crate::automation::registry::publish("__brepQualify", "Qualify panel state {selected: the connection-point address it has selected}", &self.qualify.state_json());
2212            crate::automation::registry::publish("__brepQualifyHit", "Qualify panel widget rects (qualify:*)", &self.qualify.hits_json());
2213            // The family table as the Family table pane last read it, its
2214            // problems, selection and the last Generate report; and its rects.
2215            crate::automation::registry::publish("__brepFamily", "Family table pane state {table, expressions, notColumns, selected, editing, problems, columnProblems, values, generateCalls, report, status, preview: {row, partNumber, applied, showing, message, featureErrors} or null, runsReplied}", &self.family_table.state_json());
2216            crate::automation::registry::publish("__brepFamilyHit", "Family table pane widget rects (family:*)", &self.family_table.hits_json());
2217            // The PMI block + report + active view / open annotation, and the
2218            // PMI panel's rects (`pmi:capture`, `pmi:add`, `pmi:add:<type>`,
2219            // `pmi:row:<id>`, `pmi:cell:<id>:<column>`, `pmi:menu:<id>`, the
2220            // form's `pmi:` keys).
2221            crate::automation::registry::publish("__brepPmi", "PMI block, report, active view, open annotation or view dialog, and the selected annotation or view", &self.docs.engine().pmi_state_json());
2222            crate::automation::registry::publish("__brepPluginsHit", "Declarative plugin panel action controls", &self.plugins.panel_hits_json());
2223            crate::automation::registry::publish("__brepPmiHit", "PMI panel widget rects (pmi:*)", &self.pmi.hits_json());
2224            // The `sheets` block, which sheet the viewport draws, and the OPEN
2225            // sheet's whole projection — the paper, the visible edge runs and
2226            // the annotations that passed the parallel rule, in millimetres.
2227            // The panel's rects (`sheets:add`, `sheets:place:<view>`,
2228            // `sheets:row:<id>`, the form's `sheets:` keys) ride beside it.
2229            crate::automation::registry::publish("__brepSheets", "drawing sheets, the open sheet and its projection, the open and the selected sheet object", &self.docs.engine_mut().sheet_state_json());
2230            crate::automation::registry::publish("__brepSheetsHit", "Sheets panel widget rects (sheets:*)", &self.sheets.hits_json());
2231            // The workbench logical state (resolved current id + available ids) so
2232            // the verifier can drive the dropdown and confirm the active workbench.
2233            // Hit-rects for the dropdown ride in `__brepToolbar` (self.toolbar.hits).
2234            crate::automation::registry::publish("__brepWorkbench", "active workbench id and the available ids",
2235                &crate::workbench::workbench_state_scoped(self.docs.engine()).to_string(),
2236            );
2237            crate::automation::registry::publish("__brepSelection", "selection {solids, faces, edges, datums, vertices}; the name arrays are in pick order, oldest first", &self.docs.engine().selection_json());
2238            crate::automation::registry::publish("__brepInfoWindows", "open info windows (mass properties, topology, metadata)",
2239                &self.info_windows.published_json(self.docs.engine_mut()),
2240            );
2241            crate::automation::registry::publish("__brepInfoWindowsHit", "info window widget rects", &self.info_windows.hits_json());
2242            crate::automation::registry::publish("__brepInterference", "interference check state", &self.interference.state_json());
2243            crate::automation::registry::publish("__brepInterferenceHit", "interference panel widget rects", &self.interference.hits_json());
2244            crate::automation::registry::publish("__brepAutoConstraints", "auto-constraint inference state", &self.auto_constraints.state_json());
2245            crate::automation::registry::publish("__brepAutoConstraintsHit", "auto-constraints widget rects", &self.auto_constraints.hits_json());
2246            crate::automation::registry::publish("__brepStepParts", "STEP parts library panel state", &self.step_parts.state_json());
2247            crate::automation::registry::publish("__brepStepPartsHit", "STEP parts library widget rects", &self.step_parts.hits_json());
2248            crate::automation::registry::publish("__brepSelectionFilter", "which entity kinds a viewport click may pick", &self.docs.engine().selection_filter_json());
2249            crate::automation::registry::publish("__brepSelectionHit", "selection bar widget rects (filter:kind, clear, hide)", &self.selection.hits_json());
2250            crate::automation::registry::publish("__brepContext", "context action bar state (offers for the selection)", &self.context_bar.state_json());
2251            crate::automation::registry::publish("__brepContextHit", "context action bar widget rects", &self.context_bar.hits_json());
2252            crate::automation::registry::publish("__brepModeBarHit", "mode bar widget rects (refsel:*, Sketch:*)", &self.mode_bar.hits_json());
2253            // The DOCUMENT TABS: the open models, which one is active, and the
2254            // strip's per-tab hit-rects, so an e2e script can switch and close
2255            // documents the way a user does.
2256            crate::automation::registry::publish("__brepDocuments", "open document tabs {active, tabs:[{title,name,dirty}]}", &document_tabs::state_json(&self.docs));
2257            crate::automation::registry::publish(
2258                "__brepDocumentsHit",
2259                "document tab strip widget rects",
2260                &crate::automation::hit_rects::hits_json(
2261                    self.document_tab_hits.iter().map(|(key, rect)| (key, rect)),
2262                ),
2263            );
2264            // The boot-time recovery prompt: its entries and its two buttons.
2265            crate::automation::registry::publish("__brepRecovery", "boot-time recovery prompt entries", &self.recovery.state_json());
2266            crate::automation::registry::publish("__brepRecoveryHit", "recovery prompt widget rects", &self.recovery.hits_json());
2267            crate::automation::registry::publish("__brepComponentMove", "assembly component move state", &self.docs.engine().component_move_json());
2268            crate::automation::registry::publish("__brepSketch", "sketch mode state (session, tool, selection, constraints)", &self.sketch.published_json(self.docs.engine()));
2269            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()));
2270            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()));
2271            crate::automation::registry::publish("__brepWireframe", "wireframe toggle", &format!("{}", self.docs.engine().settings.wireframe));
2272            crate::automation::registry::publish("__brepRefSelect", "reference-selection picker {active, prompt, names}",
2273                &serde_json::json!({
2274                    "active": self.docs.engine().ref_select_active(),
2275                    "prompt": self.docs.engine().ref_select_prompt(),
2276                    "names": self.docs.engine().ref_select_names(),
2277                })
2278                .to_string(),
2279            );
2280            // Viewport origin + projected probe points (viewport-local logical
2281            // px) so the verifier can click precise spots ON the Box and ON the
2282            // Pin during ref-select mode. Index 0 is a Box top-corner clear of the
2283            // pin; indices 1..4 are points on the Pin's cylindrical stub that
2284            // protrudes above the Box top (y=20), on the camera-facing sides — the
2285            // verifier tries them until one picks "Pin".
2286            crate::automation::registry::publish("__brepView", "the 3D viewport rect {x,y,w,h} in egui points", &self.viewport.viewport_rect_json());
2287            // Dock layout snapshot (per-pane visible / rendered) so the verifier
2288            // can see which side panels are on-screen and, once a user tabs panels
2289            // together, activate the right tab before asserting on its widgets.
2290            // `active=false` in sketch / ref-select (the dock is bypassed).
2291            crate::automation::registry::publish("__brepDock", "dock layout in tab-strip order: per-pane visible/activeTab/rendered", &self.dock.state_json(!sketch && !ref_select));
2292            crate::automation::registry::publish("__brepProbe", "projected seed-model probe points (viewport-local px) for the verifier",
2293                &self
2294                    .docs
2295                    .engine()
2296                    .world_to_screen_json(
2297                        "[[2.0,20.0,2.0],[14.243,22.5,14.243],[16.0,22.5,10.0],\
2298                          [10.0,22.5,16.0],[10.0,25.0,10.0]]",
2299                    )
2300                    .unwrap_or_else(|_| "[]".to_string()),
2301            );
2302            crate::automation::registry::publish("__brepPpp", "pixels per point of the surface", &format!("{ppp}"));
2303            crate::automation::registry::publish("__brepStep", "the rolled-to feature index", &format!("{}", self.docs.engine().history_rollback()));
2304            crate::automation::registry::publish("__brepParams", "inputParams of the rolled-to feature", self.params_blob());
2305        }
2306
2307        // Phase 3 of the automation frame (§4.4): reads answer from THIS frame's
2308        // registry and layout.
2309        #[cfg(feature = "automation")]
2310        self.drain_reads(&ctx);
2311
2312        // NOTE: the 3D viewport is no longer drawn here — it is a dock tile drawn
2313        // earlier this frame (normal mode) or drawn directly in the sketch /
2314        // ref-select branch above. Drawing it before the top-right overlay is what
2315        // keeps that overlay anchored to the live viewport rect.
2316    }
2317}
2318
2319
2320/// Mirror an engine JSON string to `window.<name>` (wasm/verification only).
2321
2322/// The seed model handed to the engine at startup: a 3-feature history so the
2323/// tree / roll / edit are real —
2324///   0. `P.CU` "Box"  — a 20 mm cube at the origin (spans `[0,20]³`).
2325///   1. `P.CY` "Pin"  — a r=6, h=30 cylinder (axis +Y) positioned to pierce the
2326///      cube through its centre in XZ (x=10, z=10) from below (y=-5) to above.
2327///   2. `B`    "Cut"  — SUBTRACT: `targetSolid = Box`, tools `[Pin]` → the cube
2328///      with a cylindrical through-hole (the ref-select field is visible for the
2329///      next slice). Roll-to-step shows: cube → cube+cylinder → subtracted cube.
2330///
2331/// This is just the INITIAL document — once handed to `EngineState`, the engine
2332/// OWNS the mutable history; the app keeps no copy.
2333pub(crate) fn seed_history_json() -> String {
2334    serde_json::json!({
2335        "expressions": "",
2336        "configurator": {},
2337        "features": [
2338            {
2339                "type": "P.CU",
2340                "inputParams": {
2341                    "id": "Box",
2342                    "sizeX": 20.0, "sizeY": 20.0, "sizeZ": 20.0,
2343                    "transform": {
2344                        "position": [0.0, 0.0, 0.0],
2345                        "rotationEuler": [0.0, 0.0, 0.0],
2346                        "scale": [1.0, 1.0, 1.0]
2347                    },
2348                    "boolean": { "targets": [], "operation": "NONE", "mergeCoplanarFaces": true }
2349                },
2350                "persistentData": {}
2351            },
2352            {
2353                "type": "P.CY",
2354                "inputParams": {
2355                    "id": "Pin",
2356                    "radius": 6.0, "height": 30.0,
2357                    "transform": {
2358                        "position": [10.0, -5.0, 10.0],
2359                        "rotationEuler": [0.0, 0.0, 0.0],
2360                        "scale": [1.0, 1.0, 1.0]
2361                    },
2362                    "boolean": { "targets": [], "operation": "NONE", "mergeCoplanarFaces": true }
2363                },
2364                "persistentData": {}
2365            },
2366            {
2367                "type": "B",
2368                "inputParams": {
2369                    "id": "Cut",
2370                    "targetSolid": "Box",
2371                    "boolean": { "operation": "SUBTRACT", "targets": ["Pin"], "mergeCoplanarFaces": true }
2372                },
2373                "persistentData": {}
2374            }
2375        ]
2376    })
2377    .to_string()
2378}