BREP_app 0.4.0

The BREP CAD application: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame — native + wasm from one codebase.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
//! The dockable / tabbed side-panel layout — an `egui_tiles` tree that hosts
//! every side-panel section AND the 3D viewport as tiles the user can split,
//! tab, resize, and drag-rearrange (IDE-style), with the layout persisted.
//!
//! This is **workbench-agnostic**, and strictly so: EVERY pane lives in the
//! tree permanently, at whatever position the user dragged it to, and selecting
//! a workbench changes nothing but VISIBILITY. A pane the active workbench does
//! not claim ([`workbench::panel_visible`]) is hidden *in place* — never removed
//! and re-inserted — so a workbench switch can no longer re-arrange the layout.
//! Positions / tabs / splits come from one shared, persisted layout. New
//! workbench panes plug in with one [`PaneKind`] arm.
//!
//! Structure:
//! * [`PaneKind`] — the serde discriminant of a tile; carries NO state.
//! * [`DockState`] — owns the `Tree<PaneKind>`, load/save/reconcile, and the
//!   per-frame workbench visibility pass
//!   ([`DockState::apply_workbench_visibility`]). One field on `BrepApp`.
//! * [`DockBehavior`] — a transient, per-frame `egui_tiles::Behavior` built from
//!   disjoint `&mut` borrows of the app's panels + engine (see [`DockContext`]);
//!   its `pane_ui` just delegates to each panel's existing `show(...)`.
//!
//! The shell draws the tree ONLY in normal modeling mode. In sketch / ref-select
//! mode it bypasses the tree and draws the viewport directly (see `app.rs`), so
//! the side panes simply don't appear — no reliance on container-visibility
//! edge cases.

use eframe::egui;
use egui_tiles::{
    Behavior, Container, EditAction, TabState, Tile, TileId, Tiles, Tree, UiResponse,
};
use serde::{Deserialize, Serialize};

use crate::document::Documents;
use crate::panels::assembly_constraints::AssemblyConstraintsPanel;
use crate::panels::component_actions::ComponentActionRequest;
use crate::panels::bom::BomPanel;
use crate::panels::document_tabs::TabsOutcome;
use crate::panels::expressions::ExpressionsPanel;
use crate::panels::history::HistoryPanel;
use crate::panels::scene::ScenePanel;
use crate::panels::update_components::UpdateComponents;
use crate::panels::wire_harness::WireHarnessPanel;
use crate::panels::pmi::PmiPanel;
use crate::store::{ModelStore, DOCK_LAYOUT_KEY};
use crate::viewport::Viewport;
use crate::workbench;

/// One tile in the dock tree. A pure discriminant — every panel's real state
/// lives on its own struct (a field of `BrepApp`), reached in `pane_ui`.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub enum PaneKind {
    /// ONE OPEN MODEL's 3D view, keyed by [`crate::document::Document::id`].
    ///
    /// These are the document tabs: they all live in a single `Tabs` container
    /// — the DOCUMENT GROUP — whose tab bar IS the model switcher, so the pane
    /// showing 3D views is tabbed by egui_tiles itself rather than carrying a
    /// second hand-drawn strip inside it.
    ///
    /// The id is process-unique and therefore meaningless in a RELOADED layout;
    /// [`DockState::sync_document_panes`] renumbers whatever it finds onto the
    /// live documents, which is what makes the persisted layout survive.
    Document(u64),
    History,
    AssemblyConstraints,
    Bom,
    /// The wire-harness connection list (claimed by the Wire harness
    /// workbench).
    WireHarness,
    /// The PMI view tree (claimed by the PMI workbench).
    Pmi,
    Scene,
    Expressions,
}

impl PaneKind {
    /// The side panes in default TAB-STRIP order (excludes the viewport): the
    /// three unclaimed panes first, then the workbench-claimed ones. Every one
    /// of them is in the tree at all times — the workbench only hides them — so
    /// this is the order of the default left-hand tab strip, left to right.
    const SIDE: [PaneKind; 7] = [
        PaneKind::History,
        PaneKind::Scene,
        PaneKind::Expressions,
        PaneKind::AssemblyConstraints,
        PaneKind::Bom,
        PaneKind::WireHarness,
        PaneKind::Pmi,
    ];

    /// The side panes an automation caller can name — [`Self::SIDE`] under a
    /// public name, so `describe_panes` / `show_pane` enumerate the dock rather
    /// than keeping a second list of it.
    pub const ALL: [PaneKind; 7] = Self::SIDE;

