Skip to main content

brep_app/
document.rs

1//! Open documents and their active tab. Each document owns an engine, store
2//! identity, and clean baseline for dirty tracking. Keeping engine access on
3//! `Documents` allows separate mutable borrows of other app fields.
4//!
5//! Every engine has its own history runner and resident kernel state. All open
6//! documents are pumped each frame, so switching tabs cannot redirect a pending
7//! result to another document. Each open document retains its runner and scene.
8//!
9//! Display settings are shared across tabs by `carry_settings`; workbench
10//! selection belongs to each document. A new engine initially inherits the
11//! current workbench, which a loaded document can override.
12
13use brep_render::engine_state::EngineState;
14
15pub mod cam;
16pub mod live_link;
17pub mod owned_save;
18pub mod work_part;
19pub mod ecad;
20
21/// Builds a fresh engine for a new document — the platform runner, the viewcube,
22/// and the persisted display settings, all applied before anything is loaded
23/// into it. Injected by the shell so tests (which need the SYNCHRONOUS inline
24/// runner) can construct documents without a background thread.
25pub type EngineFactory = Box<dyn Fn() -> EngineState>;
26
27/// Whether a document may be edited. Every file-based document is
28/// [`Access::Editable`]. PLM permissions apply to [`Document::save_access`],
29/// independently of editing the session copy.
30///
31/// Held by the engine's history ([`brep_render::history::History::lock`]),
32/// which refuses every change to the saved document while it is read-only —
33/// the one door every edit passes, so no panel has to remember to ask.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum Access {
36    Editable,
37    /// `reason` explains the edit or save restriction to the user.
38    ReadOnly { reason: String },
39}
40
41impl Access {
42    pub fn read_only(reason: impl Into<String>) -> Self {
43        Access::ReadOnly { reason: reason.into() }
44    }
45
46    pub fn is_editable(&self) -> bool {
47        matches!(self, Access::Editable)
48    }
49}
50
51/// Empty history for loading fixtures and creating nonpart documents.
52pub const EMPTY_DOCUMENT: &str = r#"{"expressions":"","configurator":{},"features":[]}"#;
53
54/// Workbenches share a document format. Only part workspaces seed geometry
55/// references; assembly, drawing, harness and eCAD workspaces start empty.
56fn is_part_workbench(id: &str) -> bool {
57    !matches!(crate::workbench::resolve(id).id,
58        "assembly" | "drawing" | "wireHarness" | "diagram" | "schematic" | "pcb" | "symbol" | "pads")
59}
60
61/// Seed only a feature-empty part when explicitly creating a new part. PLM
62/// adoption uses this too, preserving the source's expressions and document blocks.
63pub fn seed_new_part_datum(engine: &mut EngineState) {
64    if engine.history_len() == 0 && is_part_workbench(&engine.settings.workbench) {
65        let id = engine.next_feature_id(&brep_render::features::feature_short_name("D"));
66        let mut params = engine.feature_default_params("D");
67        params["id"] = serde_json::json!(id);
68        engine.add_feature(&serde_json::json!({
69            "type": "D", "inputParams": params, "persistentData": {}
70        }).to_string()).expect("valid default datum");
71    }
72}
73
74/// ONE open model: the engine that owns it plus the identity the file lane needs
75/// — the store name it was opened from / saved to, and the clean baseline.
76pub struct Document {
77    /// The windowing-agnostic brain for THIS document (scene, camera, history,
78    /// settings, selection). Panels borrow it; it is never forked.
79    pub engine: EngineState,
80    /// The store identity (`None` = a never-saved "untitled" model). The RAW
81    /// identity, not the display name — a native dialog hands back a full path
82    /// and a plain Save must write back to it.
83    name: Option<String>,
84    /// Which untitled document this is while it has no `name`: 1 is plain
85    /// "untitled", 2 and up read "untitled 2", … — assigned by
86    /// [`Documents::open_document`], the lowest number no other open untitled
87    /// tab holds, so two new tabs never share a label (lane U, ruling P2).
88    untitled: u32,
89    /// The tab label an agent gave an untitled document (`cad.documents.create`'s
90    /// title): display only, never a file name, so nothing is saved under it.
91    label: Option<String>,
92    /// PLM write permission is independent of editing the session copy.
93    plm_save_access: Option<Access>,
94    /// The PLM workspace folder `(id, name)` this tab was opened from (a link
95    /// in the workspace panel), for this session: the parts its Save makes
96    /// PLM items for are linked there. `None`: opened another way, so the
97    /// items go to the top of the workspace.
98    plm_folder: Option<(String, String)>,
99    /// A hash of the stored text this tab was opened from (or last reloaded
100    /// from): while the store still holds those bytes, nobody has saved it
101    /// since, and there is nothing to take — see [`Self::holds_stored`].
102    opened_from: Option<u64>,
103    /// The model request JSON as of the last New / Open / Save — the baseline
104    /// the dirty flag compares the live history against.
105    saved_signature: Option<String>,
106    /// The baseline's top-level parts library as `{entry: (sourceKey,
107    /// sourceSignature)}`, taken from the engine whenever the baseline is (a
108    /// handful of entries, where parsing `saved_signature` is the whole
109    /// document); `None` when the baseline came from elsewhere, so
110    /// [`Self::saved_sources`] parses it.
111    saved_sources: Option<SavedSources>,
112    /// Moves every time `saved_signature` is replaced (a cache key for what
113    /// is derived from the baseline).
114    baseline_generation: u64,
115    /// [`Self::content_key`] when the baseline was taken from the document
116    /// itself (`None` when it came from elsewhere): while the key is unmoved,
117    /// the document IS its baseline.
118    baseline_content: Option<ContentKey>,
119    /// While the document is as it was opened, what the runs of the open write
120    /// back is part of the open: see [`Document::settle_open_runs`]. `None`
121    /// once the user edits, or once anything else writes the document.
122    settle: Option<Settle>,
123    /// After a write that discarded the user's edits (`Take their version`),
124    /// the runs it causes re-solve the document back towards its clean
125    /// baseline, but not to the same bits: see [`Document::converge_runs`].
126    /// `None` once the user edits, once it converged, or after
127    /// [`CONVERGE_RUNS`] runs.
128    converge: Option<(Settle, u32)>,
129    /// The cached tab-strip dirty dot. See [`Document::dirty_marker`] for why
130    /// this is not simply `is_dirty()`.
131    dirty_marker: bool,
132    /// The [`Document::edit_key`] `dirty_marker` was last refreshed at.
133    marker_key: Option<(u64, u64)>,
134    /// How many times the marker has serialized the document to recompute
135    /// itself — the per-frame cost [`Document::refresh_dirty_marker`] bounds.
136    dirty_checks: u64,
137    /// A process-unique handle, so the shell can notice "the active document is
138    /// a different one now" without comparing indices (closing a tab BEFORE the
139    /// active one moves the index without changing the document).
140    id: u64,
141    /// The committed revision an agent's write names as its expectation
142    /// ([`Document::committed_revision`]): `(content key last observed, count)`.
143    committed: std::cell::Cell<(ContentKey, u64)>,
144    /// The public handle an agent names this document by
145    /// ([`crate::handles`]); random, never stored, never reused.
146    handle: String,
147    /// This document's eCAD editors — Diagram, PCB, Symbol and Pads — kept
148    /// beside its engine, so each tab has its own and a tab switch keeps their
149    /// pan, zoom and view: a switch rebuilds the PANELS
150    /// (`reset_document_scoped_state`), never a document. Built with the
151    /// document; all four measured 0.65 ms (release), so no document waits for
152    /// its first eCAD workbench to have them.
153    pub ecad: crate::workbench::ecad::Editors,
154    /// Each editor's standing with its block of this document's history: what
155    /// takes BREP's undo and redo to the editor, and the editor's edits into the
156    /// document ([`ecad::BlockSync`]).
157    pub ecad_blocks: [ecad::BlockSync; 4],
158    pub ecad_parts_revision: Option<u64>,
159    /// The components on the PCB the last frame (`ecad_parts::answer_board_checks`):
160    /// one that appears says whether it sits on its footprint. `None` until the
161    /// board is first seen, so opening a document says nothing.
162    pub ecad_placed: Option<std::collections::BTreeSet<brep_ecad_core::Uuid>>,
163    /// The broken-reference lines `crate::panels::ecad_parts::sync` has
164    /// already put in front of the user. A device whose part is missing is a
165    /// STANDING state and the revision bumps on every edit, so without this it
166    /// would toast on every keystroke — the same rule
167    /// [`ecad::BlockSync::unreported`] keeps for an UNLINKED component.
168    pub ecad_parts_reported: Vec<String>,
169    /// What `crate::panels::ecad_parts::follow_occurrences` last saw of the
170    /// assembly's occurrences; `None` until the first frame looks.
171    pub ecad_occurrences: Option<crate::panels::ecad_parts::OccurrenceMark>,
172    /// The parts-library entries whose saved part has moved on since this
173    /// document took it — the shell's `UpdateComponents` list for the active
174    /// document, handed over each frame so the Diagram and PCB workbenches can
175    /// mark the components placed from them and offer the update where the
176    /// user is looking (`viewport::ecad`).
177    pub ecad_outdated: Vec<String>,
178    /// Set by the eCAD host's Update parts button; the shell runs the update
179    /// (`UpdateComponents::run`, one undo step) on its next frame.
180    pub ecad_update_requested: bool,
181    /// The history's refused-edit count as of the last
182    /// [`Document::take_refused`], so each refusal is told once.
183    refused_seen: u64,
184    /// The [`Document::edit_key`] and baseline generation the
185    /// `insertedCopies` block was last brought up to date at
186    /// (`owned_save::note_inserted_copies`).
187    pub(crate) inserted_noted: Option<((u64, u64), u64)>,
188}
189
190/// What the dirty flag compares: the saved document ([`EngineState::history_request_json`])
191/// WITHOUT its `workbench` and derived `thumbnail`.
192///
193/// The workbench is saved, so a file reopens where it was left, but it is view state
194/// and not work. Counting it made Close ask to discard documents nobody had edited:
195/// open a board saved in PCB, look at its Diagram, and the saved document differed
196/// from the file in exactly `/workbench` (the eCAD re-audit's B5, measured in lane X).
197/// The tab's dot never counted it ([`Document::edit_key`] does not move for it), so
198/// the prompt came with no dot. Now the two agree, and Save still writes the field.
199///
200/// Built as `history_request_json` builds the saved document, less the one field,
201/// rather than by parsing that again: the dot recomputes this on every run-moving
202/// edit, and a second parse of a megabyte assembly doubles it. A test holds the two
203/// together (`the_signature_is_the_saved_document_less_its_workbench`).
204/// A parts library's top-level entries as `{entry: (sourceKey, sourceSignature)}`.
205pub(crate) type SavedSources = std::collections::HashMap<String, (String, String)>;
206
207fn sources_of(library: &serde_json::Value) -> SavedSources {
208    library
209        .as_object()
210        .map(|entries| {
211            entries
212                .iter()
213                .map(|(name, entry)| {
214                    let field = |key: &str| entry[key].as_str().unwrap_or_default().to_string();
215                    (name.clone(), (field("sourceKey"), field("sourceSignature")))
216                })
217                .collect()
218        })
219        .unwrap_or_default()
220}
221
222fn raw_hash(text: &str) -> u64 {
223    use std::hash::{Hash, Hasher};
224    let mut hasher = std::collections::hash_map::DefaultHasher::new();
225    text.hash(&mut hasher);
226    hasher.finish()
227}
228
229fn signature(engine: &EngineState) -> String {
230    signature_without(engine, None)
231}
232
233/// What [`Document::settle_open_runs`] last saw: the user's edit serial at the
234/// clean baseline, and the applied-run generation and history revision at the
235/// last check.
236#[derive(Clone, Copy, Debug, PartialEq)]
237struct Settle {
238    serial: u64,
239    generation: u64,
240    revision: u64,
241}
242
243impl Settle {
244    fn of(engine: &EngineState) -> Self {
245        Self {
246            serial: engine.history.edit_serial(),
247            generation: engine.applied_generation(),
248            revision: engine.history.revision(),
249        }
250    }
251}
252
253/// What the document holds: its runs and edits ([`Document::edit_key`]) and
254/// its object metadata, which moves neither.
255type ContentKey = ((u64, u64), u64);
256
257fn content_key(engine: &EngineState) -> ContentKey {
258    ((engine.applied_generation(), engine.history_revision()), engine.metadata.stamp())
259}
260
261/// How many applied runs [`Document::converge_runs`] watches.
262const CONVERGE_RUNS: u32 = 16;
263/// Relative tolerance of [`nearly_equal`] (absolute below 1).
264const CONVERGE_TOLERANCE: f64 = 1e-6;
265
266/// The document keys [`Document::converge_runs`] leaves out of its compare:
267/// ONLY keys whose value in the history never reaches a saved file, because
268/// the saved form (`EngineState::history_request_json`) overwrites them from
269/// the session: the rendered preview, and the active workbench (stamped into
270/// the history by any write-back of that form, e.g. a Work part's return).
271/// Adding a key here lets a difference in it read clean, so a new entry needs
272/// the same argument.
273const CONVERGE_DERIVED_DOCUMENT_KEYS: &[&str] = &["thumbnail", "workbench"];
274/// The embedded-copy keys it leaves out, at every depth, on the same terms:
275/// the copy's cached geometry, which a refresh blanks and the next run re-heals.
276const CONVERGE_DERIVED_COPY_KEYS: &[&str] = &["snapshot"];
277
278/// `document` without [`CONVERGE_DERIVED_DOCUMENT_KEYS`] and, on every
279/// embedded copy, [`CONVERGE_DERIVED_COPY_KEYS`]. Everything else is compared.
280fn without_derived(mut document: serde_json::Value) -> serde_json::Value {
281    fn strip(document: &mut serde_json::Value) {
282        if let Some(entries) = document.get_mut("partsLibrary").and_then(serde_json::Value::as_object_mut) {
283            for entry in entries.values_mut() {
284                if let Some(entry) = entry.as_object_mut() {
285                    for key in CONVERGE_DERIVED_COPY_KEYS {
286                        entry.remove(*key);
287                    }
288                }
289                strip(&mut entry["document"]);
290            }
291        }
292    }
293    if let Some(object) = document.as_object_mut() {
294        for key in CONVERGE_DERIVED_DOCUMENT_KEYS {
295            object.remove(*key);
296        }
297    }
298    strip(&mut document);
299    document
300}
301
302/// `a` and `b` alike but for floating-point numbers within
303/// [`CONVERGE_TOLERANCE`]. Keys, strings, booleans and integers (counts, ids)
304/// compare exactly.
305fn nearly_equal(a: &serde_json::Value, b: &serde_json::Value) -> bool {
306    use serde_json::Value;
307    match (a, b) {
308        (Value::Number(x), Value::Number(y)) if x.is_f64() && y.is_f64() => match (x.as_f64(), y.as_f64()) {
309            (Some(x), Some(y)) => (x - y).abs() <= CONVERGE_TOLERANCE * x.abs().max(y.abs()).max(1.0),
310            _ => false,
311        },
312        (Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(x, y)| nearly_equal(x, y)),
313        (Value::Object(x), Value::Object(y)) => {
314            x.len() == y.len() && x.iter().all(|(k, v)| y.get(k).is_some_and(|w| nearly_equal(v, w)))
315        }
316        _ => a == b,
317    }
318}
319
320/// The saved-content signature with one document block left out — the
321/// baseline of a copy saved WITHOUT that block (a family member saved as a new
322/// part drops `familySource` on the copy), in the same canonical form.
323fn signature_without(engine: &EngineState, without: Option<&str>) -> String {
324    let mut document: serde_json::Value =
325        serde_json::from_str(&engine.history.request_json()).unwrap_or_else(|_| serde_json::json!({}));
326    if let Some(object) = document.as_object_mut() {
327        if let Some(key) = without {
328            // In order, as the document drops it (`set_document_block_no_undo`):
329            // `remove` would move the last key into the gap.
330            object.shift_remove(key);
331        }
332        if !engine.metadata.is_empty() {
333            object.insert("metadata".into(), engine.metadata.to_json());
334        }
335    }
336    without_run_record(&mut document);
337    if let Some(object) = document.as_object_mut() {
338        object.shift_remove(owned_save::INSERTED_COPIES_BLOCK);
339    }
340    document.to_string()
341}
342
343/// Drop what the mate solver writes into each assembly constraint as the
344/// record of its last RUN — `persistentData.error`, `.kernel` (residual,
345/// iterations, rank, …) and `.message`, which quotes the residual — so an
346/// edit and its undo compare equal although the re-solve after the undo
347/// started from the solved pose and took 0 iterations instead of 4. What a
348/// solve decides (`status`, `satisfied`, first-solve choices) still counts.
349/// The library's saved rows go too ([`without_saved_rows`]).
350/// Comparison only: the saved file keeps the record.
351pub(crate) fn without_run_record(document: &mut serde_json::Value) {
352    without_saved_rows(document);
353    let Some(constraints) = document
354        .get_mut("assembly")
355        .and_then(|assembly| assembly.get_mut("constraints"))
356        .and_then(serde_json::Value::as_array_mut)
357    else {
358        return;
359    };
360    for constraint in constraints {
361        if let Some(record) = constraint.get_mut("persistentData").and_then(serde_json::Value::as_object_mut) {
362            for key in ["error", "kernel", "message"] {
363                record.remove(key);
364            }
365        }
366    }
367}
368
369/// Drop each library entry's `nestedRows`, at every depth: the rows of the
370/// run that made the entry's snapshot, which a run writes back and re-stamps
371/// (the kernel's `SavedRows`), the same kind of record as the solver's.
372fn without_saved_rows(document: &mut serde_json::Value) {
373    let Some(entries) = document.get_mut("partsLibrary").and_then(serde_json::Value::as_object_mut) else {
374        return;
375    };
376    for entry in entries.values_mut() {
377        if let Some(object) = entry.as_object_mut() {
378            object.shift_remove("nestedRows");
379        }
380        if let Some(child) = entry.get_mut("document") {
381            without_saved_rows(child);
382        }
383    }
384}
385
386/// One [`ecad::BlockSync`] per eCAD block, none of them pulled yet.
387fn ecad_blocks() -> [ecad::BlockSync; 4] {
388    use ecad::Block;
389    [Block::Diagram, Block::Pcb, Block::Symbol, Block::Pads].map(ecad::BlockSync::new)
390}
391
392impl Document {
393    /// Create a fresh document. Part workbenches start with the same ordinary,
394    /// schema-seeded datum a user adds from the palette. Existing content must
395    /// use `new` instead: opening a file never changes its feature history.
396    pub fn fresh(mut engine: EngineState, class: crate::document_class::DocumentClass) -> Self {
397        engine.set_history_json(EMPTY_DOCUMENT).expect("valid empty document");
398        crate::document_class::set_document_class(&mut engine, class);
399        seed_new_part_datum(&mut engine);
400        Self::new(engine)
401    }
402
403    /// Wrap `engine` as a document, taking its CURRENT model as the clean
404    /// baseline — so a freshly loaded (or freshly emptied) document is clean and
405    /// the first edit marks it dirty.
406    pub fn new(engine: EngineState) -> Self {
407        let saved_signature = Some(signature(&engine));
408        let baseline_content = Some(content_key(&engine));
409        let saved_sources = Some(sources_of(engine.history.parts_library()));
410        let settle = Some(Settle::of(&engine));
411        Self {
412            engine,
413            name: None,
414            plm_save_access: None,
415            plm_folder: None,
416            opened_from: None,
417            baseline_content,
418            saved_signature,
419            saved_sources,
420            baseline_generation: 0,
421            settle,
422            converge: None,
423            dirty_marker: false,
424            marker_key: None,
425            dirty_checks: 0,
426            id: next_document_id(),
427            committed: std::cell::Cell::new((((0, 0), 0), 0)),
428            handle: crate::handles::mint("doc"),
429            untitled: 1,
430            label: None,
431            ecad: crate::workbench::ecad::Editors::new(),
432            ecad_blocks: ecad_blocks(),
433            ecad_parts_revision: None,
434            ecad_placed: None,
435            ecad_parts_reported: Vec::new(),
436            ecad_occurrences: None,
437            ecad_outdated: Vec::new(),
438            ecad_update_requested: false,
439            refused_seen: 0,
440            inserted_noted: None,
441        }
442    }
443
444    /// Wrap `engine` as a document RESTORED from the autosave blob
445    /// (`crate::recovery`): it carries the store identity it had (`None` for
446    /// an untitled one) and NO clean baseline, so it is dirty from its first
447    /// frame — the work it holds is exactly what was never saved, and the close
448    /// guard and the tab dot must say so until a Save writes it somewhere.
449    pub fn recovered(engine: EngineState, name: Option<String>) -> Self {
450        Self {
451            engine,
452            name,
453            plm_save_access: None,
454            plm_folder: None,
455            opened_from: None,
456            saved_signature: None,
457            saved_sources: None,
458            baseline_generation: 0,
459            baseline_content: None,
460            settle: None,
461            converge: None,
462            dirty_marker: true,
463            marker_key: None,
464            dirty_checks: 0,
465            id: next_document_id(),
466            committed: std::cell::Cell::new((((0, 0), 0), 0)),
467            handle: crate::handles::mint("doc"),
468            untitled: 1,
469            label: None,
470            ecad: crate::workbench::ecad::Editors::new(),
471            ecad_blocks: ecad_blocks(),
472            ecad_parts_revision: None,
473            ecad_placed: None,
474            ecad_parts_reported: Vec::new(),
475            ecad_occurrences: None,
476            ecad_outdated: Vec::new(),
477            ecad_update_requested: false,
478            refused_seen: 0,
479            inserted_noted: None,
480        }
481    }
482
483    /// Whether this document may be edited ([`Access`]).
484    pub fn access(&self) -> Access {
485        match self.engine.history.locked() {
486            None => Access::Editable,
487            Some(reason) => Access::read_only(reason),
488        }
489    }
490
491    /// Make the document editable or read-only. Read-only locks the engine's
492    /// history, so its saved bytes cannot change until it is editable again.
493    pub fn set_access(&mut self, access: Access) {
494        match access {
495            Access::Editable => self.engine.history.unlock(),
496            Access::ReadOnly { reason } => self.engine.history.lock(reason),
497        }
498    }
499
500    /// Saving to the current PLM revision may be restricted while session
501    /// editing remains available. A local Save As clears this restriction.
502    pub fn save_access(&self) -> Access {
503        self.plm_save_access.clone().unwrap_or_else(|| self.access())
504    }
505
506    pub(crate) fn has_plm_save_access(&self) -> bool { self.plm_save_access.is_some() }
507
508    pub fn set_plm_save_access(&mut self, access: Access) {
509        self.plm_save_access = Some(access);
510        self.engine.history.unlock();
511    }
512
513    /// The sentence to show when an edit was refused since the last call —
514    /// `None` when nothing was. Called once a frame by the shell, which toasts it.
515    pub fn take_refused(&mut self) -> Option<String> {
516        let refused = self.engine.history.refused_user_edits();
517        if refused == self.refused_seen {
518            return None;
519        }
520        self.refused_seen = refused;
521        let reason = self.engine.history.locked()?;
522        Some(format!("This document is read-only: {reason}."))
523    }
524
525    /// The raw store identity, or `None` for a never-saved document.
526    pub fn name(&self) -> Option<&str> {
527        self.name.as_deref()
528    }
529
530    pub fn set_name(&mut self, name: Option<String>) {
531        if self.name != name { self.plm_save_access = None; }
532        self.name = name;
533    }
534
535    /// The tab label: PLM part/revision, the bare file name, or `untitled`
536    /// (`untitled 2`, … for the second and later untitled tabs).
537    pub fn title(&self) -> String {
538        match &self.name {
539            Some(name) => crate::panels::plm_host::revision_of(name)
540                .map(|(part, revision)| format!("{part}/{revision}"))
541                .unwrap_or_else(|| crate::store::model_display_name(name)),
542            None => self.label.clone().unwrap_or_else(|| self.untitled_title()),
543        }
544    }
545
546    /// Give an untitled document a display label (see `label`).
547    pub fn set_label(&mut self, label: Option<String>) {
548        self.label = label;
549    }
550
551    /// What an untitled document is called, and what Save As offers for it.
552    pub fn untitled_title(&self) -> String {
553        match self.untitled {
554            0 | 1 => "untitled".to_string(),
555            n => format!("untitled {n}"),
556        }
557    }
558
559    /// Snapshot the current model as the clean baseline (after New / Open /
560    /// Save, or a `?loadModel=` boot-load).
561    pub fn mark_clean(&mut self) {
562        self.saved_signature = Some(signature(&self.engine));
563        self.saved_sources = Some(sources_of(self.engine.history.parts_library()));
564        self.baseline_generation += 1;
565        self.baseline_content = Some(content_key(&self.engine));
566        self.dirty_marker = false;
567        self.marker_key = Some(self.edit_key());
568        self.settle = Some(Settle::of(&self.engine));
569    }
570
571    /// Keep taking what the open's runs write back as part of the open, from
572    /// here (a check on open that wrote the document itself and absorbed that
573    /// write, [`Self::absorb_open_write`], re-arms so the run it causes is
574    /// absorbed too).
575    pub(crate) fn arm_open_settle(&mut self) {
576        self.settle = Some(Settle::of(&self.engine));
577    }
578
579    /// A document's first runs after it is opened write back into it: the
580    /// first solve of a mate stored unsolved (the pose and the solve's
581    /// status), and the snapshots of embedded parts stored without one (the
582    /// PLM import blanks them). None of that is the user's change, so closing
583    /// the document must not ask to save it.
584    ///
585    /// Called once a frame. While the user has not edited the document since
586    /// it was opened (its edit serial is unchanged), a run that has APPLIED
587    /// moves the clean baseline to the document as that run left it. The rule
588    /// is conservative where it cannot tell: the document changing while no
589    /// run applied (a write that took no undo step, which could be the user's)
590    /// stops the settling for good, and the document stays as dirty as it is.
591    /// The worst case is one needless save prompt, never an unsaved edit that
592    /// reads saved.
593    pub fn settle_open_runs(&mut self) {
594        let Some(last) = self.settle else {
595            return;
596        };
597        let now = Settle::of(&self.engine);
598        if now.serial != last.serial || (now.generation == last.generation && now.revision != last.revision) {
599            self.settle = None;
600            return;
601        }
602        if now.generation == last.generation || self.engine.run_pending() {
603            return;
604        }
605        if now.revision != last.revision {
606            self.saved_signature = Some(signature(&self.engine));
607            self.saved_sources = Some(sources_of(self.engine.history.parts_library()));
608            self.baseline_generation += 1;
609            self.baseline_content = Some(content_key(&self.engine));
610            self.marker_key = None;
611        }
612        self.settle = Some(now);
613    }
614
615    /// Watch the runs a write that discarded the user's edits causes: see
616    /// [`Self::converge_runs`].
617    pub(crate) fn arm_converge(&mut self) {
618        self.converge = Some((Settle::of(&self.engine), 0));
619    }
620
621    /// Called once a frame. After `Self::arm_converge`, once a run has
622    /// applied and the user has not edited since: when the document equals its
623    /// clean baseline to within `CONVERGE_TOLERANCE` in every number (mates
624    /// re-solved the poses the discarded edit had moved, to ~1e-9), the solved
625    /// document becomes the baseline, as a Save's would. A real change is far
626    /// outside the tolerance and leaves the tab changed.
627    pub fn converge_runs(&mut self) {
628        let Some((last, runs)) = self.converge else {
629            return;
630        };
631        let now = Settle::of(&self.engine);
632        if now.serial != last.serial || runs >= CONVERGE_RUNS {
633            self.converge = None;
634            return;
635        }
636        if now.generation == last.generation || self.engine.run_pending() {
637            return;
638        }
639        let current = signature(&self.engine);
640        let near = self.saved_signature.as_deref().is_some_and(|saved| {
641            match (serde_json::from_str::<serde_json::Value>(saved), serde_json::from_str::<serde_json::Value>(&current)) {
642                (Ok(saved), Ok(current)) => nearly_equal(&without_derived(saved), &without_derived(current)),
643                _ => false,
644            }
645        });
646        if near {
647            if self.saved_signature.as_deref() != Some(current.as_str()) {
648                self.saved_signature = Some(current);
649                self.saved_sources = Some(sources_of(self.engine.history.parts_library()));
650                self.baseline_generation += 1;
651                self.baseline_content = Some(content_key(&self.engine));
652                self.marker_key = None;
653            }
654            self.converge = None;
655        } else {
656            self.converge = Some((now, runs + 1));
657        }
658    }
659
660    pub(crate) fn save_signature(&self) -> String { signature(&self.engine) }
661
662    /// The workspace folder this tab was opened from ([`Self::plm_folder`]'s field).
663    pub(crate) fn plm_folder(&self) -> Option<&(String, String)> {
664        self.plm_folder.as_ref()
665    }
666
667    /// The tab was opened (or reloaded) from the stored `text`.
668    pub(crate) fn note_opened_from(&mut self, text: &str) {
669        self.opened_from = Some(raw_hash(text));
670    }
671
672    /// Whether the store's `text` is still the text this tab was opened from:
673    /// a byte compare, not the document's, which the open's own runs have
674    /// written back into (snapshots, a first mate solve).
675    pub(crate) fn holds_stored(&self, text: &str) -> bool {
676        self.opened_from == Some(raw_hash(text))
677    }
678
679    pub(crate) fn set_plm_folder(&mut self, folder: Option<(String, String)>) {
680        self.plm_folder = folder;
681    }
682
683    /// The clean baseline's top-level parts library, `{entry: (sourceKey,
684    /// sourceSignature)}` (empty for a recovered, never-saved tab), without
685    /// parsing the saved document when the baseline was taken from the engine.
686    pub(crate) fn saved_sources(&self) -> SavedSources {
687        match &self.saved_sources {
688            Some(sources) => sources.clone(),
689            None => self
690                .saved_signature
691                .as_deref()
692                .and_then(|saved| serde_json::from_str::<serde_json::Value>(saved).ok())
693                .map(|saved| sources_of(&saved["partsLibrary"]))
694                .unwrap_or_default(),
695        }
696    }
697
698    /// The clean baseline as a document (`None` for a recovered, never-saved
699    /// one): what this tab last opened or saved.
700    pub(crate) fn saved_document(&self) -> Option<serde_json::Value> {
701        serde_json::from_str(self.saved_signature.as_deref()?).ok()
702    }
703
704    /// Take `baseline` (what [`Self::saved_document`] returned, changed the
705    /// way the document itself just was) as the clean baseline: a write that
706    /// is not the user's change adds no unsaved change, and the user's own
707    /// unsaved changes stay unsaved. `key` is [`Self::edit_key`] before the write.
708    pub(crate) fn rebase_saved_document(&mut self, baseline: &serde_json::Value, key: (u64, u64)) {
709        self.saved_signature = Some(baseline.to_string());
710        // Not the engine's own state: the sources are read from it on demand.
711        self.saved_sources = None;
712        self.baseline_generation += 1;
713        self.baseline_content = None;
714        if self.marker_key == Some(key) {
715            self.marker_key = Some(self.edit_key());
716        }
717    }
718
719    /// [`Self::save_signature`] of the document with one block left out: what a
720    /// copy saved without that block has as its clean baseline.
721    pub(crate) fn save_signature_without(&self, block: &str) -> String {
722        signature_without(&self.engine, Some(block))
723    }
724
725    pub(crate) fn mark_saved_signature(&mut self, saved: String) {
726        self.saved_signature = Some(saved);
727        self.saved_sources = None;
728        self.baseline_generation += 1;
729        self.baseline_content = None;
730        self.marker_key = None;
731        self.refresh_dirty_marker();
732    }
733
734    /// Restored from crash recovery and not saved since: it has no clean
735    /// baseline, and what differs from its stored document is the user's
736    /// unsaved work, not an older copy to refresh.
737    pub fn is_recovered(&self) -> bool {
738        self.saved_signature.is_none()
739    }
740
741    /// Its Save did not reach the store after all (a write-behind backend
742    /// reported the failure once `write` had returned `Ok`): unsaved again, so
743    /// the close prompt asks and Save writes it. A later Save that lands takes
744    /// a new baseline as any Save does.
745    pub(crate) fn mark_write_failed(&mut self) {
746        self.mark_saved_signature(String::new());
747    }
748
749    /// Dirty = the live model differs from the last saved/opened baseline.
750    /// (Rolling the history does NOT change the request document, so navigating
751    /// steps never marks dirty — only real edits/add/delete/reorder do.)
752    /// The workbench the document is in is not part of it (`signature`).
753    ///
754    /// HONEST but not free: it serializes the whole request document, which for
755    /// an assembly carrying an embedded parts library is megabytes. Every place
756    /// where being wrong would cost the user work — the close prompt, Save —
757    /// calls THIS. The per-frame tab dot calls [`Self::dirty_marker`] instead.
758    pub fn is_dirty(&self) -> bool {
759        match &self.saved_signature {
760            Some(saved) => *saved != signature(&self.engine),
761            None => true,
762        }
763    }
764
765    /// What moves when the saved document can have changed: the APPLIED RUN
766    /// generation and the history's revision.
767    ///
768    /// Both, because each misses edits the other sees. An ordinary edit (a
769    /// param change, add, delete, reorder, undo) re-runs the history, but a
770    /// block write runs nothing — a drawing sheet, a PMI label move, an eCAD
771    /// edit, a BOM part-attribute edit — and moves only the revision, which
772    /// every write to the SAVED document moves, the `partsLibrary` block
773    /// included (it is held in a field beside the document and both its setters
774    /// tick the revision themselves). An object-metadata change (a workbench
775    /// change is not an unsaved change at all, `signature`) moves neither and can
776    /// leave the dot one edit behind: a marker briefly optimistic, never a lost
777    /// edit, since [`Self::is_dirty`] is recomputed honestly at the close prompt.
778    pub fn edit_key(&self) -> (u64, u64) {
779        (self.engine.applied_generation(), self.engine.history_revision())
780    }
781
782    /// Whether the document is still the baseline it took from itself (an
783    /// Open, a Save, or the open's runs settling).
784    pub(crate) fn is_its_baseline(&self) -> bool {
785        self.baseline_content == Some(content_key(&self.engine))
786    }
787
788    /// The cached dirty flag the tab strip draws. Recomputing it serializes
789    /// the whole document, so it is recomputed only when the
790    /// [`Self::edit_key`] moved, and, once the tab is marked unsaved, only when
791    /// a RUN moved it (an ordinary edit, an undo, a redo).
792    ///
793    /// The second rule is for drags. Dragging a block (a PMI label, a view on
794    /// a sheet) writes the document every frame and moves only the revision;
795    /// recomputing there serialized the document on every frame, 2.6 ms in a
796    /// release build on a 1.3 MB assembly. An unsaved tab stays unsaved while
797    /// only the revision moves, so a drag pays one serialization, on the frame
798    /// the dot lights. Param-slider drags re-run the history each frame and
799    /// still recompute each frame, as they always did.
800    ///
801    /// The residue is deliberate: a block edit that lands exactly back on the
802    /// saved bytes keeps the dot on until the next run or Save. Showing unsaved
803    /// when clean costs one needless Save; the opposite loses work, which is
804    /// the bug the revision key fixed. [`Self::is_dirty`] stays honest at the
805    /// close prompt either way.
806    pub fn refresh_dirty_marker(&mut self) {
807        let key = self.edit_key();
808        let previous = self.marker_key.replace(key);
809        if previous == Some(key) {
810            return;
811        }
812        let run_moved = previous.map_or(true, |(generation, _)| generation != key.0);
813        if self.dirty_marker && !run_moved {
814            return;
815        }
816        self.dirty_checks += 1;
817        self.dirty_marker = self.is_dirty();
818    }
819
820    /// Take a write that OPENING the document made — `before` and `after` are
821    /// the saved document either side of it, `key` the [`Self::edit_key`] before
822    /// it — as though the file had been saved that way: every top-level block
823    /// the write changed, and that was still as last saved, is moved in the
824    /// clean baseline too, and a tab dot that was current stays as it was.
825    ///
826    /// For an eCAD editor's first sight of an older board (`viewport::ecad`'s
827    /// `store`). Not [`Self::mark_clean`]: whatever else was unsaved before the
828    /// open stays unsaved. So the open changes nothing a document that needed no
829    /// bringing up would show — the honest [`Self::is_dirty`] and the dot alike.
830    pub fn absorb_open_write(&mut self, before: &serde_json::Value, after: &serde_json::Value, key: (u64, u64)) {
831        // Compared as the baseline was taken ([`signature`]): without the
832        // run's records, or a block holding saved rows never matches.
833        let compared = |document: &serde_json::Value| {
834            let mut document = document.clone();
835            without_run_record(&mut document);
836            document
837        };
838        let (before, after) = (&compared(before), &compared(after));
839        let rebased = self.saved_signature.as_deref().and_then(|saved| {
840            let mut base: serde_json::Value = serde_json::from_str(saved).ok()?;
841            let (base_map, before, after) = (base.as_object_mut()?, before.as_object()?, after.as_object()?);
842            for name in before.keys().chain(after.keys()) {
843                let (was, is) = (before.get(name), after.get(name));
844                if was == is || base_map.get(name) != was {
845                    continue;
846                }
847                match is {
848                    Some(value) => base_map.insert(name.clone(), value.clone()),
849                    None => base_map.shift_remove(name),
850                };
851            }
852            Some(base.to_string())
853        });
854        if let Some(rebased) = rebased {
855            self.saved_signature = Some(rebased);
856            self.saved_sources = None;
857            self.baseline_generation += 1;
858            self.baseline_content = None;
859        }
860        if self.marker_key == Some(key) {
861            self.marker_key = Some(self.edit_key());
862        }
863    }
864
865    /// How many times [`Self::refresh_dirty_marker`] has serialized the
866    /// document.
867    pub fn dirty_checks(&self) -> u64 {
868        self.dirty_checks
869    }
870
871    pub fn dirty_marker(&self) -> bool {
872        self.dirty_marker
873    }
874
875    /// The document's process-unique handle (identity across index shuffles).
876    pub fn id(&self) -> u64 {
877        self.id
878    }
879
880    /// The public handle (`doc_<epoch>_<nonce>`) automation names it by.
881    pub fn handle(&self) -> &str {
882        &self.handle
883    }
884
885    /// The document's committed revision: a per-document count that moves
886    /// whenever its `content_key` has moved since the last observation —
887    /// a history edit, undo and redo (they write the history), a run's
888    /// write-back (the applied generation), a block write and an object
889    /// metadata change (the stamp). A view change (camera, selection,
890    /// workbench, tab switch, an idle frame) moves none of the three.
891    ///
892    /// Why observation is enough: all three components are monotonic process
893    /// counters, so a content key never recurs, and any change between two
894    /// observations reads as a different key at the second one. Two commits
895    /// between observations count as one step — the value is an equality token
896    /// for "nothing was written since", never a count of writes.
897    pub fn committed_revision(&self) -> u64 {
898        let key = content_key(&self.engine);
899        let (seen, revision) = self.committed.get();
900        if seen == key {
901            return revision;
902        }
903        // The first observation of a document is its revision 1 (0 is never
904        // handed out, so an unobserved document cannot match a guess of 0).
905        let next = revision + 1;
906        self.committed.set((key, next));
907        next
908    }
909}
910
911/// Every open document + which one is active. Always holds AT LEAST ONE
912/// document: closing the last tab leaves a fresh untitled one in its place, so
913/// [`Documents::engine_mut`] is infallible and the shell never has to render a
914/// "no document" state that would be an empty viewport with extra steps.
915pub struct Documents {
916    work_part: Option<work_part::WorkPart>,
917    /// An ancestor sub-assembly to make the Work part once its assembly's run
918    /// lands: `(assembly tab id, component path, mode)`
919    /// ([`Documents::work_part_up_to`]).
920    work_part_next: Option<(u64, String, work_part::WorkPartMode)>,
921    /// The Work part readback's `context` map (every assembly solid outside
922    /// the work occurrence, in assembly coordinates), by (component path,
923    /// host scene fingerprint): automation reads it every frame.
924    work_part_context: std::cell::RefCell<Option<((String, u64), serde_json::Value)>>,
925    /// [`Documents::owned_modified_keys_of`]'s last answer: `(tab id, edit
926    /// key, baseline length)` and the keys.
927    owned_cache: std::cell::RefCell<Option<owned_save::OwnedCacheKey>>,
928    /// [`Documents::synced_signatures`]'s last answer, by (tab id, baseline).
929    synced_cache: std::cell::RefCell<Option<owned_save::SyncedCache>>,
930    /// The signature each entry added after a tab's baseline was first seen
931    /// with, by ((tab id, baseline generation), entry name).
932    learned_signatures: std::cell::RefCell<std::collections::HashMap<((u64, u64), String), String>>,
933    /// The newest state of every source open documents hold ([`live_link`]).
934    live: live_link::LiveLinks,
935    /// The store's spelling of a document identity
936    /// ([`crate::store::ModelStore::canonicalizer`]): a tab and a `sourceKey`
937    /// naming one file the same way.
938    canon: crate::store::Canonicalizer,
939    open: Vec<Document>,
940    active: usize,
941    /// How a new tab's engine is built (platform runner + persisted settings).
942    new_engine: EngineFactory,
943}
944
945impl Documents {
946    /// A session holding one fresh document built by `new_engine`.
947    pub fn new(new_engine: EngineFactory) -> Self {
948        let first = Document::fresh(new_engine(), crate::document_class::DocumentClass::Normal);
949        Self {
950            open: vec![first],
951            work_part: None,
952            work_part_next: None,
953            work_part_context: Default::default(),
954            owned_cache: Default::default(),
955            synced_cache: Default::default(),
956            learned_signatures: Default::default(),
957            live: Default::default(),
958            canon: std::rc::Rc::new(str::to_string),
959            active: 0,
960            new_engine,
961        }
962    }
963
964    /// A fresh engine for a document about to be opened — the caller loads into
965    /// it and hands the result to [`Self::open_document`].
966    ///
967    /// Seeded with the WHOLE of the session's settings, workbench included, so
968    /// a new tab continues what you were doing. The load that follows overrides
969    /// the workbench if the document names one (see the module header).
970    /// Build every later tab's engine through `wrap` as well: the app's live
971    /// PLM reconnect puts the new store's settings over the factory's.
972    pub fn wrap_engine_factory(&mut self, wrap: impl Fn(EngineState) -> EngineState + 'static) {
973        let old = std::mem::replace(&mut self.new_engine, Box::new(EngineState::new));
974        self.new_engine = Box::new(move || wrap(old()));
975    }
976
977    pub fn spawn_engine(&self) -> EngineState {
978        let mut engine = (self.new_engine)();
979        carry_settings(&self.engine().settings_json(), &mut engine, true);
980        // ...and the LIVE VIEWPORT SIZE, which decides how the document about to
981        // be loaded is FRAMED.
982        //
983        // A brand-new engine's camera is `ViewCamera::default()` — 800x600 —
984        // until the viewport tile draws it (`Viewport::show` is the only
985        // production `EngineState::resize`), and that is a whole frame after the
986        // load. But `load_model_and_fit` arms `pending_fit`, and the app pumps
987        // every open document at the TOP of the frame (`BrepApp::ui`), before
988        // the dock lays out and before the viewport draws. So when the run
989        // lands quickly — a warm process, a small document — the deferred
990        // `zoom_to_fit` fires against 800x600 and frames the model to the wrong
991        // ASPECT; when the run lands a frame later it fires against the real
992        // viewport. Same document, same window, two different cameras decided by
993        // a race with the background runner. Handing the engine the session's
994        // viewport size HERE, before anything is loaded into it, makes both
995        // orderings frame the same way. (The app-level one-shot at
996        // `BrepApp::first_run_framed` sits in the same place in the frame and is
997        // fixed by the same line.)
998        let (width, height) = self.viewport_size();
999        engine.resize(width, height);
1000        engine
1001    }
1002
1003    /// The session's 3D viewport in logical px, as the active engine last had it
1004    /// from [`crate::viewport::Viewport::show`]. Every document in a session
1005    /// draws into the SAME tile, so this is the size any new one will get.
1006    fn viewport_size(&self) -> (f64, f64) {
1007        let camera = &self.engine().camera;
1008        (camera.width, camera.height)
1009    }
1010
1011    /// The engine the user is editing: the active tab's, or — while a Work
1012    /// part is edited in place in that tab — the hosted part's
1013    /// ([`work_part`]). Save, the dirty dot and the tab identity stay the
1014    /// tab's own ([`Self::active`], [`Self::tab_engine`]).
1015    pub fn engine(&self) -> &EngineState {
1016        match self.hosted() {
1017            Some(doc) => &doc.engine,
1018            None => &self.open[self.active].engine,
1019        }
1020    }
1021
1022    pub fn engine_mut(&mut self) -> &mut EngineState {
1023        if self.work_part_in_place() {
1024            return &mut self.hosted_mut().unwrap().engine;
1025        }
1026        &mut self.open[self.active].engine
1027    }
1028
1029    /// The active TAB's own engine — the document Save writes. The same as
1030    /// [`Self::engine`] except while a Work part is edited in place, when this
1031    /// is the assembly.
1032    pub fn tab_engine(&self) -> &EngineState {
1033        &self.open[self.active].engine
1034    }
1035
1036    pub fn tab_engine_mut(&mut self) -> &mut EngineState {
1037        &mut self.open[self.active].engine
1038    }
1039
1040    /// The identity of what the panels and viewport are drawing: the hosted
1041    /// Work part's document while one is edited in place, else the active
1042    /// tab's. The shell resets its document-scoped state when this changes.
1043    pub fn view_id(&self) -> u64 {
1044        self.hosted().map_or_else(|| self.active_id(), Document::id)
1045    }
1046
1047    pub fn active(&self) -> &Document {
1048        &self.open[self.active]
1049    }
1050
1051    pub fn active_mut(&mut self) -> &mut Document {
1052        &mut self.open[self.active]
1053    }
1054
1055    /// The document being DRAWN and edited: the hosted Work part while one is
1056    /// edited in place, else the active tab ([`Self::active`] stays the tab,
1057    /// for its name, dirty state and Save).
1058    pub fn view(&self) -> &Document {
1059        self.hosted().unwrap_or(&self.open[self.active])
1060    }
1061
1062    pub fn view_mut(&mut self) -> &mut Document {
1063        if self.work_part_in_place() {
1064            return self.hosted_mut().unwrap();
1065        }
1066        &mut self.open[self.active]
1067    }
1068
1069    pub fn active_index(&self) -> usize {
1070        self.active
1071    }
1072
1073    /// The tab holding the document whose process-unique id is `id`.
1074    pub fn index_of_id(&self, id: u64) -> Option<usize> {
1075        self.open.iter().position(|doc| doc.id == id)
1076    }
1077
1078    /// The engine of the document whose public handle is `handle` (any tab).
1079    pub fn engine_of_handle_mut(&mut self, handle: &str) -> Option<&mut EngineState> {
1080        self.open.iter_mut().find(|doc| doc.handle == handle).map(|doc| &mut doc.engine)
1081    }
1082
1083    /// The tab whose public handle is `handle`.
1084    pub fn index_of_handle(&self, handle: &str) -> Option<usize> {
1085        self.open.iter().position(|doc| doc.handle == handle)
1086    }
1087
1088    /// The ACTIVE document's handle — the shell compares it frame to frame to
1089    /// notice a switch from ANY source (a tab click, a close, New, Open, Open
1090    /// Part, a crash-recovery restore) with one check instead of a hook per site.
1091    pub fn active_id(&self) -> u64 {
1092        self.open[self.active].id
1093    }
1094
1095    pub fn len(&self) -> usize {
1096        self.open.len()
1097    }
1098
1099    pub fn get(&self, index: usize) -> Option<&Document> {
1100        self.open.get(index)
1101    }
1102
1103    pub fn get_mut(&mut self, index: usize) -> Option<&mut Document> {
1104        self.open.get_mut(index)
1105    }
1106
1107    pub fn iter(&self) -> std::slice::Iter<'_, Document> {
1108        self.open.iter()
1109    }
1110
1111    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, Document> {
1112        self.open.iter_mut()
1113    }
1114
1115    /// Land every open document's finished runs; `true` while any of them still
1116    /// has work in flight, so the frame loop keeps pumping.
1117    ///
1118    /// EVERY open document is pumped, not just the active one: a run belongs to
1119    /// the engine that submitted it (each document owns its own runner), so a
1120    /// run still in flight when the user switches tabs must land in ITS
1121    /// document rather than be dropped or, worse, applied to whatever is on
1122    /// screen. An idle document's pump is a couple of empty `try_recv`s.
1123    ///
1124    /// The kernel's parts library is one store for every tab, and a pump can
1125    /// SUBMIT a run as well as land one: `EngineState::pump` re-runs after its
1126    /// runner refused a run for a library it no longer holds, after a ports
1127    /// edit moved a point, and when a mesh reconstruction lands (its STEP is
1128    /// imported, which writes the store into the document and runs). A submit hands the runner whatever library is
1129    /// in the store, and a run that lands mirrors the store it ran with into
1130    /// its document's own `partsLibrary` block. So a tab in the BACKGROUND that
1131    /// may do either — a run in flight, or a point move waiting — is pumped with
1132    /// ITS library installed, and the active document's is put back right after.
1133    /// (A STEP probe's reply only stashes what it found, and landing a run
1134    /// submits nothing, so those need no more than `run_pending`.)
1135    /// Pumped with the active one's, it resolved its components against another
1136    /// document's parts, and the run that landed wrote that into its own file.
1137    /// An idle background tab submits and lands nothing, so it costs nothing.
1138    pub fn pump_all(&mut self) -> bool {
1139        use brep_render::brep_kernel::parts_library_revision;
1140        let mut work_in_flight = false;
1141        let in_place = self.work_part_in_place();
1142        for index in 0..self.open.len() {
1143            // While a Work part is edited in place, its assembly tab is pumped
1144            // as a background document: the store holds the PART's library.
1145            let background = index != self.active || in_place;
1146            // Only a frame where something lands needs the document's own
1147            // library: a run in flight is otherwise polled and left, and
1148            // swapping the libraries both ways on every frame of it cost
1149            // ~30 ms a frame on l500 (a Work part edit in place).
1150            let doc = &mut self.open[index];
1151            let own_library = background
1152                && (doc.engine.run_landing()
1153                    || doc.engine.mesh_imports_pending()
1154                    || doc.engine.history.ports_follow_pending());
1155            let doc = &self.open[index];
1156            if own_library {
1157                let _t = crate::perf::trace("install_library_of");
1158                install_library_of(doc);
1159            }
1160            let revision = parts_library_revision();
1161            let doc = &mut self.open[index];
1162            let _t = crate::perf::trace(if own_library { "pump (landing, own library)" } else { "pump" });
1163            if background && !own_library && doc.engine.run_pending() {
1164                doc.engine.pump_holding_runs();
1165            } else {
1166                doc.engine.pump();
1167            }
1168            work_in_flight |= doc.engine.run_pending()
1169                || doc.engine.queries_pending()
1170                || doc.engine.mesh_imports_pending()
1171                || doc.engine.step_probes_pending()
1172                || doc.engine.topology_pending()
1173                || doc.engine.sheet_lines_pending();
1174            if own_library || (background && parts_library_revision() != revision) {
1175                self.install_active_library();
1176            }
1177        }
1178        // The hosted Work part (edited in place) is the foreground engine: the
1179        // store already holds its library.
1180        if let Some(doc) = self.hosted_mut() {
1181            doc.engine.pump();
1182            let engine = &doc.engine;
1183            work_in_flight |= engine.run_pending()
1184                || engine.queries_pending()
1185                || engine.mesh_imports_pending()
1186                || engine.step_probes_pending()
1187                || engine.topology_pending()
1188                || engine.sheet_lines_pending();
1189        }
1190        self.sync_work_part();
1191        self.begin_next_work_part();
1192        work_in_flight
1193    }
1194
1195    /// Compare identities the way the store does (the shell installs it).
1196    pub fn set_canonicalizer(&mut self, canon: crate::store::Canonicalizer) {
1197        self.canon = canon;
1198        self.forget_published();
1199    }
1200
1201    /// The tab holding the document `key` names, in the store's spelling.
1202    pub fn index_of_source(&self, key: &str) -> Option<usize> {
1203        let wanted = (self.canon)(key);
1204        self.open.iter().position(|doc| doc.name.as_deref().is_some_and(|name| (self.canon)(name) == wanted))
1205    }
1206
1207    /// The tab holding the document stored under `name`, if any.
1208    pub fn index_of(&self, name: &str) -> Option<usize> {
1209        self.open
1210            .iter()
1211            .position(|doc| doc.name.as_deref() == Some(name))
1212    }
1213
1214    /// Activate the tab already holding `name`; `false` when it is not open.
1215    /// The "focus the existing tab" half of open-or-focus.
1216    pub fn focus_named(&mut self, name: &str) -> bool {
1217        match self.index_of(name) {
1218            Some(index) => {
1219                self.activate(index);
1220                true
1221            }
1222            None => false,
1223        }
1224    }
1225
1226    /// Add `doc` as a new tab and make it active.
1227    pub fn open_document(&mut self, doc: Document) -> usize {
1228        let index = self.open_document_behind(doc);
1229        self.activate(index);
1230        index
1231    }
1232
1233    /// Add a tab WITHOUT activating it: the visible document, its panels and
1234    /// camera stay as they are (an agent's `cad.documents.create`). Its seed
1235    /// run lands as a background tab's does (`pump_all`).
1236    pub fn open_document_behind(&mut self, mut doc: Document) -> usize {
1237        if doc.name.is_none() {
1238            let taken: Vec<u32> = self.open.iter().filter(|d| d.name.is_none()).map(|d| d.untitled).collect();
1239            doc.untitled = (1..).find(|n| !taken.contains(n)).unwrap_or(1);
1240        }
1241        self.open.push(doc);
1242        self.open.len() - 1
1243    }
1244
1245    /// Route an ENGINE-ONLY automation command to background tab `index`:
1246    /// for the length of one handler call, `index` stands in as the active
1247    /// document (so `engine()` / `engine_mut()` / `active()` resolve to it)
1248    /// with its own parts library in the kernel's store. Nothing the user
1249    /// sees moves — no settings carry, no live-link publish, no panel reset —
1250    /// because [`Self::route_end`] puts everything back before the frame
1251    /// draws. Returns the token `route_end` takes. Callers refuse routing
1252    /// while a Work part is edited in place (its redirect would win).
1253    pub(crate) fn route_begin(&mut self, index: usize) -> usize {
1254        let visible = self.active;
1255        self.active = index;
1256        install_library_of(&self.open[index]);
1257        visible
1258    }
1259
1260    pub(crate) fn route_end(&mut self, visible: usize) {
1261        self.active = visible.min(self.open.len().saturating_sub(1));
1262        self.install_active_library();
1263    }
1264
1265    /// Number the untitled tabs 1, 2, … in tab order. Only for a session being
1266    /// built before anyone has seen its tabs — the autosave restore, which adds
1267    /// the recovered documents beside the boot seed and then closes the seed,
1268    /// so the seed's "untitled" must not push a recovered tab to "untitled 2".
1269    pub(crate) fn renumber_untitled(&mut self) {
1270        for (n, doc) in self.open.iter_mut().filter(|d| d.name.is_none()).enumerate() {
1271            doc.untitled = n as u32 + 1;
1272        }
1273    }
1274
1275    /// Make tab `index` active, carrying the session's display settings over to
1276    /// it. Out-of-range indices are ignored (a stale click never panics).
1277    pub fn activate(&mut self, index: usize) {
1278        if index >= self.open.len() || index == self.active {
1279            return;
1280        }
1281        if self.work_part.is_some() {
1282            if let Err(error) = self.finish_work_part() {
1283                self.engine_mut().push_notice(format!("Work part: {error}"));
1284                return;
1285            }
1286        }
1287        let settings = self.open[self.active].engine.settings_json();
1288        self.publish_live(self.active);
1289        self.active = index;
1290        carry_settings(&settings, &mut self.open[index].engine, false);
1291        self.pull_live(index);
1292        self.install_active_library();
1293    }
1294
1295    /// Put the ACTIVE document's parts library into the kernel's store.
1296    ///
1297    /// That store is one per thread, not one per document: every tab's engine
1298    /// resolves its ACOMP features against it and hands it to its runner, and a
1299    /// document seeds it only as it loads. So opening a second document — a New
1300    /// tab is enough — replaced it, and switching back left the assembly running
1301    /// against the other document's parts. Its components lost every connection
1302    /// point, and the next Diagram wire read "has no connection point named '2'
1303    /// in port 'Pins'" and took the harness connections already drawn with it
1304    /// (the eCAD workflow audit, issue 13). The block in the document's own
1305    /// history is the library that document last ran with, so it is the one to
1306    /// put back; an entry the store already holds unchanged is kept as it is,
1307    /// heal included (`install_parts_library`).
1308    fn install_active_library(&self) {
1309        install_library_of(self.hosted().unwrap_or(&self.open[self.active]));
1310    }
1311
1312    /// Close tab `index`. Closing the LAST document leaves a fresh untitled one
1313    /// (the always-one-document invariant); closing a tab before the active one
1314    /// keeps the same document active at its new index.
1315    ///
1316    /// The caller is responsible for the unsaved-changes prompt — this is the
1317    /// mechanical close (`panels::file` owns the confirmation).
1318    pub fn close(&mut self, index: usize) {
1319        if index >= self.open.len() {
1320            return;
1321        }
1322        if self.work_part.as_ref().is_some_and(|session| {
1323            let id = self.open[index].id();
1324            id == session.assembly_id || id == session.part_id
1325        }) {
1326            self.engine_mut().push_notice("Return to assembly before closing a Work part session document");
1327            return;
1328        }
1329        // Taken BEFORE the removal: if the closing tab was the active one, its
1330        // settings are the session's and must survive into whatever is shown next.
1331        let settings = self.open[self.active].engine.settings_json();
1332        // Same reason as `spawn_engine`: a refill built from the factory starts
1333        // on the 800x600 default camera, so carry the live viewport size too.
1334        let viewport = self.viewport_size();
1335        let closed_active = index == self.active;
1336        // A tab closed with its changes SAVED leaves them to the linked
1337        // documents; one closed with them discarded does not.
1338        if closed_active && !self.open[index].is_dirty() {
1339            self.publish_live(index);
1340        }
1341        let closed = self.open.remove(index);
1342        self.forget_live(closed.id());
1343        // The replacement for a session closed down to nothing is a brand-new
1344        // tab, so it takes the WHOLE of the session's settings — workbench
1345        // included — exactly as `New` does through `spawn_engine`.
1346        let refilled = self.open.is_empty();
1347        if refilled {
1348            let mut engine = (self.new_engine)();
1349            carry_settings(&settings, &mut engine, true);
1350            self.open.push(Document::fresh(engine, crate::document_class::DocumentClass::Normal));
1351            self.active = 0;
1352            self.open[0].engine.resize(viewport.0, viewport.1);
1353        } else if closed_active {
1354            self.active = index.min(self.open.len() - 1);
1355        } else if index < self.active {
1356            self.active -= 1;
1357        }
1358        if closed_active {
1359            let active = self.active;
1360            carry_settings(&settings, &mut self.open[active].engine, refilled);
1361            self.pull_live(active);
1362            self.install_active_library();
1363        }
1364    }
1365
1366    /// Refresh every tab's dirty dot (see [`Document::refresh_dirty_marker`]).
1367    /// The write of document `name` failed after its Save returned: the tabs
1368    /// showing it (any spelling of the same identity) read unsaved again.
1369    /// Whether one did.
1370    pub fn mark_write_failed(&mut self, store: &dyn crate::store::ModelStore, name: &str) -> bool {
1371        let failed = store.canonical_identity(name);
1372        let mut marked = false;
1373        for doc in &mut self.open {
1374            if doc.name().is_some_and(|n| store.canonical_identity(n) == failed) {
1375                doc.mark_write_failed();
1376                marked = true;
1377            }
1378        }
1379        marked
1380    }
1381
1382    pub fn refresh_dirty_markers(&mut self) {
1383        for doc in &mut self.open {
1384            owned_save::note_inserted_copies(doc);
1385            doc.settle_open_runs();
1386            doc.converge_runs();
1387            doc.refresh_dirty_marker();
1388        }
1389    }
1390}
1391
1392/// Put `doc`'s own parts library — the block in its history, the library it
1393/// last ran with — into the kernel's store (`Documents::install_active_library`).
1394fn install_library_of(doc: &Document) {
1395    let library = serde_json::from_value(doc.engine.history.parts_library().clone()).unwrap_or_default();
1396    brep_render::brep_kernel::install_parts_library(&library);
1397}
1398
1399/// Copy the SESSION-scoped display settings (theme, UI scale, colors, wireframe,
1400/// projection, lod…) from a `settings_json()` snapshot into `target`.
1401/// `with_workbench` is true ONLY when seeding a brand-new engine — see the
1402/// module header for why activation must never carry it.
1403fn carry_settings(settings_json: &str, target: &mut EngineState, with_workbench: bool) {
1404    let Ok(mut settings) = serde_json::from_str::<serde_json::Value>(settings_json) else {
1405        return;
1406    };
1407    if !with_workbench {
1408        if let Some(object) = settings.as_object_mut() {
1409            object.remove("workbench");
1410        }
1411    }
1412    let _ = target.apply_settings_json(&settings.to_string());
1413}
1414
1415/// Hand out the next document handle. A plain process counter: handles only ever
1416/// need to be distinct WITHIN a session, and they never reach storage.
1417fn next_document_id() -> u64 {
1418    use std::sync::atomic::{AtomicU64, Ordering};
1419    static NEXT: AtomicU64 = AtomicU64::new(1);
1420    NEXT.fetch_add(1, Ordering::Relaxed)
1421}
1422