Skip to main content

brep_app/panels/
file.rs

1//! File dialog — a **reusable modal** for model-document management: **New /
2//! Open / Save / Save As** of the MODEL, driven from the toolbar. Mirrors the
3//! shape of [`crate::palette::Palette`]: the caller owns ONE [`FileDialog`],
4//! calls [`FileDialog::dispatch`] when a toolbar file button is clicked (which
5//! either acts immediately or opens the modal in a mode), and calls
6//! [`FileDialog::show`] every frame to draw the (possibly open) modal.
7//!
8//! The model document IS the engine-owned history: `EngineState` serializes it
9//! with `history_request_json()` (the `.nbrep` recipe) and loads it with
10//! `set_history_json` / `load_model_and_fit`. This dialog keeps NO model state
11//! and no document IDENTITY — the name and the clean baseline live on
12//! [`Document`], and the open set on [`Documents`]. It holds only transient UI
13//! buffers (the name field, a status line, the open modal) and drives the
14//! documents + the [`ModelStore`] seam.
15//!
16//! # New and Open never discard anything now
17//!
18//! Both ADD A TAB: New pushes an empty document, Open pushes the opened one (or
19//! focuses the tab already holding it). Nothing is replaced, so neither needs
20//! the "discard unsaved changes?" prompt they used to raise — the only place
21//! unsaved work can still be lost is CLOSING a tab, which is where that
22//! confirmation now lives (`Mode::ConfirmClose`).
23//!
24//! Persistence crosses the unified [`ModelStore`] seam — the ONE platform
25//! exception. The same embeddable explorer renders on web and desktop. The web
26//! backend lists localStorage models and can Upload; desktop lists the app's
27//! models directory. No OS-native file dialog is used.
28
29mod plm_save_as;
30
31use crate::automation::hit_keys::HitKeyDoc;
32use crate::document::{Document, Documents};
33use crate::document_class::{self, DocumentClass};
34use crate::family_table::{self, FamilySource};
35use crate::template::{self, TemplateInput};
36use crate::panels::parts_library::document_signature;
37use crate::panels::file_explorer::{self, FileExplorer, FileExplorerOptions};
38use crate::panels::kicad_import::{self, DiskFiles, KicadImport, KicadKind};
39use crate::store::{model_display_name, sibling_identity, ModelStore, PlaceKind, MODEL_EXTENSIONS};
40use brep_render::engine_state::{
41    ComponentInsert, EngineState, PartSink, StepAssemblyImport, StepAssemblyProbe,
42    StepAssemblyReport, StepProbeOutcome,
43};
44use brep_render::runner::MeshImportFormat;
45use eframe::egui;
46use std::collections::{BTreeMap, HashMap, HashSet};
47
48/// The file operation a toolbar button requests. The shell maps a clicked
49/// toolbar button to one of these and hands it to [`FileDialog::dispatch`].
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum FileAction {
52    New,
53    /// New, of a chosen class: an empty family seed or template in a new tab
54    /// (the toolbar's New menu). `NewOfClass(Normal)` is plain New.
55    NewOfClass(DocumentClass),
56    Open,
57    Save,
58    SaveAs,
59    /// Import a CAD or mesh file FROM the user's filesystem, appending it to the
60    /// model rather than replacing it. STL/OBJ use RANSAC reconstruction.
61    Import,
62    /// Export the model TO the user's filesystem in a chosen format (STEP /
63    /// IGES / STL / OBJ / JSON).
64    Export,
65    /// Export the sheet-metal FLAT PATTERN (unfold) as a 2D vector file
66    /// (DXF / SVG). Opens the flat-pattern export modal.
67    ExportFlatPattern,
68    /// Insert an ASSEMBLY COMPONENT: opens the component selector — existing
69    /// parts-library entries first, then the model store's Open list (+ Upload)
70    /// — and routes the chosen document through the engine's insert flow
71    /// (`add_part_to_library` → an ACOMP instance referencing the returned
72    /// effective part name). Dispatched when the palette picks `ACOMP`.
73    InsertComponent,
74    /// Import a part from KiCad into the open part: a `.kicad_sym` symbol (the
75    /// Symbol workbench) or a `.kicad_mod` footprint (the Pads workbench), with
76    /// the footprint and 3D model KiCad's chain leads to
77    /// ([`crate::panels::kicad_import`]).
78    ImportKicad(KicadKind),
79}
80
81/// Which modal (if any) the dialog is currently showing.
82#[derive(Clone, Copy, PartialEq, Eq)]
83enum Mode {
84    /// Confirm recovery of a missing component source from its embedded part.
85    CreateComponentPart,
86    /// Open a saved model through the common explorer.
87    Open,
88    /// Prompt for a name and save under it.
89    SaveAs,
90    /// Confirm discarding unsaved changes before CLOSING a document tab —
91    /// the ONE place unsaved work can still be lost now that New and Open
92    /// both add a tab. `pending_close` holds the document's id and the
93    /// committed revision the prompt was raised at.
94    ConfirmClose,
95    /// Choose an export format (STEP / IGES / STL / OBJ / JSON) for the current model.
96    Export,
97    /// Choose a STEP / IGES / STL / OBJ file through the common explorer.
98    Import,
99    /// Choose a 2D vector format (DXF / SVG) for the sheet-metal flat pattern.
100    FlatPattern,
101    /// Pick a part to insert as an assembly component (library entries + the
102    /// stored-model list + Upload).
103    InsertComponent,
104    /// A `.step` upload whose product structure the probe found: choose whether
105    /// to keep that structure (parts + component instances) or flatten it to
106    /// bodies. Backed by [`FileDialog::pending_step_import`].
107    StepAssembly,
108    /// A KiCad import: its file through the common explorer, then its own
109    /// stages ([`KicadImport`]).
110    Kicad,
111    /// Insert component chose a FAMILY: pick one of its members, which is
112    /// what gets placed ([`FileDialog::pick_member`]).
113    PickMember,
114    /// Insert component chose a TEMPLATE: name the new part and set its
115    /// inputs; the spun-out part is what gets placed ([`FileDialog::spin_out`]).
116    SpinOut,
117    /// The active document is a family MEMBER and the user just changed it:
118    /// save it as a new part, open the family, or undo ([`FileDialog::member_prompt`]).
119    MemberEdit,
120    /// The file chooser: ANY file on this machine, for a panel that asked
121    /// ([`FileDialog::request_pick_file`]). Browses the local files even in a
122    /// PLM session, whose own explorer shows the server's documents.
123    PickFile,
124    /// The assembly Save's questions about the documents it owns
125    /// ([`crate::document::owned_save`]): one row per document, every row
126    /// defaulting to yes ([`FileDialog::owned_prompt`]).
127    OwnedSave,
128    /// A part was saved under a new name while open assemblies place it:
129    /// point them at the new file too? Yes by default ([`FileDialog::retarget`]).
130    Retarget,
131    /// The Save-file chooser: WHERE an export goes, on desktop. A format
132    /// button (or a panel's Export) produced the file; this picks its folder
133    /// through the explorer over the local files and its name through a
134    /// field, then writes it ([`FileDialog::save_file`]). The browser never
135    /// sees it: there an export is a download, and the browser asks.
136    SaveFile,
137}
138
139/// A file a panel wants handed to the user: the one door every UI export
140/// takes ([`FileDialog::request_save_file`]). On desktop it opens the
141/// Save-file chooser (`Mode::SaveFile`); in the browser it is a download.
142#[derive(Clone, Debug, PartialEq)]
143pub struct SaveRequest {
144    /// The chooser's heading: "Export STEP", "Export the script".
145    pub title: String,
146    /// The file's full name, extension included; the chooser's name field
147    /// starts from it and the browser downloads under it.
148    pub file_name: String,
149    pub body: SaveBody,
150}
151
152/// An export's content. Text keeps the browser's string lane (its `Blob`
153/// takes a string directly, see [`ModelStore::export_file_named`]); on
154/// desktop both are bytes on disk.
155#[derive(Clone, Debug, PartialEq)]
156pub enum SaveBody {
157    Text(String),
158    Bytes(Vec<u8>),
159}
160
161impl SaveBody {
162    fn as_bytes(&self) -> &[u8] {
163        match self {
164            SaveBody::Text(text) => text.as_bytes(),
165            SaveBody::Bytes(bytes) => bytes,
166        }
167    }
168}
169
170impl SaveRequest {
171    pub fn text(title: impl Into<String>, file_name: impl Into<String>, text: String) -> Self {
172        Self { title: title.into(), file_name: file_name.into(), body: SaveBody::Text(text) }
173    }
174
175    pub fn bytes(title: impl Into<String>, file_name: impl Into<String>, bytes: Vec<u8>) -> Self {
176        Self { title: title.into(), file_name: file_name.into(), body: SaveBody::Bytes(bytes) }
177    }
178}
179
180/// An export produced and waiting for its folder: the Save-file chooser's
181/// payload, with what the write then says. Only the file is held; the
182/// dialog that produced it has closed (a format chooser) or never had a
183/// modal (a panel's Export button).
184struct PendingSave {
185    request: SaveRequest,
186    /// What the status says after the file name: " (13 files)", " (2 pages)".
187    detail: String,
188    /// The export's name for its toast ("Netlist", "Fabrication"): the PCB's
189    /// manufacturing outputs raise one, named by their output, on every
190    /// platform. Every other export's toast on desktop is the generic one.
191    label: Option<String>,
192    /// The bundle's warnings (design-rule findings): the chooser stays open
193    /// on them after the write, as the format dialog did, and they go to a
194    /// warning toast.
195    warnings: Vec<String>,
196    /// A family row was previewed: say so after the write
197    /// ([`FileDialog::say_previewed_export`]).
198    preview: bool,
199}
200
201/// How a produced export left the dialog ([`FileDialog::deliver`]).
202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
203enum Delivery {
204    /// Written (desktop, no chooser) or downloaded (browser): done.
205    Done,
206    /// The Save-file chooser is up with it; the write happens on its Save.
207    Chooser,
208    /// Not delivered; the status line says why.
209    Failed,
210}
211
212/// The file-chooser tag of the Open modal's workspace (a PLM session's Open).
213const PICK_OPEN_WORKSPACE: &str = "file:open-workspace";
214
215/// A file the chooser delivered ([`FileDialog::take_picked_file`]).
216#[derive(Clone, Debug, PartialEq)]
217pub struct PickedFile {
218    /// The file's own name, extension included (`photo.jpg`).
219    pub name: String,
220    /// Where it was on this machine; `None` in the browser, which never says.
221    pub path: Option<String>,
222    pub bytes: Vec<u8>,
223}
224
225/// What an explorer folder is FOR. The explorer's location lives in the
226/// store and every modal shares it, so each purpose remembers where the user
227/// last was and the modal opens there. With one shared folder, a KiCad import
228/// from `…/kicad/symbols` sent the next Save As and Insert component into the
229/// KiCad library (ecad-reaudit-2026-09-23, B8).
230#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
231enum Purpose {
232    /// The user's own documents: Open, Save As, Insert component.
233    Models,
234    /// Foreign CAD and mesh files: Import.
235    Imports,
236    /// KiCad symbol and footprint libraries.
237    Kicad,
238    /// Where exports go: the Save-file chooser's folder, on the local files.
239    Exports,
240}
241
242impl Purpose {
243    const ALL: [Purpose; 4] = [Purpose::Models, Purpose::Imports, Purpose::Kicad, Purpose::Exports];
244
245    fn slug(self) -> &'static str {
246        match self {
247            Purpose::Models => "models",
248            Purpose::Imports => "imports",
249            Purpose::Kicad => "kicad",
250            Purpose::Exports => "exports",
251        }
252    }
253}
254
255impl Mode {
256    /// The folder this modal browses, for the modals that browse one.
257    fn purpose(self) -> Option<Purpose> {
258        match self {
259            Mode::Open | Mode::SaveAs | Mode::InsertComponent | Mode::CreateComponentPart => {
260                Some(Purpose::Models)
261            }
262            Mode::Import => Some(Purpose::Imports),
263            Mode::Kicad => Some(Purpose::Kicad),
264            Mode::SaveFile => Some(Purpose::Exports),
265            Mode::ConfirmClose
266            | Mode::Export
267            | Mode::FlatPattern
268            | Mode::StepAssembly
269            | Mode::PickMember
270            | Mode::SpinOut
271            | Mode::MemberEdit
272            | Mode::OwnedSave
273            | Mode::Retarget
274            | Mode::PickFile => None,
275        }
276    }
277}
278
279/// The store a purpose's explorer browses. Import, the KiCad import and the
280/// Save-file chooser deal in files on THIS MACHINE: in a PLM session the session
281/// store is the server's documents, so they browse the local files the session
282/// keeps beside it ([`ModelStore::local_files`]); on a file store they are the
283/// same store.
284fn browse_store(purpose: Purpose, store: &dyn ModelStore) -> &dyn ModelStore {
285    match purpose {
286        Purpose::Imports | Purpose::Kicad | Purpose::Exports => store.local_files().unwrap_or(store),
287        Purpose::Models => store,
288    }
289}
290
291/// The store's models folder, where a purpose not yet used starts (the
292/// Save-file chooser's exports included). `None` where the store has no
293/// such place (the browser), which leaves the location alone.
294fn models_folder(store: &dyn ModelStore) -> Option<String> {
295    store.browser_places().into_iter().find(|place| place.kind == PlaceKind::Models).map(|place| place.location)
296}
297
298/// A probed `.step` upload waiting on the user's choice — the state that makes
299/// the §3.9 modal work across frames (egui draws every frame; the click can
300/// land many frames after the upload).
301///
302/// The PARSED assembly itself is NOT here: after a STEP outline nothing is
303/// parsed yet (`built == false`, the click starts the full read); after an
304/// IGES read it lives in the engine's stash, which the import consumes. This holds only what the prompt says and the `text` the flat
305/// lane needs — the two lanes that re-import from source rather than from the
306/// parse ("Import as bodies", and the structured lane's own failure fallback).
307struct PendingStepImport {
308    /// The uploaded file's name — the prompt's subject and the status line's.
309    name: String,
310    /// The file text. The engine's stash holds the PARSE, not the source, so
311    /// the flat lane's input has to be kept here.
312    text: String,
313    /// The counts the prompt shows, from the same walk the import runs.
314    probe: StepAssemblyProbe,
315    /// The §3.9 checkbox: flatten the sub-assembly tree to leaf occurrences
316    /// instead of building nested rigid sub-assembly documents. Only shown (and
317    /// only meaningful) when `probe.nested_depth > 1`; a depth-1 file imports
318    /// identically either way.
319    flatten: bool,
320    /// The engine is holding the full parse (an IGES file, read in full to
321    /// answer). `false` after a STEP outline: the counts came from the
322    /// structure alone, and "Import as assembly" starts the full read.
323    built: bool,
324}
325
326/// "Import as assembly" chosen on an outline: the full read (every product's
327/// bodies) is running on the runner, and the import consumes it when it lands.
328/// The dialog has closed; the user can keep working meanwhile.
329struct PendingStepBuild {
330    /// The engine's probe id of the full read.
331    id: u64,
332    /// The document view whose engine runs the read ([`Documents::view_id`]):
333    /// polled only while it is the one shown, so a tab switch neither loses
334    /// the answer nor reads another engine's ids for it.
335    owner: u64,
336    /// The choice as the user made it (name, text, counts, flatten).
337    import: PendingStepImport,
338    /// The read's answer, once [`FileDialog::poll_step_probe`] has taken it.
339    answer: Option<StepProbeOutcome>,
340}
341
342/// A `.step` upload whose structure read is RUNNING on the document's
343/// background runner (native thread / browser worker): the outline for a STEP
344/// file, the full read for an IGES one. Resolved by [`FileDialog::poll_step_probe`] into either the §3.9
345/// choice ([`PendingStepImport`]) or the flat lane.
346struct PendingStepProbe {
347    /// The engine's probe id, so a stale answer (a superseded upload) is ignored.
348    id: u64,
349    /// The document view whose engine runs it (see [`PendingStepBuild::owner`]).
350    owner: u64,
351    name: String,
352    /// The file text, kept for the flat lane the outcome may route to.
353    text: String,
354}
355
356/// What the user clicked in the §3.9 assembly-choice modal.
357#[derive(Clone, Copy, PartialEq, Eq)]
358enum StepChoice {
359    /// Keep the structure: parts-library entries + one component per occurrence.
360    Assembly,
361    /// Today's flat lane, unchanged: one IMPORT3D feature carrying the text.
362    Bodies,
363    /// Import nothing, and drop the parse (Esc / click-outside land here too).
364    Cancel,
365}
366
367/// What Insert component lists, and so the only files it inserts: parts, and
368/// the families and templates that each lead to a part.
369const INSERT_EXTENSIONS: &[&str] = MODEL_EXTENSIONS;
370
371/// One row of the member picker: a family row and where its member is.
372struct MemberChoice {
373    part_number: String,
374    description: String,
375    /// The member's store identity; `None` when the part number cannot be a
376    /// file name.
377    identity: Option<String>,
378    /// Whether that file exists (Generate has written it).
379    exists: bool,
380    /// On a PLM store: why the member cannot be placed (not generated, waiting
381    /// for its bake, failed it), as the server's family view says.
382    why_not: Option<String>,
383}
384
385/// An armed member picker: the family Insert component chose.
386struct PickMember {
387    /// The family's file name, for the heading.
388    family_file: String,
389    rows: Vec<MemberChoice>,
390    /// On a PLM store the members are parts: the list comes from the server
391    /// (`loading` until it has answered), and a chosen member's document is
392    /// read from it.
393    plm: bool,
394    loading: bool,
395}
396
397/// An armed template spin-out: the template Insert component chose, and the
398/// user's answers so far.
399struct SpinOut {
400    template_file: String,
401    template: serde_json::Value,
402    inputs: Vec<TemplateInput>,
403    /// The new part's name (no extension).
404    name: String,
405    /// Input name -> the value text the user typed or chose.
406    values: BTreeMap<String, String>,
407    /// Where the new part goes: the folder of the assembly being edited, or
408    /// the models folder when that assembly has never been saved.
409    assembly: Option<String>,
410    /// On a PLM store: the template part the SERVER spins out, and the new
411    /// part's number (empty lets a counter part type number it).
412    plm_template: Option<String>,
413    number: String,
414}
415
416/// PLM work the dialog waits on (plm-cad-integration-todo S9), polled each
417/// frame so the web build works the same.
418enum PlmWork {
419    /// The member picker's list.
420    Members(crate::panels::plm_family::Pending<Vec<crate::plm::family::Member>>),
421    /// A chosen member's (or a spun-out part's) document, to place: the key,
422    /// the text, and the part number it is named by.
423    Place(crate::panels::plm_family::Pending<(String, String, String)>),
424    /// Open the family a member came from: its newest revision's key.
425    OpenFamily(crate::panels::plm_family::Pending<String>),
426}
427
428/// "Also point these assemblies at the new file?" ([`Mode::Retarget`]).
429struct Retarget {
430    /// The part's previous name, as the assemblies spell their copies of it.
431    old: String,
432    new_key: String,
433    /// The part as it was saved under the new name.
434    text: String,
435    tabs: Vec<(u64, String)>,
436}
437
438/// A Save waiting for its answers ([`Mode::OwnedSave`]).
439struct OwnedPrompt {
440    plan: crate::document::owned_save::OwnedSavePlan,
441    /// The name the tab is being saved under.
442    name: String,
443    /// Save As through the explorer (`save_to_browser`), not a plain Save.
444    browser: bool,
445}
446
447/// The hand-edit prompt's subject: which tab, and the family it came from.
448struct MemberPrompt {
449    doc_id: u64,
450    source: FamilySource,
451    /// The family file's identity, beside the member.
452    family_identity: String,
453    /// The prompt came from plain Save rather than from an edit.
454    from_save: bool,
455}
456
457/// Make the engine's document a `class` document: the class field, and none
458/// of the other classes' blocks (a template saved as a part stops asking for
459/// inputs; a family saved as a template drops its table). No undo step: this
460/// is what the new FILE is, written as it is saved.
461/// The replace-component lineage stamp: a Save As under a NEW identity
462/// appends the identity the tab was saved under (and, for a family member,
463/// its family) to the document's `derivedFrom` chain. Silent: it is part of
464/// what the copy is, not an edit. A never-saved document records nothing.
465pub(crate) fn stamp_save_as_lineage(docs: &mut Documents, store: &dyn ModelStore, new_name: &str) {
466    let Some(old) = docs.active().name().map(str::to_string) else { return };
467    let old = store.canonical_identity(&old);
468    if old == store.canonical_identity(new_name) {
469        return;
470    }
471    let engine = docs.tab_engine_mut();
472    let mut document = serde_json::json!({});
473    for key in [brep_render::engine_state::replace_component::DERIVED_FROM_KEY, family_table::FAMILY_SOURCE_KEY] {
474        if let Some(block) = engine.history.document_block(key) {
475            document[key] = block.clone();
476        }
477    }
478    brep_render::engine_state::replace_component::stamp_derived_from(&mut document, &old);
479    engine.history.set_document_block_no_undo(
480        brep_render::engine_state::replace_component::DERIVED_FROM_KEY,
481        Some(document[brep_render::engine_state::replace_component::DERIVED_FROM_KEY].clone()),
482    );
483}
484
485fn adopt_class(engine: &mut EngineState, class: DocumentClass) {
486    document_class::set_document_class(engine, class);
487    let drop: &[&str] = match class {
488        DocumentClass::Normal => &[family_table::FAMILY_TABLE_KEY, template::TEMPLATE_INPUTS_KEY],
489        DocumentClass::Family => &[template::TEMPLATE_INPUTS_KEY],
490        DocumentClass::Template => &[family_table::FAMILY_TABLE_KEY],
491        DocumentClass::Instructions => &[family_table::FAMILY_TABLE_KEY, template::TEMPLATE_INPUTS_KEY],
492    };
493    for key in drop {
494        if engine.history.document_block(key).is_some() {
495            engine.history.set_document_block_no_undo(key, None);
496        }
497    }
498}
499
500/// Where a spun-out part is written: `<name>.nbrep` in the assembly's folder,
501/// or the bare file name (the models folder) when the assembly has none.
502fn spin_out_target(spin: &SpinOut) -> String {
503    let file = DocumentClass::Normal.file_name(spin.name.trim());
504    match &spin.assembly {
505        Some(assembly) => sibling_identity(assembly, &file),
506        None => file,
507    }
508}
509
510/// `"s"` unless there is exactly one — the difference between "1 parts" and a
511/// sentence a user believes.
512fn plural(count: usize) -> &'static str {
513    if count == 1 {
514        ""
515    } else {
516        "s"
517    }
518}
519
520/// The document name an imported assembly's unnamed products are stemmed from:
521/// the file's base name without its STEP extension, so a nameless product reads
522/// `bracket-assy-part-7`, not `bracket-assy.step-part-7`.
523/// A document title as a file stem: path separators and the characters a
524/// file name cannot hold become `-`; leading and trailing dots, spaces and
525/// dashes go.
526fn file_stem_of_title(title: &str) -> String {
527    let stem: String = title.chars().map(|c| if c.is_control() || "/\\:*?\"<>|".contains(c) { '-' } else { c }).collect();
528    stem.trim_matches(|c: char| c == '.' || c == ' ' || c == '-').to_string()
529}
530
531fn step_document_name(file_name: &str) -> String {
532    let base = file_name.rsplit(['/', '\\']).next().unwrap_or(file_name);
533    let cut = base
534        .rfind('.')
535        .filter(|dot| is_step_name(&base[*dot..]) || is_iges_name(&base[*dot..]) || is_parasolid_name(&base[*dot..]))
536        .unwrap_or(base.len());
537    let stem = &base[..cut];
538    if stem.is_empty() {
539        base.to_string()
540    } else {
541        stem.to_string()
542    }
543}
544
545/// The §3.9 outcome line: `imported bracket-assy.step — 7 parts, 23 components
546/// (2 mirrored instances baked)`, plus the tail an imperfect import owes the
547/// user. Every qualifier is reported ONLY when it happened, so a clean import
548/// reads clean — but a partial one never reads as a whole one:
549///
550/// * `baked_nonrigid` — occurrences whose mirror/scale was baked into a part of
551///   their own (§3.4), which is why the part count can exceed the file's;
552/// * `failed_products` — products that did not encode, skipped and counted;
553/// * `flat_fallback` — the user asked for an assembly and got bodies. Said
554///   plainly, never silently (the dialog lane reports this through the Err
555///   branch instead, which is the only way it can reach the user from here);
556/// * `first_error` — the one thing that explains the rest.
557/// The STEP-assembly import's [`PartSink`]: writes each unique part document to
558/// the model store and hands back the identity it was stored under, so an
559/// imported part carries a REAL `sourceKey` and there is no second kind of part.
560///
561/// # The destination
562///
563/// `browser_write` at the explorer's CURRENT location, under
564/// `{assembly}-{part}` — the convention `panels::step_parts` already uses for a
565/// single STEP part (that panel lets the user pick the folder first; the
566/// assembly modal inherits wherever the explorer is pointing).
567///
568/// The kernel plan's alternative — a `{assembly}/{part}.nbrep` SUB-FOLDER —
569/// is not reachable through this door: every `browser_write` implementation
570/// flattens the name to a single file (native takes `file_name()`, web takes
571/// `model_display_name`), so a sub-path would silently collapse. Writing the
572/// assembly name into the FILE name keeps a 50-part import grouped in one
573/// listing without a folder convention this seam cannot express. Creating and
574/// navigating into a folder as a side effect of an import is the prompt this
575/// lane would have to grow, and it is not bolted on here.
576///
577/// A failed write is per part: that part stays embedded-only (`None`) and the
578/// import continues. Losing one part's FILE is recoverable; losing the import
579/// is not.
580///
581/// # Known limit of a flat name
582///
583/// `taken` is per IMPORT, so re-importing the same file reuses the same names —
584/// which is what makes cross-import dedup work (same key, same signature, the
585/// resident entry is reused). But two DIFFERENT assemblies whose document names
586/// sanitize to the same stem (`as1-ug` and `as1_ug`) write to each other's file
587/// names. The second import wins the file; the first assembly's entry then
588/// disagrees with it, so it badges outdated and the write-through guard refuses
589/// to clobber it — visible and recoverable (the embedded document is intact),
590/// but two assemblies sharing one name. The fix is the per-assembly sub-folder
591/// `browser_write` cannot express; see the kernel plan's §3.5.
592struct StorePartSink<'a> {
593    store: &'a dyn ModelStore,
594    /// Prefixes every file name, so one import's parts sort together.
595    prefix: String,
596    /// File names already claimed this import — two STEP products can sanitize
597    /// to the same name, and the second must not overwrite the first's file
598    /// (that would leave two entries pointing at one document).
599    taken: std::collections::HashSet<String>,
600    written: usize,
601    failures: Vec<String>,
602    /// On a PLM store a part is an ITEM, not a file at a location: the
603    /// browser's `/models/<name>` key is one the PLM cannot hold. The parts
604    /// stay embedded and become items when the assembly is saved (the Save's
605    /// promotion, `document::owned_save`, at every depth, one item per
606    /// content), so nothing is written here and `deferred` counts them.
607    plm: bool,
608    deferred: usize,
609}
610
611impl<'a> StorePartSink<'a> {
612    fn new(store: &'a dyn ModelStore, prefix: &str) -> Self {
613        Self {
614            store,
615            prefix: sanitize_file_stem(prefix),
616            taken: std::collections::HashSet::new(),
617            written: 0,
618            failures: Vec::new(),
619            plm: store.plm_client().is_some(),
620            deferred: 0,
621        }
622    }
623}
624
625impl PartSink for StorePartSink<'_> {
626    fn store_part(&mut self, part_name: &str, document_json: &str) -> Option<String> {
627        if self.plm {
628            self.deferred += 1;
629            return None;
630        }
631        let base = format!("{}-{}", self.prefix, sanitize_file_stem(part_name));
632        let mut name = base.clone();
633        let mut suffix = 2;
634        while !self.taken.insert(name.clone()) {
635            name = format!("{base}-{suffix}");
636            suffix += 1;
637        }
638        match self.store.browser_write(&name, document_json) {
639            Ok(identity) => {
640                self.written += 1;
641                Some(identity)
642            }
643            Err(error) => {
644                self.failures.push(format!("{name}: {error}"));
645                None
646            }
647        }
648    }
649}
650
651/// A STEP product name reduced to something every store backend can hold as a
652/// file name: ASCII word characters, `.`, `-` kept; everything else (spaces,
653/// slashes, the `(mirrored)` parentheses this crate appends) becomes `_`. Runs
654/// of `_` collapse and the ends are trimmed, so a name is readable rather than
655/// a row of underscores. Empty input yields `part`.
656/// The Save dialog's row for the document being saved itself, when it is a
657/// PLM revision this user cannot save yet: check it out (default yes), or
658/// `Blocked` when nobody can say yes (checked out by someone else, released).
659/// `None` when it can be saved as it is, or is not a PLM revision.
660fn top_checkout_row(docs: &Documents, store: &dyn ModelStore, name: &str) -> Option<crate::document::owned_save::Planned> {
661    use crate::document::owned_save::{Issue, OwnedWrite, Planned};
662    let client = store.plm_client()?;
663    let (part, revision) = crate::panels::plm_host::revision_of(name)?;
664    let doc = docs.active();
665    if matches!(doc.save_access(), crate::document::Access::Editable) && doc.has_plm_save_access() {
666        return None;
667    }
668    let viewer = client.can_author() == Some(false);
669    let issue = match store.plm_revision(&crate::plm::identity::document_key(&part, &revision)) {
670        Some(entry) if entry.editable && entry.locked_by_me => return None,
671        _ if viewer => Issue::Blocked(crate::document::owned_save::VIEW_ONLY.into()),
672        Some(entry) if !entry.editable => {
673            Issue::Blocked(format!("PLM revision {} is {} and not editable", entry.revision_label, entry.lifecycle))
674        }
675        Some(entry) if entry.locked_by.is_some() => Issue::Blocked(format!("checked out by {}", entry.locked_by.unwrap_or_default())),
676        _ => Issue::CheckOut { part, revision, newer: false },
677    };
678    let write = OwnedWrite { key: name.to_string(), names: Vec::new(), depth: 0, text: String::new(), synced: String::new(), variants: Vec::new() };
679    Some(Planned { write, issue: Some(issue), proceed: true, choice: 0, edited_last: None })
680}
681
682/// A checkout or new revision the Save asked for failed AFTER the assembly
683/// `id` was written, and its copies were just marked: the stored assembly
684/// holds the change without the mark, so the next open (here or on another
685/// client) would refresh the copy and lose it. Write the mark into it.
686fn write_late_marks(docs: &mut Documents, store: &dyn ModelStore, id: u64, was_clean: bool) {
687    if let Err(error) = docs.write_unsaved_marks(store, id, was_clean) {
688        docs.engine_mut().push_notice(format!("Save the assembly again: the change it keeps could not be marked in it ({error})"));
689    }
690}
691
692/// One PLM item to make per distinct new key of `plan`'s promotions:
693/// `(new key it replaces, part name, part type)`. The type is the document's
694/// own kind, as the PLM import wizard picks it: `assembly` when it places
695/// components, else `component`.
696fn plm_promotion_requests(current: &serde_json::Value, plan: &crate::document::owned_save::OwnedSavePlan) -> Vec<(String, String, String)> {
697    let mut requests: Vec<(String, String, String)> = Vec::new();
698    for promotion in &plan.promotions {
699        if requests.iter().any(|(key, ..)| *key == promotion.new_key) {
700            continue;
701        }
702        let mut document = current;
703        for name in &promotion.names {
704            document = &document["partsLibrary"][name]["document"];
705        }
706        let part = promotion.names.last().cloned().unwrap_or_default();
707        requests.push((promotion.new_key.clone(), part, crate::plm::promote::part_type_of(document).to_string()));
708    }
709    requests
710}
711
712/// Every promotion of `plan` takes the PLM key made for its new key.
713fn assign_plm_keys(plan: &mut crate::document::owned_save::OwnedSavePlan, keys: &[String]) {
714    let mut order: Vec<String> = Vec::new();
715    for promotion in &plan.promotions {
716        if !order.contains(&promotion.new_key) {
717            order.push(promotion.new_key.clone());
718        }
719    }
720    for promotion in &mut plan.promotions {
721        if let Some(key) = order.iter().position(|k| *k == promotion.new_key).and_then(|i| keys.get(i)) {
722            promotion.new_key = key.clone();
723        }
724    }
725}
726
727pub(crate) fn sanitize_file_stem(name: &str) -> String {
728    let mut out = String::with_capacity(name.len());
729    for ch in name.chars() {
730        if ch.is_ascii_alphanumeric() || ch == '.' || ch == '-' {
731            out.push(ch);
732        } else if !out.ends_with('_') {
733            out.push('_');
734        }
735    }
736    let trimmed = out.trim_matches('_');
737    if trimmed.is_empty() {
738        "part".to_string()
739    } else {
740        trimmed.to_string()
741    }
742}
743
744fn assembly_import_message(name: &str, report: &StepAssemblyReport) -> String {
745    let mut message = format!(
746        "imported {name} \u{2014} {} part{}, {} component{}",
747        report.parts,
748        plural(report.parts),
749        report.instances,
750        plural(report.instances)
751    );
752    if report.baked_nonrigid > 0 {
753        message.push_str(&format!(
754            " ({} mirrored instance{} baked)",
755            report.baked_nonrigid,
756            plural(report.baked_nonrigid)
757        ));
758    }
759    if report.failed_products > 0 {
760        message.push_str(&format!(
761            "; {} product{} could not be built",
762            report.failed_products,
763            plural(report.failed_products)
764        ));
765    }
766    if report.flat_fallback {
767        message.push_str("; the structure was NOT used \u{2014} the bodies came in flat");
768    }
769    if let Some(error) = &report.first_error {
770        message.push_str(&format!(" [{error}]"));
771    }
772    message
773}
774
775/// What an imported file is, by its extension: the ONE routing table every
776/// import door shares — File > Import's explorer, the upload poll, and a file
777/// the OS hands the app (`brep-app part.step`, a double click on a file the
778/// app is an opener for). Each kind names the importer the File menu already
779/// uses; nothing here imports by itself.
780#[derive(Clone, Copy, Debug, PartialEq, Eq)]
781pub(crate) enum ImportKind {
782    /// A `.kicad_sym` / `.kicad_mod`: the KiCad dialog takes it from there.
783    Kicad,
784    /// STEP (Part 21): probe for an assembly, else the flat IMPORT3D lane.
785    Step,
786    /// IGES: the STEP lane's probe (subfigure instances raise the same choice).
787    Iges,
788    /// Parasolid text (`.x_t`, `.xmt_txt`, a `.p_t` partition): the STEP
789    /// lane's probe, which answers flat; the Import 3D Model feature reads it.
790    Parasolid,
791    /// Parasolid binary (`.x_b`, `.xmt_bin`, a `.p_b` partition): straight to
792    /// the Import 3D Model feature, which reads the bytes.
793    ParasolidBinary,
794    /// A SolidWorks part (`.sldprt`): its body, a Parasolid partition, into
795    /// the Import 3D Model feature.
796    SolidWorksPart,
797    /// A SolidWorks assembly (`.sldasm`): its parts, read from beside it on
798    /// disk, placed in one Import 3D Model feature.
799    SolidWorksAssembly,
800    /// STL: the mesh reconstruction preview.
801    Stl,
802    /// 3MF: the STL lane — the same preview, tolerances and accept.
803    ThreeMf,
804    /// OBJ: reconstructed in the background into an IMPORT3D feature.
805    Obj,
806}
807
808/// Every extension the app imports, lowercase without the dot, and its kind.
809/// Model documents (`.nbrep`, `.fbrep`, `.tbrep`) are not here: they open.
810pub(crate) const IMPORT_TABLE: &[(&str, ImportKind)] = &[
811    ("step", ImportKind::Step),
812    ("stp", ImportKind::Step),
813    ("p21", ImportKind::Step),
814    ("iges", ImportKind::Iges),
815    ("igs", ImportKind::Iges),
816    ("x_t", ImportKind::Parasolid),
817    ("xmt_txt", ImportKind::Parasolid),
818    ("p_t", ImportKind::Parasolid),
819    ("x_b", ImportKind::ParasolidBinary),
820    ("xmt_bin", ImportKind::ParasolidBinary),
821    ("p_b", ImportKind::ParasolidBinary),
822    ("sldprt", ImportKind::SolidWorksPart),
823    ("sldasm", ImportKind::SolidWorksAssembly),
824    ("stl", ImportKind::Stl),
825    ("3mf", ImportKind::ThreeMf),
826    ("obj", ImportKind::Obj),
827    ("kicad_sym", ImportKind::Kicad),
828    ("kicad_mod", ImportKind::Kicad),
829];
830
831/// The extensions of [`IMPORT_TABLE`], for the explorer's filter and the
832/// system file chooser (a test holds the two lists equal).
833const IMPORT_EXTENSIONS: &[&str] =
834    &["step", "stp", "p21", "iges", "igs", "x_t", "xmt_txt", "p_t", "x_b", "xmt_bin", "p_b", "sldprt", "sldasm", "stl", "3mf", "obj", "kicad_sym", "kicad_mod"];
835
836/// The import kind of a file name or path, by its last extension in any case;
837/// `None` for a model document or anything the app does not import. Model
838/// documents arrive extension-stripped (web) or as a stored model name, so
839/// this never mis-routes a `.nbrep` file.
840pub(crate) fn import_kind(name: &str) -> Option<ImportKind> {
841    let base = name.rsplit(['/', '\\']).next().unwrap_or(name);
842    let (_, ext) = base.rsplit_once('.')?;
843    let ext = ext.to_ascii_lowercase();
844    IMPORT_TABLE.iter().find(|(e, _)| *e == ext).map(|(_, kind)| *kind)
845}
846
847/// Whether an imported file name is a STEP file (`.step` / `.stp` / `.p21`,
848/// any case).
849fn is_step_name(name: &str) -> bool {
850    import_kind(name) == Some(ImportKind::Step)
851}
852
853/// Whether an imported file name is an IGES file (`.iges` / `.igs`, any case).
854fn is_iges_name(name: &str) -> bool {
855    import_kind(name) == Some(ImportKind::Iges)
856}
857
858/// Whether an imported file name is a Parasolid part or partition, text or
859/// binary (`.x_t`, `.x_b`, …, any case).
860fn is_parasolid_name(name: &str) -> bool {
861    matches!(import_kind(name), Some(ImportKind::Parasolid | ImportKind::ParasolidBinary))
862}
863
864/// The name a file imported into a tab of its own is shown under: the file's
865/// base name without its import extension (`/tmp/Bracket.STEP` -> `Bracket`).
866pub(crate) fn import_document_name(file_name: &str) -> String {
867    let base = file_name.rsplit(['/', '\\']).next().unwrap_or(file_name);
868    match base.rsplit_once('.') {
869        Some((stem, _)) if !stem.is_empty() && import_kind(base).is_some() => stem.to_string(),
870        _ => base.to_string(),
871    }
872}
873
874mod component_part;
875
876/// A Save's new PLM revisions, in flight ([`FileDialog::poll_owned_revisions`]).
877struct OwnedRevisions {
878    /// The assembly tab whose copies re-point to them.
879    doc: u64,
880    /// Deepest first, as planned.
881    requests: Vec<crate::document::owned_save::CheckoutRequest>,
882    /// Each request's new key and the text written there, or why not.
883    future: crate::plm::PlmFuture<Vec<Result<(String, String), String>>>,
884}
885
886/// The Save that follows a Save's new revisions ([`FileDialog::poll_owned_checkouts`]).
887struct OwnedFollowup {
888    doc: u64,
889    /// The new revisions' keys: the Save waits until the index has each.
890    keys: Vec<String>,
891    /// When the wait for the index began (once every checkout and new
892    /// revision had landed); past the cap the Save goes ahead and asks about
893    /// what the index still lacks. Wall time, not frames: a client that draws
894    /// frames quickly would otherwise spend the wait in a fraction of it.
895    since: Option<web_time::Instant>,
896}
897
898struct PendingInstructionsPdf {
899    document: u64,
900    name: String,
901    preview: bool,
902    job: brep_render::engine_state::InstructionsPdfExport,
903}
904
905/// The reusable file dialog — transient UI buffers + the current document
906/// identity; the model itself lives in `EngineState`'s history.
907pub struct FileDialog {
908    /// Demand-loaded open, scoped to the requesting tab. A newer open or
909    /// navigation cancels it so a delayed response cannot steal focus.
910    pending_open: Option<(String, u64)>,
911    /// A cold component read belongs to the assembly tab that requested it.
912    pending_insert: Option<(String, u64)>,
913    component_part: Option<component_part::Recovery>,
914    /// Reusable browser body shared by Open, Save As, and ACOMP selection.
915    explorer: FileExplorer,
916    /// In a PLM session the Open modal is the workspace browser instead (S14, D12). It
917    /// lives here so the folder the user was in is where Open starts next time.
918    workspace: crate::panels::plm_workspace::WorkspaceBrowser,
919    /// The name field buffer, used by the Save As modal.
920    name_buf: String,
921    /// Last-action status line, surfaced inside the modal.
922    pub(crate) status: String,
923    /// Whether a modal is currently open.
924    open: bool,
925    /// The open modal's mode (only meaningful while `open`).
926    mode: Mode,
927    /// Set on open so the Save As text input grabs focus on the next frame.
928    want_focus: bool,
929    /// A pending real-file pick belongs to the INSERT-COMPONENT flow (the
930    /// modal's Upload fired there): the next completed `take_import` routes to
931    /// the component insert instead of Open's load-document.
932    pending_component_import: bool,
933    /// The tab index a pending [`Mode::ConfirmClose`] will close on "Discard".
934    pending_close: Option<(u64, u64)>,
935    /// A probed STEP assembly waiting on the §3.9 choice modal. With `built`
936    /// the ENGINE is holding a parsed assembly for us (every product's solids
937    /// resident), so every exit from that modal must end its life: import it,
938    /// discard it, or be superseded by the next upload.
939    pending_step_import: Option<PendingStepImport>,
940    /// A `.step` upload whose probe has not answered yet (see
941    /// [`PendingStepProbe`]); the status line says "reading…" meanwhile.
942    pending_step_probe: Option<PendingStepProbe>,
943    /// An assembly import chosen before its full read finished (see
944    /// [`PendingStepBuild`]).
945    pending_step_build: Option<PendingStepBuild>,
946    /// The document view being drawn this frame ([`Documents::view_id`]), set
947    /// before the STEP polls: probe ids are per engine, so each pending read
948    /// is polled only against the engine that runs it.
949    step_view: u64,
950    /// A step-images or offline-player export held until its geometry or tool
951    /// pictures arrive. PDFs use their own incremental job below.
952    pending_instructions_export: Option<String>,
953    /// PDF preparation is polled between frames; its document and name stay pinned.
954    instructions_pdf: Option<PendingInstructionsPdf>,
955    /// A mesh file waiting to open its reconstruction preview, with the reader
956    /// the picker routed it to (STL or 3MF).
957    pending_stl_import: Option<(MeshImportFormat, String, Vec<u8>)>,
958    /// Bumped on every SUCCESSFUL store save (plain Save / Save As / native
959    /// Save-As) — one half of the update-components staleness key (saving a
960    /// part's source must re-check the outdated badges without a reload).
961    save_generation: u64,
962    plm_save_as: Option<plm_save_as::SaveAs>,
963    /// The hand-edit prompt chose "Save as a new part" on a PLM: the Save As
964    /// it opens starts on the NEW PART destination (never on overwriting the
965    /// generated member or its revision). Consumed when that Save As opens.
966    member_new_part: bool,
967    /// Per-frame widget hit-rects for the headed verifier (wasm only).
968    hits: HashMap<String, egui::Rect>,
969    /// The KiCad import's stages after its file.
970    kicad: KicadImport,
971    /// The last folder of each [`Purpose`], taken from the store's explorer
972    /// location every frame its modal is open.
973    folders: HashMap<Purpose, String>,
974    /// The file chooser: which panel asked (its tag) and the modal's title,
975    /// the folder it was last in (on the LOCAL files), and what it delivered.
976    pick_request: Option<(String, String)>,
977    pick_folder: Option<String>,
978    picked: Option<(String, PickedFile)>,
979    /// Save As → "A new part" in a PLM session: the shell opens the PLM pane's New part
980    /// form (S7), which writes this document into the new part's first revision.
981    plm_new_part: bool,
982    /// The class Save As writes (its class chooser).
983    save_class: DocumentClass,
984    /// The armed member picker ([`Mode::PickMember`]).
985    pick_member: Option<PickMember>,
986    plm_work: Option<PlmWork>,
987    /// The armed template spin-out ([`Mode::SpinOut`]).
988    spin_out: Option<SpinOut>,
989    /// The armed hand-edit prompt ([`Mode::MemberEdit`]).
990    member_prompt: Option<MemberPrompt>,
991    /// An assembly Save waiting for the answers to its questions
992    /// ([`Mode::OwnedSave`]).
993    owned_prompt: Option<OwnedPrompt>,
994    /// The last assembly Save's owned documents, for automation: the open
995    /// question (`prompt`) or what was done (`report`).
996    owned_state: serde_json::Value,
997    /// PLM items being checked out by an assembly Save; each is written when
998    /// its checkout lands.
999    owned_checkouts: Vec<(crate::document::owned_save::CheckoutRequest, crate::plm::PlmFuture<()>)>,
1000    /// The new revisions a Save asked for, made one after another deepest
1001    /// first (a holder's revision names the revisions made under it): each
1002    /// request with its new key and written text, or why not.
1003    owned_revisions: Option<OwnedRevisions>,
1004    /// The tab a Save made new revisions for: saved again once every request
1005    /// has landed and the PLM index knows the new revisions, so the documents
1006    /// holding them name them (and are not taken for missing files).
1007    owned_followup: Option<OwnedFollowup>,
1008    /// A Save of a PLM assembly held while the PLM makes an item for each part
1009    /// that has no document of its own; the answer is each item's key, in the
1010    /// order of [`plm_promotion_requests`].
1011    /// A Save held while its PLM items are made, with where they are linked
1012    /// ("your workspace folder 'X'" or "the top of your workspace").
1013    /// A Save held while PLM items are made: its prompt, and the items' keys
1014    /// with the workspace folder they were linked in (`(id, name)`; `None`:
1015    /// the top).
1016    #[allow(clippy::type_complexity)]
1017    owned_promoting: Option<(OwnedPrompt, crate::plm::PlmFuture<(Vec<String>, Option<(String, String)>)>)>,
1018    /// A Save held until the stored documents it writes have loaded (a PLM
1019    /// session lists every revision but reads one's bytes only when asked):
1020    /// `(tab id, name, keys, frames waited)`. Then the Save is planned again.
1021    owned_loading: Option<(u64, String, Vec<String>, u32)>,
1022    /// The held Save is being made again: plan it with what loaded, and do
1023    /// not hold it a second time.
1024    owned_loaded: bool,
1025    /// The Save's own document, a PLM revision that was not checked out to
1026    /// this user: written once its checkout lands. `(tab id, signature it
1027    /// was saved at, request, checkout)`.
1028    owned_top: Option<(u64, String, crate::document::owned_save::CheckoutRequest, crate::plm::PlmFuture<()>)>,
1029    /// The open assemblies that place a part just saved under a new name,
1030    /// waiting for the answer to "point them at the new file too?".
1031    retarget: Option<Retarget>,
1032    /// "Check out without asking again in this session" (the Save dialog's
1033    /// checkbox): checkout rows no longer ask.
1034    checkout_remembered: bool,
1035    /// Tabs whose user chose "Save as a new part": they may keep editing
1036    /// without being asked again; plain Save still asks.
1037    member_ack: HashSet<u64>,
1038    /// The last Generate's report, for the automation blob.
1039    last_generate: Option<family_table::GenerateReport>,
1040    /// The export the Save-file chooser holds ([`Mode::SaveFile`]), and the
1041    /// chooser's own name field — its own, so the Export dialog's stem
1042    /// (`name_buf`) is what the next export starts from again.
1043    save_file: Option<PendingSave>,
1044    save_name: String,
1045}
1046
1047impl FileDialog {
1048    /// A closed dialog with empty buffers. Document identity (name + clean
1049    /// baseline) lives on [`Document`], so there is nothing to seed here.
1050    pub fn new() -> Self {
1051        Self {
1052            pending_open: None,
1053            pending_insert: None,
1054            component_part: None,
1055            explorer: FileExplorer::new(),
1056            workspace: crate::panels::plm_workspace::WorkspaceBrowser::new(),
1057            name_buf: String::new(),
1058            status: String::new(),
1059            open: false,
1060            mode: Mode::Open,
1061            want_focus: false,
1062            pending_component_import: false,
1063            pending_close: None,
1064            pending_step_import: None,
1065            pending_step_probe: None,
1066            pending_step_build: None,
1067            step_view: 0,
1068            pending_instructions_export: None,
1069            instructions_pdf: None,
1070            pending_stl_import: None,
1071            save_generation: 0,
1072            plm_save_as: None,
1073            member_new_part: false,
1074            hits: HashMap::new(),
1075            kicad: KicadImport::new(),
1076            folders: HashMap::new(),
1077            pick_request: None,
1078            pick_folder: None,
1079            picked: None,
1080            plm_new_part: false,
1081            save_class: DocumentClass::Normal,
1082            pick_member: None,
1083            plm_work: None,
1084            spin_out: None,
1085            member_prompt: None,
1086            owned_prompt: None,
1087            owned_state: serde_json::Value::Null,
1088            owned_checkouts: Vec::new(),
1089            owned_revisions: None,
1090            owned_followup: None,
1091            owned_promoting: None,
1092            owned_loading: None,
1093            owned_loaded: false,
1094            owned_top: None,
1095            retarget: None,
1096            checkout_remembered: false,
1097            member_ack: HashSet::new(),
1098            last_generate: None,
1099            save_file: None,
1100            save_name: String::new(),
1101        }
1102    }
1103
1104    /// The dialog's own work in flight, for the status bar's working
1105    /// indicator: a KiCad part's 3D model being parsed off the UI thread.
1106    pub fn busy_activities(&self) -> Vec<crate::panels::busy::Activity> {
1107        let mut out = Vec::new();
1108        if let Some(export) = &self.instructions_pdf {
1109            let (done, total) = export.job.progress();
1110            out.push(crate::panels::busy::Activity::new("instructionsPdf", "instructionsPdf", format!("Preparing instructions PDF: {done}/{total} pictures")));
1111        }
1112        if self.owned_loading.is_some() {
1113            out.push(crate::panels::busy::Activity::new("saveReading", "saveReading", "Reading parts from the PLM before saving"));
1114        }
1115        if self.kicad.reading() {
1116            out.push(crate::panels::busy::Activity::new("kicadRead", "kicadRead", "Reading the KiCad part's 3D model"));
1117        }
1118        out
1119    }
1120
1121    pub fn instructions_pdf_pending(&self) -> bool {
1122        self.instructions_pdf.is_some()
1123    }
1124
1125    /// A PLM Save As is writing its copy. The dialog polls that future itself,
1126    /// outside the PLM executor, so automation waits ask here instead.
1127    pub fn plm_save_as_pending(&self) -> bool {
1128        self.plm_save_as.as_ref().is_some_and(|state| state.saving())
1129    }
1130
1131    /// The monotonic successful-save counter — the shell feeds it to the
1132    /// update-components checker as half its staleness key.
1133    pub fn save_generation(&self) -> u64 {
1134        self.save_generation
1135    }
1136
1137    // --- dispatch: a toolbar button was clicked -------------------------------
1138
1139    /// Act on a toolbar file button. New acts immediately (it adds a tab, so
1140    /// there is nothing to discard); all browsing flows use the same in-app
1141    /// modal on both platforms.
1142    pub fn dispatch(&mut self, action: FileAction, docs: &mut Documents, store: &dyn ModelStore) {
1143        if matches!(action, FileAction::New | FileAction::NewOfClass(_) | FileAction::Open | FileAction::Import) {
1144            self.pending_open = None;
1145            self.pending_insert = None;
1146        }
1147        match action {
1148            FileAction::New => self.new_document(docs, DocumentClass::Normal),
1149            FileAction::NewOfClass(class) => self.new_document(docs, class),
1150            FileAction::Open => {
1151                self.use_folder(Purpose::Models, store);
1152                // A PLM session's Open starts in the user's Home every time.
1153                if store.plm_client().is_some() {
1154                    self.workspace.go_home();
1155                }
1156                self.open_modal(Mode::Open);
1157            }
1158            FileAction::Save => match docs.active().name().map(str::to_string) {
1159                // A family member is not saved over by hand: the prompt says
1160                // why and offers the two ways that are.
1161                Some(name) if self.arm_member_prompt(docs, &name, true) => {}
1162                // A PLM revision saves like any document: a checkout it
1163                // needs is a row of the one Save dialog (see `top_checkout_row`).
1164                // A named document saves straight to its name.
1165                Some(name) => {
1166                    let _ = self.save_to(docs, store, name);
1167                }
1168                // An unnamed document falls through to Save As.
1169                None => self.dispatch(FileAction::SaveAs, docs, store),
1170            },
1171            FileAction::SaveAs => {
1172                self.name_buf = Self::proposed_name(docs);
1173                self.save_class = document_class::document_class(docs.engine());
1174                self.use_folder(Purpose::Models, store);
1175                self.open_modal(Mode::SaveAs);
1176            }
1177            FileAction::Import => {
1178                self.use_folder(Purpose::Imports, browse_store(Purpose::Imports, store));
1179                self.open_modal(Mode::Import);
1180            }
1181            // The stem without the class extension, like Save As: a family's
1182            // STEP is `bolt-family.step`, not `bolt-family.fbrep.step`.
1183            FileAction::Export => {
1184                self.name_buf = Self::proposed_name(docs);
1185                self.open_modal(Mode::Export);
1186            }
1187            FileAction::ExportFlatPattern => {
1188                self.name_buf = Self::proposed_name(docs);
1189                self.open_modal(Mode::FlatPattern);
1190            }
1191            // ALWAYS the in-app modal (never the native picker directly): the
1192            // "existing library entries first" list is an in-app concept; the
1193            // modal's own Upload button drives the platform picker when the
1194            // store supports interchange.
1195            FileAction::InsertComponent => {
1196                self.use_folder(Purpose::Models, store);
1197                self.open_modal(Mode::InsertComponent);
1198            }
1199            FileAction::ImportKicad(kind) => {
1200                self.kicad.start(kind, store);
1201                self.use_folder(Purpose::Kicad, browse_store(Purpose::Kicad, store));
1202                self.open_modal(Mode::Kicad);
1203            }
1204        }
1205    }
1206
1207    /// Ask for a file (plm-cad-integration-todo S8 / S14's "Add file…"). `tag`
1208    /// names the asker, which takes the file with [`Self::take_picked_file`];
1209    /// `title` heads the chooser. Natively the chooser is this dialog's own
1210    /// explorer over the machine's files (one behaviour on every platform, and
1211    /// drivable by scripts); in the browser it is the page's file input.
1212    /// `Err` where neither exists.
1213    pub fn request_pick_file(&mut self, store: &dyn ModelStore, tag: &str, title: &str) -> Result<(), String> {
1214        self.picked = None;
1215        if let Some(local) = store.local_files() {
1216            let arrived = self.pick_folder.as_deref().is_some_and(|folder| local.browser_navigate(folder).is_ok());
1217            if !arrived {
1218                let _ = local.browser_home();
1219            }
1220            self.pick_request = Some((tag.to_string(), title.to_string()));
1221            self.status.clear();
1222            self.open_modal(Mode::PickFile);
1223            return Ok(());
1224        }
1225        store.begin_pick_file()?;
1226        self.pick_request = Some((tag.to_string(), title.to_string()));
1227        Ok(())
1228    }
1229
1230    /// The file the chooser delivered for `tag`, once.
1231    pub fn take_picked_file(&mut self, tag: &str) -> Option<PickedFile> {
1232        if self.picked.as_ref().is_some_and(|(asker, _)| asker == tag) {
1233            return self.picked.take().map(|(_, file)| file);
1234        }
1235        None
1236    }
1237
1238    /// Whether a pick for `tag` is still open (the chooser is up, or the
1239    /// browser's is and has not answered).
1240    pub fn picking(&self, tag: &str) -> bool {
1241        self.pick_request.as_ref().is_some_and(|(asker, _)| asker == tag)
1242    }
1243
1244    /// The chooser: the shared explorer over the LOCAL files, every file shown.
1245    fn show_pick_file(&mut self, ctx: &egui::Context, store: &dyn ModelStore) {
1246        let Some(local) = store.local_files() else {
1247            self.open = false;
1248            self.pick_request = None;
1249            return;
1250        };
1251        let title = self.pick_request.as_ref().map(|(_, title)| title.clone()).unwrap_or_else(|| "Choose a file".into());
1252        let modal = egui::Modal::new(egui::Id::new("brep-file-pick-file")).show(ctx, |ui| {
1253            file_explorer::dialog_body(ui, |ui| {
1254                ui.heading(&title);
1255                ui.add_space(4.0);
1256                file_explorer::dialog_footer(ui, "pickfile", |ui| {
1257                    if !self.status.is_empty() {
1258                        ui.add_space(4.0);
1259                        ui.weak(&self.status);
1260                    }
1261                });
1262                let options = FileExplorerOptions {
1263                    hit_prefix: "pickfile",
1264                    empty_label: "(this folder is empty)",
1265                    row_icon: "\u{1F5CE}",
1266                    current: None,
1267                    allow_delete: false,
1268                    allow_import: false,
1269                    import_label: "",
1270                    import_hit: "pickfile:upload",
1271                    show_cancel: true,
1272                    confirm_label: Some("Choose"),
1273                    extensions: &[],
1274                };
1275                let output = self.explorer.show_store(ui, local, options);
1276                self.record_explorer_hits(&output.hits);
1277                output
1278            })
1279        });
1280        let should_close = modal.should_close();
1281        let output = modal.inner;
1282        self.pick_folder = Some(local.browser_location());
1283        if let Some(path) = output.activated {
1284            match local.read_external_file(&path) {
1285                Some(bytes) => {
1286                    let name = std::path::Path::new(&path)
1287                        .file_name()
1288                        .map(|n| n.to_string_lossy().into_owned())
1289                        .unwrap_or_else(|| path.clone());
1290                    if let Some((tag, _)) = self.pick_request.take() {
1291                        self.status = format!("chose {name}");
1292                        self.picked = Some((tag, PickedFile { name, path: Some(path), bytes }));
1293                    }
1294                    self.open = false;
1295                }
1296                None => self.status = format!("'{path}' could not be read"),
1297            }
1298        } else if output.cancel || should_close {
1299            self.pick_request = None;
1300            self.status.clear();
1301            self.open = false;
1302        }
1303    }
1304
1305    /// Move the explorer to where `purpose` was last, or to the models folder
1306    /// the first time. A remembered folder that is gone falls back to the
1307    /// models folder too.
1308    fn use_folder(&mut self, purpose: Purpose, store: &dyn ModelStore) {
1309        let remembered = self.folders.get(&purpose).cloned();
1310        let arrived = remembered.is_some_and(|folder| store.browser_navigate(&folder).is_ok());
1311        if !arrived {
1312            if let Some(models) = models_folder(store) {
1313                let _ = store.browser_navigate(&models);
1314            }
1315        }
1316    }
1317
1318    /// Where the open modal's explorer is is where its purpose was last.
1319    fn remember_folder(&mut self, store: &dyn ModelStore) {
1320        if let Some(purpose) = self.mode.purpose() {
1321            self.folders.insert(purpose, browse_store(purpose, store).browser_location());
1322        }
1323    }
1324
1325    /// Open the modal in `mode` (and focus its input next frame).
1326    fn open_modal(&mut self, mode: Mode) {
1327        // Every opening is a new choice: the explorer is shared by every mode,
1328        // so a highlight left by the last one (Import's `Timer.kicad_sym`) would
1329        // otherwise be this one's confirm target (Insert component's).
1330        self.pending_insert = None;
1331        self.explorer.clear_selection();
1332        self.mode = mode;
1333        self.open = true;
1334        self.want_focus = true;
1335    }
1336
1337    // --- per-frame draw -------------------------------------------------------
1338
1339    /// Draw the modal (if open) and pick up any completed async import. Called
1340    /// every frame by the shell with a ctx-level handle (the modal is ctx-level,
1341    /// like the command palette).
1342    pub fn show(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
1343        self.hits.clear();
1344        self.poll_pending_open(ctx, docs, store);
1345        self.poll_pending_insert(ctx, docs, store);
1346        self.poll_plm_save_as(ctx, docs, store);
1347        self.poll_plm_work(ctx, docs, store);
1348        self.poll_open_workspace_pick(store);
1349        self.poll_owned_checkouts(ctx, docs, store);
1350        self.poll_owned_promotions(ctx, docs, store);
1351        self.poll_owned_loading(ctx, docs, store);
1352        if self.retarget.is_some() && !self.open {
1353            self.open_modal(Mode::Retarget);
1354        }
1355        // The browser's file chooser answered a pick.
1356        if let Some(file) = store.take_picked_file() {
1357            if let Some((tag, _)) = self.pick_request.take() {
1358                self.picked = Some((tag, PickedFile { name: file.name, path: None, bytes: file.bytes }));
1359            }
1360        }
1361
1362        // A STEP probe the runner has answered since last frame resolves into
1363        // the assembly choice or the flat import now, before drawing.
1364        self.step_view = docs.view_id();
1365        // A deferred assembly import whose document was closed has nobody left
1366        // to import into.
1367        if let Some(owner) = self.pending_step_build.as_ref().map(|build| build.owner) {
1368            if owner != self.step_view && docs.index_of_id(owner).is_none() {
1369                let build = self.pending_step_build.take().unwrap();
1370                docs.engine_mut().push_notice(format!(
1371                    "import of \"{}\" was cancelled: its document was closed",
1372                    build.import.name
1373                ));
1374            }
1375        }
1376        self.poll_step_probe(docs.engine_mut());
1377        // An assembly import chosen on the outline lands once its read has.
1378        self.poll_step_build(docs.engine_mut(), store);
1379        self.poll_instructions_pdf(ctx, docs, store);
1380        // An instructions export held for the exact solids runs once they
1381        // have landed (the busy line says "Loading exact geometry" meanwhile).
1382        if self.pending_instructions_export.is_some() && !docs.engine().topology_pending() && crate::plm::tool_pictures::pending() == 0 {
1383            if let Some(format) = self.pending_instructions_export.take() {
1384                self.export_as(docs, store, &format);
1385            }
1386        }
1387
1388        // A completed async browser upload is picked up
1389        // here, before drawing, so the model is live for this frame. Routed by
1390        // extension: a STEP file (`.step`/`.stp`) is APPENDED to the model as an
1391        // IMPORT3D feature; anything else is a `.nbrep` model document loaded
1392        // (replacing the model). The model lanes deliver an extension-less name
1393        // (web, stripped by `model_display_name`) or a stored model name, so only
1394        // real STEP files route here.
1395        if let Some(imported) = store.take_import() {
1396            // A new delivery SUPERSEDES an armed assembly choice. The modal
1397            // describes a parse this routing is about to replace (a STEP probe
1398            // drops the previous stash by contract, and a document load drops it
1399            // outright), so leaving the choice armed would offer the user a
1400            // button whose stash is already gone.
1401            self.cancel_pending_step_import(docs.engine_mut());
1402            let name = imported.name;
1403            let bytes = imported.bytes;
1404            // CAD/mesh imports target the active document. STL waits for
1405            // preview acceptance; model documents open in a separate tab.
1406            if let Some(kind) = import_kind(&name) {
1407                self.step_view = docs.view_id();
1408                if !self.import_file(kind, docs.engine_mut(), store, name, bytes) {
1409                    return;
1410                }
1411            } else if std::mem::take(&mut self.pending_component_import) {
1412                // The insert-component modal's Upload fired this pick: the
1413                // chosen document becomes a parts-library entry + an instance,
1414                // NOT a new tab — or, for a family or a template, the prompt
1415                // that leads to one.
1416                match String::from_utf8(bytes) {
1417                    Ok(contents) => {
1418                        let assembly = docs.active().name().map(str::to_string);
1419                        if !self.begin_class_insert(store, &name, &contents, assembly) {
1420                            self.insert_component_document(docs.engine_mut(), &name, &contents)
1421                        }
1422                        if self.pick_member.is_some() || self.spin_out.is_some() {
1423                            return;
1424                        }
1425                    }
1426                    Err(_) => self.status = format!("open failed: {name} is not UTF-8 text"),
1427                }
1428            } else {
1429                match String::from_utf8(bytes) {
1430                    Ok(contents) => self.load_document(docs, &name, &contents, store),
1431                    Err(_) => self.status = format!("open failed: {name} is not UTF-8 text"),
1432                }
1433            }
1434            self.close_after_import();
1435        }
1436
1437        // A family member the user has just started to change raises the
1438        // hand-edit prompt (unless they already chose "Save as a new part").
1439        // On every store (integrator ruling 2026-10-03): on a PLM the
1440        // prompt's "Save as a new part" hands off to the PLM Save As with a
1441        // NEW PART preselected, so the generated member is never written
1442        // over by hand.
1443        if !self.open {
1444            self.watch_member_edit(docs);
1445        }
1446
1447        if !self.open {
1448            return;
1449        }
1450        self.remember_folder(store);
1451
1452        match self.mode {
1453            Mode::CreateComponentPart => self.show_create_component_part(ctx, docs, store),
1454            Mode::ConfirmClose => self.show_confirm_close(ctx, docs),
1455            Mode::SaveAs => self.show_save_as(ctx, docs, store),
1456            Mode::Open => self.show_open(ctx, docs, store),
1457            Mode::Import => self.show_import(ctx, docs.engine_mut(), store),
1458            Mode::Export => self.show_export(ctx, docs, store),
1459            Mode::FlatPattern => self.show_flat_pattern(ctx, docs, store),
1460            Mode::InsertComponent => self.show_insert_component(ctx, docs, store),
1461            Mode::PickMember => self.show_pick_member(ctx, docs.engine_mut(), store),
1462            Mode::SpinOut => self.show_spin_out(ctx, docs.engine_mut(), store),
1463            Mode::MemberEdit => self.show_member_edit(ctx, docs, store),
1464            Mode::OwnedSave => self.show_owned_save(ctx, docs, store),
1465            Mode::Retarget => self.show_retarget(ctx, docs),
1466            Mode::PickFile => self.show_pick_file(ctx, store),
1467            Mode::SaveFile => self.show_save_file(ctx, docs, store),
1468            Mode::StepAssembly => self.show_step_assembly(ctx, docs.engine_mut(), store),
1469            Mode::Kicad => self.show_kicad(ctx, docs.engine_mut(), store),
1470        }
1471    }
1472
1473    /// Close the modal after a completed import — unless the import ARMED the
1474    /// §3.9 assembly choice, in which case the modal stays open and switches to
1475    /// it. Both import routing sites (the async-upload poll and the Import
1476    /// modal's own pick) end here, so neither can close a dialog the probe just
1477    /// raised.
1478    fn close_after_import(&mut self) {
1479        if self.pending_step_import.is_some() {
1480            self.open_modal(Mode::StepAssembly);
1481        } else {
1482            self.open = false;
1483        }
1484    }
1485
1486    /// Abandon an armed assembly choice and the engine stash behind it. The ONE
1487    /// place the app-side pending state and the engine-side parse are dropped
1488    /// together — they are two halves of one thing, and a half-drop is either a
1489    /// dialog with no stash or solids nobody will ever consume.
1490    fn cancel_pending_step_import(&mut self, state: &mut EngineState) {
1491        if self.pending_step_import.take().is_some() {
1492            state.discard_probed_step_assembly();
1493        }
1494    }
1495
1496    /// Common CAD/mesh browser. Desktop enumerates files in the application's
1497    /// models directory; web shows the same explorer shell with an Upload action.
1498    fn show_import(
1499        &mut self,
1500        ctx: &egui::Context,
1501        state: &mut EngineState,
1502        store: &dyn ModelStore,
1503    ) {
1504        const EXTENSIONS: &[&str] = IMPORT_EXTENSIONS;
1505        let modal = egui::Modal::new(egui::Id::new("brep-file-import")).show(ctx, |ui| {
1506            file_explorer::dialog_body(ui, |ui| {
1507                ui.heading("Import CAD file");
1508                ui.add_space(4.0);
1509                file_explorer::dialog_footer(ui, "import", |ui| {
1510                    if !self.status.is_empty() {
1511                        ui.add_space(4.0);
1512                        ui.weak(&self.status);
1513                    }
1514                });
1515                let options = FileExplorerOptions {
1516                    hit_prefix: "import",
1517                    empty_label: "(no STEP, IGES, STL, 3MF, OBJ, or KiCad files)",
1518                    row_icon: "\u{1F5CE}",
1519                    current: None,
1520                    allow_delete: false,
1521                    allow_import: store.supports_file_interchange(),
1522                    import_label: "Upload\u{2026}",
1523                    import_hit: "import:upload",
1524                    show_cancel: true,
1525                    confirm_label: Some("Import"),
1526                    extensions: EXTENSIONS,
1527                };
1528                let output = self.explorer.show_store(ui, browse_store(Purpose::Imports, store), options);
1529                self.record_explorer_hits(&output.hits);
1530                output
1531            })
1532        });
1533        let should_close = modal.should_close();
1534        let output = modal.inner;
1535        if let Some(name) = output.activated {
1536            match browse_store(Purpose::Imports, store).read_external_file(&name) {
1537                Some(bytes) => match import_kind(&name) {
1538                    Some(kind) => {
1539                        if !self.import_file(kind, state, store, name, bytes) {
1540                            return;
1541                        }
1542                    }
1543                    None => self.status = format!("unsupported import file: {name}"),
1544                },
1545                None => self.status = format!("import failed: '{name}' not found"),
1546            }
1547            self.close_after_import();
1548        } else if output.import {
1549            match store.begin_import_filtered(("CAD / mesh", EXTENSIONS)) {
1550                Ok(()) => {
1551                    self.status =
1552                        "choose a STEP, IGES, Parasolid, STL, 3MF, OBJ, or KiCad file\u{2026}".into();
1553                    self.open = false;
1554                }
1555                Err(e) => self.status = format!("import failed: {e}"),
1556            }
1557        } else if output.cancel || should_close {
1558            self.open = false;
1559        }
1560    }
1561
1562    /// A `.kicad_sym` or `.kicad_mod` arrived (picked in Import, in the KiCad
1563    /// explorer, or uploaded): the KiCad dialog reads it and goes on to its
1564    /// next stage. `name` is the file's full path on desktop, which is where a
1565    /// footprint's relative model path starts from.
1566    fn take_kicad_file(&mut self, name: &str, bytes: &[u8], store: &dyn ModelStore) {
1567        if !(self.open && self.mode == Mode::Kicad) {
1568            if let Some(kind) = KicadKind::of_file(name) {
1569                self.kicad.start(kind, store);
1570            }
1571        }
1572        self.kicad.take_file(name, bytes, &DiskFiles);
1573        self.open_modal(Mode::Kicad);
1574    }
1575
1576    /// The KiCad import: the common explorer for its file, then its own
1577    /// stages. Hit keys are `kicad:*`.
1578    fn show_kicad(&mut self, ctx: &egui::Context, state: &mut EngineState, store: &dyn ModelStore) {
1579        if !self.kicad.wants_file() {
1580            match self.kicad.show(ctx, state, store, &mut self.hits) {
1581                kicad_import::Outcome::Open => {}
1582                kicad_import::Outcome::Closed => self.open = false,
1583                kicad_import::Outcome::Imported(imported) => {
1584                    // The modal closes on the click, so the toasts are what the
1585                    // user sees: the summary, then each note.
1586                    self.status = imported.summary.clone();
1587                    state.push_notice_as(brep_render::engine_state::NoticeSeverity::Info, imported.summary);
1588                    const SHOWN: usize = 5;
1589                    let hidden = imported.notes.len().saturating_sub(SHOWN);
1590                    for note in imported.notes.into_iter().take(SHOWN) {
1591                        state.push_notice_as(brep_render::engine_state::NoticeSeverity::Warning, note);
1592                    }
1593                    if hidden > 0 {
1594                        state.push_notice_as(
1595                            brep_render::engine_state::NoticeSeverity::Warning,
1596                            format!("and {hidden} more notes on this import"),
1597                        );
1598                    }
1599                    self.open = false;
1600                }
1601            }
1602            return;
1603        }
1604        let extension = self.kicad.kind().extension();
1605        let heading = match self.kicad.kind() {
1606            KicadKind::Symbol => "Import a symbol from KiCad",
1607            KicadKind::Footprint => "Import a footprint from KiCad",
1608        };
1609        let extensions = [extension];
1610        let modal = egui::Modal::new(egui::Id::new("brep-file-kicad")).show(ctx, |ui| {
1611            file_explorer::dialog_body(ui, |ui| {
1612                ui.heading(heading);
1613                ui.add_space(4.0);
1614                file_explorer::dialog_footer(ui, "kicad", |ui| {
1615                    let status = if self.kicad.status.is_empty() { &self.status } else { &self.kicad.status };
1616                    if !status.is_empty() {
1617                        ui.add_space(4.0);
1618                        ui.weak(status);
1619                    }
1620                });
1621                let empty_label = format!("(no .{extension} files)");
1622                let options = FileExplorerOptions {
1623                    hit_prefix: "kicad",
1624                    empty_label: &empty_label,
1625                    row_icon: "\u{1F5CE}",
1626                    current: None,
1627                    allow_delete: false,
1628                    allow_import: store.supports_file_interchange(),
1629                    import_label: "Upload\u{2026}",
1630                    import_hit: "kicad:upload",
1631                    show_cancel: true,
1632                    confirm_label: Some("Open"),
1633                    extensions: &extensions,
1634                };
1635                let output = self.explorer.show_store(ui, browse_store(Purpose::Kicad, store), options);
1636                self.record_explorer_hits(&output.hits);
1637                output
1638            })
1639        });
1640        let should_close = modal.should_close();
1641        let output = modal.inner;
1642        if let Some(name) = output.activated {
1643            match browse_store(Purpose::Kicad, store).read_external_file(&name) {
1644                Some(bytes) => self.take_kicad_file(&name, &bytes, store),
1645                None => self.kicad.status = format!("import failed: '{name}' not found"),
1646            }
1647        } else if output.import {
1648            match store.begin_import_filtered(("KiCad", &extensions)) {
1649                Ok(()) => {
1650                    self.status = format!("choose a .{extension} file\u{2026}");
1651                    self.open = false;
1652                }
1653                Err(e) => self.kicad.status = format!("import failed: {e}"),
1654            }
1655        } else if output.cancel || should_close {
1656            self.open = false;
1657        }
1658    }
1659
1660    /// CLOSE tab `index` with the unsaved-changes contract: a DIRTY document
1661    /// prompts to discard first (the confirm modal); a clean one closes
1662    /// immediately. The tab strip's `\u{2715}` routes here — it is the only
1663    /// door through which unsaved work can be dropped, so it is the only one
1664    /// that asks.
1665    pub fn request_close(&mut self, docs: &mut Documents, index: usize) {
1666        let dirty = docs.get(index).is_some_and(Document::is_dirty);
1667        if dirty {
1668            self.pending_close = docs.get(index).map(|doc| (doc.id(), doc.committed_revision()));
1669            self.open_modal(Mode::ConfirmClose);
1670        } else {
1671            docs.close(index);
1672        }
1673    }
1674
1675    /// The **Discard unsaved changes?** confirmation shown before closing a
1676    /// dirty document tab. Keeps the verifier's `confirm:discard` /
1677    /// `confirm:cancel` hit keys — the same two buttons, one door further on.
1678    fn show_confirm_close(&mut self, ctx: &egui::Context, docs: &mut Documents) {
1679        // The prompt names a DOCUMENT, not a tab position: a tab closed or
1680        // moved under it (an agent's close, a reorder) cannot redirect the
1681        // discard to whatever now sits at the old index, and a document that
1682        // changed since (an agent's write) dismisses the prompt — the user
1683        // confirmed discarding what they saw, not what it has become.
1684        let Some(title) = self
1685            .pending_close
1686            .and_then(|(id, revision)| docs.index_of_id(id).and_then(|i| docs.get(i)).filter(|doc| doc.committed_revision() == revision))
1687            .map(Document::title)
1688        else {
1689            self.pending_close = None;
1690            self.open = false;
1691            return;
1692        };
1693        let mut discard = false;
1694        let mut cancel = false;
1695        let modal = egui::Modal::new(egui::Id::new("brep-file-confirm-close")).show(ctx, |ui| {
1696            ui.set_width(340.0);
1697            ui.heading("Discard unsaved changes?");
1698            ui.add_space(4.0);
1699            ui.label(format!("\"{title}\" has unsaved changes. Close it?"));
1700            ui.add_space(6.0);
1701            ui.horizontal(|ui| {
1702                let d = ui.add(crate::ui_kit::Button::new("Discard and close"));
1703                self.hit("confirm:discard", &d);
1704                if d.clicked() {
1705                    discard = true;
1706                }
1707                let c = ui.add(crate::ui_kit::Button::new("Cancel"));
1708                self.hit("confirm:cancel", &c);
1709                if c.clicked() {
1710                    cancel = true;
1711                }
1712            });
1713        });
1714        if discard {
1715            if let Some(index) = self.pending_close.take().and_then(|(id, _)| docs.index_of_id(id)) {
1716                docs.close(index);
1717            }
1718            self.open = false;
1719        } else if cancel || modal.should_close() {
1720            self.pending_close = None;
1721            self.open = false;
1722        }
1723    }
1724
1725    /// The §3.9 **assembly choice**, raised when a `.step` upload's probe found a
1726    /// product structure:
1727    ///
1728    /// > **"bracket-assy.step" contains an assembly** — 7 parts, 23 instances.
1729    /// > [ Import as assembly ] [ Import as bodies ] [ Cancel ]
1730    ///
1731    /// Default (and first) is **Import as assembly**. "Import as bodies" is
1732    /// today's flat lane, unchanged. Cancel — and Esc / click-outside, which
1733    /// egui folds into `should_close` — import nothing and DROP the parse: the
1734    /// engine is holding every product's solids until one of these three lands.
1735    ///
1736    /// **Flatten sub-assemblies** (§3.9) is offered only when the file actually
1737    /// HAS sub-assemblies (`nested_depth > 1`) — on a single-level file both
1738    /// lanes produce the identical document, so a box there would teach the user
1739    /// a distinction that does not exist. Unchecked (the default) keeps the
1740    /// tree; checked flattens to leaf occurrences, which is the right answer for
1741    /// a deep or pathological file and stores a part reused across two levels
1742    /// once rather than once per level.
1743    fn show_step_assembly(
1744        &mut self,
1745        ctx: &egui::Context,
1746        state: &mut EngineState,
1747        store: &dyn ModelStore,
1748    ) {
1749        // Nothing armed means nothing to choose about (a supersession raced the
1750        // draw): close rather than render an empty prompt.
1751        let Some(pending) = self.pending_step_import.as_ref() else {
1752            self.open = false;
1753            return;
1754        };
1755        let name = pending.name.clone();
1756        let probe = pending.probe;
1757        let built = pending.built;
1758        let mut flatten = pending.flatten;
1759        let mut choice: Option<StepChoice> = None;
1760        let modal = egui::Modal::new(egui::Id::new("brep-file-step-assembly")).show(ctx, |ui| {
1761            ui.set_width(360.0);
1762            ui.heading(format!("\"{name}\" contains an assembly"));
1763            ui.add_space(4.0);
1764            ui.label(format!(
1765                "{} part{}, {} instance{}{}.",
1766                probe.parts,
1767                plural(probe.parts),
1768                probe.instances,
1769                plural(probe.instances),
1770                match probe.nested_depth {
1771                    0 | 1 => String::new(),
1772                    depth => format!(", {depth} levels deep"),
1773                }
1774            ));
1775            if !built {
1776                // Asked from the structure alone: the bodies are read after the
1777                // choice, in the background.
1778                ui.weak("Its parts are read after you choose; you can keep working meanwhile.");
1779            }
1780            if probe.nested_depth > 1 {
1781                ui.add_space(4.0);
1782                let check = crate::ui_kit::checkbox(ui, &mut flatten, "Flatten sub-assemblies");
1783                self.hit("stepassembly:flatten", &check);
1784                check.on_hover_text(
1785                    "Off: each sub-assembly becomes one rigid component you can \
1786                     expand in the structure tree.\nOn: every part is placed \
1787                     directly in this document at its world position.",
1788                );
1789            }
1790            ui.add_space(6.0);
1791            ui.horizontal(|ui| {
1792                let a = ui.add(crate::ui_kit::Button::new("Import as assembly"));
1793                self.hit("stepassembly:assembly", &a);
1794                if a.clicked() {
1795                    choice = Some(StepChoice::Assembly);
1796                }
1797                let b = ui.add(crate::ui_kit::Button::new("Import as bodies"));
1798                self.hit("stepassembly:bodies", &b);
1799                if b.clicked() {
1800                    choice = Some(StepChoice::Bodies);
1801                }
1802                let c = ui.add(crate::ui_kit::Button::new("Cancel"));
1803                self.hit("stepassembly:cancel", &c);
1804                if c.clicked() {
1805                    choice = Some(StepChoice::Cancel);
1806                }
1807            });
1808        });
1809        // The box must survive the frames between the tick and the click.
1810        if let Some(pending) = self.pending_step_import.as_mut() {
1811            pending.flatten = flatten;
1812        }
1813        // Esc / click-outside is a Cancel, not a no-op: the stash must not
1814        // outlive the prompt that was going to consume it.
1815        let choice = choice.or_else(|| modal.should_close().then_some(StepChoice::Cancel));
1816        let Some(choice) = choice else { return };
1817        match choice {
1818            StepChoice::Assembly => self.step_assembly_import(state, store),
1819            StepChoice::Bodies => self.step_assembly_bodies(state),
1820            StepChoice::Cancel => self.step_assembly_cancel(state),
1821        }
1822        self.open = false;
1823    }
1824
1825    /// Save As asked for a new PLM part: the shell opens the PLM pane's New part form.
1826    /// Once: true the frame after it was chosen.
1827    pub fn take_plm_new_part(&mut self) -> bool {
1828        std::mem::take(&mut self.plm_new_part)
1829    }
1830
1831    /// The **Save As** name prompt.
1832    fn show_save_as(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
1833        // A PLM session saves as a new part or a new revision, not under a file name.
1834        if let Some(client) = store.plm_client() {
1835            self.show_save_as_plm(ctx, docs, store, client);
1836            return;
1837        }
1838        let current = docs.active().name().map(str::to_string);
1839        let mut do_save = false;
1840        let mut cancel = false;
1841        let modal = egui::Modal::new(egui::Id::new("brep-file-saveas")).show(ctx, |ui| {
1842            file_explorer::dialog_body(ui, |ui| {
1843                ui.heading("Save model as");
1844                ui.add_space(4.0);
1845                // The name field and its buttons are the dialog's footer: pinned
1846                // under the browser, which fills whatever is left.
1847                file_explorer::dialog_footer(ui, "saveas", |ui| {
1848                    ui.label("File name");
1849                    let field = crate::ui_kit::text_input(&mut self.name_buf).placeholder("model name").width(ui.available_width()).show(ui).framed();
1850                    self.hit("field:name", &field);
1851                    if self.want_focus {
1852                        field.request_focus();
1853                        self.want_focus = false;
1854                    }
1855                    let enter =
1856                        field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
1857                    // The class the file is saved as. A part's class is fixed
1858                    // for its life, so Save As is the one place it is chosen:
1859                    // saving a part as a Family or a Template makes a new file
1860                    // of that class.
1861                    ui.horizontal(|ui| {
1862                        ui.label("Save as");
1863                        // One dropdown (the form's enum field): saveas:class, its
1864                        // open entries saveas:class#<slug>.
1865                        let texts: Vec<String> = DocumentClass::ALL.iter().map(|class| format!("{} ({})", class.label(), class.extension())).collect();
1866                        let choices: Vec<(DocumentClass, &str, &str)> =
1867                            DocumentClass::ALL.iter().zip(&texts).map(|(class, text)| (*class, class.slug(), text.as_str())).collect();
1868                        crate::form::enum_dropdown(ui, "saveas:class", &choices, &mut self.save_class, None, Some(&mut self.hits));
1869                    });
1870                    ui.add_space(6.0);
1871                    ui.horizontal(|ui| {
1872                        let save = ui.add(crate::ui_kit::Button::new("Save"));
1873                        self.hit("save", &save);
1874                        if save.clicked() || enter {
1875                            do_save = true;
1876                        }
1877                        let c = ui.add(crate::ui_kit::Button::new("Cancel"));
1878                        self.hit("cancel", &c);
1879                        if c.clicked() {
1880                            cancel = true;
1881                        }
1882                    });
1883                    if !self.status.is_empty() {
1884                        ui.add_space(4.0);
1885                        ui.weak(&self.status);
1886                    }
1887                });
1888                let options = FileExplorerOptions {
1889                    hit_prefix: "saveas:file",
1890                    empty_label: "(no saved models)",
1891                    row_icon: "\u{1F5CE}",
1892                    current: current.as_deref(),
1893                    allow_delete: false,
1894                    allow_import: false,
1895                    import_label: "",
1896                    import_hit: "saveas:upload",
1897                    show_cancel: false,
1898                    confirm_label: None,
1899                    extensions: MODEL_EXTENSIONS,
1900                };
1901                let output = self.explorer.show_store(ui, store, options);
1902                self.record_explorer_hits(&output.hits);
1903                // Selecting (or double-clicking) a stored model fills the name
1904                // field so it can be overwritten; `picked`/`activated` are
1905                // one-shot so it never clobbers a name the user then types. The
1906                // field itself was drawn above, so the explorer asks for the
1907                // repaint that shows the new name.
1908                if let Some(name) = output.picked.or(output.activated) {
1909                    self.name_buf =
1910                        document_class::strip_class_extension(&model_display_name(&name)).to_string();
1911                    if let Some(class) = DocumentClass::of_name(&name) {
1912                        self.save_class = class;
1913                    }
1914                }
1915            })
1916        });
1917        if do_save {
1918            let name = self.save_class.file_name(self.name_buf.trim());
1919            if self.save_to_browser(docs, store, name) {
1920                self.open = false;
1921            }
1922        } else if cancel || modal.should_close() {
1923            self.open = false;
1924        }
1925    }
1926
1927    /// The **Export** chooser: pick a format (STEP / IGES / STL / OBJ / GLB /
1928    /// 3MF) and write the current model to the user's filesystem under
1929    /// `<name>.<ext>` through the store's format-typed interchange. STEP and
1930    /// IGES serialize the exact NURBS topology; STL, OBJ, GLB and 3MF are the
1931    /// display mesh (ASCII facets, one indexed object, binary glTF 2.0 with a
1932    /// mesh per body, and a 3MF package with an object per body and the
1933    /// document's colours as base materials).
1934    /// No solids → a clear status line,
1935    /// nothing written. A second row offers the BOM (CSV / JSON), enabled only
1936    /// while the document has components or harness wires.
1937    fn show_export(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
1938        // BOM gating: `component_ids` scans the history (cheap, no kernel
1939        // session), and a harness wire is a BOM line of its own, so a
1940        // harness-only document exports too. A rolled-back/failed ACOMP can
1941        // still enable the buttons — the export's own loud "no components or
1942        // harness wires" error covers that gap.
1943        let has_bom = !docs.engine().component_ids().is_empty()
1944            || !docs.engine().wire_harness_state().connections.is_empty();
1945        // The drawing sheets of THIS document: the sheet button writes the open
1946        // one (else the first), so it is offered only when there is one to
1947        // write — the BOM row's gating, for the same reason.
1948        let has_sheets = !docs.engine().sheet_state().sheets.is_empty();
1949        let has_instructions = docs.engine().is_instructions();
1950        // The board's manufacturing files: offered once the PCB has parts on
1951        // its board, the BOM row's gating for the same reason.
1952        let has_board = super::fabrication_export::has_board(docs.engine());
1953        let has_schematic = super::fabrication_export::has_schematic(docs.engine());
1954        let mut chosen: Option<&'static str> = None;
1955        let mut bom_chosen: Option<&'static str> = None;
1956        let mut fab_chosen: Option<super::fabrication_export::Output> = None;
1957        let mut cancel = false;
1958        let modal = egui::Modal::new(egui::Id::new("brep-file-export")).show(ctx, |ui| {
1959            // Wide enough for the 3D formats on one line; each group wraps
1960            // rather than widening the modal (lane U audit item 7).
1961            ui.set_width(440.0);
1962            ui.heading("Export model");
1963            ui.add_space(4.0);
1964            Self::preview_export_line(ui, docs);
1965            let field = crate::ui_kit::text_input(&mut self.name_buf).placeholder("file name").width(ui.available_width()).show(ui).framed();
1966            self.hit("field:name", &field);
1967            if self.want_focus {
1968                field.request_focus();
1969                self.want_focus = false;
1970            }
1971            // One headed, wrapping row per kind of output, and Cancel on its
1972            // own row below them all — it used to sit among the 3D formats,
1973            // with "Sheets + 3D (PDF)" orphaned on a line of its own.
1974            let group = |ui: &mut egui::Ui, title: &str| {
1975                ui.add_space(6.0);
1976                ui.label(egui::RichText::new(title).weak());
1977            };
1978            group(ui, "3D model");
1979            ui.horizontal_wrapped(|ui| {
1980                let step = ui.add(crate::ui_kit::Button::new("STEP (.step)"));
1981                self.hit("export:step", &step);
1982                if step.clicked() {
1983                    chosen = Some("step");
1984                }
1985                let iges = ui.add(crate::ui_kit::Button::new("IGES (.igs)"));
1986                self.hit("export:iges", &iges);
1987                if iges.clicked() {
1988                    chosen = Some("iges");
1989                }
1990                // Parasolid is what SolidWorks, NX and Solid Edge open
1991                // natively: the route to SolidWorks.
1992                let xt = ui.add(crate::ui_kit::Button::new("Parasolid (.x_t)")).on_hover_text("For SolidWorks, NX and Solid Edge: they open Parasolid natively");
1993                self.hit("export:parasolid", &xt);
1994                if xt.clicked() {
1995                    chosen = Some("parasolid");
1996                }
1997                let xb = ui.add(crate::ui_kit::Button::new("Parasolid binary (.x_b)"));
1998                self.hit("export:parasolidbinary", &xb);
1999                if xb.clicked() {
2000                    chosen = Some("parasolidbinary");
2001                }
2002                let stl = ui.add(crate::ui_kit::Button::new("STL (.stl)"));
2003                self.hit("export:stl", &stl);
2004                if stl.clicked() {
2005                    chosen = Some("stl");
2006                }
2007                let obj = ui.add(crate::ui_kit::Button::new("OBJ (.obj)"));
2008                self.hit("export:obj", &obj);
2009                if obj.clicked() {
2010                    chosen = Some("obj");
2011                }
2012                let glb = ui.add(crate::ui_kit::Button::new("GLB (.glb)"));
2013                self.hit("export:glb", &glb);
2014                if glb.clicked() {
2015                    chosen = Some("glb");
2016                }
2017                // The slicer format: the display mesh as a 3MF package, one
2018                // object per body, with the document's colours carried as
2019                // base materials so a multi-colour print arrives painted.
2020                let three_mf = ui.add(crate::ui_kit::Button::new("3MF (.3mf)"))
2021                    .on_hover_text("For slicers: one object per body, with the model's colours");
2022                self.hit("export:3mf", &three_mf);
2023                if three_mf.clicked() {
2024                    chosen = Some("3mf");
2025                }
2026                // The same package shaped for Bambu Studio: touching bodies
2027                // as one multipart object, each body a part on its own
2028                // filament number (model_settings.config).
2029                let bambu = ui.add(crate::ui_kit::Button::new("3MF for Bambu Studio (.3mf)"))
2030                    .on_hover_text("Touching bodies as one multipart object, a filament per colour that the slicer's part list can change");
2031                self.hit("export:3mfbambu", &bambu);
2032                if bambu.clicked() {
2033                    chosen = Some("3mfbambu");
2034                }
2035                // The full model RECIPE (`.nbrep`) — for saving a document to
2036                // disk / sharing a failing model for a bug report. Re-openable via
2037                // Open / Import.
2038                let json = ui.add(crate::ui_kit::Button::new("Model (.nbrep)"));
2039                self.hit("export:json", &json);
2040                if json.clicked() {
2041                    chosen = Some("json");
2042                }
2043            });
2044            group(ui, "Bill of materials");
2045            ui.horizontal_wrapped(|ui| {
2046                // The BOM: one row per parts-library entry with the live
2047                // instance count, then one per harness wire with its cut
2048                // length. Disabled while the document has neither.
2049                let csv = ui.add(crate::ui_kit::Button::new("BOM (CSV)").enabled(has_bom));
2050                self.hit("export:bomcsv", &csv);
2051                if csv.clicked() {
2052                    bom_chosen = Some("csv");
2053                }
2054                let json = ui.add(crate::ui_kit::Button::new("BOM (JSON)").enabled(has_bom));
2055                self.hit("export:bomjson", &json);
2056                if json.clicked() {
2057                    bom_chosen = Some("json");
2058                }
2059            });
2060            group(ui, "Drawing");
2061            ui.horizontal_wrapped(|ui| {
2062                // The DRAWING SHEET: the paper as an SVG of lines and text.
2063                // Not the sheet-METAL flat pattern, which is its own dialog.
2064                let sheet = ui.add_enabled(has_sheets, crate::ui_kit::Button::new("Sheet (SVG)").enabled(has_sheets))
2065                    .on_disabled_hover_text("Add a drawing sheet in the Drawing workbench first");
2066                self.hit("export:sheetsvg", &sheet);
2067                if sheet.clicked() {
2068                    chosen = Some("sheetsvg");
2069                }
2070                // EVERY sheet as one PDF: a page per sheet, in sheet order, each
2071                // at its own paper size — the drawing set, not the page on
2072                // screen. The SVG beside it stays one file per sheet.
2073                let pdf = ui.add_enabled(has_sheets, crate::ui_kit::Button::new("Sheets (PDF)").enabled(has_sheets))
2074                    .on_hover_text("Every drawing sheet of the document as one PDF, a page per sheet")
2075                    .on_disabled_hover_text("Add a drawing sheet in the Drawing workbench first");
2076                self.hit("export:sheetpdf", &pdf);
2077                if pdf.clicked() {
2078                    chosen = Some("sheetpdf");
2079                }
2080                // The same drawing set with the LIVE 3D model: a 3D box over
2081                // every placement marked "Live 3D in PDF", and a last page
2082                // given over to the model with a button per saved PMI view.
2083                // Its own file, so the plain drawing set is never replaced.
2084                let pdf3d = ui.add_enabled(has_sheets, crate::ui_kit::Button::new("Sheets + 3D (PDF)").enabled(has_sheets))
2085                    .on_hover_text("The drawing set with the live 3D model: Acrobat and Foxit turn and zoom it and switch PMI views; other PDF readers show the drawings")
2086                    .on_disabled_hover_text("Add a drawing sheet in the Drawing workbench first");
2087                self.hit("export:sheetpdf3d", &pdf3d);
2088                if pdf3d.clicked() {
2089                    chosen = Some("sheetpdf3d");
2090                }
2091            });
2092            group(ui, "Electronics");
2093            ui.horizontal_wrapped(|ui| {
2094                // The PCB's manufacturing files. The zip is what a board house
2095                // takes; the two CSVs are also inside it, and on their own for
2096                // an assembler that asks for them separately.
2097                use super::fabrication_export::Output;
2098                let no_board = "Place the schematic's parts on the PCB board first";
2099                for (key, label, hover, output) in [
2100                    ("export:fabrication", "Fabrication (zip)", "Gerber X2 layers, Excellon drills, pick and place, the parts BOM and a README of the layers, in one zip for the board house", Output::Bundle),
2101                    ("export:pickplace", "Pick & place (CSV)", "One row per placed part: Designator, Val, Package, Mid X, Mid Y, Rotation, Layer (JLCPCB's columns), in mm from the board's lower-left corner", Output::PickPlace),
2102                    ("export:ecadbom", "Parts BOM (CSV)", "The electronic parts: Comment (the value), Designator, Footprint, Quantity (JLCPCB's columns), one line per value and footprint", Output::Bom),
2103                    ("export:kicadnet", "Netlist (KiCad)", "The PCB diagram's nets as a KiCad .net file, the netlist Pcbnew and other tools read: every part with its value and footprint, every net with its pins, under the names the Connectivity panel lists", Output::Netlist),
2104                ] {
2105                    let (enabled, why) = match output {
2106                        Output::Netlist => (has_schematic, "Put parts on the PCB diagram first"),
2107                        _ => (has_board, no_board),
2108                    };
2109                    let button = ui.add_enabled(enabled, crate::ui_kit::Button::new(&label).enabled(enabled))
2110                        .on_hover_text(hover)
2111                        .on_disabled_hover_text(why);
2112                    self.hit(key, &button);
2113                    if button.clicked() {
2114                        fab_chosen = Some(output);
2115                    }
2116                }
2117            });
2118            group(ui, "Instructions");
2119            ui.horizontal_wrapped(|ui| {
2120                // The printed instructions on the page template the Instructions
2121                // pane sets, and every step's picture as PNG and SVG in one zip.
2122                let not_instructions = "Open manufacturing instructions first (New from assembly in the Instructions workbench)";
2123                let pdf = ui.add_enabled(has_instructions, crate::ui_kit::Button::new("Instructions (PDF)").enabled(has_instructions))
2124                    .on_hover_text("The cover, the parts list, the tools list and the steps, on the page template set in the Instructions pane")
2125                    .on_disabled_hover_text(not_instructions);
2126                self.hit("export:instructionspdf", &pdf);
2127                if pdf.clicked() {
2128                    chosen = Some("instructionspdf");
2129                }
2130                let images = ui.add_enabled(has_instructions, crate::ui_kit::Button::new("Step images").enabled(has_instructions))
2131                    .on_hover_text("Every step's picture as PNG and SVG, in one zip")
2132                    .on_disabled_hover_text(not_instructions);
2133                self.hit("export:instructionsimages", &images);
2134                if images.clicked() {
2135                    chosen = Some("instructionsimages");
2136                }
2137                let html = ui.add_enabled(has_instructions, crate::ui_kit::Button::new("Player (HTML)").enabled(has_instructions))
2138                    .on_hover_text("The interactive player in one self-contained page: Next/Back, a live 3D view per step and a step checklist, with no server")
2139                    .on_disabled_hover_text(not_instructions);
2140                self.hit("export:instructionshtml", &html);
2141                if html.clicked() {
2142                    chosen = Some("instructionshtml");
2143                }
2144            });
2145            if !self.status.is_empty() {
2146                ui.add_space(4.0);
2147                ui.weak(&self.status);
2148            }
2149            ui.add_space(6.0);
2150            ui.separator();
2151            let c = ui.add(crate::ui_kit::Button::new("Cancel"));
2152            self.hit("cancel", &c);
2153            if c.clicked() {
2154                cancel = true;
2155            }
2156        });
2157        // A delivered export closes this dialog; one the Save-file chooser
2158        // took over has switched the modal to the chooser, which stays up.
2159        if let Some(format) = chosen {
2160            if self.export_as(docs, store, format) && self.mode == Mode::Export {
2161                self.open = false;
2162            }
2163        } else if let Some(format) = bom_chosen {
2164            if self.export_bom_as(docs, store, format) && self.mode == Mode::Export {
2165                self.open = false;
2166            }
2167        } else if let Some(output) = fab_chosen {
2168            if self.export_fabrication_as(docs, store, output) && self.mode == Mode::Export {
2169                self.open = false;
2170            }
2171        } else if cancel || modal.should_close() {
2172            self.open = false;
2173        }
2174    }
2175
2176    /// The **Flat pattern** chooser: pick a 2D vector format (DXF R12 / SVG) and
2177    /// write the sheet-metal body's unfolded flat pattern to the user's filesystem
2178    /// under `<name>.<ext>`. The unfold runs TRANSIENTLY in the engine (no feature,
2179    /// no history change). A part with no sheet-metal body reports it in the status
2180    /// line AND queues a toast (see [`Self::export_flat_pattern_as`]).
2181    fn show_flat_pattern(
2182        &mut self,
2183        ctx: &egui::Context,
2184        docs: &mut Documents,
2185        store: &dyn ModelStore,
2186    ) {
2187        let mut chosen: Option<&'static str> = None;
2188        let mut cancel = false;
2189        let modal = egui::Modal::new(egui::Id::new("brep-file-flatpattern")).show(ctx, |ui| {
2190            ui.set_width(340.0);
2191            ui.heading("Export flat pattern");
2192            ui.add_space(2.0);
2193            Self::preview_export_line(ui, docs);
2194            ui.weak("Unfolds the sheet-metal body to a 2D vector file.");
2195            ui.add_space(4.0);
2196            let field = crate::ui_kit::text_input(&mut self.name_buf).placeholder("file name").width(ui.available_width()).show(ui).framed();
2197            self.hit("field:name", &field);
2198            if self.want_focus {
2199                field.request_focus();
2200                self.want_focus = false;
2201            }
2202            ui.add_space(6.0);
2203            ui.horizontal(|ui| {
2204                let dxf = ui.add(crate::ui_kit::Button::new("DXF (.dxf)"));
2205                self.hit("flat:dxf", &dxf);
2206                if dxf.clicked() {
2207                    chosen = Some("dxf");
2208                }
2209                let svg = ui.add(crate::ui_kit::Button::new("SVG (.svg)"));
2210                self.hit("flat:svg", &svg);
2211                if svg.clicked() {
2212                    chosen = Some("svg");
2213                }
2214                let c = ui.add(crate::ui_kit::Button::new("Cancel"));
2215                self.hit("cancel", &c);
2216                if c.clicked() {
2217                    cancel = true;
2218                }
2219            });
2220            if !self.status.is_empty() {
2221                ui.add_space(4.0);
2222                ui.weak(&self.status);
2223            }
2224        });
2225        if let Some(format) = chosen {
2226            if self.export_flat_pattern_as(docs, store, format) && self.mode == Mode::FlatPattern {
2227                self.open = false;
2228            }
2229        } else if cancel || modal.should_close() {
2230            self.open = false;
2231        }
2232    }
2233
2234    /// The **Open** browser: the saved-model list (+ Upload where the platform
2235    /// supports real-file interchange).
2236    fn show_open(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
2237        // A PLM session opens from the user's workspace, not from a list of store keys.
2238        if let Some(client) = store.plm_client() {
2239            self.show_open_workspace(ctx, docs, store, client);
2240            return;
2241        }
2242        let current = docs.active().name().map(str::to_string);
2243        let modal = egui::Modal::new(egui::Id::new("brep-file-open")).show(ctx, |ui| {
2244            file_explorer::dialog_body(ui, |ui| {
2245                ui.heading("Open model");
2246                ui.add_space(4.0);
2247                file_explorer::dialog_footer(ui, "open", |ui| {
2248                    if !self.status.is_empty() {
2249                        ui.add_space(4.0);
2250                        ui.weak(&self.status);
2251                    }
2252                });
2253                let mut options = FileExplorerOptions::open(current.as_deref());
2254                options.allow_import = store.supports_file_interchange();
2255                let output = self.explorer.show_store(ui, store, options);
2256                self.record_explorer_hits(&output.hits);
2257                output
2258            })
2259        });
2260        let should_close = modal.should_close();
2261        let output = modal.inner;
2262        if let Some(name) = output.activated {
2263            self.open_document(docs, store, &name);
2264            self.open = false;
2265        } else if let Some(name) = output.remove {
2266            let _ = store.remove(&name);
2267            self.status = format!("removed {name}");
2268            // A tab holding the removed document keeps its content but loses its
2269            // file: it becomes an untitled document, so a later Save asks where
2270            // to put it rather than silently recreating what was deleted.
2271            if let Some(index) = docs.index_of(&name) {
2272                if let Some(doc) = docs.get_mut(index) {
2273                    doc.set_name(None);
2274                }
2275            }
2276        } else if output.import {
2277            // Fire the platform picker; the file arrives via take_import() and is
2278            // loaded on a later frame (the modal closes now).
2279            match store.begin_import() {
2280                Ok(()) => {
2281                    self.status = "choose a file…".into();
2282                    self.open = false;
2283                }
2284                Err(e) => self.status = format!("import failed: {e}"),
2285            }
2286        } else if output.cancel || should_close {
2287            self.open = false;
2288        }
2289    }
2290
2291    /// The **Open** browser in a PLM session: the workspace (S14) — folders of links and
2292    /// files, other users' workspaces read-only, and Open by number. A link opens its
2293    /// part's document. Workspace changes are linked to the web app; downloads
2294    /// go out through the store's export lane.
2295    fn show_open_workspace(
2296        &mut self,
2297        ctx: &egui::Context,
2298        docs: &mut Documents,
2299        store: &dyn ModelStore,
2300        client: std::rc::Rc<crate::plm::client::PlmClient>,
2301    ) {
2302        use crate::panels::plm_workspace::{document_name, load_pins, save_pins, PlmWorkspaces};
2303        let plm = PlmWorkspaces { client };
2304        if self.workspace.pins.is_none() {
2305            self.workspace.pins = Some(load_pins(store));
2306        }
2307        self.workspace.browse_only = true;
2308        let mut cancel = false;
2309        let modal = egui::Modal::new(egui::Id::new("brep-file-open")).show(ctx, |ui| {
2310            file_explorer::dialog_body(ui, |ui| {
2311                ui.heading("Open from the PLM");
2312                if let Some(url) = crate::panels::plm_host::web_url(store, "#/workspace") {
2313                    crate::panels::plm_host::web_link(ui, "Manage workspace in PLM", url);
2314                }
2315                ui.add_space(4.0);
2316                file_explorer::dialog_footer(ui, "open", |ui| {
2317                    if !self.status.is_empty() {
2318                        ui.add_space(4.0);
2319                        ui.weak(&self.status);
2320                    }
2321                    let button = ui.add(crate::ui_kit::Button::new("Cancel"));
2322                    self.hits.insert("open:cancel".into(), button.rect);
2323                    cancel = button.clicked();
2324                });
2325                self.workspace.show(ui, &plm, "open:")
2326            })
2327        });
2328        let hits: Vec<(String, egui::Rect)> = self.workspace.hits.iter().map(|(k, r)| (k.clone(), *r)).collect();
2329        self.record_explorer_hits(&hits);
2330        let should_close = modal.should_close();
2331        let outcome = modal.inner;
2332        if let Some(pins) = &outcome.pins {
2333            if let Err(e) = save_pins(store, pins) {
2334                self.status = format!("could not save the pinned folders: {e}");
2335            }
2336        }
2337        if let Some((name, bytes)) = outcome.downloaded {
2338            self.status = match store.export_file_named_bytes(&name, &bytes) {
2339                Ok(()) => format!("saved {name}"),
2340                Err(e) => format!("could not save {name}: {e}"),
2341            };
2342        }
2343        if outcome.pick_file {
2344            // The chooser takes the modal over; the file comes back to
2345            // `poll_open_workspace_pick`, which reopens Open on the folder.
2346            if let Err(error) = self.request_pick_file(store, PICK_OPEN_WORKSPACE, "Add a file to this folder") {
2347                self.status = error;
2348            }
2349            return;
2350        }
2351        if let Some(key) = outcome.open {
2352            let name = document_name(store, &key);
2353            self.open_document(docs, store, &name);
2354            self.open = false;
2355        } else if cancel || should_close {
2356            self.open = false;
2357        }
2358    }
2359
2360    /// A file picked for the Open modal's workspace: added to the folder shown,
2361    /// and the Open modal comes back.
2362    fn poll_open_workspace_pick(&mut self, store: &dyn ModelStore) {
2363        let Some(file) = self.take_picked_file(PICK_OPEN_WORKSPACE) else { return };
2364        if let Some(client) = store.plm_client() {
2365            let plm = crate::panels::plm_workspace::PlmWorkspaces { client };
2366            self.workspace.add_file(&plm, &file.name, file.bytes);
2367            self.open_modal(Mode::Open);
2368        }
2369    }
2370
2371    /// The **Insert component** selector: the
2372    /// EXISTING parts-library entries first (instant re-insert — no store read),
2373    /// then the model store's document list, + Upload where the platform
2374    /// supports real-file interchange. REUSES the Open modal's machinery (the
2375    /// same list + `take_import` poll), routed to the engine's insert flow.
2376    fn show_insert_component(
2377        &mut self,
2378        ctx: &egui::Context,
2379        docs: &mut Documents,
2380        store: &dyn ModelStore,
2381    ) {
2382        let library = docs.engine_mut().parts_library_names();
2383        let modal = egui::Modal::new(egui::Id::new("brep-file-insert-component")).show(ctx, |ui| {
2384            file_explorer::dialog_body(ui, |ui| {
2385                ui.heading("Insert component");
2386                ui.add_space(4.0);
2387                file_explorer::dialog_footer(ui, "insert", |ui| {
2388                    if !self.status.is_empty() {
2389                        ui.add_space(4.0);
2390                        ui.weak(&self.status);
2391                    }
2392                });
2393                let mut chosen_library = None;
2394                if !library.is_empty() {
2395                    ui.weak("In this document (parts library)");
2396                    for name in &library {
2397                        let row = ui.add_sized(
2398                            egui::vec2(ui.available_width(), 18.0),
2399                            crate::icon_text::icon_button(ui, &format!("\u{25A3} {name}"))
2400                                .frame(false),
2401                        );
2402                        self.hit(&format!("insert:lib:{name}"), &row);
2403                        if row.clicked() {
2404                            chosen_library = Some(name.clone());
2405                        }
2406                    }
2407                    ui.add_space(4.0);
2408                }
2409                let options = FileExplorerOptions {
2410                    hit_prefix: "insert:model",
2411                    empty_label: "(no saved models)",
2412                    row_icon: "\u{1F5CE}",
2413                    current: None,
2414                    allow_delete: false,
2415                    allow_import: store.supports_file_interchange(),
2416                    import_label: "Upload\u{2026}",
2417                    import_hit: "insert:upload",
2418                    show_cancel: true,
2419                    confirm_label: Some("Insert"),
2420                    extensions: INSERT_EXTENSIONS,
2421                };
2422                let output = self.explorer.show_store(ui, store, options);
2423                self.record_explorer_hits(&output.hits);
2424                (chosen_library, output)
2425            })
2426        });
2427        let should_close = modal.should_close();
2428        let (chosen_library, output) = modal.inner;
2429        if let Some(part_name) = chosen_library {
2430            // An already-inserted library part: skip the store read entirely.
2431            match docs.engine_mut().insert_component(ComponentInsert::Existing { part_name: &part_name }) {
2432                Ok(id) => {
2433                    self.status = format!("inserted {part_name} ({id})");
2434                    self.open = false;
2435                }
2436                Err(e) => self.status = format!("insert failed: {e}"),
2437            }
2438        } else if let Some(name) = output.activated.filter(|name| {
2439            // Only a file the list OFFERS is a component: a part document. A
2440            // highlight left by another purpose (Import's `.kicad_sym`) is not
2441            // one, and reached the parts library as a non-document.
2442            let listed = store
2443                .browser_entries(INSERT_EXTENSIONS)
2444                .iter()
2445                .any(|entry| !entry.is_dir && entry.identity == *name);
2446            if !listed {
2447                self.status = format!(
2448                    "insert refused: {name} is not a part, family or template document (.nbrep / .fbrep / .tbrep)"
2449                );
2450            }
2451            listed
2452        }) {
2453            self.request_component_document(docs, store, &name);
2454            if self.pending_insert.is_some() {
2455                ctx.request_repaint_after(std::time::Duration::from_millis(100));
2456            }
2457        } else if output.import {
2458            match store.begin_import() {
2459                Ok(()) => {
2460                    // The picked file routes to the component insert (not Open).
2461                    self.pending_component_import = true;
2462                    self.status = "choose a part file…".into();
2463                    self.open = false;
2464                }
2465                Err(e) => self.status = format!("insert failed: {e}"),
2466            }
2467        } else if output.cancel || should_close {
2468            self.open = false;
2469        }
2470    }
2471
2472    fn request_component_document(&mut self, docs: &mut Documents, store: &dyn ModelStore, name: &str) {
2473        self.pending_insert = None;
2474        match crate::store::read_now(store, name) {
2475            crate::store::ReadNow::Ready(contents) => self.finish_component_document(docs, store, name, &contents),
2476            crate::store::ReadNow::Loading => {
2477                self.pending_insert = Some((name.to_owned(), docs.active_id()));
2478                self.status = format!("'{name}' is still loading");
2479            }
2480            crate::store::ReadNow::Absent => self.status = format!("insert failed: '{name}' not found"),
2481        }
2482    }
2483
2484    fn finish_component_document(&mut self, docs: &mut Documents, store: &dyn ModelStore, name: &str, contents: &str) {
2485        let assembly = docs.active().name().map(str::to_string);
2486        if !self.begin_class_insert(store, name, contents, assembly) {
2487            self.insert_component_document(docs.engine_mut(), name, contents);
2488            self.open = false;
2489        }
2490    }
2491
2492    fn poll_pending_insert(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
2493        let Some((name, requester)) = self.pending_insert.take() else { return };
2494        if !self.open || self.mode != Mode::InsertComponent || docs.active_id() != requester {
2495            return;
2496        }
2497        match crate::store::read_now(store, &name) {
2498            crate::store::ReadNow::Ready(contents) => self.finish_component_document(docs, store, &name, &contents),
2499            crate::store::ReadNow::Loading => {
2500                self.pending_insert = Some((name, requester));
2501                ctx.request_repaint_after(std::time::Duration::from_millis(100));
2502            }
2503            crate::store::ReadNow::Absent => self.status = format!("insert failed: '{name}' not found"),
2504        }
2505    }
2506
2507    /// Insert a part DOCUMENT as an assembly component: library-add (dedup by
2508    /// sourceKey + content signature; the RETURNED effective name is what the
2509    /// instance references) + an ACOMP feature, through the engine's one insert
2510    /// flow. The first instance of an empty assembly is written `isFixed:true`.
2511    /// `sourceSignature` is written with [`document_signature`] — the ONE
2512    /// signature fn — so the update-components comparison reads a freshly
2513    /// inserted, unchanged part as up-to-date.
2514    fn insert_component_document(&mut self, state: &mut EngineState, name: &str, contents: &str) {
2515        self.insert_component_named(state, name, &model_display_name(name), contents);
2516    }
2517
2518    /// [`Self::insert_component_document`] under a given name: a PLM member
2519    /// is named by its part number, which its key does not carry.
2520    fn insert_component_named(&mut self, state: &mut EngineState, name: &str, display: &str, contents: &str) {
2521        let display = display.to_string();
2522        match state.insert_component(ComponentInsert::New {
2523            name: &display,
2524            source_key: name,
2525            source_signature: &document_signature(contents),
2526            document_json: contents,
2527        }) {
2528            Ok(id) => self.status = format!("inserted {display} ({id})"),
2529            Err(e) => self.status = format!("insert failed: {e}"),
2530        }
2531    }
2532
2533    // --- model operations -----------------------------------------------------
2534
2535    /// The name to save under: the field if non-empty, else the active
2536    /// document's display name, else its untitled name (`"untitled"`, `"untitled 2"`, …).
2537    fn effective_name(&self, docs: &Documents) -> String {
2538        let field = self.name_buf.trim();
2539        if !field.is_empty() {
2540            field.to_string()
2541        } else {
2542            Self::proposed_name(docs)
2543        }
2544    }
2545
2546    /// The name Save As and every export start from: the active document's
2547    /// stem, or, for an instructions tab not saved yet, the instructions'
2548    /// own title (`valve`), so its player, PDF and pictures are
2549    /// `valve.html`, `valve.pdf`, … rather than `untitled 2.html`.
2550    fn proposed_name(docs: &Documents) -> String {
2551        if docs.active().name().is_none() {
2552            if let Ok(Some(block)) = docs.engine().instructions() {
2553                let title = file_stem_of_title(&block.front.title);
2554                if !title.is_empty() {
2555                    return title;
2556                }
2557            }
2558        }
2559        document_class::strip_class_extension(&Self::document_name(docs)).to_string()
2560    }
2561
2562    /// The ACTIVE document's display name, what Save As and Export start
2563    /// their name field from: the file's stem, never the full path a saved
2564    /// document is named by (whose `/`s became `_`s in every exported file
2565    /// name), and never the field's last contents, which belong to whichever
2566    /// tab last used it. An untitled tab with a label (a file imported into
2567    /// a tab of its own, an agent's titled document) offers its label.
2568    fn document_name(docs: &Documents) -> String {
2569        docs.active().name().map(model_display_name).unwrap_or_else(|| file_stem_of_title(&docs.active().title()))
2570    }
2571
2572    /// **New** — a fresh document in a NEW TAB. Nothing is replaced, so there is
2573    /// nothing to confirm.
2574    fn new_document(&mut self, docs: &mut Documents, class: DocumentClass) {
2575        docs.open_document(Document::fresh(docs.spawn_engine(), class));
2576        self.name_buf.clear();
2577        self.status = match class {
2578            DocumentClass::Normal => "new model".into(),
2579            _ => format!("new {}", class.label().to_ascii_lowercase()),
2580        };
2581    }
2582
2583    /// Refuse a save that would give TWO open tabs the same store identity —
2584    /// "focus the tab holding this document" has no answer then, and the second
2585    /// save would silently overwrite the first tab's file. `true` = go ahead.
2586    ///
2587    /// PLM documents compare their full part/revision key in either spelling.
2588    /// Local documents compare DISPLAY names: on desktop an open document
2589    /// carries the full path it was loaded from while the Save As field holds a
2590    /// bare name, so an identity compare would never match and the clobber would
2591    /// happen before anything noticed. Two same-stemmed files in different
2592    /// folders are refused too — stricter than strictly necessary, and the side
2593    /// to err on when the alternative is overwriting another tab's file.
2594    fn name_is_free(&mut self, docs: &mut Documents, name: &str) -> bool {
2595        let display = model_display_name(name);
2596        let target_revision = crate::plm::uses::revision_key_in(name);
2597        let taken = docs.iter().enumerate().any(|(index, doc)| {
2598            index != docs.active_index()
2599                && doc
2600                    .name()
2601                    .is_some_and(|open| {
2602                        match (&target_revision, crate::plm::uses::revision_key_in(open)) {
2603                            (Some(target), Some(other)) => *target == other,
2604                            (None, None) => model_display_name(open) == display,
2605                            _ => false,
2606                        }
2607                    })
2608        });
2609        if taken {
2610            let identity = target_revision.as_deref().unwrap_or(&display);
2611            self.status = format!("Save refused: '{identity}' is already open in another tab");
2612            docs.engine_mut().push_notice(&self.status);
2613        }
2614        !taken
2615    }
2616
2617    /// Write the active document's request JSON through the store under `name`.
2618    /// Returns `true` on success (so the caller can close the modal).
2619    fn save_to(&mut self, docs: &mut Documents, store: &dyn ModelStore, name: String) -> bool {
2620        let name = name.trim().to_string();
2621        if name.is_empty() {
2622            self.status = "enter a name to save".into();
2623            return false;
2624        }
2625        if !self.name_is_free(docs, &name) {
2626            return false;
2627        }
2628        // A Work part edited in place: Save writes the ASSEMBLY (its tab),
2629        // with the part's latest state pushed into it first.
2630        docs.flush_work_part();
2631        let mut plan = docs.plan_owned_save(store, &name);
2632        // A document the Save writes whose bytes have not been read yet (the
2633        // plan's read asked for them): wait for them rather than refuse it
2634        // "still loading", which left a held part unsaved on the first Save.
2635        if !std::mem::take(&mut self.owned_loaded) {
2636            let loading: Vec<String> = plan
2637                .rows
2638                .iter()
2639                .map(|row| row.write.key.clone())
2640                .filter(|key| store.residency(key) == crate::store::Residency::OnDisk)
2641                .collect();
2642            for key in &loading {
2643                // A row the plan settled without its bytes (a checkout) asked
2644                // for none: ask now, so the wait is only as long as the load.
2645                let _ = store.read(key);
2646            }
2647            if !loading.is_empty() {
2648                self.status = format!("Reading {} part(s) from the PLM before saving…", loading.len());
2649                self.owned_loading = Some((docs.active_id(), name, loading, 0));
2650                return false;
2651            }
2652        }
2653        match top_checkout_row(docs, store, &name) {
2654            Some(row) if matches!(row.issue, Some(crate::document::owned_save::Issue::Blocked(_))) => {
2655                // The revision this tab is cannot take the Save (another user
2656                // holds it, or it is released): the changes exist only in the
2657                // tab, so offer the way to keep them instead of a dead end (owner
2658                // rule: prompts that default to proceed). Held by someone else,
2659                // the Save As starts on a new part, as a new revision would sit
2660                // beside their draft; not editable, on its next revision.
2661                let Some(crate::document::owned_save::Issue::Blocked(why)) = &row.issue else { unreachable!() };
2662                // A viewer has nowhere on the PLM to save to: Save As would
2663                // offer destinations that are all refused.
2664                if why == crate::document::owned_save::VIEW_ONLY {
2665                    self.status = format!(
2666                        "{} is not saved: {why}. Your changes are only in this tab: Export keeps a copy as a file.",
2667                        docs.active().title()
2668                    );
2669                    docs.engine_mut().push_notice_as(brep_render::engine_state::NoticeSeverity::Warning, self.status.clone());
2670                    return false;
2671                }
2672                let held = why.starts_with("checked out by");
2673                self.status = format!(
2674                    "{} is not saved: {why}. Your changes are only in this tab: Save As keeps them as {}, or Save again once it can be written.",
2675                    docs.active().title(),
2676                    if held { "a new part" } else { "a new revision" }
2677                );
2678                docs.engine_mut().push_notice_as(brep_render::engine_state::NoticeSeverity::Warning, self.status.clone());
2679                let status = self.status.clone();
2680                self.member_new_part = held;
2681                self.dispatch(FileAction::SaveAs, docs, store);
2682                self.status = status;
2683                return false;
2684            }
2685            Some(row) => plan.rows.insert(0, row),
2686            None => {}
2687        }
2688        if self.hold_for_plm_items(docs, store, plan.clone(), &name, false) {
2689            return false;
2690        }
2691        if self.asks(&plan) {
2692            self.ask_owned_save(plan, name, false);
2693            return false;
2694        }
2695        self.commit_save(docs, store, name, plan)
2696    }
2697
2698    /// Whether `plan` needs the Save dialog: a question, unless the only
2699    /// questions are checkouts the user said not to ask about again.
2700    fn asks(&self, plan: &crate::document::owned_save::OwnedSavePlan) -> bool {
2701        use crate::document::owned_save::Issue;
2702        plan.rows
2703            .iter()
2704            .any(|row| row.asks() && !(self.checkout_remembered && matches!(row.issue, Some(Issue::CheckOut { newer: false, .. }))))
2705    }
2706
2707    /// A PLM assembly's parts with no document get PLM items, not files: start
2708    /// making them and hold the Save until they exist (`true`).
2709    fn hold_for_plm_items(&mut self, docs: &Documents, store: &dyn ModelStore, plan: crate::document::owned_save::OwnedSavePlan, name: &str, browser: bool) -> bool {
2710        let Some(client) = store.plm_client() else { return false };
2711        if plan.promotions.is_empty() || crate::panels::plm_host::revision_of(name).is_none() {
2712            return false;
2713        }
2714        let current: serde_json::Value = serde_json::from_str(&docs.tab_engine().history_request_json()).unwrap_or_default();
2715        let requests = plm_promotion_requests(&current, &plan);
2716        let count = requests.len();
2717        // Linked into the workspace folder the assembly was opened from;
2718        // opened any other way (by number, from a search), the one folder of
2719        // the user's workspace that links it; else the top of the workspace.
2720        let opened = docs.active().plm_folder().cloned();
2721        let part = crate::panels::plm_host::revision_of(name).map(|(part, _)| part);
2722        let future = async move {
2723            let folder = match (opened, part) {
2724                (Some(folder), _) => Some(folder),
2725                (None, Some(part)) => crate::plm::promote::linking_folder(&client, &part).await.filter(|(id, _)| !id.is_empty()),
2726                (None, None) => None,
2727            };
2728            let keys = crate::plm::promote::make_items(client, requests, folder.as_ref().map_or(String::new(), |(id, _)| id.clone())).await?;
2729            Ok((keys, folder))
2730        };
2731        self.owned_promoting = Some((OwnedPrompt { plan, name: name.to_string(), browser }, Box::pin(future)));
2732        self.status = format!("Making PLM items for {count} part(s) with no document of their own…");
2733        true
2734    }
2735
2736    /// Continue a Save held until its documents loaded: plan it again once
2737    /// none is waiting, or after ~20 s (the Save then says which part is still
2738    /// loading, as before). A load that failed is asked again every ~2 s.
2739    fn poll_owned_loading(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
2740        const LOAD_WAIT_FRAMES: u32 = 400;
2741        let Some((_, _, keys, frames)) = self.owned_loading.as_mut() else { return };
2742        if *frames < LOAD_WAIT_FRAMES && keys.iter().any(|key| store.residency(key) == crate::store::Residency::OnDisk) {
2743            *frames += 1;
2744            if *frames % 40 == 0 {
2745                for key in keys.iter() {
2746                    let _ = store.read(key);
2747                }
2748            }
2749            ctx.request_repaint_after(std::time::Duration::from_millis(50));
2750            return;
2751        }
2752        let Some((doc, name, _, _)) = self.owned_loading.take() else { return };
2753        if doc != docs.active_id() {
2754            self.status = "Save cancelled because the active document changed".into();
2755            return;
2756        }
2757        self.owned_loaded = true;
2758        self.save_to(docs, store, name);
2759    }
2760
2761    /// Continue a Save held by [`Self::hold_for_plm_items`] once its items
2762    /// exist; a failure saves nothing and says why (never into the assembly).
2763    fn poll_owned_promotions(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
2764        let Some((_, future)) = self.owned_promoting.as_mut() else { return };
2765        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
2766        let std::task::Poll::Ready(result) = std::future::Future::poll(future.as_mut(), &mut cx) else {
2767            ctx.request_repaint_after(std::time::Duration::from_millis(50));
2768            return;
2769        };
2770        let Some((mut prompt, _)) = self.owned_promoting.take() else { return };
2771        if prompt.plan.doc_id != docs.active_id() {
2772            self.status = "Save cancelled because the active document changed".into();
2773            return;
2774        }
2775        match result {
2776            Ok((keys, folder)) => {
2777                let place = folder.map_or_else(|| "the top of your workspace".to_string(), |(_, name)| format!("your workspace folder '{name}'"));
2778                docs.engine_mut().push_notice_as(
2779                    brep_render::engine_state::NoticeSeverity::Info,
2780                    format!("Made {} PLM item(s) for parts with no document, linked in {place}", keys.len()),
2781                );
2782                assign_plm_keys(&mut prompt.plan, &keys);
2783                if self.asks(&prompt.plan) {
2784                    self.ask_owned_save(prompt.plan, prompt.name, prompt.browser);
2785                } else if prompt.browser {
2786                    self.commit_save_browser(docs, store, prompt.name, prompt.plan);
2787                } else {
2788                    self.commit_save(docs, store, prompt.name, prompt.plan);
2789                }
2790            }
2791            Err(error) => {
2792                self.status = format!("Save stopped: the PLM could not make an item for a part with no document: {error}");
2793                docs.engine_mut().push_notice(&self.status);
2794            }
2795        }
2796    }
2797
2798    /// Hold a Save until the user answers its questions about the documents
2799    /// the assembly owns.
2800    fn ask_owned_save(&mut self, plan: crate::document::owned_save::OwnedSavePlan, name: String, browser: bool) {
2801        self.owned_state = serde_json::json!({"prompt": plan.to_json()});
2802        self.owned_prompt = Some(OwnedPrompt { plan, name, browser });
2803        self.open_modal(Mode::OwnedSave);
2804    }
2805
2806    /// Write the documents the assembly owns (with the user's answers), then
2807    /// return the Save summary to fold into the status line.
2808    fn save_owned(&mut self, docs: &mut Documents, store: &dyn ModelStore, plan: crate::document::owned_save::OwnedSavePlan) -> String {
2809        let (report, checkouts) = docs.execute_owned_save(store, plan);
2810        if let Some(client) = store.plm_client() {
2811            use crate::panels::plm::PlmLifecycle;
2812            let (revisions, checkouts): (Vec<_>, Vec<_>) = checkouts.into_iter().partition(|r| r.new_revision);
2813            for request in checkouts {
2814                let future = client.checkout(&request.part, &request.revision);
2815                self.owned_checkouts.push((request, future));
2816            }
2817            if !revisions.is_empty() {
2818                // Deepest first, as the Save planned them: each text names the
2819                // revisions made before it.
2820                let client = client.clone();
2821                let requests = revisions.clone();
2822                let future: crate::plm::PlmFuture<Vec<Result<(String, String), String>>> = Box::pin(async move {
2823                    let mut done: Vec<(String, String, String)> = Vec::new();
2824                    let mut answers = Vec::new();
2825                    for request in &requests {
2826                        let text = crate::document::owned_save::retarget_text(&request.text, &done);
2827                        match crate::panels::plm_parts::save_as_new_revision(&client, &request.part, "", &text).await {
2828                            Ok(new_key) => {
2829                                done.push((request.key.clone(), new_key.clone(), text.clone()));
2830                                answers.push(Ok((new_key, text)));
2831                            }
2832                            Err(why) => answers.push(Err(why)),
2833                        }
2834                    }
2835                    Ok(answers)
2836                });
2837                self.owned_revisions = Some(OwnedRevisions { doc: docs.active_id(), requests: revisions, future });
2838            }
2839        }
2840        self.owned_state = serde_json::json!({"report": report.to_json()});
2841        let summary = report.summary();
2842        if !summary.is_empty() {
2843            docs.engine_mut().push_notice_as(brep_render::engine_state::NoticeSeverity::Info, format!("Save: {summary}"));
2844        }
2845        summary
2846    }
2847
2848    /// The new revisions a Save asked for, once their chain has answered:
2849    /// each one's copies re-point to it (in order, so a holder's re-point
2850    /// keeps the ones beneath it), a failed one stays marked.
2851    fn poll_owned_revisions(&mut self, docs: &mut Documents, store: &dyn ModelStore) {
2852        let Some(revisions) = self.owned_revisions.as_mut() else { return };
2853        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
2854        let std::task::Poll::Ready(result) = std::future::Future::poll(revisions.future.as_mut(), &mut cx) else { return };
2855        let OwnedRevisions { doc, requests, .. } = self.owned_revisions.take().unwrap();
2856        let answers = result.unwrap_or_else(|why| requests.iter().map(|_| Err(why.clone())).collect());
2857        for (request, answer) in requests.iter().zip(answers) {
2858            match answer {
2859                Ok((new_key, text)) => match docs.retarget_revised_copies(doc, &request.key, &new_key, &text) {
2860                    Ok(()) => {
2861                        // As Save As → new revision: the mirror holds it now and
2862                        // the index learns it, or the next Save reads it absent.
2863                        store.remember_saved_document(&store.canonical_identity(&new_key), &text);
2864                        store.refresh_plm_index(std::slice::from_ref(&new_key), false);
2865                        docs.engine_mut().push_notice_as(
2866                            brep_render::engine_state::NoticeSeverity::Info,
2867                            format!(
2868                                "Made a new revision of {} and saved the change into it: {}",
2869                                request.shown,
2870                                crate::document::owned_save::shown(&new_key, &[])
2871                            ),
2872                        );
2873                        let followup = self.owned_followup.get_or_insert(OwnedFollowup { doc, keys: Vec::new(), since: None });
2874                        followup.keys.push(new_key);
2875                    }
2876                    Err(why) => docs.engine_mut().push_notice(format!("'{new_key}' holds the change, but the assembly could not name it: {why}")),
2877                },
2878                Err(why) => {
2879                    docs.engine_mut().push_notice(format!("{} NOT saved: {why} — the change is kept in the assembly", request.shown));
2880                    let was_clean = docs.iter().find(|d| d.id() == doc).is_some_and(|d| !d.is_dirty());
2881                    if docs.mark_unsaved_copies(doc, &request.key, &format!("a new revision could not be made: {why}")) {
2882                        write_late_marks(docs, store, doc, was_clean);
2883                    }
2884                }
2885            }
2886        }
2887    }
2888
2889    /// Write the PLM items whose checkout landed since last frame.
2890    fn poll_owned_checkouts(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
2891        if let Some((_, _, _, future)) = self.owned_top.as_mut() {
2892            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
2893            match std::future::Future::poll(future.as_mut(), &mut cx) {
2894                std::task::Poll::Ready(result) => {
2895                    if let Some((id, signature, request, _)) = self.owned_top.take() {
2896                        let saved = crate::document::owned_save::finish_checkout(docs.engine_mut(), store, &request, result);
2897                        if saved {
2898                            if let Some(doc) = docs.iter_mut().find(|d| d.id() == id) {
2899                                doc.mark_saved_signature(signature);
2900                                doc.set_plm_save_access(crate::document::Access::Editable);
2901                            }
2902                            self.save_generation += 1;
2903                            remember_document(store, &request.key);
2904                            self.status = format!("saved {}", request.key);
2905                        } else {
2906                            self.status = format!("{} NOT saved: the checkout or the write failed; your edits are kept", request.key);
2907                        }
2908                    }
2909                }
2910                std::task::Poll::Pending => ctx.request_repaint_after(std::time::Duration::from_millis(50)),
2911            }
2912        }
2913        self.poll_owned_revisions(docs, store);
2914        if self.owned_checkouts.is_empty() && self.owned_revisions.is_none() {
2915            // The follow-up Save also waits for the assembly's own checkout.
2916            if self.owned_top.is_some() {
2917                return;
2918            }
2919            if let Some(followup) = self.owned_followup.as_mut() {
2920                const INDEX_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
2921                let since = *followup.since.get_or_insert_with(web_time::Instant::now);
2922                if since.elapsed() < INDEX_WAIT && followup.keys.iter().any(|key| store.plm_revision(key).is_none()) {
2923                    ctx.request_repaint_after(std::time::Duration::from_millis(50));
2924                    return;
2925                }
2926            }
2927            if let Some(OwnedFollowup { doc: id, keys, .. }) = self.owned_followup.take() {
2928                // Every new revision landed: save the assembly again so the
2929                // documents holding them (and the assembly itself) name them.
2930                // This session made each of them and saved the change into it,
2931                // so each is checked out to us: say so to the index first, or a
2932                // row read before the change feed caught up (a loaded machine)
2933                // has the Save ask to check it out again and stop at that prompt.
2934                for key in &keys {
2935                    store.note_checked_out(key);
2936                }
2937                if docs.active_id() == id {
2938                    if let Some(name) = docs.active().name().map(str::to_string) {
2939                        self.save_to(docs, store, name);
2940                    }
2941                } else {
2942                    docs.engine_mut().push_notice("Save the assembly again: it names the new revisions now");
2943                }
2944            }
2945            return;
2946        }
2947        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
2948        let mut i = 0;
2949        while i < self.owned_checkouts.len() {
2950            match std::future::Future::poll(self.owned_checkouts[i].1.as_mut(), &mut cx) {
2951                std::task::Poll::Ready(result) => {
2952                    let (request, _) = self.owned_checkouts.remove(i);
2953                    let failure = result.as_ref().err().cloned();
2954                    let id = docs.active_id();
2955                    if crate::document::owned_save::finish_checkout(docs.engine_mut(), store, &request, result) {
2956                        if docs.clear_unsaved_copies(id, &request.key) {
2957                            // A change kept by an earlier Save is written now; the
2958                            // assembly was written before it landed and still marks
2959                            // it: save the assembly again, as for new revisions.
2960                            self.owned_followup.get_or_insert(OwnedFollowup { doc: id, keys: Vec::new(), since: None });
2961                        }
2962                    } else {
2963                        // Kept in the assembly: marked, so it reads unsaved, the
2964                        // next Save asks again and no refresh replaces it.
2965                        let why = failure.unwrap_or_else(|| "the write after the checkout failed".into());
2966                        let was_clean = docs.iter().find(|d| d.id() == id).is_some_and(|d| !d.is_dirty());
2967                        if docs.mark_unsaved_copies(id, &request.key, &format!("checkout failed: {why}")) {
2968                            write_late_marks(docs, store, id, was_clean);
2969                        }
2970                    }
2971                }
2972                std::task::Poll::Pending => i += 1,
2973            }
2974        }
2975        if !self.owned_checkouts.is_empty() || self.owned_revisions.is_some() {
2976            ctx.request_repaint_after(std::time::Duration::from_millis(50));
2977        }
2978    }
2979
2980    /// After the owned documents: a part that should have been given a file
2981    /// of its own and could not be stops the Save BEFORE the assembly is
2982    /// written — written now, it would keep that part only inside the
2983    /// assembly. Everything else already saved stays saved, the tab stays
2984    /// unsaved, and Save can simply be pressed again.
2985    fn promotion_failed(&mut self, docs: &mut Documents) -> bool {
2986        let failed: Vec<String> = self.owned_state["report"]["failedPromotions"]
2987            .as_array()
2988            .map(|keys| keys.iter().filter_map(|k| k.as_str().map(str::to_string)).collect())
2989            .unwrap_or_default();
2990        if failed.is_empty() {
2991            return false;
2992        }
2993        self.status = format!(
2994            "Save stopped: could not create {} — the assembly was not written, so no part is kept only inside it. Fix the problem and Save again.",
2995            failed.join(", ")
2996        );
2997        docs.engine_mut().push_notice(&self.status);
2998        true
2999    }
3000
3001    /// The Save itself, once nothing is left to ask: the owned documents
3002    /// first (deepest first), then the active tab.
3003    fn commit_save(&mut self, docs: &mut Documents, store: &dyn ModelStore, name: String, plan: crate::document::owned_save::OwnedSavePlan) -> bool {
3004        use crate::document::owned_save::{CheckoutRequest, Issue};
3005        let top = plan.rows.first().filter(|row| row.write.key == name).cloned();
3006        if let Some(row) = &top {
3007            if !row.proceed {
3008                self.status = format!("Save cancelled: {name} was not checked out");
3009                return false;
3010            }
3011        }
3012        let summary = self.save_owned(docs, store, plan);
3013        if self.promotion_failed(docs) {
3014            return false;
3015        }
3016        let document = docs.tab_engine().history_request_json();
3017        if let (Some(row), Some(client)) = (top, store.plm_client()) {
3018            if let Some(Issue::CheckOut { part, revision, .. }) = row.issue {
3019                use crate::panels::plm::PlmLifecycle;
3020                let signature = docs.active().save_signature();
3021                let future = client.checkout(&part, &revision);
3022                let shown = crate::document::owned_save::shown(&name, &[]);
3023                let request = CheckoutRequest { key: name.clone(), part, revision, text: document, shown: shown.clone(), new_revision: false };
3024                self.owned_top = Some((docs.active_id(), signature, request, future));
3025                self.status = if summary.is_empty() {
3026                    format!("checking out and saving {shown}")
3027                } else {
3028                    format!("checking out and saving {shown}; {summary}")
3029                };
3030                return true;
3031            }
3032        }
3033        crate::plm::thumbnail::stage_save(store, &name, &document, docs.tab_engine(), docs.active_id());
3034        match store.write(&name, &document) {
3035            Ok(()) => {
3036                // The document keeps the raw identity (a full path when a
3037                // native dialog chose it); the name field shows the bare name.
3038                self.name_buf = model_display_name(&name);
3039                let doc = docs.active_mut();
3040                doc.set_name(Some(name.clone()));
3041                doc.mark_clean();
3042                self.save_generation += 1;
3043                remember_document(store, &name);
3044                self.status = if summary.is_empty() { format!("saved {name}") } else { format!("saved {name}; {summary}") };
3045                true
3046            }
3047            Err(e) => {
3048                self.status = format!("save failed: {e}");
3049                docs.engine_mut().push_notice(&self.status);
3050                false
3051            }
3052        }
3053    }
3054
3055    /// Save As through the explorer's current directory, then retain the
3056    /// backend's returned identity (an absolute path on desktop or a virtual
3057    /// `/models/...` path in the browser) for subsequent plain Save commands.
3058    fn save_to_browser(
3059        &mut self,
3060        docs: &mut Documents,
3061        store: &dyn ModelStore,
3062        name: String,
3063    ) -> bool {
3064        let name = name.trim().to_string();
3065        if name.is_empty() {
3066            self.status = "enter a name to save".into();
3067            return false;
3068        }
3069        if !self.name_is_free(docs, &name) {
3070            return false;
3071        }
3072        // Save As makes a NEW file: its class is the one the name carries
3073        // (the chooser put it there), the blocks of the other classes go, and
3074        // a family member's stamp goes — the copy is a part of its own, which
3075        // is what "Save as a new part" means.
3076        docs.flush_work_part();
3077        let plan = docs.plan_owned_save(store, &name);
3078        if self.hold_for_plm_items(docs, store, plan.clone(), &name, true) {
3079            return false;
3080        }
3081        if plan.needs_asking() {
3082            self.ask_owned_save(plan, name, true);
3083            return false;
3084        }
3085        self.commit_save_browser(docs, store, name, plan)
3086    }
3087
3088    /// [`Self::save_to_browser`] once nothing is left to ask.
3089    fn commit_save_browser(&mut self, docs: &mut Documents, store: &dyn ModelStore, name: String, plan: crate::document::owned_save::OwnedSavePlan) -> bool {
3090        let summary = self.save_owned(docs, store, plan);
3091        if self.promotion_failed(docs) {
3092            return false;
3093        }
3094        let class = DocumentClass::of_name(&name).unwrap_or_default();
3095        adopt_class(docs.tab_engine_mut(), class);
3096        // The copy remembers what it was saved from (before the family stamp
3097        // goes: the chain keeps the family too), so Replace component knows
3098        // an edited variation is still that part's relative.
3099        stamp_save_as_lineage(docs, store, &name);
3100        if docs.tab_engine().history.document_block(family_table::FAMILY_SOURCE_KEY).is_some() {
3101            docs.tab_engine_mut()
3102                .history
3103                .set_document_block_no_undo(family_table::FAMILY_SOURCE_KEY, None);
3104        }
3105        let previous = docs.active().name().map(str::to_string);
3106        let saved_text = docs.tab_engine().history_request_json();
3107        match store.browser_write(&name, &saved_text) {
3108            Ok(identity) => {
3109                // Open assemblies that place this part under its OLD name:
3110                // ask once whether they follow it to the new file.
3111                if let Some(old) = previous.filter(|old| store.canonical_identity(old) != store.canonical_identity(&identity)) {
3112                    let tabs = docs.tabs_holding(&old, docs.active_id());
3113                    if !tabs.is_empty() {
3114                        self.retarget = Some(Retarget { old, new_key: identity.clone(), text: saved_text.clone(), tabs });
3115                    }
3116                }
3117                // The recent list's picture, under the identity the backend
3118                // chose (the name the recent row will carry).
3119                crate::plm::thumbnail::stage_recent(&identity, docs.tab_engine(), docs.active_id());
3120                self.name_buf = model_display_name(&identity);
3121                let doc = docs.active_mut();
3122                self.member_ack.remove(&doc.id());
3123                doc.set_name(Some(identity.clone()));
3124                doc.mark_clean();
3125                self.save_generation += 1;
3126                remember_document(store, &identity);
3127                self.status = if summary.is_empty() { format!("saved {identity}") } else { format!("saved {identity}; {summary}") };
3128                true
3129            }
3130            Err(e) => {
3131                self.status = format!("save failed: {e}");
3132                false
3133            }
3134        }
3135    }
3136
3137    /// **Open** — read a stored document into its own tab (or focus the tab
3138    /// already holding it). The one door every open lane uses: File>Open, the
3139    /// Edit-Part flow, and the session restore's siblings.
3140    pub fn open_document(&mut self, docs: &mut Documents, store: &dyn ModelStore, name: &str) {
3141        self.pending_open = None;
3142        if docs.focus_named(name) {
3143            remember_document(store, name);
3144            self.status = format!("{name} is already open");
3145            return;
3146        }
3147        match crate::store::read_now(store, name) {
3148            crate::store::ReadNow::Ready(contents) => self.load_document(docs, name, &contents, store),
3149            // An index-hydrated PLM store lists what it has not loaded yet;
3150            // the read above asked for it.
3151            crate::store::ReadNow::Loading => {
3152                self.pending_open = Some((name.to_owned(), docs.active_id()));
3153                self.status = format!("'{name}' is still loading");
3154            }
3155            crate::store::ReadNow::Absent => self.status = format!("open failed: '{name}' not found"),
3156        }
3157    }
3158
3159    /// Complete the common File>Open / Edit-Part demand read on a later frame.
3160    /// Store reads are already deduplicated while a request is in flight.
3161    fn poll_pending_open(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
3162        let Some((name, requester)) = self.pending_open.take() else { return };
3163        if docs.active_id() != requester {
3164            return;
3165        }
3166        if docs.focus_named(&name) {
3167            self.status = format!("{name} is already open");
3168            return;
3169        }
3170        match crate::store::read_now(store, &name) {
3171            crate::store::ReadNow::Ready(contents) => {
3172                self.load_document(docs, &name, &contents, store);
3173            }
3174            crate::store::ReadNow::Loading => {
3175                self.pending_open = Some((name, requester));
3176                ctx.request_repaint_after(std::time::Duration::from_millis(100));
3177            }
3178            crate::store::ReadNow::Absent => {
3179                self.status = format!("open failed: '{name}' not found");
3180            }
3181        }
3182    }
3183
3184    /// Serialize the current model in `format` (`"step"` | `"iges"` | `"stl"` |
3185    /// `"obj"` | `"glb"` | `"3mf"` | `"3mfbambu"` | `"json"`) and
3186    /// write it through the store's format-typed interchange under `<name>.<ext>`.
3187    /// `"json"` is the full model RECIPE (`.nbrep`, `history_request_json`) —
3188    /// the exact document Open/Import consume, for sharing a failing model. Returns
3189    /// `true` on success (so the caller can close the modal); a guard message and
3190    /// `false` when there is nothing to export or the engine/store errs.
3191    /// An export of the geometry taken while a family row is previewed is of
3192    /// THAT row: say so on the status line and in a toast, so a user does not
3193    /// ship the wrong size without knowing.
3194    fn say_previewed_export(&mut self, docs: &mut Documents) {
3195        let Some(label) = docs.engine().expression_preview().map(|p| p.label.clone()) else {
3196            return;
3197        };
3198        let note = format!("exported {label} (preview): the family's own values are not in this file");
3199        self.status = format!("{} — {label} (preview)", self.status);
3200        docs.engine_mut().push_notice(note);
3201    }
3202
3203    /// The line the export dialogs show while a family row is previewed.
3204    fn preview_export_line(ui: &mut egui::Ui, docs: &Documents) {
3205        if let Some(label) = docs.engine().expression_preview().map(|p| p.label.clone()) {
3206            let text = format!(
3207                "Previewing {label}: STEP, IGES, meshes, drawings and flat patterns export {label}, \
3208                 not the family's own values. The .nbrep recipe keeps the family's own."
3209            );
3210            ui.add(egui::Label::new(egui::RichText::new(text).color(ui.visuals().warn_fg_color)).wrap());
3211            ui.add_space(4.0);
3212        }
3213    }
3214
3215    fn poll_instructions_pdf(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
3216        let Some(mut export) = self.instructions_pdf.take() else { return };
3217        if export.document != docs.view_id() {
3218            self.status = "PDF export cancelled: the active document changed".into();
3219            docs.engine_mut().push_notice(self.status.clone());
3220            return;
3221        }
3222        match docs.engine_mut().poll_instructions_pdf(&mut export.job) {
3223            Ok(None) => {
3224                self.instructions_pdf = Some(export);
3225                ctx.request_repaint_after(std::time::Duration::from_millis(16));
3226            }
3227            Ok(Some((bytes, pages))) => {
3228                let pending = PendingSave {
3229                    request: SaveRequest::bytes("Export the instructions", format!("{}.pdf", export.name), bytes),
3230                    detail: format!(" ({pages} page{})", if pages == 1 { "" } else { "s" }),
3231                    label: None, warnings: vec![], preview: export.preview,
3232                };
3233                self.deliver(docs, store, pending);
3234            }
3235            Err(error) => {
3236                self.status = format!("PDF export failed: {error}");
3237                docs.engine_mut().push_notice(self.status.clone());
3238            }
3239        }
3240    }
3241
3242    fn export_as(&mut self, docs: &mut Documents, store: &dyn ModelStore, format: &str) -> bool {
3243        let name = self.effective_name(docs);
3244        // The `.nbrep` recipe is the document; every other format is of the
3245        // geometry, which a family-row preview has replaced — said once the
3246        // file is delivered.
3247        let preview = format != "json";
3248        let export = |request: SaveRequest| PendingSave { request, detail: String::new(), label: None, warnings: vec![], preview };
3249        // GLB and 3MF are BINARY, so they take the store's byte-shaped
3250        // interchange rather than the text one below — a `.glb` routed through
3251        // a `&str` would be mangled the moment a chunk length happened not to
3252        // be valid UTF-8, and a 3MF is a ZIP.
3253        // The offline player: one page, named for the document, the tools'
3254        // pictures fetched from the library and inlined (the door is held
3255        // while they load; without a session the page carries none).
3256        if format == "instructionshtml" {
3257            let ids = linked_tool_ids(docs.engine());
3258            if let Some(client) = store.plm_client().filter(|_| !ids.is_empty()) {
3259                crate::plm::tool_pictures::request(&client, &ids);
3260                if crate::plm::tool_pictures::pending_of(&ids) > 0 {
3261                    self.pending_instructions_export = Some(format.to_string());
3262                    self.status = "loading the tool pictures for the export…".into();
3263                    return true;
3264                }
3265            }
3266            let made = docs.engine().instructions_player_data().map(|mut data| {
3267                data.inline_tool_pictures(&crate::plm::tool_pictures::fetched(&ids));
3268                brep_instructions::player::offline_html(&data, brep_instructions::player::Mode::Shop)
3269            });
3270            return match made {
3271                Ok(html) => {
3272                    let pending = export(SaveRequest::text("Export the offline player", format!("{name}.html"), html));
3273                    self.deliver(docs, store, pending) != Delivery::Failed
3274                }
3275                Err(e) => {
3276                    self.status = format!("export failed: {e}");
3277                    false
3278                }
3279            };
3280        }
3281        // The instructions' PDF and their step pictures: byte formats, named
3282        // for the document (`<name>.pdf`, `<name>-steps.zip`).
3283        if format == "instructionspdf" {
3284            if self.instructions_pdf.is_some() {
3285                self.status = "an instructions PDF is already being prepared".into();
3286                return false;
3287            }
3288            return match docs.engine_mut().begin_instructions_pdf() {
3289                Ok(job) => {
3290                    self.instructions_pdf = Some(PendingInstructionsPdf { document: docs.view_id(), name, preview, job });
3291                    self.status = "preparing the instructions PDF…".into();
3292                    true
3293                }
3294                Err(error) => { self.status = format!("export failed: {error}"); false }
3295            };
3296        }
3297        if format == "instructionsimages" {
3298            // The pictures are drawn from the exact solids: asked of the
3299            // runner first, and on a runner that cannot be waited on the
3300            // export is held until they land.
3301            if !docs.engine_mut().instructions_topology_ready() {
3302                self.pending_instructions_export = Some(format.to_string());
3303                self.status = "loading the exact geometry for the export…".into();
3304                return true;
3305            }
3306            let made = super::instructions::images_zip(docs.engine_mut()).map(|bytes| (bytes, String::new()));
3307            return match made {
3308                Ok((bytes, detail)) => {
3309                    let (title, file) = ("Export the step images", format!("{name}-steps.zip"));
3310                    let pending = PendingSave { detail, ..export(SaveRequest::bytes(title, file, bytes)) };
3311                    self.deliver(docs, store, pending) != Delivery::Failed
3312                }
3313                Err(e) => {
3314                    self.status = format!("export failed: {e}");
3315                    false
3316                }
3317            };
3318        }
3319        if format == "glb" || format == "3mf" || format == "3mfbambu" {
3320            // The document's name becomes the root NODE's (GLB) or the model's
3321            // Title (3MF), as it becomes the root PRODUCT's on a STEP export.
3322            let written = match format {
3323                "glb" => docs.engine().export_glb_bytes(&name),
3324                "3mf" => docs.engine().export_3mf_bytes(&name),
3325                _ => docs.engine().export_3mf_bambu_bytes(&name),
3326            };
3327            return match written {
3328                Ok(bytes) => {
3329                    let (title, extension) = match format {
3330                        "glb" => ("Export GLB", "glb"),
3331                        "3mf" => ("Export 3MF", "3mf"),
3332                        _ => ("Export 3MF for Bambu Studio", "3mf"),
3333                    };
3334                    let request = SaveRequest::bytes(title, format!("{name}.{extension}"), bytes);
3335                    self.deliver(docs, store, export(request)) != Delivery::Failed
3336                }
3337                Err(e) => {
3338                    self.status = format!("export failed: {e}");
3339                    false
3340                }
3341            };
3342        }
3343        let state = docs.engine_mut();
3344        // A drawing sheet's SVG writes `<name>-<sheet>.svg`: a document can
3345        // carry several sheets, and one file per export must not overwrite the
3346        // last. The PDF is the whole drawing SET, one page per sheet, so it is
3347        // the document's own `<name>.pdf`. It takes the BYTE lane — it is a
3348        // byte format, and both lanes type the file from its extension, so the
3349        // user gets `application/pdf` either way.
3350        // The 3D drawing set is `<name>-3d.pdf`, beside the plain one rather
3351        // than over it.
3352        if format == "sheetsvg" || format == "sheetpdf" || format == "sheetpdf3d" {
3353            let pdf = format != "sheetsvg";
3354            let three_d = format == "sheetpdf3d";
3355            let (file, made) = if pdf {
3356                let file = if three_d { format!("{name}-3d.pdf") } else { format!("{name}.pdf") };
3357                let bytes = if three_d { state.export_document_pdf_3d() } else { state.export_document_pdf() };
3358                (file, bytes.map(SaveBody::Bytes))
3359            } else {
3360                let sheet_name = state
3361                    .resolve_sheet("")
3362                    .ok()
3363                    .and_then(|id| state.sheet_state().find_sheet(&id).map(|sheet| sheet.name.clone()))
3364                    .unwrap_or_default();
3365                let file = format!("{name}-{}.svg", slug(&sheet_name));
3366                let text = state.resolve_sheet("").and_then(|id| state.export_sheet_svg(&id));
3367                (file, text.map(SaveBody::Text))
3368            };
3369            let pages = state.sheet_state().sheets.len() + usize::from(three_d);
3370            return match made {
3371                Ok(body) => {
3372                    let detail = if pdf {
3373                        format!(" ({pages} page{})", if pages == 1 { "" } else { "s" })
3374                    } else {
3375                        String::new()
3376                    };
3377                    let title = if pdf { "Export the drawing set" } else { "Export the drawing sheet" };
3378                    let request = SaveRequest { title: title.into(), file_name: file, body };
3379                    let pending = PendingSave { detail, ..export(request) };
3380                    self.deliver(docs, store, pending) != Delivery::Failed
3381                }
3382                Err(e) => {
3383                    self.status = format!("export failed: {e}");
3384                    false
3385                }
3386            };
3387        }
3388        if format == "parasolid" || format == "parasolidbinary" {
3389            let binary = format == "parasolidbinary";
3390            let ext = if binary { "x_b" } else { "x_t" };
3391            return match state.export_parasolid_selected(&name, None, binary) {
3392                Ok(bytes) => {
3393                    let title = format!("Export Parasolid ({})", if binary { ".x_b" } else { ".x_t" });
3394                    let body = if binary { SaveBody::Bytes(bytes) } else { SaveBody::Text(String::from_utf8_lossy(&bytes).into_owned()) };
3395                    let request = SaveRequest { title, file_name: format!("{name}.{ext}"), body };
3396                    self.deliver(docs, store, export(request)) != Delivery::Failed
3397                }
3398                Err(e) => {
3399                    self.status = format!("export failed: {e}");
3400                    false
3401                }
3402            };
3403        }
3404        let (text, ext) = match format {
3405            "stl" => (state.export_stl_text(), "stl"),
3406            "obj" => (state.export_obj_text(), "obj"),
3407            "iges" => (state.export_iges_text_selected(&name, None), "igs"),
3408            "json" => (Ok(state.history_request_json()), "nbrep"),
3409            // The document's name becomes the root PRODUCT's — an assembly
3410            // exports as `<name>` with its parts named under it.
3411            _ => (state.export_step_text_named(&name), "step"),
3412        };
3413        match text {
3414            Ok(contents) => {
3415                let title = if format == "json" { "Export the model".to_string() } else { format!("Export {}", ext.to_ascii_uppercase()) };
3416                let request = SaveRequest::text(title, format!("{name}.{ext}"), contents);
3417                self.deliver(docs, store, export(request)) != Delivery::Failed
3418            }
3419            Err(e) => {
3420                self.status = format!("export failed: {e}");
3421                false
3422            }
3423        }
3424    }
3425
3426    /// Hand a produced export to the user — the one door every export takes.
3427    /// Desktop (a store with local files): the Save-file chooser, which the
3428    /// modal switches to; the write happens on its Save. Browser: the
3429    /// download, now. What a written export says (status, toasts, the
3430    /// preview note) is [`Self::say_written`], on both roads.
3431    fn deliver(&mut self, docs: &mut Documents, store: &dyn ModelStore, pending: PendingSave) -> Delivery {
3432        if let Some(local) = store.local_files() {
3433            self.save_name = pending.request.file_name.clone();
3434            self.save_file = Some(pending);
3435            self.use_folder(Purpose::Exports, local);
3436            self.status.clear();
3437            self.open_modal(Mode::SaveFile);
3438            return Delivery::Chooser;
3439        }
3440        let file = pending.request.file_name.clone();
3441        let written = match &pending.request.body {
3442            SaveBody::Text(text) => store.export_file_named(&file, text),
3443            SaveBody::Bytes(bytes) => store.export_file_named_bytes(&file, bytes),
3444        };
3445        match written {
3446            Ok(()) => {
3447                self.say_written(docs, &pending, &file, None);
3448                Delivery::Done
3449            }
3450            Err(e) => {
3451                self.status = match &pending.label {
3452                    Some(label) => format!("{label} export failed: {e}"),
3453                    None => format!("export failed: {e}"),
3454                };
3455                Delivery::Failed
3456            }
3457        }
3458    }
3459
3460    /// What a written export says: the status line ("exported <file>
3461    /// [detail] [into <folder>]"), the family-preview note, and the toast —
3462    /// a labelled export's own (the PCB outputs name themselves: "Netlist:
3463    /// …"), a warning one carrying the bundle's warnings, or on desktop,
3464    /// where the chooser closes on the write and the status with it, the
3465    /// generic "exported … into …". Returns whether the dialog should STAY
3466    /// open: it does on warnings, so they are read before boards are ordered.
3467    fn say_written(&mut self, docs: &mut Documents, pending: &PendingSave, file: &str, folder: Option<&str>) -> bool {
3468        let into = folder.map(|folder| format!(" into {folder}")).unwrap_or_default();
3469        self.status = format!("exported {file}{}{into}", pending.detail);
3470        if pending.preview {
3471            self.say_previewed_export(docs);
3472        }
3473        use brep_render::engine_state::NoticeSeverity;
3474        let state = docs.engine_mut();
3475        match &pending.label {
3476            Some(label) if !pending.warnings.is_empty() => {
3477                let warnings = pending.warnings.join(" ");
3478                self.status = format!("{}. Before ordering: {warnings}", self.status);
3479                state.push_notice_as(NoticeSeverity::Warning, format!("{label}: {warnings}"));
3480                true
3481            }
3482            Some(label) => {
3483                state.push_notice_as(NoticeSeverity::Info, format!("{label}: {}", self.status));
3484                false
3485            }
3486            None => {
3487                if folder.is_some() {
3488                    state.push_notice_as(NoticeSeverity::Info, self.status.clone());
3489                }
3490                false
3491            }
3492        }
3493    }
3494
3495    /// A panel's export (the JavaScript editor's script, a plugin bundle, a
3496    /// PLM download): hand `request` to the user through the export door.
3497    /// Desktop: the Save-file chooser opens. Browser: the download, now.
3498    /// `Err` only when the download could not start.
3499    pub fn request_save_file(&mut self, docs: &mut Documents, store: &dyn ModelStore, request: SaveRequest) -> Result<(), String> {
3500        let pending = PendingSave { request, detail: String::new(), label: None, warnings: vec![], preview: false };
3501        match self.deliver(docs, store, pending) {
3502            Delivery::Failed => Err(std::mem::take(&mut self.status)),
3503            Delivery::Done | Delivery::Chooser => Ok(()),
3504        }
3505    }
3506
3507    /// The **Save-file** chooser ([`Mode::SaveFile`]): the explorer over the
3508    /// local files picks the FOLDER, the field the NAME, and Save writes the
3509    /// held export there. Shaped like Save As (the name field and buttons
3510    /// pinned under the browser), over the exports' own remembered folder,
3511    /// which starts in the models folder.
3512    fn show_save_file(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
3513        let Some(local) = store.local_files() else {
3514            self.save_file = None;
3515            self.open = false;
3516            return;
3517        };
3518        let title = self.save_file.as_ref().map(|pending| pending.request.title.clone()).unwrap_or_else(|| "Save file".into());
3519        let pending = self.save_file.is_some();
3520        // The explorer lists the files of the export's own kind beside the
3521        // folders, so a name to overwrite can be picked; a name without an
3522        // extension lists every file.
3523        let extension = std::path::Path::new(self.save_name.trim())
3524            .extension()
3525            .map(|extension| extension.to_string_lossy().into_owned());
3526        let extensions: Vec<&str> = extension.iter().map(String::as_str).collect();
3527        let mut do_save = false;
3528        let mut cancel = false;
3529        let modal = egui::Modal::new(egui::Id::new("brep-file-savefile")).show(ctx, |ui| {
3530            file_explorer::dialog_body(ui, |ui| {
3531                ui.heading(&title);
3532                ui.add_space(4.0);
3533                file_explorer::dialog_footer(ui, "savefile", |ui| {
3534                    ui.label("File name");
3535                    let field = crate::ui_kit::text_input(&mut self.save_name).placeholder("file name").width(ui.available_width()).show(ui).framed();
3536                    self.hit("savefile:name", &field);
3537                    if self.want_focus {
3538                        field.request_focus();
3539                        self.want_focus = false;
3540                    }
3541                    let enter = field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
3542                    ui.add_space(6.0);
3543                    ui.horizontal(|ui| {
3544                        // Written already (the chooser stays up on a warning):
3545                        // nothing is left to save, only to read and close.
3546                        let save = ui.add(crate::ui_kit::Button::new("Save").enabled(pending));
3547                        self.hit("save", &save);
3548                        if save.clicked() || (enter && pending) {
3549                            do_save = true;
3550                        }
3551                        let c = ui.add(crate::ui_kit::Button::new(if pending { "Cancel" } else { "Close" }));
3552                        self.hit("cancel", &c);
3553                        if c.clicked() {
3554                            cancel = true;
3555                        }
3556                    });
3557                    if !self.status.is_empty() {
3558                        ui.add_space(4.0);
3559                        ui.weak(&self.status);
3560                    }
3561                });
3562                let options = FileExplorerOptions {
3563                    hit_prefix: "savefile",
3564                    empty_label: "(no files of this kind here)",
3565                    row_icon: "\u{1F5CE}",
3566                    current: None,
3567                    allow_delete: false,
3568                    allow_import: false,
3569                    import_label: "",
3570                    import_hit: "savefile:upload",
3571                    show_cancel: false,
3572                    confirm_label: None,
3573                    extensions: &extensions,
3574                };
3575                let output = self.explorer.show_store(ui, local, options);
3576                self.record_explorer_hits(&output.hits);
3577                // A row fills the name field (to overwrite that file); the
3578                // row's identity is its full path on desktop, so just its
3579                // name. One-shot, so it never clobbers a name typed after.
3580                if let Some(identity) = output.picked.or(output.activated) {
3581                    self.save_name = std::path::Path::new(&identity)
3582                        .file_name()
3583                        .map(|name| name.to_string_lossy().into_owned())
3584                        .unwrap_or(identity);
3585                    ui.ctx().request_repaint();
3586                }
3587            })
3588        });
3589        if do_save {
3590            if self.save_file(docs, store) {
3591                self.open = false;
3592            }
3593        } else if cancel || modal.should_close() {
3594            if self.save_file.take().is_some() {
3595                self.status = "export cancelled: nothing written".into();
3596            }
3597            self.open = false;
3598        }
3599    }
3600
3601    /// The Save-file chooser's Save: write the held export under the name
3602    /// field, where the explorer is, and remember that folder for the next
3603    /// export. `true` once written, so the chooser closes — unless the export
3604    /// carried warnings, which keep it open to be read (what the format
3605    /// dialog did before the chooser existed).
3606    pub(crate) fn save_file(&mut self, docs: &mut Documents, store: &dyn ModelStore) -> bool {
3607        let Some(local) = store.local_files() else {
3608            return false;
3609        };
3610        let name = self.save_name.trim().to_string();
3611        if name.is_empty() {
3612            self.status = "enter a file name".into();
3613            return false;
3614        }
3615        let Some(pending) = self.save_file.take() else {
3616            return false;
3617        };
3618        match local.browser_write_bytes(&name, pending.request.body.as_bytes()) {
3619            Ok(path) => {
3620                self.folders.insert(Purpose::Exports, local.browser_location());
3621                let path = std::path::Path::new(&path);
3622                let folder = path.parent().map(|folder| folder.display().to_string()).unwrap_or_else(|| local.browser_location());
3623                let file = path.file_name().map(|file| file.to_string_lossy().into_owned()).unwrap_or(name);
3624                !self.say_written(docs, &pending, &file, Some(&folder))
3625            }
3626            Err(e) => {
3627                self.status = format!("export failed: {e}");
3628                self.save_file = Some(pending);
3629                false
3630            }
3631        }
3632    }
3633
3634    /// Serialize the sheet-metal flat pattern in `format` (`"dxf"` | `"svg"`) and
3635    /// write it through the store under `<name>.<ext>`. Returns `true` on success
3636    /// (so the caller can close the modal). On failure the message goes to the
3637    /// status line AND is queued as a toast (the existing engine notice path), so
3638    /// a "no sheet-metal body in the part" error is surfaced prominently.
3639    fn export_flat_pattern_as(
3640        &mut self,
3641        docs: &mut Documents,
3642        store: &dyn ModelStore,
3643        format: &str,
3644    ) -> bool {
3645        let name = self.effective_name(docs);
3646        let state = docs.engine_mut();
3647        let (text, ext) = match format {
3648            "svg" => (state.export_flat_pattern_svg(), "svg"),
3649            _ => (state.export_flat_pattern_dxf(), "dxf"),
3650        };
3651        match text {
3652            Ok(contents) => {
3653                let request = SaveRequest::text("Export the flat pattern", format!("{name}.{ext}"), contents);
3654                let pending = PendingSave { request, detail: String::new(), label: None, warnings: vec![], preview: true };
3655                self.deliver(docs, store, pending) != Delivery::Failed
3656            }
3657            Err(e) => {
3658                self.status = format!("flat-pattern export failed: {e}");
3659                state.push_notice(format!("Flat pattern: {e}"));
3660                false
3661            }
3662        }
3663    }
3664
3665    /// Serialize the assembly BOM in `format` (`"csv"` | `"json"`) and write it
3666    /// through the store under `<name>.bom.<ext>` (a compound extension naming
3667    /// the content, like the `.nbrep` recipe). On failure the message goes
3668    /// to the status line AND is queued as a toast — the flat-pattern error
3669    /// pattern — so a componentless document reports loudly.
3670    fn export_bom_as(
3671        &mut self,
3672        docs: &mut Documents,
3673        store: &dyn ModelStore,
3674        format: &str,
3675    ) -> bool {
3676        let name = self.effective_name(docs);
3677        let state = docs.engine_mut();
3678        let (text, ext) = match format {
3679            "json" => (state.export_bom_json(), "bom.json"),
3680            _ => (state.export_bom_csv(), "bom.csv"),
3681        };
3682        match text {
3683            Ok(contents) => {
3684                let request = SaveRequest::text("Export the bill of materials", format!("{name}.{ext}"), contents);
3685                let pending = PendingSave { request, detail: String::new(), label: None, warnings: vec![], preview: false };
3686                self.deliver(docs, store, pending) != Delivery::Failed
3687            }
3688            Err(e) => {
3689                self.status = format!("BOM export failed: {e}");
3690                state.push_notice(format!("BOM export: {e}"));
3691                false
3692            }
3693        }
3694    }
3695
3696    /// Write one of the PCB's manufacturing outputs through the store under
3697    /// [`Output::file_name`](super::fabrication_export::Output::file_name).
3698    /// The bundle's warnings (design-rule findings, silkscreen characters
3699    /// the font lacks) keep the dialog OPEN with the warnings on its status
3700    /// line, and go to a toast: the files are complete, but the user should
3701    /// read why before ordering boards. Returns `true` to close the dialog.
3702    fn export_fabrication_as(
3703        &mut self,
3704        docs: &mut Documents,
3705        store: &dyn ModelStore,
3706        output: super::fabrication_export::Output,
3707    ) -> bool {
3708        use super::fabrication_export::{self as fab, Output};
3709        let name = self.effective_name(docs);
3710        let file = output.file_name(&name);
3711        let state = docs.engine_mut();
3712        let made = match output {
3713            Output::Bundle => fab::bundle(state, &name).map(|bundle| {
3714                let detail = format!(" ({} files)", bundle.files.len());
3715                (SaveBody::Bytes(bundle.zip()), detail, bundle.warnings)
3716            }),
3717            _ => fab::text(state, output, &name).map(|text| (SaveBody::Text(text), String::new(), vec![])),
3718        };
3719        match made {
3720            Ok((body, detail, warnings)) => {
3721                // The output names itself in its toast (Netlist, Pick & place,
3722                // BOM, Fabrication), and the chooser's status says WHERE the
3723                // files went: on desktop that is the folder the user chose.
3724                let request = SaveRequest { title: format!("Export: {}", output.label()), file_name: file, body };
3725                let pending = PendingSave { request, detail, label: Some(output.label().to_string()), warnings, preview: false };
3726                match self.deliver(docs, store, pending) {
3727                    Delivery::Done => !self.status.contains("Before ordering"),
3728                    Delivery::Chooser => true,
3729                    Delivery::Failed => {
3730                        docs.engine_mut().push_notice(format!("{} export: {}", output.label(), self.status));
3731                        false
3732                    }
3733                }
3734            }
3735            Err(e) => {
3736                self.status = format!("{} export failed: {e}", output.label());
3737                state.push_notice(format!("{} export: {e}", output.label()));
3738                false
3739            }
3740        }
3741    }
3742
3743    /// Route an imported STEP file: **outline first**. The outline reads the
3744    /// product structure without building a body, so a structured file arms
3745    /// the choice modal within the parse time; "Import as assembly" then runs
3746    /// the full read ([`Self::step_assembly_import`]) and "Import as bodies"
3747    /// the flat lane, so the bodies are built once, by the lane chosen.
3748    ///
3749    /// Everything else goes straight to today's flat lane, unchanged:
3750    ///
3751    /// * `Ok(None)` — no product structure. A part file must NEVER see the
3752    ///   dialog, and its behaviour stays byte-for-byte what it was.
3753    /// * `Err` — text the Part 21 parser refuses. Handing it to the flat lane
3754    ///   keeps the failure wording exactly today's (the two share the same
3755    ///   `ISO-10303-21` guard), rather than inventing a second one.
3756    fn import_step(&mut self, state: &mut EngineState, name: &str, contents: &str) {
3757        // A previous file's armed choice cannot survive this one: the probe
3758        // below REPLACES the engine's stash on every outcome (including the
3759        // structureless one), so an app-side pending left standing would offer
3760        // a button whose parse is already gone. A probe still running for an
3761        // earlier upload is superseded the same way (its answer is ignored).
3762        self.pending_step_import = None;
3763        // An assembly import still reading its parts is superseded too: the
3764        // stash it is waiting for is the one this upload replaces. Said out
3765        // loud, since its dialog closed long ago.
3766        if let Some(build) = self.pending_step_build.take_if(|build| build.owner == self.step_view) {
3767            // Its answer must not stash the old file's parse after this one.
3768            state.forget_step_probe(build.id);
3769            state.push_notice(format!(
3770                "import of \"{}\" as an assembly was cancelled by the next import",
3771                build.import.name
3772            ));
3773        }
3774        // The OUTLINE, not the full read: the structure alone is a parse, the
3775        // bodies are seconds more, and the user should be asked before that.
3776        let id = state.submit_step_outline(contents);
3777        self.pending_step_probe = Some(PendingStepProbe {
3778            id,
3779            owner: self.step_view,
3780            name: name.to_string(),
3781            text: contents.to_string(),
3782        });
3783        self.status = format!("reading \"{name}\"\u{2026}");
3784        // The synchronous Inline runner (tests, headless) has answered inside
3785        // the submit; a background runner answers on a later frame's poll.
3786        self.poll_step_probe(state);
3787    }
3788
3789    /// Resolve an answered STEP probe: structure arms the §3.9 choice, no
3790    /// structure (or a parse the flat lane will refuse with its own wording)
3791    /// takes the flat lane. A probe the engine no longer holds — a document
3792    /// switch or a cancelled run dropped it — is reported and forgotten.
3793    fn poll_step_probe(&mut self, state: &mut EngineState) {
3794        let view = self.step_view;
3795        let scan_here = self.pending_step_probe.as_ref().is_some_and(|scan| scan.owner == view);
3796        let build_here = self.pending_step_build.as_ref().is_some_and(|build| build.owner == view);
3797        if !scan_here && !build_here {
3798            return; // nothing of ours runs on this engine
3799        }
3800        while let Some((id, outcome)) = state.take_step_probe() {
3801            if let Some(build) = self.pending_step_build.as_mut().filter(|build| build_here && build.id == id) {
3802                build.answer = Some(outcome);
3803                continue;
3804            }
3805            let Some(pending) = self.pending_step_probe.as_ref().filter(|_| scan_here) else {
3806                continue;
3807            };
3808            if pending.id != id {
3809                continue; // an earlier upload's answer; a newer probe replaced it
3810            }
3811            let PendingStepProbe { name, text, .. } = self.pending_step_probe.take().unwrap();
3812            let built = matches!(outcome, StepProbeOutcome::Structure(_));
3813            match outcome {
3814                StepProbeOutcome::Structure(probe) | StepProbeOutcome::Outline(probe) => {
3815                    self.status = format!(
3816                        "\"{name}\" contains an assembly — {} part{}, {} instance{}",
3817                        probe.parts,
3818                        plural(probe.parts),
3819                        probe.instances,
3820                        plural(probe.instances)
3821                    );
3822                    self.pending_step_import = Some(PendingStepImport {
3823                        name,
3824                        text,
3825                        probe,
3826                        // Default = keep the tree (§3.9). Flattening is the escape
3827                        // hatch for a deep or pathological file, not the norm.
3828                        flatten: false,
3829                        built,
3830                    });
3831                    // The routing site's `close_after_import` ran frames ago,
3832                    // while the probe was still out, and closed the modal: the
3833                    // choice is raised HERE, when the answer lands. (Under the
3834                    // synchronous Inline runner both run in the same call, and
3835                    // the second open is idempotent.)
3836                    self.open_modal(Mode::StepAssembly);
3837                }
3838                StepProbeOutcome::Flat | StepProbeOutcome::Failed(_) => {
3839                    self.import_step_flat(state, &name, &text);
3840                }
3841            }
3842        }
3843        if scan_here && self.pending_step_probe.is_some() && !state.step_probes_pending() {
3844            // Nothing is running and no answer came: the engine dropped the
3845            // probe (document switch / cancel). Say so rather than reading
3846            // "reading…" forever.
3847            let pending = self.pending_step_probe.take().unwrap();
3848            self.status = format!("import of \"{}\" was cancelled", pending.name);
3849        }
3850        if build_here
3851            && self.pending_step_build.as_ref().is_some_and(|build| build.answer.is_none())
3852            && !state.step_probes_pending()
3853        {
3854            let build = self.pending_step_build.take().unwrap();
3855            let message = format!("import of \"{}\" was cancelled", build.import.name);
3856            self.status = message.clone();
3857            state.push_notice(message);
3858        }
3859    }
3860
3861    /// Finish an assembly import chosen on the outline, once its full read has
3862    /// answered: the structure is consumed exactly as a click on a built parse
3863    /// would; a read that found no buildable structure after all comes in as
3864    /// bodies, and says so.
3865    fn poll_step_build(&mut self, state: &mut EngineState, store: &dyn ModelStore) {
3866        if !self
3867            .pending_step_build
3868            .as_ref()
3869            .is_some_and(|build| build.owner == self.step_view && build.answer.is_some())
3870        {
3871            return;
3872        }
3873        let PendingStepBuild { import, answer, .. } = self.pending_step_build.take().unwrap();
3874        match answer {
3875            Some(StepProbeOutcome::Structure(_)) => {
3876                self.consume_step_assembly(state, store, PendingStepImport { built: true, ..import });
3877            }
3878            _ => {
3879                let message = match state.import_model_text_feature(&import.text) {
3880                    Ok(_) => format!(
3881                        "imported {} as bodies \u{2014} the assembly structure could not be built",
3882                        import.name
3883                    ),
3884                    Err(error) => format!("import failed: {error}"),
3885                };
3886                self.status = message.clone();
3887                state.push_notice(message);
3888            }
3889        }
3890    }
3891
3892    /// Append an imported STEP file to the model (an IMPORT3D feature), then treat
3893    /// the enlarged model as dirty (an import is an edit, not an Open — the model
3894    /// keeps its current name / save baseline). THE flat lane, reached from a
3895    /// structureless file, an unparseable one, and the dialog's "Import as
3896    /// bodies".
3897    fn import_step_flat(&mut self, state: &mut EngineState, name: &str, contents: &str) {
3898        // A STEP or an IGES text alike: the probe routes both.
3899        match state.import_model_text_feature(contents) {
3900            // Framing is deferred to the engine (`pending_fit`): under the native
3901            // thread / wasm worker runner the body is not resident yet, so framing
3902            // here would frame the empty scene. See [`EngineState::pending_fit`].
3903            Ok(_) => self.status = format!("imported {name}"),
3904            Err(e) => self.status = format!("import failed: {e}"),
3905        }
3906    }
3907
3908    /// **Import as assembly** — consume the probe's stash into parts-library
3909    /// entries + one component per occurrence, in the engine's single batch.
3910    ///
3911    /// An `Err` here means the structured lane produced nothing, and the engine
3912    /// returns BEFORE it touches history when that happens — so the honest
3913    /// answer is the one A6's contract prescribes: re-run the flat import with
3914    /// the text this dialog is still holding, and say plainly that the assembly
3915    /// the user asked for came in as bodies. Silence there would leave them
3916    /// believing they have a structure tree that does not exist.
3917    fn step_assembly_import(&mut self, state: &mut EngineState, store: &dyn ModelStore) {
3918        let Some(pending) = self.pending_step_import.take() else {
3919            return;
3920        };
3921        if pending.built {
3922            self.consume_step_assembly(state, store, pending);
3923            return;
3924        }
3925        // Chosen on the outline: start the full read now and import when it
3926        // lands. The dialog closes on this click, so the user is told what is
3927        // running (the busy line shows it too).
3928        let id = state.submit_step_probe(&pending.text);
3929        let message = format!(
3930            "importing {} as an assembly \u{2014} reading its {} part{}\u{2026}",
3931            pending.name,
3932            pending.probe.parts,
3933            plural(pending.probe.parts)
3934        );
3935        self.status = message.clone();
3936        state.push_notice(message);
3937        self.pending_step_build = Some(PendingStepBuild {
3938            id,
3939            owner: self.step_view,
3940            import: pending,
3941            answer: None,
3942        });
3943        // The synchronous Inline runner has answered inside the submit.
3944        self.poll_step_probe(state);
3945        self.poll_step_build(state, store);
3946    }
3947
3948    /// Consume a full parse the engine holds into the assembly (the click on a
3949    /// built parse, or a deferred import whose read has landed).
3950    fn consume_step_assembly(
3951        &mut self,
3952        state: &mut EngineState,
3953        store: &dyn ModelStore,
3954        pending: PendingStepImport,
3955    ) {
3956        // Read BEFORE the import: afterwards its own ACOMP features make the
3957        // answer unconditionally "yes" and the workbench switch never fires.
3958        let was_assembly = state.history_has_assembly();
3959        let doc_name = step_document_name(&pending.name);
3960        // The §3.9 checkbox. A depth-1 file imports identically either way, so
3961        // an un-shown box costs nothing.
3962        let opts = StepAssemblyImport {
3963            nested: !pending.flatten,
3964        };
3965        // Every unique part is written to the store as its own document, at the
3966        // browser's current location and under `{assembly}-{part}` — the same
3967        // `browser_write` door + "wherever the explorer is pointing" convention
3968        // the STEP parts-library import uses (`panels::step_parts`). So an
3969        // imported part is a part like any other: Open Part opens it, Update
3970        // Components tracks it, a part edit writes through to it.
3971        let mut sink = StorePartSink::new(store, &doc_name);
3972        let message = match state.import_probed_step_assembly(&doc_name, opts, &mut sink) {
3973            Ok(report) => {
3974                if !was_assembly {
3975                    self.enter_assembly_workbench(state);
3976                }
3977                // The store side effect is REPORTED, never silent: a 50-part
3978                // import writes 50 files the user did not individually ask for.
3979                for failure in &sink.failures {
3980                    state.push_notice(format!("part not saved — {failure}"));
3981                }
3982                let saved = sink.written;
3983                let base = assembly_import_message(&pending.name, &report);
3984                match (saved, sink.failures.len()) {
3985                    (0, _) if sink.deferred > 0 => format!(
3986                        "{base}; its {} part documents become PLM items when you save the assembly",
3987                        sink.deferred
3988                    ),
3989                    (0, _) => base,
3990                    (saved, 0) => format!("{base}; saved {saved} part file(s)"),
3991                    (saved, failed) => {
3992                        format!("{base}; saved {saved} part file(s), {failed} could not be saved")
3993                    }
3994                }
3995            }
3996            Err(error) => match state.import_step_feature(&pending.text) {
3997                Ok(_) => format!(
3998                    "imported {} as bodies — the assembly structure could not be built ({error})",
3999                    pending.name
4000                ),
4001                Err(flat) => format!("import failed: {flat}"),
4002            },
4003        };
4004        // The status line only renders inside an OPEN modal and this one closes
4005        // on the click, so the toast is the half the user actually sees.
4006        self.status = message.clone();
4007        state.push_notice(message);
4008    }
4009
4010    /// **Import as bodies** — today's flat lane, unchanged. Drops the probe's
4011    /// stash first: the user chose the text, so the parsed assembly (and every
4012    /// product's solids it is holding resident) has no consumer left.
4013    fn step_assembly_bodies(&mut self, state: &mut EngineState) {
4014        let Some(pending) = self.pending_step_import.take() else {
4015            return;
4016        };
4017        state.discard_probed_step_assembly();
4018        self.import_step_flat(state, &pending.name, &pending.text);
4019    }
4020
4021    /// **Cancel** — import nothing and drop the parse (§3.9).
4022    fn step_assembly_cancel(&mut self, state: &mut EngineState) {
4023        let Some(pending) = self.pending_step_import.take() else {
4024            return;
4025        };
4026        state.discard_probed_step_assembly();
4027        self.status = format!("import cancelled: {}", pending.name);
4028    }
4029
4030    /// Switch to the **Assembly** workbench so a freshly imported structure is
4031    /// actually reachable: the Assembly Structure tree and the Constraints panel
4032    /// are CLAIMED by that workbench, so an assembly imported under Modeling
4033    /// would land with its structure invisible.
4034    ///
4035    /// No-op when the active workbench already shows those panels: the
4036    /// predicate asks whether the BOM panel is visible, which is true for
4037    /// Assembly itself, for Wire harness (it lists the assembly panels too),
4038    /// and for "All", whose users must not be yanked out of it. Applied
4039    /// through the same settings seam the toolbar dropdown and the saved-
4040    /// workbench restore use, and like the restore NOT persisted to the settings
4041    /// blob: that blob stays the user's boot preference, and a document's
4042    /// workbench is session-scoped.
4043    fn enter_assembly_workbench(&mut self, state: &mut EngineState) {
4044        if crate::workbench::panel_visible(
4045            &state.settings.workbench,
4046            crate::workbench::assembly::BOM_PANEL_ID,
4047            &crate::workbench::ButtonState::of(state),
4048        ) {
4049            return;
4050        }
4051        let _ = state.apply_settings_json(
4052            &serde_json::json!({ "workbench": crate::workbench::assembly::ASSEMBLY.id })
4053                .to_string(),
4054        );
4055    }
4056
4057    /// Append an imported IGES file to the model (an IMPORT3D feature) — the
4058    /// IGES sibling of [`Self::import_step`].
4059    fn stage_mesh_preview(
4060        &mut self,
4061        format: MeshImportFormat,
4062        name: String,
4063        contents: Vec<u8>,
4064    ) {
4065        self.pending_stl_import = Some((format, name, contents));
4066        self.status.clear();
4067    }
4068
4069    /// Selecting an STL or a 3MF starts a preview session; only its Accept
4070    /// action edits the destination document.
4071    pub fn take_stl_import(&mut self) -> Option<(MeshImportFormat, String, Vec<u8>)> {
4072        self.pending_stl_import.take()
4073    }
4074
4075    /// A binary Parasolid file has no assembly probe: its bodies go straight
4076    /// into one Import 3D Model feature.
4077    fn import_parasolid_bytes(&mut self, state: &mut EngineState, name: &str, contents: &[u8]) {
4078        match state.import_xt_bytes_feature(contents) {
4079            Ok(_) => self.status = format!("imported {name}"),
4080            Err(e) => self.status = format!("import failed: {e}"),
4081        }
4082    }
4083
4084    fn import_obj(&mut self, state: &mut EngineState, name: &str, contents: &[u8]) {
4085        match state.import_obj_bytes_feature(contents) {
4086            Ok(_) => self.status = format!("reconstructing {name} in background…"),
4087            Err(e) => self.status = format!("import failed: {e}"),
4088        }
4089    }
4090
4091    /// Hand a file to the importer File > Import uses for its kind. `false`
4092    /// when the file is not imported yet but has moved to a dialog of its own
4093    /// (KiCad): the caller then leaves the dialog state alone.
4094    fn import_file(
4095        &mut self,
4096        kind: ImportKind,
4097        state: &mut EngineState,
4098        store: &dyn ModelStore,
4099        name: String,
4100        bytes: Vec<u8>,
4101    ) -> bool {
4102        match kind {
4103            ImportKind::Kicad => {
4104                self.take_kicad_file(&name, &bytes, store);
4105                return false;
4106            }
4107            ImportKind::Step | ImportKind::Iges | ImportKind::Parasolid => {
4108                self.import_text(state, &name, &bytes, Self::import_step)
4109            }
4110            ImportKind::ParasolidBinary => self.import_parasolid_bytes(state, &name, &bytes),
4111            ImportKind::SolidWorksPart | ImportKind::SolidWorksAssembly => {
4112                match state.import_solidworks_feature(&bytes, &name, kind == ImportKind::SolidWorksAssembly) {
4113                    Ok(_) => self.status = format!("imported {name}"),
4114                    Err(e) => self.status = format!("import failed: {e}"),
4115                }
4116            }
4117            ImportKind::Stl => self.stage_mesh_preview(MeshImportFormat::Stl, name, bytes),
4118            ImportKind::ThreeMf => self.stage_mesh_preview(MeshImportFormat::ThreeMf, name, bytes),
4119            ImportKind::Obj => self.import_obj(state, &name, &bytes),
4120        }
4121        true
4122    }
4123
4124    /// A file the OS handed the app that is not a model document — `brep-app
4125    /// part.step`, or a double click on a file the app is an opener for —
4126    /// imported exactly as File > Import would, into a NEW untitled tab shown
4127    /// under the file's stem. The tab has no store identity, so a plain Save
4128    /// asks for a name and never writes over the imported file. The tab is
4129    /// opened BEFORE the import starts: the STEP probe and the mesh preview
4130    /// bind to the active document. `file_name` is the path or the bare name;
4131    /// the status line and the importer's notices name it.
4132    ///
4133    /// A name the table does not know is refused without a new tab.
4134    pub fn import_into_new_tab(
4135        &mut self,
4136        docs: &mut Documents,
4137        store: &dyn ModelStore,
4138        file_name: &str,
4139        bytes: Vec<u8>,
4140    ) -> Result<(), String> {
4141        let Some(kind) = import_kind(file_name) else {
4142            return Err(format!("{file_name} is not a BREP document or a file BREP imports"));
4143        };
4144        self.cancel_pending_step_import(docs.engine_mut());
4145        self.new_document(docs, DocumentClass::Normal);
4146        let title = import_document_name(file_name);
4147        docs.active_mut().set_label(Some(title.clone()));
4148        let base = file_name.rsplit(['/', '\\']).next().unwrap_or(file_name).to_string();
4149        self.status.clear();
4150        // A SolidWorks assembly reads its parts from beside it: it keeps its path.
4151        let given = if kind == ImportKind::SolidWorksAssembly { file_name.to_string() } else { base };
4152        // The new tab is the view this import's STEP read belongs to.
4153        self.step_view = docs.view_id();
4154        if self.import_file(kind, docs.engine_mut(), store, given, bytes) {
4155            self.close_after_import();
4156        }
4157        if self.status.starts_with("import failed") {
4158            docs.engine_mut().push_notice(self.status.clone());
4159            return Err(self.status.clone());
4160        }
4161        Ok(())
4162    }
4163
4164    fn import_text(
4165        &mut self,
4166        state: &mut EngineState,
4167        name: &str,
4168        bytes: &[u8],
4169        importer: fn(&mut Self, &mut EngineState, &str, &str),
4170    ) {
4171        match std::str::from_utf8(bytes) {
4172            Ok(contents) => importer(self, state, name, contents),
4173            Err(_) => self.status = format!("import failed: {name} is not UTF-8 text"),
4174        }
4175    }
4176
4177    /// Load a model document's contents into a NEW TAB (roll to the last
4178    /// feature + zoom-to-fit), clean from the start. A document that fails to
4179    /// load leaves no tab behind — the engine it was loading into is dropped
4180    /// with its runner.
4181    fn load_document(&mut self, docs: &mut Documents, name: &str, contents: &str, store: &dyn ModelStore) {
4182        let plm = store.plm_client().is_some();
4183        let mut engine = docs.spawn_engine();
4184        match engine.load_model_and_fit(contents) {
4185            Ok(_) => {
4186                // The extension names the class on the file system; the
4187                // document field follows it, before `Document::new` takes the
4188                // clean baseline so a hand-renamed file does not open dirty.
4189                // On a PLM store the name is a revision key the explorer spells
4190                // with `.nbrep` whatever the part is, so the document's own
4191                // field is the class (the part's fixed `document_class`).
4192                if let Some(class) = DocumentClass::of_name(name).filter(|_| !plm) {
4193                    document_class::set_document_class(&mut engine, class);
4194                }
4195                // The document keeps the raw identity — the full path when a
4196                // native dialog picked the file, so plain Save writes back to
4197                // it; the name field shows only the bare display name.
4198                let mut doc = Document::new(engine);
4199                doc.set_name(Some(name.to_string()));
4200                doc.note_opened_from(contents);
4201                docs.open_document(doc);
4202                self.name_buf = model_display_name(name);
4203                self.status = format!("opened {name}");
4204                remember_document(store, name);
4205            }
4206            Err(e) => self.status = format!("open failed: {e}"),
4207        }
4208    }
4209
4210    // --- document classes: families, templates, members ------------------------
4211
4212    /// The session's PLM client and the revision key `identity` names, when
4213    /// the store IS the PLM and `identity` is one of its revisions.
4214    fn plm_revision(&self, store: &dyn ModelStore, identity: &str) -> Option<(std::rc::Rc<crate::plm::client::PlmClient>, String)> {
4215        let client = store.plm_client()?;
4216        let key = crate::plm::family::revision_key(identity)?;
4217        Some((client, key))
4218    }
4219
4220    /// Poll the PLM work in flight (S9) and act on what finished.
4221    fn poll_plm_work(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
4222        let Some(work) = self.plm_work.as_mut() else { return };
4223        ctx.request_repaint_after(std::time::Duration::from_millis(30));
4224        match work {
4225            PlmWork::Members(pending) => {
4226                let Some(result) = pending.poll() else { return };
4227                self.plm_work = None;
4228                let Some(pick) = self.pick_member.as_mut() else { return };
4229                pick.loading = false;
4230                match result {
4231                    Ok(members) => {
4232                        pick.rows = members
4233                            .into_iter()
4234                            .map(|member| MemberChoice {
4235                                why_not: member.not_placeable(),
4236                                exists: member.not_placeable().is_none(),
4237                                identity: member.key(),
4238                                description: member.name.clone(),
4239                                part_number: member.number,
4240                            })
4241                            .collect();
4242                    }
4243                    Err(error) => self.status = format!("the members could not be read: {error}"),
4244                }
4245            }
4246            PlmWork::Place(pending) => {
4247                let Some(result) = pending.poll() else { return };
4248                self.plm_work = None;
4249                match result {
4250                    Ok((key, text, number)) => {
4251                        self.insert_component_named(docs.engine_mut(), &key, &number, &text);
4252                        self.pick_member = None;
4253                        self.spin_out = None;
4254                        self.open = false;
4255                    }
4256                    Err(error) => self.status = error,
4257                }
4258            }
4259            PlmWork::OpenFamily(pending) => {
4260                let Some(result) = pending.poll() else { return };
4261                self.plm_work = None;
4262                match result {
4263                    Ok(key) => self.open_document(docs, store, &key),
4264                    Err(error) => self.status = format!("the family could not be opened: {error}"),
4265                }
4266            }
4267        }
4268    }
4269
4270    /// Route an Insert-component choice by its class. A FAMILY arms the member
4271    /// picker and a TEMPLATE the spin-out prompt; both return `true` (handled,
4272    /// the modal switches). A normal part returns `false` and is inserted as
4273    /// it always was. The class is the file's extension, or the document's own
4274    /// field when the name carries none (a browser upload's bare name).
4275    fn begin_class_insert(
4276        &mut self,
4277        store: &dyn ModelStore,
4278        identity: &str,
4279        contents: &str,
4280        assembly: Option<String>,
4281    ) -> bool {
4282        let document: serde_json::Value = serde_json::from_str(contents).unwrap_or_default();
4283        let class = DocumentClass::of_name(identity)
4284            .filter(|class| *class != DocumentClass::Normal)
4285            .unwrap_or_else(|| DocumentClass::of_document(&document));
4286        let file = crate::store::file_name_of(identity);
4287        match class {
4288            DocumentClass::Normal | DocumentClass::Instructions => false,
4289            DocumentClass::Family if self.plm_revision(store, identity).is_some() => {
4290                let (client, key) = self.plm_revision(store, identity).unwrap_or_else(|| unreachable!());
4291                let Some((part, _)) = crate::plm::family::key_ids(&key).map(|(p, r)| (p.to_string(), r.to_string())) else {
4292                    return false;
4293                };
4294                self.plm_work = Some(PlmWork::Members(crate::panels::plm_family::Pending::new(Box::pin(async move {
4295                    crate::plm::family::family_view(&client, &part).await.map(|view| view.members()).map_err(|e| e.to_string())
4296                }))));
4297                self.pick_member = Some(PickMember { family_file: file, rows: Vec::new(), plm: true, loading: true });
4298                self.status.clear();
4299                self.open_modal(Mode::PickMember);
4300                true
4301            }
4302            DocumentClass::Family => {
4303                let table = family_table::read_table(contents);
4304                let rows = table
4305                    .rows
4306                    .iter()
4307                    .map(|row| {
4308                        let identity = family_table::member_identity(Some(identity), &row.part_number);
4309                        let exists = identity.as_deref().is_some_and(|id| store.read(id).is_some());
4310                        MemberChoice {
4311                            part_number: row.part_number.clone(),
4312                            description: row.description.clone(),
4313                            identity,
4314                            exists,
4315                            why_not: None,
4316                        }
4317                    })
4318                    .collect();
4319                self.pick_member = Some(PickMember { family_file: file, rows, plm: false, loading: false });
4320                self.status.clear();
4321                self.open_modal(Mode::PickMember);
4322                true
4323            }
4324            DocumentClass::Template => {
4325                let inputs = template::inputs_of(&document);
4326                let values = inputs
4327                    .iter()
4328                    .map(|input| (input.name.clone(), template::default_value(&document, input)))
4329                    .collect();
4330                let stem = document_class::strip_class_extension(&file).to_string();
4331                let plm_template = self
4332                    .plm_revision(store, identity)
4333                    .and_then(|(_, key)| crate::plm::family::key_ids(&key).map(|(part, _)| part.to_string()));
4334                self.spin_out = Some(SpinOut {
4335                    template_file: file,
4336                    template: document,
4337                    inputs,
4338                    name: format!("{stem}-1"),
4339                    values,
4340                    assembly,
4341                    plm_template,
4342                    number: String::new(),
4343                });
4344                self.status.clear();
4345                self.open_modal(Mode::SpinOut);
4346                true
4347            }
4348        }
4349    }
4350
4351    /// The **member picker**: a family is never placed itself. Each table row
4352    /// is a button; one whose member file exists inserts that `.nbrep` as a
4353    /// normal component, one that was never generated says so.
4354    fn show_pick_member(&mut self, ctx: &egui::Context, state: &mut EngineState, store: &dyn ModelStore) {
4355        let Some(pick) = self.pick_member.take() else {
4356            self.open = false;
4357            return;
4358        };
4359        let mut chosen = None;
4360        let mut cancel = false;
4361        let modal = egui::Modal::new(egui::Id::new("brep-file-pick-member")).show(ctx, |ui| {
4362            ui.set_width(420.0);
4363            ui.heading(format!("Insert a member of {}", pick.family_file));
4364            ui.add_space(2.0);
4365            ui.weak("A family is never placed itself: choose the member to place.");
4366            ui.add_space(6.0);
4367            if pick.loading {
4368                ui.label("Reading the family's members from the PLM\u{2026}");
4369            } else if pick.rows.is_empty() {
4370                ui.label("This family's table has no rows yet.");
4371            }
4372            egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
4373                for (index, row) in pick.rows.iter().enumerate() {
4374                    ui.horizontal(|ui| {
4375                        let text = if row.description.trim().is_empty() {
4376                            row.part_number.clone()
4377                        } else {
4378                            format!("{} \u{2014} {}", row.part_number, row.description)
4379                        };
4380                        let button = ui.add(crate::ui_kit::Button::new(&text).min_width(220.0).enabled(row.exists));
4381                        self.hit(&format!("member:{}", row.part_number), &button);
4382                        if button.clicked() {
4383                            chosen = Some(index);
4384                        }
4385                        if let Some(why) = &row.why_not {
4386                            ui.weak(format!("({why})"));
4387                        } else if row.identity.is_none() {
4388                            ui.weak("(the part number is not a file name)");
4389                        } else if !row.exists {
4390                            ui.weak("(not generated yet: open the family and Generate)");
4391                        }
4392                    });
4393                }
4394            });
4395            ui.add_space(6.0);
4396            if !self.status.is_empty() {
4397                ui.weak(&self.status);
4398                ui.add_space(4.0);
4399            }
4400            let c = ui.add(crate::ui_kit::Button::new("Cancel"));
4401            self.hit("member:cancel", &c);
4402            cancel = c.clicked();
4403        });
4404        let should_close = modal.should_close();
4405        if let (Some(index), true) = (chosen, pick.plm) {
4406            let row = &pick.rows[index];
4407            if let (Some(client), Some(key)) = (store.plm_client(), row.identity.clone()) {
4408                self.status = format!("reading {} from the PLM\u{2026}", row.part_number);
4409                self.plm_work = Some(PlmWork::Place(fetch_document(client, key, row.part_number.clone())));
4410            }
4411        } else if let Some(index) = chosen {
4412            let row = &pick.rows[index];
4413            let identity = row.identity.clone().unwrap_or_default();
4414            match store.read(&identity) {
4415                Some(contents) => {
4416                    self.insert_component_document(state, &identity, &contents);
4417                    self.open = false;
4418                    return;
4419                }
4420                None => self.status = format!("'{}' has not been generated yet ({identity})", row.part_number),
4421            }
4422        } else if cancel || should_close {
4423            self.status.clear();
4424            self.open = false;
4425            return;
4426        }
4427        self.pick_member = Some(pick);
4428    }
4429
4430    /// The **template spin-out** prompt: a template is never placed itself.
4431    /// The user names the new part and sets each marked input (a fixed list
4432    /// is offered as buttons; limits are checked as they type), then Create
4433    /// writes the specialised copy as `<name>.nbrep` beside the assembly and
4434    /// places it. A name that already exists is refused, never overwritten.
4435    fn show_spin_out(&mut self, ctx: &egui::Context, state: &mut EngineState, store: &dyn ModelStore) {
4436        let Some(mut spin) = self.spin_out.take() else {
4437            self.open = false;
4438            return;
4439        };
4440        let mut create = false;
4441        let mut cancel = false;
4442        let problems: Vec<Option<String>> = spin
4443            .inputs
4444            .iter()
4445            .map(|input| {
4446                let text = spin.values.get(&input.name).map(String::as_str).unwrap_or("");
4447                template::value_problem(&spin.template, input, text)
4448            })
4449            .collect();
4450        let name_problem = template::name_problem(&spin.name);
4451        let modal = egui::Modal::new(egui::Id::new("brep-file-spin-out")).show(ctx, |ui| {
4452            ui.set_width(440.0);
4453            ui.heading(format!("New part from {}", spin.template_file));
4454            ui.add_space(2.0);
4455            ui.weak("A template is never placed itself: this makes a new part from it and places that.");
4456            ui.add_space(6.0);
4457            egui::Grid::new("brep-spin-out-grid").num_columns(2).spacing([10.0, 6.0]).show(ui, |ui| {
4458                ui.label("New part name");
4459                let field = crate::ui_kit::text_input(&mut spin.name).width(240.0).show(ui).framed();
4460                self.hit("spinout:name", &field);
4461                ui.end_row();
4462                if spin.plm_template.is_some() {
4463                    ui.label("Part number");
4464                    let field = crate::ui_kit::text_input(&mut spin.number).placeholder("empty: the part type numbers it").width(240.0).show(ui).framed();
4465                    self.hit("spinout:number", &field);
4466                    ui.end_row();
4467                }
4468                for (input, problem) in spin.inputs.iter().zip(&problems) {
4469                    ui.label(input.shown());
4470                    ui.vertical(|ui| {
4471                        let value = spin.values.entry(input.name.clone()).or_default();
4472                        if input.choices.is_empty() {
4473                            let field = crate::ui_kit::text_input(value).width(240.0).show(ui).framed();
4474                            self.hit(&format!("spinout:input:{}", input.name), &field);
4475                        } else {
4476                            // The input's choices as one dropdown: spinout:choice:<name>,
4477                            // its open entries spinout:choice:<name>#<choice>.
4478                            let trimmed: Vec<String> = input.choices.iter().map(|choice| choice.trim().to_string()).collect();
4479                            let choices: Vec<(String, &str, &str)> = trimmed.iter().map(|choice| (choice.clone(), choice.as_str(), choice.as_str())).collect();
4480                            let mut chosen = value.trim().to_string();
4481                            let (changed, _) = crate::form::enum_dropdown(ui, &format!("spinout:choice:{}", input.name), &choices, &mut chosen, None, Some(&mut self.hits));
4482                            if changed {
4483                                *value = chosen;
4484                            }
4485                        }
4486                        let limits = match (input.min, input.max) {
4487                            (Some(min), Some(max)) => format!("{min} to {max}"),
4488                            (Some(min), None) => format!("at least {min}"),
4489                            (None, Some(max)) => format!("at most {max}"),
4490                            (None, None) => String::new(),
4491                        };
4492                        if !limits.is_empty() {
4493                            ui.weak(limits);
4494                        }
4495                        if let Some(problem) = problem {
4496                            ui.colored_label(ui.visuals().warn_fg_color, problem);
4497                        }
4498                    });
4499                    ui.end_row();
4500                }
4501            });
4502            if spin.inputs.is_empty() {
4503                ui.weak("This template marks no inputs; the copy is the template as it is.");
4504            }
4505            ui.add_space(4.0);
4506            let file = crate::store::file_name_of(&spin_out_target(&spin));
4507            ui.weak(match &spin.assembly {
4508                _ if spin.plm_template.is_some() => {
4509                    "The PLM makes the new part from the template and bakes it; it is placed as its first revision.".to_string()
4510                }
4511                Some(assembly) => format!(
4512                    "Saved as {file}, in the folder of {}",
4513                    crate::store::file_name_of(assembly)
4514                ),
4515                None => format!("The assembly is not saved yet: the part goes to the models folder as {file}"),
4516            });
4517            if let Some(problem) = &name_problem {
4518                ui.colored_label(ui.visuals().warn_fg_color, problem);
4519            }
4520            if !self.status.is_empty() {
4521                ui.weak(&self.status);
4522            }
4523            ui.add_space(6.0);
4524            ui.horizontal(|ui| {
4525                let ok = name_problem.is_none() && problems.iter().all(Option::is_none) && self.plm_work.is_none();
4526                let c = ui.add(crate::ui_kit::Button::new("Create and insert").enabled(ok));
4527                self.hit("spinout:create", &c);
4528                create = c.clicked();
4529                let x = ui.add(crate::ui_kit::Button::new("Cancel"));
4530                self.hit("spinout:cancel", &x);
4531                cancel = x.clicked();
4532            });
4533        });
4534        let should_close = modal.should_close();
4535        if create {
4536            match self.create_spin_out(state, store, &spin) {
4537                Ok(()) => {
4538                    self.open = false;
4539                    return;
4540                }
4541                Err(error) => self.status = error,
4542            }
4543        } else if cancel || should_close {
4544            self.status.clear();
4545            self.open = false;
4546            return;
4547        }
4548        self.spin_out = Some(spin);
4549    }
4550
4551    /// Write the spun-out part and place it. `Err` is the status line.
4552    fn create_spin_out(&mut self, state: &mut EngineState, store: &dyn ModelStore, spin: &SpinOut) -> Result<(), String> {
4553        if let (Some(template_part), Some(client)) = (spin.plm_template.clone(), store.plm_client()) {
4554            // The server makes the part; it is placed when it answers. The
4555            // dialog stays open until then, saying so.
4556            let (name, number, values) = (spin.name.trim().to_string(), spin.number.trim().to_string(), spin.values.clone());
4557            self.plm_work = Some(PlmWork::Place(crate::panels::plm_family::Pending::new(Box::pin(async move {
4558                let spun = crate::plm::family::spin_out(&client, &template_part, &name, &number, &values)
4559                    .await
4560                    .map_err(|e| e.to_string())?;
4561                let bytes = client.get_document(&spun.key).await.map_err(|e| e.to_string())?;
4562                let text = bytes.map(|b| String::from_utf8_lossy(&b).into_owned()).ok_or_else(|| {
4563                    format!("{} was made, but has no document yet", spun.number)
4564                })?;
4565                Ok((spun.key, text, spun.number))
4566            }))));
4567            return Err("making the part on the PLM\u{2026}".into());
4568        }
4569        if let Some(problem) = template::name_problem(&spin.name) {
4570            return Err(problem);
4571        }
4572        let target = spin_out_target(spin);
4573        if store.read(&target).is_some() {
4574            return Err(format!("'{target}' already exists: choose another name"));
4575        }
4576        let copy = template::spin_out(&spin.template, &spin.template_file, &spin.values)?;
4577        let text = copy.to_string();
4578        store.write(&target, &text).map_err(|error| format!("could not save {target}: {error}"))?;
4579        self.save_generation += 1;
4580        self.insert_component_document(state, &target, &text);
4581        if spin.assembly.is_none() {
4582            self.status = format!(
4583                "{} — saved to the models folder as {target}, because the assembly is not saved yet",
4584                self.status
4585            );
4586        }
4587        Ok(())
4588    }
4589
4590    /// Arm the hand-edit prompt when the active tab is a family member. `true`
4591    /// when it was armed (the caller does not go on to write). Raise the
4592    /// hand-edit prompt the frame a family member first shows an unsaved
4593    /// change — the moment the user "starts to change it".
4594    fn watch_member_edit(&mut self, docs: &Documents) {
4595        let doc = docs.active();
4596        if !doc.dirty_marker() || self.member_ack.contains(&doc.id()) {
4597            return;
4598        }
4599        if let Some(name) = doc.name().map(str::to_string) {
4600            self.arm_member_prompt(docs, &name, false);
4601        }
4602    }
4603
4604    fn arm_member_prompt(&mut self, docs: &Documents, name: &str, from_save: bool) -> bool {
4605        let Some(source) = family_table::engine_family_source(docs.engine()) else {
4606            return false;
4607        };
4608        self.member_prompt = Some(MemberPrompt {
4609            doc_id: docs.active().id(),
4610            family_identity: sibling_identity(name, &source.family),
4611            source,
4612            from_save,
4613        });
4614        self.status.clear();
4615        self.open_modal(Mode::MemberEdit);
4616        true
4617    }
4618
4619    /// Undo the active tab back to its saved state (bounded), so a member the
4620    /// user declined to change is left exactly as generated.
4621    fn revert_member_edit(docs: &mut Documents) {
4622        for _ in 0..64 {
4623            if !docs.active().is_dirty() || !docs.engine().history.can_undo() {
4624                break;
4625            }
4626            docs.engine_mut().undo();
4627        }
4628    }
4629
4630    /// The assembly Save's ONE dialog about the documents it owns: a row per
4631    /// document that needs a decision, each ticked (yes) by default, so Enter
4632    /// saves everything. An unticked row is not written and its change stays
4633    /// in the assembly. Cancel saves nothing.
4634    fn show_owned_save(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
4635        let Some(mut prompt) = self.owned_prompt.take() else {
4636            self.open = false;
4637            return;
4638        };
4639        if docs.active_id() != prompt.plan.doc_id {
4640            self.status = "Save cancelled because the active document changed".into();
4641            self.open = false;
4642            return;
4643        }
4644        let mut choice = None;
4645        let modal = egui::Modal::new(egui::Id::new("brep-file-owned-save")).show(ctx, |ui| {
4646            ui.set_width(520.0);
4647            ui.heading("Save the parts this assembly changed");
4648            ui.add_space(4.0);
4649            ui.label("Saving writes these documents too. Untick any you do not want written; its change stays in the assembly.");
4650            ui.add_space(6.0);
4651            for (i, row) in prompt.plan.rows.iter_mut().enumerate() {
4652                if !row.asks() {
4653                    if let Some(crate::document::owned_save::Issue::Blocked(_)) = row.issue {
4654                        ui.weak(row.question());
4655                    }
4656                    continue;
4657                }
4658                let question = row.question();
4659                let tick = crate::ui_kit::toggle::checkbox_wrapped(ui, &mut row.proceed, &question);
4660                self.hit(&format!("owned:row:{i}"), &tick);
4661                if row.issue == Some(crate::document::owned_save::Issue::Conflict) && row.proceed {
4662                    ui.indent(("owned-conflict", i), |ui| {
4663                        // Which copy to keep, as one dropdown: owned:choice:<row>, its
4664                        // open entries owned:choice:<row>#<variant>.
4665                        let labels: Vec<(String, String)> = row
4666                            .write
4667                            .variants
4668                            .iter()
4669                            .enumerate()
4670                            .map(|(j, (names, _))| {
4671                                let last = if row.edited_last == Some(j) { " (edited last)" } else { "" };
4672                                (j.to_string(), format!("keep the copy in {}{last}", names.join(" > ")))
4673                            })
4674                            .collect();
4675                        let choices: Vec<(usize, &str, &str)> = labels.iter().enumerate().map(|(j, (id, label))| (j, id.as_str(), label.as_str())).collect();
4676                        crate::form::enum_dropdown(ui, &format!("owned:choice:{i}"), &choices, &mut row.choice, None, Some(&mut self.hits));
4677                    });
4678                }
4679            }
4680            if prompt.plan.rows.iter().any(|row| matches!(row.issue, Some(crate::document::owned_save::Issue::CheckOut { .. }))) {
4681                ui.add_space(4.0);
4682                let remember = crate::ui_kit::checkbox(ui, &mut self.checkout_remembered, "Check out without asking again in this session");
4683                self.hit("owned:remember", &remember);
4684            }
4685            for promotion in &prompt.plan.promotions {
4686                let part = promotion.names.last().map_or("", String::as_str);
4687                ui.weak(if promotion.recreates() {
4688                    format!("{part}: its file is missing — re-created as {}", promotion.new_key)
4689                } else {
4690                    format!("{part}: saved to a new part file {}", promotion.new_key)
4691                });
4692            }
4693            ui.add_space(8.0);
4694            ui.horizontal(|ui| {
4695                let save = ui.add(crate::ui_kit::Button::new("Save"));
4696                self.hit("owned:save", &save);
4697                if save.clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) {
4698                    choice = Some(true);
4699                }
4700                let cancel = ui.add(crate::ui_kit::Button::new("Cancel"));
4701                self.hit("owned:cancel", &cancel);
4702                if cancel.clicked() {
4703                    choice = Some(false);
4704                }
4705            });
4706        });
4707        let choice = choice.or_else(|| modal.should_close().then_some(false));
4708        self.owned_state = serde_json::json!({"prompt": prompt.plan.to_json()});
4709        match choice {
4710            Some(true) => {
4711                self.open = false;
4712                let OwnedPrompt { plan, name, browser } = prompt;
4713                if browser {
4714                    self.commit_save_browser(docs, store, name, plan);
4715                } else {
4716                    self.commit_save(docs, store, name, plan);
4717                }
4718            }
4719            Some(false) => {
4720                self.status = "Save cancelled".into();
4721                self.owned_state = serde_json::Value::Null;
4722                self.open = false;
4723            }
4724            None => self.owned_prompt = Some(prompt),
4725        }
4726    }
4727
4728    /// "Also point these assemblies at the new file?" — one question for every
4729    /// open assembly that places the part just saved under a new name. Yes
4730    /// (the default, Enter) moves each of their copies to the new file as one
4731    /// undoable edit per assembly; No leaves them on the old file.
4732    fn show_retarget(&mut self, ctx: &egui::Context, docs: &mut Documents) {
4733        let Some(retarget) = self.retarget.as_ref() else {
4734            self.open = false;
4735            return;
4736        };
4737        let mut choice = None;
4738        let new_name = model_display_name(&retarget.new_key);
4739        let old_name = model_display_name(&retarget.old);
4740        let titles: Vec<String> = retarget.tabs.iter().map(|(_, title)| title.clone()).collect();
4741        egui::Modal::new(egui::Id::new("brep-file-retarget")).show(ctx, |ui| {
4742            ui.set_width(480.0);
4743            ui.heading("Point the assemblies at the new file?");
4744            ui.label(format!(
4745                "{} {} '{old_name}'. Point {} at '{new_name}' too?",
4746                titles.join(", "),
4747                if titles.len() == 1 { "places" } else { "place" },
4748                if titles.len() == 1 { "it" } else { "them" },
4749            ));
4750            ui.add_space(8.0);
4751            ui.horizontal(|ui| {
4752                let yes = ui.add(crate::ui_kit::Button::new(&format!("Yes, use '{new_name}'")));
4753                self.hit("retarget:yes", &yes);
4754                if yes.clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) {
4755                    choice = Some(true);
4756                }
4757                let no = ui.add(crate::ui_kit::Button::new(&format!("No, keep '{old_name}'")));
4758                self.hit("retarget:no", &no);
4759                if no.clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
4760                    choice = Some(false);
4761                }
4762            });
4763        });
4764        let Some(yes) = choice else { return };
4765        let Some(retarget) = self.retarget.take() else { return };
4766        self.open = false;
4767        if !yes {
4768            self.status = format!("kept the assemblies on '{old_name}'");
4769            return;
4770        }
4771        let mut moved = Vec::new();
4772        for (id, title) in &retarget.tabs {
4773            match docs.retarget_copies(*id, &retarget.old, &retarget.new_key, &retarget.text) {
4774                Ok(n) if n > 0 => moved.push(title.clone()),
4775                Ok(_) => {}
4776                Err(error) => docs.engine_mut().push_notice(format!("{title}: could not point it at '{new_name}': {error}")),
4777            }
4778        }
4779        self.status = format!("{} now {} '{new_name}' (unsaved)", moved.join(", "), if moved.len() == 1 { "uses" } else { "use" });
4780        docs.engine_mut().push_notice_as(brep_render::engine_state::NoticeSeverity::Info, self.status.clone());
4781    }
4782
4783    /// The **hand-edit prompt** on a family member: a member is the family's
4784    /// output, so a change belongs either in a NEW part or in the family.
4785    fn show_member_edit(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
4786        let Some(prompt) = self.member_prompt.take() else {
4787            self.open = false;
4788            return;
4789        };
4790        if docs.active().id() != prompt.doc_id {
4791            self.open = false;
4792            return;
4793        }
4794        let mut choice = None;
4795        let plm = docs.active().name().and_then(|name| self.plm_revision(store, name));
4796        let modal = egui::Modal::new(egui::Id::new("brep-file-member-edit")).show(ctx, |ui| {
4797            ui.set_width(440.0);
4798            ui.heading("This part is a family member");
4799            ui.add_space(4.0);
4800            ui.label(format!(
4801                "'{}' was generated from the family '{}'. A member is written by its family, not edited by hand.",
4802                prompt.source.part_number, prompt.source.family
4803            ));
4804            ui.add_space(4.0);
4805            ui.weak(if prompt.from_save {
4806                "Save it as a new part, or open the family and make the change there."
4807            } else {
4808                "Keep the change in a new part, or open the family and make it there."
4809            });
4810            if !self.status.is_empty() {
4811                ui.add_space(4.0);
4812                ui.weak(&self.status);
4813            }
4814            ui.add_space(8.0);
4815            ui.horizontal(|ui| {
4816                let a = ui.add(crate::ui_kit::Button::new("Save as a new part\u{2026}"));
4817                self.hit("member-edit:saveas", &a);
4818                if a.clicked() {
4819                    choice = Some("saveas");
4820                }
4821                // On a PLM only someone who may edit the family is offered it.
4822                let offer_family = match &plm {
4823                    Some((client, _)) => client.me().is_some_and(|me| me.groups.iter().any(|g| g == "author" || g == "admin")),
4824                    None => true,
4825                };
4826                if offer_family {
4827                    let b = ui.add(crate::ui_kit::Button::new("Open the family"));
4828                    self.hit("member-edit:family", &b);
4829                    if b.clicked() {
4830                        choice = Some("family");
4831                    }
4832                }
4833                let c = ui.add(crate::ui_kit::Button::new(if prompt.from_save { "Cancel" } else { "Cancel (undo the change)" }));
4834                self.hit("member-edit:cancel", &c);
4835                if c.clicked() {
4836                    choice = Some("cancel");
4837                }
4838            });
4839        });
4840        let choice = choice.or_else(|| modal.should_close().then_some("cancel"));
4841        match choice {
4842            Some("saveas") => {
4843                // The tab may keep changing; Save As strips the stamp from
4844                // the copy it writes. Plain Save still asks. On a PLM the
4845                // Save As opens on "A new part".
4846                self.member_ack.insert(prompt.doc_id);
4847                self.member_new_part = store.plm_client().is_some();
4848                self.status.clear();
4849                self.dispatch(FileAction::SaveAs, docs, store);
4850            }
4851            Some("family") if plm.is_some() => {
4852                let (client, _) = plm.unwrap_or_else(|| unreachable!());
4853                let number = document_class::strip_class_extension(&prompt.source.family).to_string();
4854                Self::revert_member_edit(docs);
4855                self.status = format!("opening the family {number}\u{2026}");
4856                self.plm_work = Some(PlmWork::OpenFamily(crate::panels::plm_family::Pending::new(Box::pin(async move {
4857                    let head = crate::plm::family::part_head(&client, &number).await.map_err(|e| e.to_string())?;
4858                    // The newest revision, drafts included (D13).
4859                    let newest = head.revisions.last().ok_or_else(|| format!("the family {number} has no revision"))?;
4860                    Ok(crate::plm::identity::document_key(&head.id, &newest.id))
4861                }))));
4862                self.open = false;
4863            }
4864            Some("family") => {
4865                if store.read(&prompt.family_identity).is_none() {
4866                    self.status = format!("the family file is not there: {}", prompt.family_identity);
4867                    self.member_prompt = Some(prompt);
4868                    return;
4869                }
4870                Self::revert_member_edit(docs);
4871                self.open = false;
4872                self.open_document(docs, store, &prompt.family_identity);
4873            }
4874            Some(_) => {
4875                if !prompt.from_save {
4876                    Self::revert_member_edit(docs);
4877                }
4878                self.status.clear();
4879                self.open = false;
4880            }
4881            None => self.member_prompt = Some(prompt),
4882        }
4883    }
4884
4885    /// Run the family's Generate on the ACTIVE document (a family seed) and
4886    /// keep the report for the automation blob. The one door the automation
4887    /// command and the table editor's button share.
4888    /// Generate the active family. On a PLM store (the document is a
4889    /// `part/…/rev/…` revision and the session has a client) the server
4890    /// writes the members from the family's SAVED revision: a family with
4891    /// unsaved edits is refused unless `save` is set, which saves it first
4892    /// (plm-cad-integration-todo S9). Everywhere else this is the file-system
4893    /// Generate, and `save` is ignored.
4894    pub fn generate_active_family(
4895        &mut self,
4896        docs: &mut Documents,
4897        store: &dyn ModelStore,
4898        save: bool,
4899    ) -> Result<family_table::GenerateReport, String> {
4900        let plm_key = docs.active().name().and_then(crate::plm::family::revision_key);
4901        let report = match (store.plm_client(), plm_key) {
4902            (Some(client), Some(key)) => self.generate_on_plm(docs, store, &client, &key, save)?,
4903            _ => family_table::generate_family(store, docs.active().name(), &docs.engine().history_request_json()),
4904        };
4905        Ok(self.record_generate(report))
4906    }
4907
4908    /// The PLM half of [`Self::generate_active_family`]: blocks this thread
4909    /// while the members are built and the server answers (native; the web
4910    /// build's editor polls instead).
4911    #[cfg(not(target_arch = "wasm32"))]
4912    fn generate_on_plm(
4913        &mut self,
4914        docs: &mut Documents,
4915        store: &dyn ModelStore,
4916        client: &std::rc::Rc<crate::plm::client::PlmClient>,
4917        key: &str,
4918        save: bool,
4919    ) -> Result<family_table::GenerateReport, String> {
4920        let json = docs.tab_engine().history_request_json();
4921        if docs.active().is_dirty() {
4922            if !save {
4923                return Err(crate::plm::family::UNSAVED_FAMILY.into());
4924            }
4925            store.write(key, &json)?;
4926            docs.active_mut().mark_clean();
4927            self.save_generation += 1;
4928            // The write is behind: wait for it to land before the server reads it.
4929            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
4930            while store.pending_writes() > 0 {
4931                if std::time::Instant::now() > deadline {
4932                    return Err("the family's save did not reach the server within 60 s".into());
4933                }
4934                crate::plm::native::run_pending();
4935                std::thread::sleep(std::time::Duration::from_millis(5));
4936            }
4937            if let Some(error) = store.take_persistence_errors().into_iter().next() {
4938                return Err(format!("the family was not saved, so nothing was generated: {error}"));
4939            }
4940        }
4941        crate::plm::native::block_on_for(crate::plm::family::generate(client, key, &json), std::time::Duration::from_secs(300))
4942            .ok_or("the PLM server did not answer Generate within 5 minutes")?
4943            .map_err(|e| e.to_string())
4944    }
4945
4946    #[cfg(target_arch = "wasm32")]
4947    fn generate_on_plm(
4948        &mut self,
4949        _: &mut Documents,
4950        _: &dyn ModelStore,
4951        _: &std::rc::Rc<crate::plm::client::PlmClient>,
4952        _: &str,
4953        _: bool,
4954    ) -> Result<family_table::GenerateReport, String> {
4955        Err("in the browser, Generate a PLM family from the family table's Generate button".into())
4956    }
4957
4958    /// The non-blocking door automation takes (`family_generate`): a local
4959    /// Generate finishes here (`Ok(Some(report))`); a PLM Generate saves the
4960    /// family first if asked (the write is queued, not waited for) and
4961    /// answers `Ok(None)` with its revision key — the caller then waits for
4962    /// the store's writes and runs [`crate::plm::family::generate`] as a task
4963    /// on later frames, and hands the report to `record_generate_report`.
4964    pub(crate) fn begin_generate_active_family(
4965        &mut self,
4966        docs: &mut Documents,
4967        store: &dyn ModelStore,
4968        save: bool,
4969    ) -> Result<Result<family_table::GenerateReport, String>, String> {
4970        let plm_key = docs.active().name().and_then(crate::plm::family::revision_key);
4971        match (store.plm_client(), plm_key) {
4972            (Some(_), Some(key)) => {
4973                if docs.active().is_dirty() {
4974                    if !save {
4975                        return Err(crate::plm::family::UNSAVED_FAMILY.into());
4976                    }
4977                    store.write(&key, &docs.tab_engine().history_request_json())?;
4978                    docs.active_mut().mark_clean();
4979                    self.save_generation += 1;
4980                }
4981                Ok(Err(key))
4982            }
4983            _ => Ok(Ok(self.record_generate(family_table::generate_family(store, docs.active().name(), &docs.engine().history_request_json())))),
4984        }
4985    }
4986
4987    #[cfg(not(target_arch = "wasm32"))]
4988    pub(crate) fn record_generate_report(&mut self, report: family_table::GenerateReport) -> family_table::GenerateReport {
4989        self.record_generate(report)
4990    }
4991
4992    fn record_generate(&mut self, report: family_table::GenerateReport) -> family_table::GenerateReport {
4993        if report.rows.iter().any(|row| row.status() == "written") {
4994            self.save_generation += 1;
4995        }
4996        self.status = format!("generate: {}", report.summary());
4997        self.last_generate = Some(report.clone());
4998        report
4999    }
5000
5001    // --- verifier hooks (wasm only) -------------------------------------------
5002
5003    /// The published state for the headed verifier: current name, dirty flag,
5004    /// backend label, the stored-document list, and the modal's open/mode.
5005    pub fn file_state_json(&self, docs: &Documents, store: &dyn ModelStore) -> String {
5006        serde_json::json!({
5007            "name": docs.active().name(),
5008            "nameBuf": self.name_buf,
5009            "selected": self.explorer.selected(),
5010            // The highlighted FOLDER: one click selects a folder row without
5011            // entering it (a double click, Enter or Open enters it).
5012            "selectedFolder": self.explorer.selected_folder(),
5013            "location": store.browser_location(),
5014            // The last folder of each purpose (Open/Save As/Insert, Import,
5015            // KiCad), which is where that modal opens next.
5016            "folders": Purpose::ALL
5017                .iter()
5018                .map(|purpose| (purpose.slug().to_string(), serde_json::json!(self.folders.get(purpose))))
5019                .collect::<serde_json::Map<_, _>>(),
5020            // The CACHED marker, not `is_dirty()`: this blob is published every
5021            // frame, and `is_dirty()` answers by serializing the whole document
5022            // — for a document whose history holds an imported model that is
5023            // hundreds of KB of JSON built and thrown away per frame, on the
5024            // thread that also has to answer the pointer. `Document::refresh_dirty_marker`
5025            // exists for exactly this and is refreshed once per frame; the tab
5026            // strip's dot already reads it, so the two cannot disagree.
5027            "dirty": docs.active().dirty_marker(),
5028            "backend": store.backend_label(),
5029            "interchange": store.supports_file_interchange(),
5030            "list": store.list(),
5031            "status": self.status,
5032            "ownedSave": self.owned_state,
5033            // What an assembly Save still has out after its status says
5034            // "saved": checkouts (the assembly's own included), new revisions, and the Save that names them.
5035            // 0 = the PLM holds everything this Save will write.
5036            "ownedInFlight": self.owned_checkouts.len()
5037                + self.owned_revisions.as_ref().map_or(0, |r| r.requests.len())
5038                + usize::from(self.owned_followup.is_some())
5039                + usize::from(self.owned_top.is_some()),
5040            "retarget": self.retarget.as_ref().map(|r| serde_json::json!({
5041                "from": r.old,
5042                "to": r.new_key,
5043                "tabs": r.tabs.iter().map(|(_, title)| title.clone()).collect::<Vec<_>>(),
5044            })),
5045            "open": self.open,
5046            "mode": match self.mode {
5047                Mode::CreateComponentPart => "createcomponentpart",
5048                Mode::Open => "open",
5049                Mode::SaveAs => "saveas",
5050                Mode::ConfirmClose => "confirmclose",
5051                Mode::Export => "export",
5052                Mode::Import => "import",
5053                Mode::FlatPattern => "flatpattern",
5054                Mode::InsertComponent => "insertcomponent",
5055                Mode::StepAssembly => "stepassembly",
5056                Mode::Kicad => "kicad",
5057                Mode::PickMember => "pickmember",
5058                Mode::SpinOut => "spinout",
5059                Mode::MemberEdit => "memberedit",
5060                Mode::OwnedSave => "ownedsave",
5061                Mode::Retarget => "retarget",
5062                Mode::PickFile => "pickfile",
5063                Mode::SaveFile => "savefile",
5064            },
5065            // The Save-file chooser's export: its title, the name field, the
5066            // folder the explorer is in (where Save writes) and the size.
5067            "saveFile": self.save_file.as_ref().map(|pending| serde_json::json!({
5068                "title": pending.request.title,
5069                "name": self.save_name,
5070                "folder": store.local_files().map(|local| local.browser_location()),
5071                "bytes": pending.request.body.as_bytes().len(),
5072            })),
5073            "pickFile": self.pick_request.as_ref().map(|(tag, title)| serde_json::json!({ "tag": tag, "title": title })),
5074            "picked": self.picked.as_ref().map(|(tag, file)| serde_json::json!({
5075                "tag": tag, "name": file.name, "path": file.path, "size": file.bytes.len(),
5076            })),
5077            // The active document's class (from its own `documentClass`
5078            // field) and, for a family member, its stamp.
5079            "class": document_class::document_class(docs.engine()).slug(),
5080            "saveClass": self.save_class.slug(),
5081            "plmSaveAs": self.plm_save_as.as_ref().map(|state| state.state_json()),
5082            "familySource": family_table::engine_family_source(docs.engine()).map(|source| serde_json::json!({
5083                "family": source.family,
5084                "partNumber": source.part_number,
5085                "valuesHash": source.values_hash,
5086                "historyHash": source.history_hash,
5087            })),
5088            // The armed member picker: each row, where its member is, and
5089            // whether Generate has written it.
5090            "pickMember": self.pick_member.as_ref().map(|pick| serde_json::json!({
5091                "family": pick.family_file,
5092                "plm": pick.plm,
5093                "loading": pick.loading,
5094                "rows": pick.rows.iter().map(|row| serde_json::json!({
5095                    "partNumber": row.part_number,
5096                    "identity": row.identity,
5097                    "exists": row.exists,
5098                    "whyNot": row.why_not,
5099                })).collect::<Vec<_>>(),
5100            })),
5101            "plmBusy": self.plm_work.is_some(),
5102            // What the PLM workspace browser (the Open dialog) says went wrong.
5103            "workspaceProblem": self.workspace.problem_text(),
5104            // The armed template spin-out: the answers so far, where the new
5105            // part will go, and what (if anything) blocks Create.
5106            "spinOut": self.spin_out.as_ref().map(|spin| serde_json::json!({
5107                "template": spin.template_file,
5108                "name": spin.name,
5109                "values": spin.values,
5110                "inputs": spin.inputs.iter().map(|input| input.name.clone()).collect::<Vec<_>>(),
5111                "target": spin_out_target(spin),
5112                "problems": spin.inputs.iter().filter_map(|input| template::value_problem(
5113                    &spin.template,
5114                    input,
5115                    spin.values.get(&input.name).map(String::as_str).unwrap_or(""),
5116                )).chain(template::name_problem(&spin.name)).collect::<Vec<_>>(),
5117            })),
5118            "memberPrompt": self.member_prompt.as_ref().map(|prompt| serde_json::json!({
5119                "partNumber": prompt.source.part_number,
5120                "family": prompt.source.family,
5121                "familyIdentity": prompt.family_identity,
5122                "fromSave": prompt.from_save,
5123            })),
5124            "generate": self.last_generate.as_ref().map(|report| serde_json::json!({
5125                "summary": report.summary(),
5126                "rows": report.to_json(),
5127            })),
5128            "kicad": (self.open && self.mode == Mode::Kicad).then(|| self.kicad.state_json()),
5129            // The armed §3.9 assembly choice: the file it belongs to and the
5130            // counts the prompt is showing, so the headed verifier can confirm
5131            // the dialog appeared with the numbers the import will deliver.
5132            // A `.step` upload whose structure probe is still running on the
5133            // background runner (the "reading…" state).
5134            "probing": self.pending_step_probe.as_ref().map(|pending| pending.name.clone()),
5135            // An assembly import chosen on the outline whose parts are still
5136            // being read (the dialog has closed).
5137            "importingAssembly": self.pending_step_build.as_ref().map(|build| build.import.name.clone()),
5138            "stepAssembly": self.pending_step_import.as_ref().map(|pending| {
5139                serde_json::json!({
5140                    "name": pending.name,
5141                    "parts": pending.probe.parts,
5142                    "instances": pending.probe.instances,
5143                    "nestedDepth": pending.probe.nested_depth,
5144                    // The §3.9 checkbox: shown only when there is a tree to
5145                    // flatten, and OFF by default (import keeps the tree).
5146                    "flatten": pending.flatten,
5147                })
5148            }),
5149        })
5150        .to_string()
5151    }
5152
5153    /// The published widget hit-rects (egui points) for the headed verifier.
5154    pub fn hits_json(&self) -> String {
5155        crate::automation::hit_rects::hits_json(&self.hits)
5156    }
5157
5158    /// Record a widget's screen rect for the headed verifier (wasm only; a no-op
5159    /// elsewhere so the dialog code reads the same on both targets).
5160    fn hit(&mut self, key: &str, resp: &egui::Response) {
5161        self.hits.insert(key.to_string(), resp.rect);
5162    }
5163
5164    fn record_explorer_hits(&mut self, hits: &[(String, egui::Rect)]) {
5165        self.hits.extend(hits.iter().cloned());
5166    }
5167}
5168
5169
5170/// A sheet's name as a file-name fragment: spaces and separators become
5171/// hyphens, so `Sheet 1` exports as `<document>-Sheet-1.svg` and cannot
5172/// reach the store as a path.
5173fn slug(name: &str) -> String {
5174    let cleaned: String = name
5175        .chars()
5176        .map(|c| if c.is_alphanumeric() { c } else { '-' })
5177        .collect();
5178    let trimmed = cleaned.trim_matches('-').to_string();
5179    if trimmed.is_empty() { "sheet".into() } else { trimmed }
5180}
5181/// The hit keys this panel publishes (see `automation::hit_keys`).
5182pub static HIT_KEYS: &[HitKeyDoc] = &[
5183    HitKeyDoc { panel: "file", prefix: "field:name", meaning: "the document name field", command: None },
5184    HitKeyDoc { panel: "file", prefix: "save", meaning: "confirm save / save-as", command: None },
5185    HitKeyDoc { panel: "file", prefix: "cancel", meaning: "close the modal", command: None },
5186    HitKeyDoc { panel: "file", prefix: "confirm:cancel", meaning: "keep the dirty document open", command: None },
5187    HitKeyDoc { panel: "file", prefix: "confirm:discard", meaning: "discard the dirty document", command: None },
5188    HitKeyDoc { panel: "file", prefix: "export:", meaning: "export in a format (export:step, export:iges, Parasolid as export:parasolid (.x_t) and export:parasolidbinary (.x_b), export:stl, export:obj, export:glb, export:3mf, the Bambu Studio-shaped 3MF (touching bodies as one multipart object, a filament per colour) as export:3mfbambu, export:json, export:bomcsv, export:bomjson, the open DRAWING SHEET as export:sheetsvg, every drawing sheet as ONE multi-page PDF as export:sheetpdf, and the same drawing set with the live 3D model as export:sheetpdf3d; for a document whose PCB board has parts, its manufacturing files: the Gerber/drill/pick-and-place/BOM zip as export:fabrication, the pick-and-place CSV as export:pickplace, the electronics BOM CSV as export:ecadbom; for manufacturing instructions, the printed PDF as export:instructionspdf, every step's PNG and SVG as one zip as export:instructionsimages, and the self-contained offline player as export:instructionshtml)", command: None },
5189    HitKeyDoc { panel: "file", prefix: "flat:", meaning: "export the flat pattern (flat:dxf, flat:svg)", command: None },
5190    HitKeyDoc { panel: "file", prefix: "savefile:", meaning: "the Save-file chooser a desktop export opens after its format click, for WHERE the file goes: savefile:name is the file name field, and its explorer over this machine's files publishes the explorer's key set under the `savefile` prefix (savefile:<file name> a row to overwrite, savefile:crumb:<i>, savefile:place:<label>, savefile:up, savefile:path-edit, …); `save` writes the file where the explorer is, `cancel` drops it. In the browser an export is a download and the chooser never opens", command: None },
5191    HitKeyDoc { panel: "file", prefix: "stepassembly:", meaning: "a STEP-with-structure import choice (assembly, bodies, flatten, cancel)", command: None },
5192    HitKeyDoc { panel: "file", prefix: "insert:lib:", meaning: "insert a parts-library entry (insert:lib:name)", command: None },
5193    HitKeyDoc { panel: "file", prefix: "filesystem:", meaning: "an entry of the file explorer", command: None },
5194    HitKeyDoc { panel: "file", prefix: "saveas:", meaning: "PLM Save As: saveas:destination (one dropdown; its open entries saveas:destination#new-revision, #new-part, #existing), destination fields (part, revision, name, number), save and cancel", command: None },
5195    HitKeyDoc { panel: "file", prefix: "saveas:class", meaning: "Save As's class dropdown: saveas:class, its open entries saveas:class#normal (.nbrep), saveas:class#family (.fbrep), saveas:class#template (.tbrep)", command: None },
5196    HitKeyDoc { panel: "file", prefix: "member:", meaning: "the member picker Insert component raises for a family: member:<part number> places that member (disabled until Generate has written it), member:cancel", command: None },
5197    HitKeyDoc { panel: "file", prefix: "spinout:", meaning: "the template spin-out prompt: spinout:name, spinout:input:<name> (a value field), spinout:choice:<name> (a fixed-list input's dropdown; its open entries spinout:choice:<name>#<value>), spinout:create, spinout:cancel", command: None },
5198    HitKeyDoc { panel: "file", prefix: "retarget:", meaning: "after a part is saved under a new name, point the open assemblies that place it at the new file (retarget:yes, the default) or keep them on the old one (retarget:no)", command: None },
5199    HitKeyDoc { panel: "file", prefix: "owned:", meaning: "the assembly Save's questions about the documents it owns: owned:save (save, every ticked row), owned:cancel (save nothing), owned:row:<i> (tick/untick row i), owned:choice:<i> (which copy of a document changed differently to keep, a dropdown; its open entries owned:choice:<i>#<j>), owned:remember (check out without asking again in this session)", command: None },
5200    HitKeyDoc { panel: "file", prefix: "member-edit:", meaning: "the hand-edit prompt on a family member: member-edit:saveas, member-edit:family (open the family), member-edit:cancel (undo the change)", command: None },
5201    HitKeyDoc { panel: "file", prefix: "pickfile:", meaning: "the file chooser (any file on this machine, for a panel's Add file…): the explorer's key set under the `pickfile` prefix — pickfile:<file name> (a row), pickfile:confirm, pickfile:path-edit-toggle, …", command: Some("file_pick") },
5202    HitKeyDoc { panel: "file", prefix: "kicad:", meaning: "the KiCad import: its explorer (kicad:<file name>, kicad:confirm, kicad:upload and the explorer's other keys), then kicad:symbol:<library:name>, kicad:next, kicad:footprint:<library:name>, kicad:use-footprint, kicad:no-footprint, kicad:search, kicad:field:footprints, kicad:field:models, kicad:apply-folders, kicad:import, kicad:cancel", command: None },
5203];
5204
5205/// Read `key`'s document from the PLM, for placing it.
5206fn fetch_document(
5207    client: std::rc::Rc<crate::plm::client::PlmClient>,
5208    key: String,
5209    number: String,
5210) -> crate::panels::plm_family::Pending<(String, String, String)> {
5211    crate::panels::plm_family::Pending::new(Box::pin(async move {
5212        let bytes = client.get_document(&key).await.map_err(|e| e.to_string())?;
5213        let text = bytes
5214            .map(|b| String::from_utf8_lossy(&b).into_owned())
5215            .ok_or_else(|| format!("{key} has no document yet"))?;
5216        Ok((key, text, number))
5217    }))
5218}
5219
5220/// Recent documents are global store identities, never document content.
5221use crate::store::RECENT_DOCUMENTS_KEY;
5222pub fn recent_documents(store: &dyn ModelStore) -> Vec<String> {
5223    store
5224        .read(RECENT_DOCUMENTS_KEY)
5225        .and_then(|s| serde_json::from_str(&s).ok())
5226        .unwrap_or_default()
5227}
5228fn remember_document(store: &dyn ModelStore, name: &str) {
5229    let mut recent = recent_documents(store);
5230    recent.retain(|item| item != name);
5231    recent.insert(0, name.into());
5232    recent.truncate(20);
5233    let _ = store.write(
5234        RECENT_DOCUMENTS_KEY,
5235        &serde_json::to_string(&recent).unwrap(),
5236    );
5237}
5238
5239#[derive(Default)]
5240pub struct FileMenuOutcome {
5241    pub action: Option<FileAction>,
5242    pub recent: Option<String>,
5243    /// The Plugins row under Settings was clicked: open the plugin manager.
5244    pub plugins: bool,
5245    /// The JavaScript row under Settings was clicked: open the editor.
5246    pub javascript: bool,
5247}
5248
5249/// The side of a recent row's thumbnail square, in points.
5250pub const RECENT_THUMB_SIDE: f32 = crate::plm::thumbnail::RECENT_SIDE;
5251
5252/// The neutral square a recent document without a picture yet shows: the
5253/// same size as a thumbnail, never a gap. Drawn through the SVG loader the
5254/// menu's artwork already uses.
5255const RECENT_PLACEHOLDER_SVG: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><rect x="1.5" y="1.5" width="37" height="37" rx="4" fill="#8a8a8a" fill-opacity="0.16" stroke="#8a8a8a" stroke-opacity="0.45"/></svg>"##;
5256
5257/// File actions and recent documents, shared by Ribbon and Classic.
5258pub fn file_menu(
5259    ui: &mut egui::Ui,
5260    _state: &mut EngineState,
5261    store: &dyn ModelStore,
5262    settings_open: &mut bool,
5263    properties_open: &mut bool,
5264    hits: &mut HashMap<String, egui::Rect>,
5265) -> FileMenuOutcome {
5266    use crate::panels::toolbar_button;
5267    let mut outcome = FileMenuOutcome::default();
5268    let presentation = crate::workbench::file_presentation;
5269    egui_extras::install_image_loaders(ui.ctx());
5270    let menu = ui.menu_button("File", |ui| {
5271        let file_rows: Vec<_> = crate::workbench::FILE_COMMANDS
5272            .iter()
5273            .map(|p| (p.glyph, p.label()))
5274            .collect();
5275        let compact = crate::viewport::touch::compact(ui.ctx());
5276        let width = toolbar_button::menu_width(ui, &file_rows)
5277            .min((ui.ctx().content_rect().width() - 32.0).max(100.0));
5278        let right_width = width;
5279        ui.set_width(width);
5280        let max_height = ui.ctx().content_rect().height() * 0.8;
5281        ui.set_max_height(max_height);
5282        // The whole body sits in one scroll area so a window too short for
5283        // the columns themselves still shows a menu that fits; on any taller
5284        // window the columns never scroll and only the recent list does, up
5285        // to the room left under the cap (`cap_bottom`).
5286        let cap_bottom = ui.max_rect().bottom();
5287        let body = egui::ScrollArea::vertical()
5288            .id_salt("file-menu-body")
5289            .auto_shrink([false, true])
5290            .max_height(max_height)
5291            .show(ui, |ui| {
5292                let columns = |ui: &mut egui::Ui| {
5293                    ui.vertical(|ui| {
5294                        ui.set_width(right_width);
5295                        ui.weak("Document");
5296                        for (class, p) in DocumentClass::ALL
5297                            .into_iter()
5298                            .zip(crate::workbench::NEW_DOCUMENT_COMMANDS)
5299                        {
5300                            let row = toolbar_button::menu_row(ui, p.glyph, p.label(), false, right_width);
5301                            hits.insert(p.id.into(), row.rect);
5302                            if class == DocumentClass::Normal {
5303                                hits.insert("file:new".into(), row.rect);
5304                                hits.insert("file:newmenu".into(), row.rect);
5305                            }
5306                            if row.clicked() {
5307                                outcome.action = Some(FileAction::NewOfClass(class));
5308                                ui.close();
5309                            }
5310                        }
5311                        for (id, action) in [
5312                            ("file:open", FileAction::Open),
5313                            ("file:save", FileAction::Save),
5314                            ("file:saveas", FileAction::SaveAs),
5315                            ("file:import", FileAction::Import),
5316                            ("file:export", FileAction::Export),
5317                        ] {
5318                            let p = presentation(id);
5319                            let row = toolbar_button::menu_row(ui, p.glyph, p.label(), false, right_width);
5320                            hits.insert(id.into(), row.rect);
5321                            if row.clicked() {
5322                                outcome.action = Some(action);
5323                                ui.close();
5324                            }
5325                        }
5326                        let properties = toolbar_button::menu_row(
5327                            ui,
5328                            presentation("properties").glyph,
5329                            presentation("properties").label(),
5330                            *properties_open,
5331                            right_width,
5332                        );
5333                        hits.insert("properties".into(), properties.rect);
5334                        if properties.clicked() {
5335                            *properties_open = !*properties_open;
5336                            ui.close();
5337                        }
5338                        let settings = toolbar_button::menu_row(
5339                            ui,
5340                            presentation("settings").glyph,
5341                            presentation("settings").label(),
5342                            *settings_open,
5343                            right_width,
5344                        );
5345                        hits.insert("settings".into(), settings.rect);
5346                        if settings.clicked() {
5347                            *settings_open = !*settings_open;
5348                            ui.close();
5349                        }
5350                        // Plugin management sits under Settings: the plugin manager
5351                        // and the JavaScript editor, the same rows in both styles.
5352                        for (id, flag) in [
5353                            ("workbench:manage:plugins", &mut outcome.plugins),
5354                            ("workbench:manage:javascript", &mut outcome.javascript),
5355                        ] {
5356                            let row = toolbar_button::menu_row(
5357                                ui,
5358                                presentation(id).glyph,
5359                                presentation(id).label(),
5360                                false,
5361                                right_width,
5362                            );
5363                            hits.insert(id.into(), row.rect);
5364                            if row.clicked() {
5365                                *flag = true;
5366                                ui.close();
5367                            }
5368                        }
5369                    });
5370                };
5371                if compact { ui.vertical(columns); } else { ui.horizontal_top(columns); }
5372
5373                // BELOW BOTH: the recent documents, one column, a thumbnail each. The
5374                // list scrolls under the 80% cap; the columns above it never do.
5375                let recent = recent_documents(store);
5376                if !recent.is_empty() {
5377                    ui.separator();
5378                    let caption = ui.weak("Recent Documents");
5379                    hits.insert("file:recent".into(), caption.rect);
5380                    let thumbs = crate::plm::thumbnail::recent_textures(ui.ctx(), store);
5381                    let side = egui::Vec2::splat(RECENT_THUMB_SIDE);
5382                    let row_height = RECENT_THUMB_SIDE + 2.0 * ui.spacing().button_padding.y;
5383                    // The room left under the cap; at least two rows even when the
5384                    // columns already fill it (then the outer area scrolls).
5385                    let room = cap_bottom - ui.cursor().top();
5386                    let list_height = room.max(2.0 * row_height + ui.spacing().item_spacing.y);
5387                    egui::ScrollArea::vertical()
5388                        .id_salt("file-recent")
5389                        .auto_shrink([false, true])
5390                        .max_height(list_height)
5391                        .show(ui, |ui| {
5392                            for name in &recent {
5393                                let image = match thumbs.get(name) {
5394                                    Some((_, texture)) => egui::Image::from_texture((texture.id(), side)),
5395                                    None => egui::Image::new(egui::ImageSource::Bytes {
5396                                        uri: "bytes://brep-recent-thumb/placeholder.svg".into(),
5397                                        bytes: egui::load::Bytes::Static(RECENT_PLACEHOLDER_SVG.as_bytes()),
5398                                    }),
5399                                }
5400                                .fit_to_exact_size(side);
5401                                let row = crate::ui_kit::surface::image_row(ui, image, &model_display_name(name), egui::vec2(width, row_height))
5402                                    .on_hover_text(name);
5403                                hits.insert(format!("file:recent:{name}"), row.rect);
5404                                let padding = ui.spacing().button_padding;
5405                                let thumb = egui::Rect::from_min_size(
5406                                    row.rect.min + egui::vec2(padding.x, (row.rect.height() - RECENT_THUMB_SIDE) / 2.0),
5407                                    side,
5408                                );
5409                                hits.insert(format!("file:recent:thumb:{name}"), thumb);
5410                                if row.clicked() {
5411                                    outcome.recent = Some(name.clone());
5412                                    ui.close();
5413                                }
5414                            }
5415                        });
5416                }
5417            });
5418        if compact { hits.insert("file:clip".into(), body.inner_rect); }
5419    });
5420    hits.insert("file:menu".into(), menu.response.rect);
5421    outcome
5422}
5423
5424
5425/// The library ids of the tools the open instructions use (the tools whose
5426/// pictures an export fetches).
5427pub fn linked_tool_ids(engine: &EngineState) -> Vec<String> {
5428    engine
5429        .instructions()
5430        .ok()
5431        .flatten()
5432        .map(|block| block.tools_list().into_iter().filter_map(|(tool, _)| tool.tool_id).collect())
5433        .unwrap_or_default()
5434}