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