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 ecad;
16
17/// Builds a fresh engine for a new document — the platform runner, the viewcube,
18/// and the persisted display settings, all applied before anything is loaded
19/// into it. Injected by the shell so tests (which need the SYNCHRONOUS inline
20/// runner) can construct documents without a background thread.
21pub type EngineFactory = Box<dyn Fn() -> EngineState>;
22
23/// Whether a document may be edited. Every file-based document is
24/// [`Access::Editable`]; a document opened from a PLM is [`Access::ReadOnly`]
25/// until its revision is checked out by this user (plan S3, D2), and a released
26/// revision always is.
27///
28/// Held by the engine's history ([`brep_render::history::History::lock`]),
29/// which refuses every change to the saved document while it is read-only —
30/// the one door every edit passes, so no panel has to remember to ask.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum Access {
33    Editable,
34    /// `reason` is the sentence the user reads: "revision B is released and
35    /// cannot change".
36    ReadOnly { reason: String },
37}
38
39impl Access {
40    pub fn read_only(reason: impl Into<String>) -> Self {
41        Access::ReadOnly { reason: reason.into() }
42    }
43
44    pub fn is_editable(&self) -> bool {
45        matches!(self, Access::Editable)
46    }
47}
48
49/// The empty model a **New** document starts from.
50pub const EMPTY_DOCUMENT: &str = r#"{"expressions":"","configurator":{},"features":[]}"#;
51
52/// ONE open model: the engine that owns it plus the identity the file lane needs
53/// — the store name it was opened from / saved to, and the clean baseline.
54pub struct Document {
55    /// The windowing-agnostic brain for THIS document (scene, camera, history,
56    /// settings, selection). Panels borrow it; it is never forked.
57    pub engine: EngineState,
58    /// The store identity (`None` = a never-saved "untitled" model). The RAW
59    /// identity, not the display name — a native dialog hands back a full path
60    /// and a plain Save must write back to it.
61    name: Option<String>,
62    /// The model request JSON as of the last New / Open / Save — the baseline
63    /// the dirty flag compares the live history against.
64    saved_signature: Option<String>,
65    /// The cached tab-strip dirty dot. See [`Document::dirty_marker`] for why
66    /// this is not simply `is_dirty()`.
67    dirty_marker: bool,
68    /// The [`Document::edit_key`] `dirty_marker` was last refreshed at.
69    marker_key: Option<(u64, u64)>,
70    /// How many times the marker has serialized the document to recompute
71    /// itself — the per-frame cost [`Document::refresh_dirty_marker`] bounds.
72    dirty_checks: u64,
73    /// A process-unique handle, so the shell can notice "the active document is
74    /// a different one now" without comparing indices (closing a tab BEFORE the
75    /// active one moves the index without changing the document).
76    id: u64,
77    /// This document's eCAD editors — Diagram, PCB, Symbol and Pads — kept
78    /// beside its engine, so each tab has its own and a tab switch keeps their
79    /// pan, zoom and view: a switch rebuilds the PANELS
80    /// (`reset_document_scoped_state`), never a document. Built with the
81    /// document; all four measured 0.65 ms (release), so no document waits for
82    /// its first eCAD workbench to have them.
83    pub ecad: crate::workbench::ecad::Editors,
84    /// Each editor's standing with its block of this document's history: what
85    /// takes BREP's undo and redo to the editor, and the editor's edits into the
86    /// document ([`ecad::BlockSync`]).
87    pub ecad_blocks: [ecad::BlockSync; 4],
88    pub ecad_parts_revision: Option<u64>,
89    /// The broken-reference lines [`crate::panels::ecad_parts::sync`] has
90    /// already put in front of the user. A device whose part is missing is a
91    /// STANDING state and the revision bumps on every edit, so without this it
92    /// would toast on every keystroke — the same rule
93    /// [`ecad::BlockSync::unreported`] keeps for an UNLINKED component.
94    pub ecad_parts_reported: Vec<String>,
95    /// What [`crate::panels::ecad_parts::follow_occurrences`] last saw of the
96    /// assembly's occurrences; `None` until the first frame looks.
97    pub ecad_occurrences: Option<crate::panels::ecad_parts::OccurrenceMark>,
98    /// The parts-library entries whose saved part has moved on since this
99    /// document took it — the shell's `UpdateComponents` list for the active
100    /// document, handed over each frame so the Diagram and PCB workbenches can
101    /// mark the components placed from them and offer the update where the
102    /// user is looking (`viewport::ecad`).
103    pub ecad_outdated: Vec<String>,
104    /// Set by the eCAD host's Update parts button; the shell runs the update
105    /// (`UpdateComponents::run`, one undo step) on its next frame.
106    pub ecad_update_requested: bool,
107    /// The history's refused-edit count as of the last
108    /// [`Document::take_refused`], so each refusal is told once.
109    refused_seen: u64,
110}
111
112/// What the dirty flag compares: the saved document ([`EngineState::history_request_json`])
113/// WITHOUT its `workbench`.
114///
115/// The workbench is saved, so a file reopens where it was left, but it is view state
116/// and not work. Counting it made Close ask to discard documents nobody had edited:
117/// open a board saved in PCB, look at its Diagram, and the saved document differed
118/// from the file in exactly `/workbench` (the eCAD re-audit's B5, measured in lane X).
119/// The tab's dot never counted it ([`Document::edit_key`] does not move for it), so
120/// the prompt came with no dot. Now the two agree, and Save still writes the field.
121///
122/// Built as `history_request_json` builds the saved document, less the one field,
123/// rather than by parsing that again: the dot recomputes this on every run-moving
124/// edit, and a second parse of a megabyte assembly doubles it. A test holds the two
125/// together (`the_signature_is_the_saved_document_less_its_workbench`).
126fn signature(engine: &EngineState) -> String {
127    let mut document: serde_json::Value =
128        serde_json::from_str(&engine.history.request_json()).unwrap_or_else(|_| serde_json::json!({}));
129    if let Some(object) = document.as_object_mut() {
130        if !engine.metadata.is_empty() {
131            object.insert("metadata".into(), engine.metadata.to_json());
132        }
133    }
134    document.to_string()
135}
136
137/// One [`ecad::BlockSync`] per eCAD block, none of them pulled yet.
138fn ecad_blocks() -> [ecad::BlockSync; 4] {
139    use ecad::Block;
140    [Block::Diagram, Block::Pcb, Block::Symbol, Block::Pads].map(ecad::BlockSync::new)
141}
142
143impl Document {
144    /// Wrap `engine` as a document, taking its CURRENT model as the clean
145    /// baseline — so a freshly loaded (or freshly emptied) document is clean and
146    /// the first edit marks it dirty.
147    pub fn new(engine: EngineState) -> Self {
148        let saved_signature = Some(signature(&engine));
149        Self {
150            engine,
151            name: None,
152            saved_signature,
153            dirty_marker: false,
154            marker_key: None,
155            dirty_checks: 0,
156            id: next_document_id(),
157            ecad: crate::workbench::ecad::Editors::new(),
158            ecad_blocks: ecad_blocks(),
159            ecad_parts_revision: None,
160            ecad_parts_reported: Vec::new(),
161            ecad_occurrences: None,
162            ecad_outdated: Vec::new(),
163            ecad_update_requested: false,
164            refused_seen: 0,
165        }
166    }
167
168    /// Wrap `engine` as a document RESTORED from the autosave blob
169    /// (`crate::recovery`): it carries the store identity it had (`None` for
170    /// an untitled one) and NO clean baseline, so it is dirty from its first
171    /// frame — the work it holds is exactly what was never saved, and the close
172    /// guard and the tab dot must say so until a Save writes it somewhere.
173    pub fn recovered(engine: EngineState, name: Option<String>) -> Self {
174        Self {
175            engine,
176            name,
177            saved_signature: None,
178            dirty_marker: true,
179            marker_key: None,
180            dirty_checks: 0,
181            id: next_document_id(),
182            ecad: crate::workbench::ecad::Editors::new(),
183            ecad_blocks: ecad_blocks(),
184            ecad_parts_revision: None,
185            ecad_parts_reported: Vec::new(),
186            ecad_occurrences: None,
187            ecad_outdated: Vec::new(),
188            ecad_update_requested: false,
189            refused_seen: 0,
190        }
191    }
192
193    /// Whether this document may be edited ([`Access`]).
194    pub fn access(&self) -> Access {
195        match self.engine.history.locked() {
196            None => Access::Editable,
197            Some(reason) => Access::read_only(reason),
198        }
199    }
200
201    /// Make the document editable or read-only. Read-only locks the engine's
202    /// history, so its saved bytes cannot change until it is editable again.
203    pub fn set_access(&mut self, access: Access) {
204        match access {
205            Access::Editable => self.engine.history.unlock(),
206            Access::ReadOnly { reason } => self.engine.history.lock(reason),
207        }
208    }
209
210    /// The sentence to show when an edit was refused since the last call —
211    /// `None` when nothing was. Called once a frame by the shell, which toasts it.
212    pub fn take_refused(&mut self) -> Option<String> {
213        let refused = self.engine.history.refused_user_edits();
214        if refused == self.refused_seen {
215            return None;
216        }
217        self.refused_seen = refused;
218        let reason = self.engine.history.locked()?;
219        Some(format!("This document is read-only: {reason}."))
220    }
221
222    /// The raw store identity, or `None` for a never-saved document.
223    pub fn name(&self) -> Option<&str> {
224        self.name.as_deref()
225    }
226
227    pub fn set_name(&mut self, name: Option<String>) {
228        self.name = name;
229    }
230
231    /// The tab label: the bare display name, or `untitled`.
232    pub fn title(&self) -> String {
233        match &self.name {
234            Some(name) => crate::store::model_display_name(name),
235            None => "untitled".to_string(),
236        }
237    }
238
239    /// Snapshot the current model as the clean baseline (after New / Open /
240    /// Save, or a `?loadModel=` boot-load).
241    pub fn mark_clean(&mut self) {
242        self.saved_signature = Some(signature(&self.engine));
243        self.dirty_marker = false;
244        self.marker_key = Some(self.edit_key());
245    }
246
247    /// Dirty = the live model differs from the last saved/opened baseline.
248    /// (Rolling the history does NOT change the request document, so navigating
249    /// steps never marks dirty — only real edits/add/delete/reorder do.)
250    /// The workbench the document is in is not part of it ([`signature`]).
251    ///
252    /// HONEST but not free: it serializes the whole request document, which for
253    /// an assembly carrying an embedded parts library is megabytes. Every place
254    /// where being wrong would cost the user work — the close prompt, Save —
255    /// calls THIS. The per-frame tab dot calls [`Self::dirty_marker`] instead.
256    pub fn is_dirty(&self) -> bool {
257        match &self.saved_signature {
258            Some(saved) => *saved != signature(&self.engine),
259            None => true,
260        }
261    }
262
263    /// What moves when the saved document can have changed: the APPLIED RUN
264    /// generation and the history's revision.
265    ///
266    /// Both, because each misses edits the other sees. An ordinary edit (a
267    /// param change, add, delete, reorder, undo) re-runs the history, but a
268    /// block write runs nothing — a drawing sheet, a PMI label move, an eCAD
269    /// edit, a BOM part-attribute edit — and moves only the revision, which
270    /// every write to the SAVED document moves, the `partsLibrary` block
271    /// included (it is held in a field beside the document and both its setters
272    /// tick the revision themselves). An object-metadata change (a workbench
273    /// change is not an unsaved change at all, [`signature`]) moves neither and can
274    /// leave the dot one edit behind: a marker briefly optimistic, never a lost
275    /// edit, since [`Self::is_dirty`] is recomputed honestly at the close prompt.
276    pub fn edit_key(&self) -> (u64, u64) {
277        (self.engine.applied_generation(), self.engine.history_revision())
278    }
279
280    /// The cached dirty flag the tab strip draws. Recomputing it serializes
281    /// the whole document, so it is recomputed only when the
282    /// [`Self::edit_key`] moved, and, once the tab is marked unsaved, only when
283    /// a RUN moved it (an ordinary edit, an undo, a redo).
284    ///
285    /// The second rule is for drags. Dragging a block (a PMI label, a view on
286    /// a sheet) writes the document every frame and moves only the revision;
287    /// recomputing there serialized the document on every frame, 2.6 ms in a
288    /// release build on a 1.3 MB assembly. An unsaved tab stays unsaved while
289    /// only the revision moves, so a drag pays one serialization, on the frame
290    /// the dot lights. Param-slider drags re-run the history each frame and
291    /// still recompute each frame, as they always did.
292    ///
293    /// The residue is deliberate: a block edit that lands exactly back on the
294    /// saved bytes keeps the dot on until the next run or Save. Showing unsaved
295    /// when clean costs one needless Save; the opposite loses work, which is
296    /// the bug the revision key fixed. [`Self::is_dirty`] stays honest at the
297    /// close prompt either way.
298    pub fn refresh_dirty_marker(&mut self) {
299        let key = self.edit_key();
300        let previous = self.marker_key.replace(key);
301        if previous == Some(key) {
302            return;
303        }
304        let run_moved = previous.map_or(true, |(generation, _)| generation != key.0);
305        if self.dirty_marker && !run_moved {
306            return;
307        }
308        self.dirty_checks += 1;
309        self.dirty_marker = self.is_dirty();
310    }
311
312    /// Take a write that OPENING the document made — `before` and `after` are
313    /// the saved document either side of it, `key` the [`Self::edit_key`] before
314    /// it — as though the file had been saved that way: every top-level block
315    /// the write changed, and that was still as last saved, is moved in the
316    /// clean baseline too, and a tab dot that was current stays as it was.
317    ///
318    /// For an eCAD editor's first sight of an older board (`viewport::ecad`'s
319    /// `store`). Not [`Self::mark_clean`]: whatever else was unsaved before the
320    /// open stays unsaved. So the open changes nothing a document that needed no
321    /// bringing up would show — the honest [`Self::is_dirty`] and the dot alike.
322    pub fn absorb_open_write(&mut self, before: &serde_json::Value, after: &serde_json::Value, key: (u64, u64)) {
323        let rebased = self.saved_signature.as_deref().and_then(|saved| {
324            let mut base: serde_json::Value = serde_json::from_str(saved).ok()?;
325            let (base_map, before, after) = (base.as_object_mut()?, before.as_object()?, after.as_object()?);
326            for name in before.keys().chain(after.keys()) {
327                let (was, is) = (before.get(name), after.get(name));
328                if was == is || base_map.get(name) != was {
329                    continue;
330                }
331                match is {
332                    Some(value) => base_map.insert(name.clone(), value.clone()),
333                    None => base_map.remove(name),
334                };
335            }
336            Some(base.to_string())
337        });
338        if let Some(rebased) = rebased {
339            self.saved_signature = Some(rebased);
340        }
341        if self.marker_key == Some(key) {
342            self.marker_key = Some(self.edit_key());
343        }
344    }
345
346    /// How many times [`Self::refresh_dirty_marker`] has serialized the
347    /// document.
348    pub fn dirty_checks(&self) -> u64 {
349        self.dirty_checks
350    }
351
352    pub fn dirty_marker(&self) -> bool {
353        self.dirty_marker
354    }
355
356    /// The document's process-unique handle (identity across index shuffles).
357    pub fn id(&self) -> u64 {
358        self.id
359    }
360}
361
362/// Every open document + which one is active. Always holds AT LEAST ONE
363/// document: closing the last tab leaves a fresh untitled one in its place, so
364/// [`Documents::engine_mut`] is infallible and the shell never has to render a
365/// "no document" state that would be an empty viewport with extra steps.
366pub struct Documents {
367    open: Vec<Document>,
368    active: usize,
369    /// How a new tab's engine is built (platform runner + persisted settings).
370    new_engine: EngineFactory,
371}
372
373impl Documents {
374    /// A session holding ONE empty document built by `new_engine`.
375    pub fn new(new_engine: EngineFactory) -> Self {
376        let first = Document::new(new_engine());
377        Self {
378            open: vec![first],
379            active: 0,
380            new_engine,
381        }
382    }
383
384    /// A fresh engine for a document about to be opened — the caller loads into
385    /// it and hands the result to [`Self::open_document`].
386    ///
387    /// Seeded with the WHOLE of the session's settings, workbench included, so
388    /// a new tab continues what you were doing. The load that follows overrides
389    /// the workbench if the document names one (see the module header).
390    /// Build every later tab's engine through `wrap` as well: the app's live
391    /// PLM reconnect puts the new store's settings over the factory's.
392    pub fn wrap_engine_factory(&mut self, wrap: impl Fn(EngineState) -> EngineState + 'static) {
393        let old = std::mem::replace(&mut self.new_engine, Box::new(EngineState::new));
394        self.new_engine = Box::new(move || wrap(old()));
395    }
396
397    pub fn spawn_engine(&self) -> EngineState {
398        let mut engine = (self.new_engine)();
399        carry_settings(&self.engine().settings_json(), &mut engine, true);
400        // ...and the LIVE VIEWPORT SIZE, which decides how the document about to
401        // be loaded is FRAMED.
402        //
403        // A brand-new engine's camera is `ViewCamera::default()` — 800x600 —
404        // until the viewport tile draws it (`Viewport::show` is the only
405        // production `EngineState::resize`), and that is a whole frame after the
406        // load. But `load_model_and_fit` arms `pending_fit`, and the app pumps
407        // every open document at the TOP of the frame (`BrepApp::ui`), before
408        // the dock lays out and before the viewport draws. So when the run
409        // lands quickly — a warm process, a small document — the deferred
410        // `zoom_to_fit` fires against 800x600 and frames the model to the wrong
411        // ASPECT; when the run lands a frame later it fires against the real
412        // viewport. Same document, same window, two different cameras decided by
413        // a race with the background runner. Handing the engine the session's
414        // viewport size HERE, before anything is loaded into it, makes both
415        // orderings frame the same way. (The app-level one-shot at
416        // `BrepApp::first_run_framed` sits in the same place in the frame and is
417        // fixed by the same line.)
418        let (width, height) = self.viewport_size();
419        engine.resize(width, height);
420        engine
421    }
422
423    /// The session's 3D viewport in logical px, as the active engine last had it
424    /// from [`crate::viewport::Viewport::show`]. Every document in a session
425    /// draws into the SAME tile, so this is the size any new one will get.
426    fn viewport_size(&self) -> (f64, f64) {
427        let camera = &self.engine().camera;
428        (camera.width, camera.height)
429    }
430
431    pub fn engine(&self) -> &EngineState {
432        &self.open[self.active].engine
433    }
434
435    pub fn engine_mut(&mut self) -> &mut EngineState {
436        &mut self.open[self.active].engine
437    }
438
439    pub fn active(&self) -> &Document {
440        &self.open[self.active]
441    }
442
443    pub fn active_mut(&mut self) -> &mut Document {
444        &mut self.open[self.active]
445    }
446
447    pub fn active_index(&self) -> usize {
448        self.active
449    }
450
451    /// The ACTIVE document's handle — the shell compares it frame to frame to
452    /// notice a switch from ANY source (a tab click, a close, New, Open, Open
453    /// Part, a crash-recovery restore) with one check instead of a hook per site.
454    pub fn active_id(&self) -> u64 {
455        self.open[self.active].id
456    }
457
458    pub fn len(&self) -> usize {
459        self.open.len()
460    }
461
462    pub fn get(&self, index: usize) -> Option<&Document> {
463        self.open.get(index)
464    }
465
466    pub fn get_mut(&mut self, index: usize) -> Option<&mut Document> {
467        self.open.get_mut(index)
468    }
469
470    pub fn iter(&self) -> std::slice::Iter<'_, Document> {
471        self.open.iter()
472    }
473
474    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, Document> {
475        self.open.iter_mut()
476    }
477
478    /// Land every open document's finished runs; `true` while any of them still
479    /// has work in flight, so the frame loop keeps pumping.
480    ///
481    /// EVERY open document is pumped, not just the active one: a run belongs to
482    /// the engine that submitted it (each document owns its own runner), so a
483    /// run still in flight when the user switches tabs must land in ITS
484    /// document rather than be dropped or, worse, applied to whatever is on
485    /// screen. An idle document's pump is a couple of empty `try_recv`s.
486    ///
487    /// The kernel's parts library is one store for every tab, and a pump can
488    /// SUBMIT a run as well as land one: `EngineState::pump` re-runs after its
489    /// runner refused a run for a library it no longer holds, after a ports
490    /// edit moved a point, and when a mesh reconstruction lands (its STEP is
491    /// imported, which writes the store into the document and runs). A submit hands the runner whatever library is
492    /// in the store, and a run that lands mirrors the store it ran with into
493    /// its document's own `partsLibrary` block. So a tab in the BACKGROUND that
494    /// may do either — a run in flight, or a point move waiting — is pumped with
495    /// ITS library installed, and the active document's is put back right after.
496    /// (A STEP probe's reply only stashes what it found, and landing a run
497    /// submits nothing, so those need no more than `run_pending`.)
498    /// Pumped with the active one's, it resolved its components against another
499    /// document's parts, and the run that landed wrote that into its own file.
500    /// An idle background tab submits and lands nothing, so it costs nothing.
501    pub fn pump_all(&mut self) -> bool {
502        use brep_render::brep_kernel::parts_library_revision;
503        let mut work_in_flight = false;
504        for index in 0..self.open.len() {
505            let background = index != self.active;
506            let doc = &self.open[index];
507            let own_library = background
508                && (doc.engine.run_pending()
509                    || doc.engine.mesh_imports_pending()
510                    || doc.engine.history.ports_follow_pending());
511            if own_library {
512                install_library_of(doc);
513            }
514            let revision = parts_library_revision();
515            let doc = &mut self.open[index];
516            doc.engine.pump();
517            work_in_flight |= doc.engine.run_pending()
518                || doc.engine.queries_pending()
519                || doc.engine.mesh_imports_pending()
520                || doc.engine.step_probes_pending()
521                || doc.engine.topology_pending()
522                || doc.engine.sheet_lines_pending();
523            if own_library || (background && parts_library_revision() != revision) {
524                self.install_active_library();
525            }
526        }
527        work_in_flight
528    }
529
530    /// The tab holding the document stored under `name`, if any.
531    pub fn index_of(&self, name: &str) -> Option<usize> {
532        self.open
533            .iter()
534            .position(|doc| doc.name.as_deref() == Some(name))
535    }
536
537    /// Activate the tab already holding `name`; `false` when it is not open.
538    /// The "focus the existing tab" half of open-or-focus.
539    pub fn focus_named(&mut self, name: &str) -> bool {
540        match self.index_of(name) {
541            Some(index) => {
542                self.activate(index);
543                true
544            }
545            None => false,
546        }
547    }
548
549    /// Add `doc` as a new tab and make it active.
550    pub fn open_document(&mut self, doc: Document) -> usize {
551        self.open.push(doc);
552        let index = self.open.len() - 1;
553        self.activate(index);
554        index
555    }
556
557    /// Make tab `index` active, carrying the session's display settings over to
558    /// it. Out-of-range indices are ignored (a stale click never panics).
559    pub fn activate(&mut self, index: usize) {
560        if index >= self.open.len() || index == self.active {
561            return;
562        }
563        let settings = self.open[self.active].engine.settings_json();
564        self.active = index;
565        carry_settings(&settings, &mut self.open[index].engine, false);
566        self.install_active_library();
567    }
568
569    /// Put the ACTIVE document's parts library into the kernel's store.
570    ///
571    /// That store is one per thread, not one per document: every tab's engine
572    /// resolves its ACOMP features against it and hands it to its runner, and a
573    /// document seeds it only as it loads. So opening a second document — a New
574    /// tab is enough — replaced it, and switching back left the assembly running
575    /// against the other document's parts. Its components lost every connection
576    /// point, and the next Diagram wire read "has no connection point named '2'
577    /// in port 'Pins'" and took the harness connections already drawn with it
578    /// (the eCAD workflow audit, issue 13). The block in the document's own
579    /// history is the library that document last ran with, so it is the one to
580    /// put back; an entry the store already holds unchanged is kept as it is,
581    /// heal included (`install_parts_library`).
582    fn install_active_library(&self) {
583        install_library_of(&self.open[self.active]);
584    }
585
586    /// Close tab `index`. Closing the LAST document leaves a fresh untitled one
587    /// (the always-one-document invariant); closing a tab before the active one
588    /// keeps the same document active at its new index.
589    ///
590    /// The caller is responsible for the unsaved-changes prompt — this is the
591    /// mechanical close (`panels::file` owns the confirmation).
592    pub fn close(&mut self, index: usize) {
593        if index >= self.open.len() {
594            return;
595        }
596        // Taken BEFORE the removal: if the closing tab was the active one, its
597        // settings are the session's and must survive into whatever is shown next.
598        let settings = self.open[self.active].engine.settings_json();
599        // Same reason as `spawn_engine`: a refill built from the factory starts
600        // on the 800x600 default camera, so carry the live viewport size too.
601        let viewport = self.viewport_size();
602        let closed_active = index == self.active;
603        self.open.remove(index);
604        // The replacement for a session closed down to nothing is a brand-new
605        // tab, so it takes the WHOLE of the session's settings — workbench
606        // included — exactly as `New` does through `spawn_engine`.
607        let refilled = self.open.is_empty();
608        if refilled {
609            self.open.push(Document::new((self.new_engine)()));
610            self.active = 0;
611            self.open[0].engine.resize(viewport.0, viewport.1);
612        } else if closed_active {
613            self.active = index.min(self.open.len() - 1);
614        } else if index < self.active {
615            self.active -= 1;
616        }
617        if closed_active {
618            let active = self.active;
619            carry_settings(&settings, &mut self.open[active].engine, refilled);
620            self.install_active_library();
621        }
622    }
623
624    /// Refresh every tab's dirty dot (see [`Document::refresh_dirty_marker`]).
625    pub fn refresh_dirty_markers(&mut self) {
626        for doc in &mut self.open {
627            doc.refresh_dirty_marker();
628        }
629    }
630}
631
632/// Put `doc`'s own parts library — the block in its history, the library it
633/// last ran with — into the kernel's store (`Documents::install_active_library`).
634fn install_library_of(doc: &Document) {
635    let library = serde_json::from_value(doc.engine.history.parts_library().clone()).unwrap_or_default();
636    brep_render::brep_kernel::install_parts_library(&library);
637}
638
639/// Copy the SESSION-scoped display settings (theme, UI scale, colors, wireframe,
640/// projection, lod…) from a `settings_json()` snapshot into `target`.
641/// `with_workbench` is true ONLY when seeding a brand-new engine — see the
642/// module header for why activation must never carry it.
643fn carry_settings(settings_json: &str, target: &mut EngineState, with_workbench: bool) {
644    let Ok(mut settings) = serde_json::from_str::<serde_json::Value>(settings_json) else {
645        return;
646    };
647    if !with_workbench {
648        if let Some(object) = settings.as_object_mut() {
649            object.remove("workbench");
650        }
651    }
652    let _ = target.apply_settings_json(&settings.to_string());
653}
654
655/// Hand out the next document handle. A plain process counter: handles only ever
656/// need to be distinct WITHIN a session, and they never reach storage.
657fn next_document_id() -> u64 {
658    use std::sync::atomic::{AtomicU64, Ordering};
659    static NEXT: AtomicU64 = AtomicU64::new(1);
660    NEXT.fetch_add(1, Ordering::Relaxed)
661}
662