    /// Human tab title.
    pub fn title(self) -> &'static str {
        match self {
            // Only a fallback: the real per-document title (file name + dirty
            // marker) comes from `DockBehavior::tab_title_for_pane`, which can
            // reach the open documents.
            PaneKind::Document(_) => "3D View",
            PaneKind::History => "History",
            // The component TREE. It was titled "BOM" before the BOM
            // existed; now that there is a real columned parts list next to
            // it, the honest name is what it draws.
            PaneKind::Bom => "BOM",
            PaneKind::AssemblyConstraints => "Constraints",
            PaneKind::WireHarness => "Wire Harness",
            PaneKind::Pmi => "PMI",
            PaneKind::Scene => "Scene",
            PaneKind::Expressions => "Expressions",
        }
    }

    /// The workbench-registry panel id this pane is claimed under, or `None` for
    /// the viewport (which is not a workbench-filterable panel). Must match the
    /// ids used in `app.rs`'s old `panel_visible` gates + `workbench::assembly`.
    fn panel_id(self) -> Option<&'static str> {
        match self {
            PaneKind::Document(_) => None,
            PaneKind::History => Some("history"),
            PaneKind::Bom => Some(workbench::assembly::BOM_PANEL_ID),
            PaneKind::AssemblyConstraints => Some(workbench::assembly::CONSTRAINTS_PANEL_ID),
            PaneKind::WireHarness => Some(workbench::wire_harness::PANEL_ID),
            PaneKind::Pmi => Some(workbench::pmi::PANEL_ID),
            PaneKind::Scene => Some("scene"),
            PaneKind::Expressions => Some("expressions"),
        }
    }

    /// [`Self::visible_in`] under a public name, so `show_pane` can refuse a
    /// pane the active workbench does not carry instead of no-op'ing.
    pub fn visible_under_workbench(self, wb: &str) -> bool {
        self.visible_in(wb)
    }

    /// Whether this pane is visible under workbench `wb`. The viewport is always
    /// visible; side panes defer to the workbench claim system.
    fn visible_in(self, wb: &str) -> bool {
        match self.panel_id() {
            None => true,
            Some(id) => workbench::panel_visible(wb, id),
        }
    }
}

/// The dock layout: the tile tree + a dirty flag so a user layout edit persists.
/// One field on `BrepApp`.
pub struct DockState {
    tree: Tree<PaneKind>,
    /// Set by [`DockBehavior::on_edit`] when the user drags / resizes a tile;
    /// drained in [`DockState::ui`] to persist the new layout. A workbench
    /// switch never sets it: visibility is derived per frame, not stored state.
    dirty: bool,
    /// Per-pane `(kind, visible, rendered-this-frame)` from the last `ui()` — the
    /// source for the `__brepDock` verifier global. EVERY pane is listed, always:
    /// `visible` is false for one the active workbench does not claim (it keeps
    /// its place in the tree), and `rendered` is false for a pane sitting behind
    /// an inactive tab (egui_tiles skips its `pane_ui`), so an e2e script knows
    /// to switch workbench and/or activate that tab before asserting on its
    /// widgets.
    snapshot: Vec<(PaneKind, bool, bool)>,
}

/// The disjoint `&mut` borrows the dock needs to draw a frame — assembled by the
/// shell from `BrepApp`'s fields (all distinct, so the borrow checker allows it).
pub struct DockContext<'a> {
    /// The open documents. The dock reaches the ACTIVE engine through
    /// `docs.engine_mut()` — a borrow of one FIELD, so it still composes with
    /// the disjoint panel borrows beside it (see `crate::document`).
    pub docs: &'a mut Documents,
    pub viewport: &'a mut Viewport,
    pub history: &'a mut HistoryPanel,
    pub bom: &'a mut BomPanel,
    pub assembly_constraints: &'a mut AssemblyConstraintsPanel,
    pub wire_harness: &'a mut WireHarnessPanel,
    pub pmi: &'a mut PmiPanel,
    pub scene: &'a mut ScenePanel,
    pub expressions: &'a mut ExpressionsPanel,
    pub update_components: &'a mut UpdateComponents,
    pub model_store: &'a dyn ModelStore,
}

/// What a dock frame hands back to the shell — the SAME cross-panel requests the
/// old left-panel closure bubbled out (borrows inside prevent acting there).
#[derive(Default)]
pub struct DockOutcome {
    /// The ACOMP palette pick asked to open the component-selector modal.
    pub insert_component_requested: bool,
    /// A structure-tree Edit asked to expand this feature in the history tree.
    pub feature_focus: Option<String>,
    /// Structure-tree row interactions (Move / Edit-in-place / Open Part).
    /// A document-level component flow a pane's row menu asked for (the BOM's;
    /// the engine-mutating half already ran in the shared dispatcher).
    pub component_request: Option<ComponentActionRequest>,
    /// What the DOCUMENT TAB STRIP inside the viewport tile was clicked for —
    /// acted on by the shell, which owns the unsaved-changes prompt (close) and
    /// the shared-panel reset (activate).
    pub document_tabs: TabsOutcome,
}

impl DockState {
    /// Load the persisted layout (reconciled against the current pane set), or
    /// fall back to the default layout.
    pub fn new(store: &dyn ModelStore) -> Self {
        let tree = store
            .read(DOCK_LAYOUT_KEY)
            .and_then(|json| serde_json::from_str::<Tree<PaneKind>>(&json).ok())
            .filter(salvageable)
            .unwrap_or_else(default_tree);
        Self {
            tree,
            dirty: false,
            snapshot: Vec::new(),
        }
    }

