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