    /// Draw the dock tree, delegating each visible pane to its panel's `show`.
    /// Applies workbench visibility first, then persists if the user re-laid it.
    pub fn ui(&mut self, ui: &mut egui::Ui, ctx: DockContext<'_>) -> DockOutcome {
        let wb = ctx.docs.engine().settings.workbench.clone();
        self.apply_workbench_visibility(&wb);
        // One tab per open model, active tab = active model. Must run BEFORE the
        // draw so a document opened or closed last frame is already reflected in
        // the bar the user is about to see.
        if self.sync_document_panes(ctx.docs) {
            self.dirty = true;
        }
        // Restore the group's exclusivity, so a pane the user dropped in there
        // last frame never gets a second frame among the document tabs.
        if self.evict_foreign_panes_from_document_group() {
            self.dirty = true;
        }

        // Snapshot the document identity before the behavior takes `&mut docs`,
        // so the post-draw tab-click read has something to compare against.
        let active_id = ctx.docs.active_id();
        let document_ids: Vec<u64> = ctx.docs.iter().map(|d| d.id()).collect();

        let store = ctx.model_store;
        let mut behavior = DockBehavior {
            docs: ctx.docs,
            viewport: ctx.viewport,
            history: ctx.history,
            bom: ctx.bom,
            assembly_constraints: ctx.assembly_constraints,
            wire_harness: ctx.wire_harness,
            pmi: ctx.pmi,
            scene: ctx.scene,
            expressions: ctx.expressions,
            update_components: ctx.update_components,
            model_store: ctx.model_store,
            insert_component_requested: false,
            feature_focus: None,
            component_request: None,
            document_tabs: TabsOutcome::default(),
            tab_title_spacing: 0.0,
            layout_changed: false,
            rendered: Vec::new(),
        };
        behavior.tab_title_spacing = behavior.tab_title_spacing(ui.visuals());
        self.tree.ui(&mut behavior, ui);

        // A tab CLICK shows up as egui_tiles' own active tab disagreeing with
        // `Documents`; the shell resolves it by activating that document.
        behavior.document_tabs.activate = self.tab_bar_selection(active_id, &document_ids);

        let outcome = DockOutcome {
            insert_component_requested: behavior.insert_component_requested,
            feature_focus: behavior.feature_focus.take(),
            component_request: behavior.component_request.take(),
            document_tabs: std::mem::take(&mut behavior.document_tabs),
        };
        if behavior.layout_changed {
            self.dirty = true;
        }
        let rendered = std::mem::take(&mut behavior.rendered);
        drop(behavior);

        // Snapshot for the `__brepDock` verifier global (in-tree order).
        self.snapshot = self
            .tree
            .tiles
            .iter()
            .filter_map(|(id, tile)| match tile {
                Tile::Pane(kind) => Some((
                    *kind,
                    self.tree.tiles.is_visible(*id),
                    rendered.contains(kind),
                )),
                Tile::Container(_) => None,
            })
            .collect();

        // Persist the layout, but DEBOUNCED: `on_edit` fires every frame while a
        // tile is being drag-resized (the shares change per mouse-move), so only
        // serialize once the pointer is released — mirrors how the shell defers
        // `applied_ui_scale`. A dirty flag set mid-drag simply waits for release.
        if self.dirty && !ui.ctx().input(|i| i.pointer.any_down()) {
            self.save(store);
            self.dirty = false;
        }
        outcome
    }

    /// The `__brepDock` verifier global: `{active, panes:[{kind,visible,rendered}]}`.
    /// `active` is whether the dock owns the layout right now (false in sketch /
    /// ref-select mode, where the shell draws the viewport directly). When
    /// inactive, no side pane is rendered — the caller passes `active=false`.
    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
    pub fn state_json(&self, active: bool) -> String {
        let panes: Vec<serde_json::Value> = self
            .snapshot
            .iter()
            .map(|(kind, visible, rendered)| {
                serde_json::json!({
                    "kind": format!("{kind:?}"),
                    "visible": visible,
                    "rendered": active && *rendered,
                })
            })
            .collect();
        serde_json::json!({ "active": active, "panes": panes }).to_string()
    }

    /// Surface the pane of `kind` — make it the ACTIVE tab in its tab group so a
    /// pane sitting behind another tab becomes visible. No-op if it is already
    /// active. Used to bring the History tab forward when a feature is added (a
    /// context-bar create can happen while another side tab is showing), so the
    /// new row is actually seen (`app.rs`, paired with `history.focus_feature`).
    ///
    /// A pane the active WORKBENCH hides is left alone. Activating its tab would
    /// not show it — `Tabs::ensure_active` moves `active` back to a VISIBLE tab
    /// during layout — but it would drag the user off whatever tab they were on
    /// and onto the first visible one, which is worse than doing nothing. Every
    /// caller today is already gated on the workbench that claims the pane, and
    /// the automation entry point refuses the call outright rather than no-op'ing
    /// (see `automation::cmd_shell::show_pane`); this keeps a future one honest.
    pub fn show_pane(&mut self, kind: PaneKind) {
        match self.find_pane(kind) {
            Some(id) if self.tree.tiles.is_visible(id) => {}
            _ => return,
        }
        self.tree
            .make_active(|_id, tile| matches!(tile, Tile::Pane(k) if *k == kind));
    }

    /// Point the tree's VISIBILITY at the active workbench — the only thing
    /// selecting a workbench is allowed to change about the dock.
    ///
    /// Every pane stays exactly where the user put it; one the active workbench
    /// does not claim is merely hidden. Hiding is PROPAGATED up: a container
    /// whose every child ends up hidden is hidden too, so a claimed pane parked
    /// in its own split leaves behind neither an empty tab bar nor a dead strip
    /// of layout — which is what an earlier revision removed panes structurally
    /// to avoid, at the cost of forgetting their position on every switch.
    ///
    /// Runs EVERY frame rather than on workbench change, because a drag can
    /// create the very container that now needs hiding (drop the Constraints
    /// pane into its own split, then switch to Modeling). It is a walk of a
    /// tree with a dozen nodes, and it sets no dirty flag: visibility is
    /// derived from the workbench, never persisted state.
    fn apply_workbench_visibility(&mut self, wb: &str) {
        let Some(root) = self.tree.root() else {
            return;
        };
        self.refresh_visibility(root, wb);
        // The root is what the dock draws into: it shows even in the degenerate
        // case where the workbench claims none of what is in it.
        self.tree.tiles.set_visible(root, true);
    }

    /// The post-order half of [`Self::apply_workbench_visibility`]: set `id`'s
    /// visibility and answer whether its subtree has anything left to show.
    fn refresh_visibility(&mut self, id: TileId, wb: &str) -> bool {
        let visible = match self.tree.tiles.get(id) {
            Some(Tile::Pane(kind)) => kind.visible_in(wb),
            // `children_vec` first: the recursion needs `&mut tiles` back.
            // `|=` on `bool` does not short-circuit, so every child is visited
            // (each one has its OWN visibility to set, not just a vote here).
            Some(Tile::Container(container)) => {
                let mut any = false;
                for child in container.children_vec() {
                    any |= self.refresh_visibility(child, wb);
                }
                any
            }
            None => return false,
        };
        self.tree.tiles.set_visible(id, visible);
        visible
    }

    /// The tile id of the pane of `kind`, if present.
    fn find_pane(&self, kind: PaneKind) -> Option<TileId> {
        self.tree.tiles.iter().find_map(|(id, tile)| match tile {
            Tile::Pane(k) if *k == kind => Some(*id),
            _ => None,
        })
    }

    /// The DOCUMENT GROUP: the `Tabs` container whose tab bar is the model
    /// switcher. Identified by content — the container holding document panes —
    /// so it survives the user re-docking it anywhere in the tree.
    fn document_group(&self) -> Option<TileId> {
        let pane = self.tree.tiles.iter().find_map(|(id, tile)| {
            matches!(tile, Tile::Pane(PaneKind::Document(_))).then_some(*id)
        })?;
        let parent = self.tree.tiles.parent_of(pane)?;
        matches!(self.tree.tiles.get(parent), Some(Tile::Container(Container::Tabs(_))))
            .then_some(parent)
    }

    /// Match the document panes to the OPEN DOCUMENTS: one pane per document, in
    /// the documents' own order, with the active document's pane as the active
    /// tab.
    ///
    /// This is what lets the tab bar be egui_tiles' own rather than a strip drawn
    /// inside a pane. It also absorbs the id problem: `Document` ids are
    /// process-unique, so the panes in a RELOADED layout carry ids from a dead
    /// session. Rather than special-casing that, the pass simply rewrites
    /// whatever it finds onto the live documents — a restored layout keeps its
    /// shape (where the group sits, how wide it is) and gets this session's
    /// documents in it.
    ///
    /// Returns whether the tree changed, so the caller can persist.
    fn sync_document_panes(&mut self, docs: &Documents) -> bool {
        let Some(group) = self.document_group() else {
            return false;
        };
        let wanted: Vec<u64> = docs.iter().map(|d| d.id()).collect();
        let present: Vec<(TileId, u64)> = match self.tree.tiles.get(group) {
            Some(Tile::Container(Container::Tabs(tabs))) => tabs
                .children
                .iter()
                .filter_map(|id| match self.tree.tiles.get(*id) {
                    Some(Tile::Pane(PaneKind::Document(doc))) => Some((*id, *doc)),
                    _ => None,
                })
                .collect(),
            _ => return false,
        };

        let mut changed = false;

        // Re-key the panes we already have onto the wanted documents, in order.
        // A reloaded layout hits this path for every pane; a steady-state frame
        // hits it for none.
        for ((tile, current), want) in present.iter().zip(wanted.iter()) {
            if current != want {
                if let Some(Tile::Pane(kind)) = self.tree.tiles.get_mut(*tile) {
                    *kind = PaneKind::Document(*want);
                    changed = true;
                }
            }
        }

        // Too few panes: a document was opened. Too many: one was closed.
        for want in wanted.iter().skip(present.len()) {
            let tile = self.tree.tiles.insert_pane(PaneKind::Document(*want));
            if let Some(Tile::Container(container)) = self.tree.tiles.get_mut(group) {
                container.add_child(tile);
                changed = true;
            }
        }
        for (tile, _) in present.iter().skip(wanted.len()) {
            self.tree.remove_recursively(*tile);
            changed = true;
        }

        // Point the tab bar at the active document. Done every frame (not only
        // on change) because egui_tiles also moves `active` itself — when a tab
        // is closed, say — and the two must not drift apart.
        let active_id = docs.active_id();
        let active_tile = self.tree.tiles.iter().find_map(|(id, tile)| {
            matches!(tile, Tile::Pane(PaneKind::Document(d)) if *d == active_id).then_some(*id)
        });
        if let (Some(active_tile), Some(Tile::Container(Container::Tabs(tabs)))) =
            (active_tile, self.tree.tiles.get_mut(group))
        {
            if tabs.active != Some(active_tile) {
                tabs.set_active(active_tile);
            }
        }
        changed
    }

    /// Which document the tab bar is currently showing, if it disagrees with
    /// `Documents`. That disagreement is exactly how a TAB CLICK reaches us:
    /// egui_tiles moves its own `active` when the user clicks, and the shell
    /// then activates that document (which `sync_document_panes` will agree with
    /// on the next frame).
    /// Takes an id SNAPSHOT rather than `&Documents` because the live
    /// `Documents` is mutably borrowed by the behavior while the tree draws.
    fn tab_bar_selection(&self, active_id: u64, ids: &[u64]) -> Option<usize> {
        let group = self.document_group()?;
        let Some(Tile::Container(Container::Tabs(tabs))) = self.tree.tiles.get(group) else {
            return None;
        };
        let Some(Tile::Pane(PaneKind::Document(id))) = self.tree.tiles.get(tabs.active?) else {
            return None;
        };
        (*id != active_id).then(|| ids.iter().position(|d| d == id))?
    }

    /// Turf any pane that is not a document out of the DOCUMENT GROUP.
    ///
    /// The group's tab bar must list open models and nothing else. egui_tiles
    /// offers no hook to refuse a drop into a container — `Behavior` can say a
    /// tile is not draggable, which stops a document tab being torn OUT, but
    /// nothing stops a side pane being dropped IN. So the invariant is restored
    /// after the fact instead: a pane dropped in there is moved back to the side
    /// column on the very same frame, before anything is drawn or persisted.
    ///
    /// Returns whether it moved anything, so the caller can persist the layout —
    /// otherwise the eviction would silently repeat on every reload.
    fn evict_foreign_panes_from_document_group(&mut self) -> bool {
        let Some(group) = self.document_group() else {
            return false;
        };
        let intruders: Vec<TileId> = match self.tree.tiles.get(group) {
            Some(Tile::Container(Container::Tabs(tabs))) => tabs
                .children
                .iter()
                .copied()
                .filter(|id| {
                    !matches!(self.tree.tiles.get(*id), Some(Tile::Pane(PaneKind::Document(_))))
                })
                .collect(),
            _ => return false,
        };
        if intruders.is_empty() {
            return false;
        }

        // Detach first, then re-home. The side home is looked up AFTER
        // detaching so it cannot be skewed by the intruders it is re-homing.
        if let Some(Tile::Container(container)) = self.tree.tiles.get_mut(group) {
            for id in &intruders {
                container.remove_child(*id);
            }
        }
        let target = self.side_home().or_else(|| self.tree.root());
        match target {
            Some(target) if target != group => {
                if let Some(Tile::Container(container)) = self.tree.tiles.get_mut(target) {
                    for id in &intruders {
                        container.add_child(*id);
                    }
                    return true;
                }
                self.put_back(group, &intruders);
                false
            }
            _ => {
                self.put_back(group, &intruders);
                false
            }
        }
    }

    /// Return detached panes to `group`. Losing a pane the user can no longer
    /// reach would be a worse outcome than the layout violation being fixed.
    fn put_back(&mut self, group: TileId, panes: &[TileId]) {
        if let Some(Tile::Container(container)) = self.tree.tiles.get_mut(group) {
            for id in panes {
                container.add_child(*id);
            }
        }
    }

    /// Where side panes belong: the container holding the MOST of them — the
    /// left tab strip in the default layout, or wherever the user has gathered
    /// them — preferring a `Tabs` when two containers tie. Never the document
    /// group (3D views own that one), so a pane re-homed here cannot land back
    /// among the model tabs.
    ///
    /// Identified by CONTENT rather than by shape, so it follows the user's
    /// arrangement instead of assuming the default one.
    fn side_home(&self) -> Option<TileId> {
        let group = self.document_group();
        // `Tiles::iter` walks a HashMap, so the ranking key has to break every
        // tie by itself or the answer wanders between runs: most side panes,
        // then a `Tabs` over a split, then the OLDEST tile (ids count up, so
        // reversing the id prefers the container that was there first).
        let mut best: Option<((usize, bool, std::cmp::Reverse<u64>), TileId)> = None;
        for (id, tile) in self.tree.tiles.iter() {
            let Tile::Container(container) = tile else {
                continue;
            };
            if Some(*id) == group {
                continue;
            }
            let side_panes = container
                .children()
                .filter(|child| {
                    matches!(
                        self.tree.tiles.get(**child),
                        Some(Tile::Pane(kind)) if !matches!(kind, PaneKind::Document(_))
                    )
                })
                .count();
            if side_panes == 0 {
                continue;
            }
            let rank = (
                side_panes,
                matches!(container, Container::Tabs(_)),
                std::cmp::Reverse(id.0),
            );
            if best.is_none_or(|(current, _)| rank > current) {
                best = Some((rank, *id));
            }
        }
        best.map(|(_, id)| id)
    }

    /// Serialize the layout through the unified persistence seam (best-effort).
    fn save(&self, store: &dyn ModelStore) {
        if let Ok(json) = serde_json::to_string(&self.tree) {
            let _ = store.write(DOCK_LAYOUT_KEY, &json);
        }
    }
}

/// The default layout: a horizontal split of `[ tabs(side panes) | viewport ]`.
///
/// Every side pane is a TAB in one full-height strip down the left, so a fresh
/// install opens on one titled pane using the whole height rather than seven
/// slivers stacked in a column. Splitting them apart is a drag away; gathering
/// them back is not obvious, which is why the tabbed arrangement is the default
/// and not the other way round.
fn default_tree() -> Tree<PaneKind> {
    let mut tiles = Tiles::default();
    let side: Vec<TileId> = PaneKind::SIDE
        .into_iter()
        .map(|k| tiles.insert_pane(k))
        .collect();
    let side_container = tiles.insert_tab_tile(side);
    // A placeholder document: ids are process-unique, so the real one is put in
    // by `sync_document_panes` on the first frame. It lives in a `Tabs`
    // container from the start — that container IS the document tab bar.
    let placeholder = tiles.insert_pane(PaneKind::Document(0));
    let viewport = tiles.insert_tab_tile(vec![placeholder]);
    let root = tiles.insert_horizontal_tile(vec![side_container, viewport]);
    // Bias the root split so the side column starts narrow (relative shares).
    if let Some(Tile::Container(Container::Linear(linear))) = tiles.get_mut(root) {
        linear.shares.set_share(side_container, 0.30);
        linear.shares.set_share(viewport, 0.70);
    }
    Tree::new("brep-dock", root, tiles)
}

/// Whether a deserialized tree still describes the CURRENT pane set: a root, at
/// least one document pane, and EVERY [`PaneKind::SIDE`] pane. `false` → the
/// caller uses [`default_tree`] instead.
///
/// A layout with no document pane has nowhere to put the 3D views and no record
/// of where the group belonged. (The document COUNT is not checked: a saved
/// layout legitimately holds as many as were open, and `sync_document_panes`
/// renumbers them onto this session's documents.)
///
/// A layout missing a SIDE pane is DISCARDED, not patched. Nothing this code
/// writes can lack one — side tabs don't close, an evicted pane is re-homed,
/// and neither simplify nor GC drops a hidden tile — so such a file was written
/// by a retired scheme (the workbench used to DELETE the panes it didn't claim,
/// which is exactly the layout amnesia this module no longer has) and it holds
/// no opinion about where the missing panes belong. Guessing one produces a
/// layout nobody chose; the default layout is at least the documented one. A
/// future pane addition resets saved layouts by the same rule.
fn salvageable(tree: &Tree<PaneKind>) -> bool {
    let Some(_) = tree.root() else {
        return false;
    };
    let mut documents = false;
    let mut side = std::collections::HashSet::new();
    for tile in tree.tiles.tiles() {
        match tile {
            Tile::Pane(PaneKind::Document(_)) => documents = true,
            Tile::Pane(kind) => {
                side.insert(*kind);
            }
            Tile::Container(_) => {}
        }
    }
    documents && PaneKind::SIDE.iter().all(|kind| side.contains(kind))
}

/// The per-frame `egui_tiles::Behavior`: draws each pane by delegating to the
/// owning panel's existing `show(...)`, and collects the cross-panel requests +
/// a layout-edit flag for the shell to act on after `Tree::ui`.
struct DockBehavior<'a> {
    docs: &'a mut Documents,
    viewport: &'a mut Viewport,
    history: &'a mut HistoryPanel,
    bom: &'a mut BomPanel,
    assembly_constraints: &'a mut AssemblyConstraintsPanel,
    wire_harness: &'a mut WireHarnessPanel,
    pmi: &'a mut PmiPanel,
    scene: &'a mut ScenePanel,
    expressions: &'a mut ExpressionsPanel,
    update_components: &'a mut UpdateComponents,
    model_store: &'a dyn ModelStore,
    // --- outputs, drained after Tree::ui -----------------------------------
    insert_component_requested: bool,
    feature_focus: Option<String>,
    component_request: Option<ComponentActionRequest>,
    document_tabs: TabsOutcome,
    /// The tab bar's own title spacing, captured at construction from the live
    /// visuals. `on_tab_button` gets no `Ui`, and it needs this to reproduce
    /// egui_tiles' close-button geometry for the verifier's hit rect.
    tab_title_spacing: f32,
    layout_changed: bool,
    /// Panes whose `pane_ui` ran this frame (drawn = visible AND, if tabbed, the
    /// active tab) — feeds the `__brepDock` snapshot.
    rendered: Vec<PaneKind>,
}

/// Whether `tile_id` is a DOCUMENT tab. That single predicate is the whole rule
/// for the document group: such a tab closes (its `✕` shuts the model) and
/// cannot be dragged (tearing it out would put a 3D view outside the group).
fn is_document_tile(tiles: &Tiles<PaneKind>, tile_id: TileId) -> bool {
    matches!(tiles.get(tile_id), Some(Tile::Pane(PaneKind::Document(_))))
}

impl<'a> Behavior<PaneKind> for DockBehavior<'a> {
    fn pane_ui(
        &mut self,
        ui: &mut egui::Ui,
        _tile_id: TileId,
        pane: &mut PaneKind,
    ) -> UiResponse {
        self.rendered.push(*pane);
        // Paint the side-pane background with the SAME fill the old
        // `Panel::left("brep-controls")` used (`visuals().panel_fill`), so the
        // docked panels read exactly like the previous side panel — not the
        // egui_tiles default (which leaves the pane transparent over the darker
        // central fill). The viewport paints its own 3D, so skip it.
        if !matches!(*pane, PaneKind::Document(_)) {
            let visuals = ui.visuals();
            ui.painter()
                .rect_filled(ui.max_rect(), 0.0, visuals.panel_fill);
        }
        match *pane {
            // Only the ACTIVE document's pane is ever drawn — egui_tiles shows
            // one tab at a time, and the tab bar was pointed at the active
            // document by `sync_document_panes` before this ran. The 3D body
            // keeps its own click/drag (camera orbit + picking), so we NEVER
            // report a pane drag here.
            PaneKind::Document(_) => {
                self.viewport.show(ui, self.docs.engine_mut());
            }
            PaneKind::History => scroll(ui, "dock-history", |ui| {
                self.history.show(ui, self.docs.engine_mut());
                // The ACOMP palette pick opens the COMPONENT SELECTOR, not a bare
                // feature dialog — bubbled to the shell (the file dialog is shell-owned).
                self.insert_component_requested |= self.history.take_insert_component_request();
            }),
            PaneKind::Bom => {
                // VERTICAL only, even though a BOM is as wide as its configured
                // columns: the column tree owns its own HORIZONTAL scrolling,
                // because a scroll area out here would carry the frozen columns
                // away with everything else. (The shared `scroll` helper is
                // vertical-only too, but the BOM wants `auto_shrink` off.)
                egui::ScrollArea::vertical()
                    .id_salt("dock-bom")
                    .auto_shrink([false, false])
                    .show(ui, |ui| {
                        let outcome = self.bom.show(
                            ui,
                            self.docs.engine_mut(),
                            self.model_store,
                            self.update_components,
                        );
                        if outcome.focus.is_some() {
                            // The BOM's Edit action: roll to the owning feature
                            // and open it in the history panel.
                            self.feature_focus = outcome.focus;
                        }
                        if outcome.component.is_some() {
                            self.component_request = outcome.component;
                        }
                    });
            }
            PaneKind::AssemblyConstraints => scroll(ui, "dock-constraints", |ui| {
                self.assembly_constraints.show(
                    ui,
                    self.docs.engine_mut(),
                    self.model_store,
                    self.update_components,
                );
            }),
            PaneKind::WireHarness => {
                // Vertical only, like the BOM: the column tree owns its own
                // horizontal scrolling (a frozen column must not scroll away).
                egui::ScrollArea::vertical()
                    .id_salt("dock-wire-harness")
                    .auto_shrink([false, false])
                    .show(ui, |ui| {
                        self.wire_harness.show(ui, self.docs.engine_mut());
                    });
            }
            PaneKind::Pmi => scroll(ui, "dock-pmi", |ui| {
                self.pmi.show(ui, self.docs.engine_mut());
            }),
            PaneKind::Scene => scroll(ui, "dock-scene", |ui| {
                self.scene.show(ui, self.docs.engine_mut());
            }),
            PaneKind::Expressions => {
                // Expressions self-scrolls (its own ScrollArea) — no outer wrap.
                self.expressions.show(ui, self.docs.engine_mut());
            }
        }
        UiResponse::None
    }

    /// A document tab is titled by its FILE, with a bullet while it has unsaved
    /// changes — the tab bar is the only place that state is visible now that
    /// several models are open at once. Every other pane keeps its fixed title.
    fn tab_title_for_pane(&mut self, pane: &PaneKind) -> egui::WidgetText {
        match pane {
            PaneKind::Document(id) => match self.docs.iter().find(|d| d.id() == *id) {
                Some(doc) => {
                    let title = doc.title();
                    // U+2022, not U+25CF: the icon font draws the latter as a
                    // hollow ring, which reads as a status light rather than
                    // "unsaved".
                    if doc.dirty_marker() {
                        format!("{title} \u{2022}").into()
                    } else {
                        title.into()
                    }
                }
                // A pane whose document is gone is about to be removed by
                // `sync_document_panes`; it must not panic in the meantime.
                None => pane.title().into(),
            },
            _ => pane.title().into(),
        }
    }

    /// Only a DOCUMENT tab closes — that is the model's `✕`. Side panels have no
    /// re-open affordance, so they are shown/hidden by workbench and rearranged
    /// by drag, never destroyed.
    fn is_tab_closable(&self, tiles: &Tiles<PaneKind>, tile_id: TileId) -> bool {
        is_document_tile(tiles, tile_id)
    }

    /// A `✕` click. We REFUSE the removal (`false`) and hand the request to the
    /// shell instead: closing a model has to run the unsaved-changes prompt and
    /// drop the document, and only then does its pane go — removed by
    /// `sync_document_panes`. Letting egui_tiles delete the tile here would
    /// close the tab while leaving the document open.
    fn on_tab_close(&mut self, tiles: &mut Tiles<PaneKind>, tile_id: TileId) -> bool {
        if let Some(Tile::Pane(PaneKind::Document(id))) = tiles.get(tile_id) {
            if let Some(index) = self.docs.iter().position(|d| d.id() == *id) {
                self.document_tabs.close = Some(index);
            }
        }
        false
    }

    /// Publish each document tab's screen rect for the headed verifier, keyed
    /// `doctab:<index>` exactly as the old hand-drawn strip did, so the existing
    /// browser checks drive the real tab bar unchanged. This is the hook the
    /// default tab renderer offers for precisely this — it hands back the tab
    /// button's own `Response`, so we keep egui_tiles' native tab drawing.
    fn on_tab_button(
        &mut self,
        tiles: &mut Tiles<PaneKind>,
        tile_id: TileId,
        button_response: egui::Response,
    ) -> egui::Response {
        if let Some(Tile::Pane(PaneKind::Document(id))) = tiles.get(tile_id) {
            if let Some(index) = self.docs.iter().position(|d| d.id() == *id) {
                let tab = button_response.rect;
                // The `✕` is not routed through this hook (egui_tiles calls it
                // once per tab, with the whole tab), so its rect is DERIVED the
                // same way the default tab renderer lays it out: a
                // `close_button_outer_size` square, right-centered in the tab
                // inset by the title spacing. Both inputs come from this same
                // `Behavior`, so an override moves the published rect with it.
                let close = egui::Align2::RIGHT_CENTER.align_size_within_rect(
                    egui::Vec2::splat(self.close_button_outer_size()),
                    tab.shrink(self.tab_title_spacing),
                );
                self.document_tabs.hits.push((format!("doctab:{index}"), tab));
                self.document_tabs
                    .hits
                    .push((format!("doctab:{index}:close"), close));
            }
        }
        button_response
    }

    /// A document tab can't be picked up: dragging one out would tear a 3D view
    /// into its own container somewhere else in the tree, which is the mirror
    /// image of the violation `evict_foreign_panes_from_document_group` guards —
    /// the group must be the ONLY home for 3D views, as well as holding nothing
    /// but them. Side panes drag freely to re-dock.
    fn is_tile_draggable(&self, tiles: &Tiles<PaneKind>, tile_id: TileId) -> bool {
        !is_document_tile(tiles, tile_id)
    }

    fn on_edit(&mut self, _edit_action: EditAction) {
        self.layout_changed = true;
    }

    /// Every pane gets its own tab bar — that tab is the label AND the drag
    /// handle, so a default vertical stack still reads as titled, re-dockable
    /// panes (egui_tiles gives bare linear panes neither). Other simplifications
    /// stay at their defaults so the tree tidies itself after a drag / a
    /// workbench-membership removal.
    fn simplification_options(&self) -> egui_tiles::SimplificationOptions {
        egui_tiles::SimplificationOptions {
            all_panes_must_have_tabs: true,
            ..Default::default()
        }
    }

    /// Match the tab strip to the old side panel's fill (`panel_fill`) so a docked
    /// panel reads as one continuous surface (tab bar + body) in the SAME colour
    /// the previous `Panel::left` used — not the egui_tiles default strip colour.
    fn tab_bar_color(&self, visuals: &egui::Visuals) -> egui::Color32 {
        visuals.panel_fill
    }

    /// Give EVERY tab a visible chip so it reads as a tab — egui_tiles' default
    /// leaves inactive tabs fully transparent (they vanish into the strip). Reuse
    /// egui's standard widget fills: the active tab uses the "active" fill (it
    /// stands out as selected), inactive tabs the "inactive" resting fill (a muted
    /// but clearly-there chip). No hand-picked colours — same DRY rule as the rest.
    fn tab_bg_color(
        &self,
        visuals: &egui::Visuals,
        _tiles: &Tiles<PaneKind>,
        _tile_id: TileId,
        state: &TabState,
    ) -> egui::Color32 {
        if state.active {
            visuals.widgets.active.bg_fill
        } else {
            visuals.widgets.inactive.bg_fill
        }
    }
}

/// Wrap a pane body in its own vertical scroll area (unique id per pane so egui
/// never conflates their scroll state). Panels that self-scroll skip this.
fn scroll(ui: &mut egui::Ui, salt: &str, add: impl FnOnce(&mut egui::Ui)) {
    egui::ScrollArea::vertical()
        .id_salt(salt)
        .auto_shrink([false, false])
        .show(ui, add);
}

// BREP private tests: 8b4a90a0167e6b15