Skip to main content

gpui_base/dock/
dock_area.rs

1//! The dock area: the trees, the entity cache that mirrors them, and the
2//! reconciliation that keeps the two in step.
3
4use crate::TestSupportExt as _;
5use std::{
6    collections::{HashMap, HashSet},
7    rc::Rc,
8    sync::Arc,
9};
10
11use anyhow::Result;
12use gpui::{
13    AnyElement, AnyView, App, AppContext as _, Axis, Bounds, Context, Div, Empty, Entity,
14    EventEmitter, FocusHandle, Focusable, InteractiveElement as _, IntoElement, ParentElement,
15    Pixels, Point, Render, SharedString, Stateful, Styled as _, Subscription, WeakEntity, Window,
16    div, prelude::FluentBuilder as _, px,
17};
18
19use crate::{
20    ElementExt as _, LogicalStyledExt as _, Placement, ResizablePanelEvent, ResizableState,
21    ResizeHandleContext, h_resizable, resizable::PANEL_MIN_SIZE, resizable_panel, v_resizable,
22};
23
24use super::{
25    dock_placement::{Dock, DockSizing},
26    drag::{AnyDrag, DropTarget},
27    layout::{
28        DockLayout, EditResult, InsertTarget, NodeId, NodeKind, PaneNode, PaneRef, PaneTree,
29        PanelId, RootKind,
30    },
31    panel::{LivePanels, Panel, PanelEvent, PanelView},
32    registry::{PanelBuildContext, PanelRegistry},
33    state::{DockAreaState, DockPlacement, DockState, PanelInfo, PanelState},
34    state_convert::{PanelBuilder, PanelSource as _},
35    tab_group::{BareTabGroup, TabGroup, TabGroupConstraints, TabGroupEvent, TabGroupRenderer},
36};
37
38/// What the dock area reports outward.
39pub enum DockEvent {
40    /// The layout changed. Subscribe to persist it; this fires on every edit,
41    /// so a subscriber that writes to disk should debounce.
42    LayoutChanged,
43    /// A host-owned drag item was dropped inside the dock.
44    DragDrop { item: AnyDrag, target: DropTarget },
45}
46
47/// What fills the whole area, when something does.
48///
49/// A zoom names a *container*, never the panel inside it. The old dock zoomed
50/// the `TabPanel`: `TabPanel` is the only thing that ever emitted
51/// `PanelEvent::ZoomIn` — `subscribe_panel` was handed `StackPanel`s too, but
52/// those never zoom — so `set_zoomed_in` only ever received a whole tab panel,
53/// and a zoomed panel kept its tab bar, its toolbar and its menu. That is
54/// where the control that zooms back out lives. Naming the panel instead would
55/// strip all of it and leave the user with no way back.
56#[derive(Clone, Copy, PartialEq, Eq, Debug)]
57enum Zoomed {
58    /// A tab group, rendered whole through its own [`TabGroupRenderer`].
59    Group(NodeId),
60}
61
62/// One dock: its own layout tree plus the open/size/collapsible state.
63struct DockRegion {
64    tree: PaneTree,
65    dock: Dock,
66}
67
68/// A cached container entity together with the subscription that carries its
69/// intents back here. Kept as one value so dropping the cache entry drops the
70/// subscription with it.
71struct Cached<T> {
72    entity: Entity<T>,
73    _subscription: Subscription,
74}
75
76/// A split's cached `ResizableState`, plus the child order that state's panel
77/// list currently mirrors.
78///
79/// The order is what makes a reconcile index-precise. `ResizableState` keeps
80/// the authoritative size on `panels[ix]` and only ever consults the tree's
81/// size as an initial value, so appending and truncating at the tail —
82/// which is all `sync_panels_count` can do — leaves the survivors of a
83/// non-tail removal wearing their predecessors' widths.
84struct CachedSplit {
85    entity: Entity<ResizableState>,
86    children: Vec<NodeId>,
87    /// The tree sizes the state last adopted. A reconcile that finds them
88    /// unchanged leaves the state alone: re-adopting a `None` un-pins the
89    /// measurement the layout pass resolved it to, and the split re-flexes
90    /// although the edit never touched it.
91    sizes: Vec<Option<Pixels>>,
92    _subscription: Subscription,
93}
94
95/// The main area of the dock.
96///
97/// It owns one [`PaneTree`] per region and the entity cache that mirrors
98/// them. Nothing else turns a tree edit into live entities.
99pub struct DockArea {
100    id: SharedString,
101    version: Option<usize>,
102    bounds: Bounds<Pixels>,
103    this: WeakEntity<Self>,
104
105    center: PaneTree,
106    docks: HashMap<DockPlacement, DockRegion>,
107
108    groups: HashMap<NodeId, Cached<TabGroup>>,
109    splits: HashMap<NodeId, CachedSplit>,
110    panels: HashMap<PanelId, Arc<dyn PanelView>>,
111
112    locked: bool,
113    zoomed: Option<Zoomed>,
114    focus_handle: FocusHandle,
115    renderer: Rc<dyn DockAreaRenderer>,
116}
117
118impl DockArea {
119    /// An empty area that draws nothing but its panels.
120    ///
121    /// `id` names the area for the host's own persistence; `version` is
122    /// written into [`Self::dump`] and read back by [`Self::load`], for a host
123    /// that wants to reject or migrate a layout an older build wrote.
124    ///
125    /// Install appearance with [`Self::with_renderer`].
126    pub fn new(
127        id: impl Into<SharedString>,
128        version: Option<usize>,
129        _window: &mut Window,
130        cx: &mut Context<Self>,
131    ) -> Self {
132        PanelRegistry::init(cx);
133
134        Self {
135            id: id.into(),
136            version,
137            bounds: Bounds::default(),
138            this: cx.weak_entity(),
139            center: PaneTree::new(RootKind::Split),
140            docks: HashMap::new(),
141            groups: HashMap::new(),
142            splits: HashMap::new(),
143            panels: HashMap::new(),
144            locked: false,
145            zoomed: None,
146            focus_handle: cx.focus_handle(),
147            renderer: Rc::new(BareDockArea),
148        }
149    }
150
151    /// Install the appearance for this area and everything under it: the
152    /// renderer also supplies the [`TabGroupRenderer`] every group it builds
153    /// will use.
154    pub fn with_renderer(mut self, renderer: Rc<dyn DockAreaRenderer>) -> Self {
155        self.renderer = renderer;
156        self
157    }
158
159    pub fn id(&self) -> SharedString {
160        self.id.clone()
161    }
162
163    pub fn version(&self) -> Option<usize> {
164        self.version
165    }
166
167    /// Change the schema version a later [`dump`](Self::dump) writes.
168    ///
169    /// Set at construction for an area whose layout never changes shape. A
170    /// host that installs one of several preset layouts into the same area
171    /// picks the version with the preset, which is after the area exists.
172    pub fn set_version(&mut self, version: Option<usize>, cx: &mut Context<Self>) {
173        self.version = version;
174        cx.notify();
175    }
176
177    /// The area's own bounds, recorded each frame. Dock resizing measures
178    /// against it.
179    pub fn bounds(&self) -> Bounds<Pixels> {
180        self.bounds
181    }
182
183    /// The tree for one region, or `None` for a dock that does not exist.
184    ///
185    /// The `Option` is in the signature rather than hidden behind a panic
186    /// because a dock is genuinely optional — it is `Option<DockState>` in the
187    /// persisted schema — and there is no borrowable empty tree to hand back
188    /// for one that is absent.
189    pub fn layout(&self, placement: DockPlacement) -> Option<&PaneTree> {
190        match placement {
191            DockPlacement::Center => Some(&self.center),
192            _ => self.docks.get(&placement).map(|pane| &pane.tree),
193        }
194    }
195
196    /// The live view for a panel, if the dock still holds it.
197    pub fn panel(&self, panel: PanelId) -> Option<&Arc<dyn PanelView>> {
198        self.panels.get(&panel)
199    }
200
201    pub fn is_locked(&self) -> bool {
202        self.locked
203    }
204
205    /// Whether a region currently holds no visible panel.
206    ///
207    /// This is the question the old `DockItem::is_empty` answered, and it is
208    /// the same one [`Self::is_node_visible`] answers per container: a region
209    /// is empty when nothing in it would be drawn. A region that does not
210    /// exist — a dock that was never installed — is empty too.
211    pub fn is_empty(&self, placement: DockPlacement, cx: &App) -> bool {
212        self.layout(placement)
213            .is_none_or(|tree| !self.is_node_visible(tree.root(), cx))
214    }
215
216    /// Lock the layout against rearranging. Resizing stays available.
217    pub fn set_locked(&mut self, locked: bool, window: &mut Window, cx: &mut Context<Self>) {
218        if self.locked == locked {
219            return;
220        }
221        self.locked = locked;
222        // The lock is one of the facts every group is told, so it only takes
223        // effect once the groups have been re-told.
224        self.reconcile(window, cx);
225    }
226}
227
228/// Installing layouts: the center region and the three docks.
229impl DockArea {
230    /// Replace the center region with a described layout. Whatever was there
231    /// leaves the dock, so its panels are told [`Panel::on_removed`].
232    pub fn set_center(&mut self, layout: DockLayout, window: &mut Window, cx: &mut Context<Self>) {
233        let (tree, panels) = PaneTree::from_layout(layout, RootKind::Split);
234        self.center = tree;
235        self.panels.extend(panels);
236        self.reconcile(window, cx);
237        cx.emit(DockEvent::LayoutChanged);
238    }
239
240    /// Replace one dock with a described layout, creating the dock if the area
241    /// does not have one there yet. A new dock keeps the size and open state of
242    /// the one it replaces, so re-filling a dock does not resize it.
243    ///
244    /// [`DockPlacement::Center`] defers to [`Self::set_center`]: the center is
245    /// not a dock and has no size or open state of its own.
246    pub fn set_dock(
247        &mut self,
248        placement: DockPlacement,
249        layout: DockLayout,
250        window: &mut Window,
251        cx: &mut Context<Self>,
252    ) {
253        if placement == DockPlacement::Center {
254            return self.set_center(layout, window, cx);
255        }
256
257        let (tree, panels) = PaneTree::from_layout(layout, RootKind::Any);
258        let dock = self
259            .docks
260            .get(&placement)
261            .map(|pane| pane.dock)
262            .unwrap_or_else(|| Dock::new(PANEL_MIN_SIZE * 2.));
263        self.docks.insert(placement, DockRegion { tree, dock });
264        self.panels.extend(panels);
265        self.reconcile(window, cx);
266        cx.emit(DockEvent::LayoutChanged);
267    }
268
269    /// Take a dock away entirely, panels and all. Distinct from
270    /// [`Self::toggle_dock`], which only takes it off screen.
271    pub fn remove_dock(
272        &mut self,
273        placement: DockPlacement,
274        window: &mut Window,
275        cx: &mut Context<Self>,
276    ) {
277        if self.docks.remove(&placement).is_none() {
278            return;
279        }
280        // The dock's panels leave the dock entirely, so they are told, unlike
281        // the panels of a dock that merely closed.
282        self.reconcile(window, cx);
283        cx.emit(DockEvent::LayoutChanged);
284    }
285
286    pub fn has_dock(&self, placement: DockPlacement) -> bool {
287        self.docks.contains_key(&placement)
288    }
289
290    /// Whether a dock is on screen. A dock the area does not have is never
291    /// open, so this answers the question a caller usually means without a
292    /// preceding [`Self::has_dock`].
293    pub fn is_dock_open(&self, placement: DockPlacement) -> bool {
294        self.docks
295            .get(&placement)
296            .is_some_and(|pane| pane.dock.is_open())
297    }
298
299    /// Open a closed dock or close an open one. A dock that is not
300    /// collapsible refuses to close; there is nothing to refuse when opening.
301    pub fn toggle_dock(
302        &mut self,
303        placement: DockPlacement,
304        window: &mut Window,
305        cx: &mut Context<Self>,
306    ) {
307        let Some(pane) = self.docks.get_mut(&placement) else {
308            return;
309        };
310        if !pane.dock.is_collapsible() && pane.dock.is_open() {
311            return;
312        }
313        let open = pane.dock.is_open();
314        pane.dock.set_open(!open);
315        // A closed dock takes its displayed panel off screen, which the
316        // active-state contract counts as no panel being displayed — that is
317        // what `TabGroupConstraints::collapsed` carries.
318        self.reconcile(window, cx);
319        cx.emit(DockEvent::LayoutChanged);
320    }
321
322    /// Whether a dock may be collapsed at all. A skin drawing a collapse
323    /// affordance in a tab bar reads this to decide whether to offer one.
324    pub fn is_dock_collapsible(&self, placement: DockPlacement) -> bool {
325        self.docks
326            .get(&placement)
327            .is_some_and(|pane| pane.dock.is_collapsible())
328    }
329
330    pub fn set_dock_collapsible(
331        &mut self,
332        placement: DockPlacement,
333        collapsible: bool,
334        _window: &mut Window,
335        cx: &mut Context<Self>,
336    ) {
337        if let Some(pane) = self.docks.get_mut(&placement) {
338            pane.dock.set_collapsible(collapsible);
339            cx.notify();
340        }
341    }
342
343    /// The dock's size along its axis.
344    pub fn dock_size(&self, placement: DockPlacement) -> Option<Pixels> {
345        self.docks.get(&placement).map(|pane| pane.dock.size())
346    }
347
348    pub fn set_dock_size(
349        &mut self,
350        placement: DockPlacement,
351        size: Pixels,
352        _window: &mut Window,
353        cx: &mut Context<Self>,
354    ) {
355        if let Some(pane) = self.docks.get_mut(&placement) {
356            let previous = pane.dock.size();
357            pane.dock.set_size(size);
358            if pane.dock.size() == previous {
359                return;
360            }
361            cx.notify();
362            cx.emit(DockEvent::LayoutChanged);
363        }
364    }
365}
366
367/// Editing the layout.
368impl DockArea {
369    /// Add a panel to a region, merging it into the first tab group there,
370    /// or starting a group when the region is empty.
371    pub fn add_panel<P: Panel>(
372        &mut self,
373        panel: Entity<P>,
374        placement: DockPlacement,
375        size: Option<Pixels>,
376        window: &mut Window,
377        cx: &mut Context<Self>,
378    ) {
379        let id = PanelId::from(panel.entity_id());
380        self.add_panel_inner(id, Arc::new(panel), placement, size, window, cx);
381    }
382
383    /// Add an already-wrapped panel handle to a region.
384    ///
385    /// The companion to [`Self::add_panel`], for a layer that hands base its
386    /// own concrete handle — see [`PanelView::as_any`] — rather than a bare
387    /// entity. The id comes from [`PanelView::panel_id`], which is the only
388    /// place it can come from once the entity is behind the handle.
389    pub fn add_panel_view(
390        &mut self,
391        panel: Arc<dyn PanelView>,
392        placement: DockPlacement,
393        size: Option<Pixels>,
394        window: &mut Window,
395        cx: &mut Context<Self>,
396    ) {
397        let id = panel.panel_id(cx);
398        self.add_panel_inner(id, panel, placement, size, window, cx);
399    }
400
401    fn add_panel_inner(
402        &mut self,
403        id: PanelId,
404        panel: Arc<dyn PanelView>,
405        placement: DockPlacement,
406        size: Option<Pixels>,
407        window: &mut Window,
408        cx: &mut Context<Self>,
409    ) {
410        // The registration is written before the target is resolved, because
411        // both want `&mut self`, so an add that finds nowhere to put the panel
412        // has to undo it. *Undo*, not remove: adding a panel the dock already
413        // holds is a legitimate call — a host re-placing one it owns — and
414        // dropping its view would strand it in a tree with no entity, which is
415        // what `reconcile`'s `views_of` asserts against.
416        let previous = self.panels.insert(id, panel);
417
418        // A dock is created to hold the panel; `size` seeds it.
419        if placement != DockPlacement::Center && !self.docks.contains_key(&placement) {
420            self.docks.insert(
421                placement,
422                DockRegion {
423                    tree: PaneTree::new(RootKind::Any),
424                    dock: Dock::new(size.unwrap_or(PANEL_MIN_SIZE * 2.)),
425                },
426            );
427        }
428
429        let Some(tree) = self.tree_mut(placement) else {
430            self.restore_registration(id, previous);
431            return;
432        };
433        let target = match first_tab_group(tree.root()) {
434            Some(node) => InsertTarget::Tabs {
435                node,
436                ix: None,
437                activate: true,
438            },
439            // An empty region has no container to merge into, so the panel
440            // makes one beside the root. `normalize` then removes the emptied
441            // root and, for a dock, collapses the wrapper away again.
442            None => InsertTarget::Split {
443                node: tree.root().id(),
444                placement: Placement::Right,
445                size,
446            },
447        };
448        let result = tree.insert_panel(id, target);
449        if !result.changed() {
450            // Nothing took the panel, so a newly registered one must not
451            // linger in the view map and be told `on_removed` by the next
452            // reconcile.
453            self.restore_registration(id, previous);
454            return;
455        }
456        self.commit(result, window, cx);
457    }
458
459    /// Put the view map back the way an add found it, for one that placed
460    /// nothing. `previous` is what [`HashMap::insert`] handed back.
461    fn restore_registration(&mut self, id: PanelId, previous: Option<Arc<dyn PanelView>>) {
462        match previous {
463            Some(view) => self.panels.insert(id, view),
464            None => self.panels.remove(&id),
465        };
466    }
467
468    /// Remove a panel from wherever it lives, telling it that it was removed.
469    pub fn remove_panel<P: Panel>(
470        &mut self,
471        panel: Entity<P>,
472        window: &mut Window,
473        cx: &mut Context<Self>,
474    ) {
475        self.remove_panel_id(PanelId::from(panel.entity_id()), window, cx);
476    }
477
478    /// Move a panel to a new home. The panel never leaves the dock, so it is
479    /// never told it was removed.
480    pub fn move_panel(
481        &mut self,
482        panel: PanelId,
483        target: InsertTarget,
484        window: &mut Window,
485        cx: &mut Context<Self>,
486    ) {
487        // A panel this area does not own (e.g. dropped from a nested dock) has
488        // no backing entity here; inserting it would strand a ghost tab.
489        if self.panel(panel).is_none() {
490            return;
491        }
492        let Some(destination) = self.placement_of_node(target_node(&target)) else {
493            return;
494        };
495        let source = self.placement_of_panel(panel);
496
497        // A split target divides an existing slot, so the tree needs real
498        // pixels to divide.
499        if matches!(target, InsertTarget::Split { .. }) {
500            self.adopt_measured_sizes(destination, cx);
501        }
502
503        // Read what the source group last told the panel *before* the edit,
504        // so the destination can be seeded with it. Without this a panel
505        // dragged between groups while displayed is told `true` twice.
506        let was_active = self
507            .layout(source.unwrap_or(destination))
508            .and_then(|tree| tree.find_panel_node(panel))
509            .and_then(|node| self.groups.get(&node))
510            .and_then(|cached| cached.entity.read(cx).last_notified_active(panel));
511
512        let changed = match source {
513            Some(source) if source == destination => {
514                let Some(tree) = self.tree_mut(destination) else {
515                    return;
516                };
517                tree.move_panel(panel, target).changed()
518            }
519            source => {
520                // Across trees a move is a detach plus an insert. The detach's
521                // `removed_panels` is deliberately dropped on the floor: the
522                // panel is still in the dock, so it must not hear `on_removed`.
523                //
524                // Both halves are committed on, not just the insert. A target
525                // whose node kind does not match the insert is a silent no-op
526                // in `apply_insert`, and committing on the insert alone would
527                // early-return with the panel already gone from the source —
528                // stranded in `self.panels`, belonging to no tree, for the
529                // next reconcile to prune and destroy.
530                let detached = source
531                    .and_then(|source| self.tree_mut(source))
532                    .is_some_and(|tree| tree.remove_panel(panel).changed());
533                let Some(tree) = self.tree_mut(destination) else {
534                    return;
535                };
536                let inserted = tree.insert_panel(panel, target).changed();
537                detached || inserted
538            }
539        };
540
541        self.commit_changed(changed, window, cx);
542
543        if let Some(active) = was_active {
544            if let Some(cached) = self
545                .layout(destination)
546                .and_then(|tree| tree.find_panel_node(panel))
547                .and_then(|node| self.groups.get(&node))
548            {
549                let group = cached.entity.clone();
550                group.update(cx, |group, _| group.seed_active(panel, active));
551            }
552        }
553    }
554
555    /// Display `panel` in the tab group that holds it, wherever that is.
556    ///
557    /// A host that is handed a file already open, or restores the tab a
558    /// layout recorded as active, wants that tab shown where it sits.
559    /// [`Self::move_panel`] with `activate` would also move it, and the group
560    /// entities are the dock's own, so this is the one way to select a panel
561    /// by identity. Nothing happens for a panel the dock does not hold, or
562    /// one already displayed.
563    pub fn select_panel(&mut self, panel: PanelId, window: &mut Window, cx: &mut Context<Self>) {
564        let Some(placement) = self.placement_of_panel(panel) else {
565            return;
566        };
567        let Some(tree) = self.tree_mut(placement) else {
568            return;
569        };
570        let Some(node) = tree.find_panel_node(panel) else {
571            return;
572        };
573        let ix = tree.find_node(node).and_then(|node| match node.kind() {
574            PaneRef::Tabs { panels, .. } => panels.iter().position(|held| *held == panel),
575            PaneRef::Split { .. } => None,
576        });
577        let Some(ix) = ix else {
578            return;
579        };
580        let result = tree.set_active(node, ix);
581        self.commit(result, window, cx);
582    }
583
584    /// Replace the slot sizes of the split at `node` in place.
585    pub fn set_split_sizes(
586        &mut self,
587        node: NodeId,
588        sizes: Vec<Pixels>,
589        window: &mut Window,
590        cx: &mut Context<Self>,
591    ) {
592        let Some(placement) = self.placement_of_node(node) else {
593            return;
594        };
595        let Some(tree) = self.tree_mut(placement) else {
596            return;
597        };
598        let result = tree.set_sizes(node, sizes.into_iter().map(Some).collect());
599        self.commit(result, window, cx);
600    }
601
602    /// Put `panel` in a new tab group beside `node`.
603    pub fn split_at(
604        &mut self,
605        node: NodeId,
606        panel: PanelId,
607        placement: Placement,
608        window: &mut Window,
609        cx: &mut Context<Self>,
610    ) {
611        let Some(region) = self.placement_of_node(node) else {
612            return;
613        };
614        self.adopt_measured_sizes(region, cx);
615        let Some(tree) = self.tree_mut(region) else {
616            return;
617        };
618        let result = tree.split(node, panel, placement, None);
619        self.commit(result, window, cx);
620    }
621
622    fn remove_panel_id(&mut self, panel: PanelId, window: &mut Window, cx: &mut Context<Self>) {
623        let Some(region) = self.placement_of_panel(panel) else {
624            return;
625        };
626        let focused = window.focused(cx);
627        let had_focus = self
628            .panel(panel)
629            .is_some_and(|view| view.focus_handle(cx).contains_focused(window, cx));
630        // Prefer the same group, then the groups following it in layout order,
631        // then preceding groups from nearest to farthest. Preserve this order
632        // before normalization removes an emptied group or collapses its split.
633        let mut candidates = Vec::new();
634        if had_focus && let Some(tree) = self.layout(region) {
635            tree.root().walk(&mut |node| {
636                if matches!(node.kind(), PaneRef::Tabs { .. }) {
637                    candidates.push(node.id());
638                }
639            });
640            if let Some(ix) = tree
641                .find_panel_node(panel)
642                .and_then(|node| candidates.iter().position(|candidate| *candidate == node))
643            {
644                candidates = candidates[ix..]
645                    .iter()
646                    .chain(candidates[..ix].iter().rev())
647                    .copied()
648                    .collect();
649            }
650        }
651        let Some(tree) = self.tree_mut(region) else {
652            return;
653        };
654        let result = tree.remove_panel(panel);
655        self.commit(result, window, cx);
656
657        // on_removed may deliberately focus another control (or clear focus).
658        // Automatic handoff is only the fallback when the callback left it alone.
659        if !had_focus || window.focused(cx) != focused {
660            return;
661        }
662        let next = candidates
663            .into_iter()
664            .find_map(|node| self.focus_target_in_group(node, cx))
665            .or_else(|| {
666                [
667                    DockPlacement::Center,
668                    DockPlacement::Left,
669                    DockPlacement::Right,
670                    DockPlacement::Bottom,
671                ]
672                .into_iter()
673                .filter(|placement| *placement != region)
674                .filter(|placement| {
675                    *placement == DockPlacement::Center
676                        || self
677                            .docks
678                            .get(placement)
679                            .is_some_and(|pane| pane.dock.is_open())
680                })
681                .find_map(|placement| {
682                    self.layout(placement)
683                        .and_then(|tree| self.focus_target_in_node(tree.root(), cx))
684                })
685            });
686        if let Some(next) = next {
687            next.focus_handle(cx).focus(window, cx);
688        }
689    }
690
691    fn focus_target_in_group(&self, node: NodeId, cx: &App) -> Option<Arc<dyn PanelView>> {
692        if self.zoomed.is_some_and(|zoom| zoom != Zoomed::Group(node)) {
693            return None;
694        }
695        let group = self.groups.get(&node)?.entity.read(cx);
696        if group.is_collapsed() {
697            return None;
698        }
699        group.active_panel(cx)
700    }
701
702    fn focus_target_in_node(&self, node: &PaneNode, cx: &App) -> Option<Arc<dyn PanelView>> {
703        match node.kind() {
704            PaneRef::Tabs { .. } => self.focus_target_in_group(node.id(), cx),
705            PaneRef::Split { children, .. } => children
706                .iter()
707                .find_map(|child| self.focus_target_in_node(child, cx)),
708        }
709    }
710}
711
712/// Zooming.
713///
714/// There is no `set_zoomed_in(panel)` here. A zoom is a container's own act:
715/// only the container knows whether its displayed panel is zoomable, and only
716/// the container can tell that panel it was zoomed. So the way in is
717/// [`TabGroupContext::toggle_zoom`](super::TabGroupContext::toggle_zoom) — a
718/// skin has one wherever it draws a zoom control — or
719/// [`Self::set_zoomed_in`] by node, which delegates to the same place. The
720/// area then installs the container that reported it.
721impl DockArea {
722    /// Zoom the tab group at `node` in, as if its own zoom control had been
723    /// used.
724    ///
725    /// Nothing happens for a node that is not a live tab group, or when the
726    /// group refuses — the group is the one that knows.
727    pub fn set_zoomed_in(&mut self, node: NodeId, window: &mut Window, cx: &mut Context<Self>) {
728        self.set_zoom(Some(Zoomed::Group(node)), window, cx);
729    }
730
731    /// Clear the zoom, putting the zoomed container's own flag back with it.
732    ///
733    /// A container toggles its zoom itself and only reports it, so an area
734    /// that dropped the view without telling the container would leave it
735    /// believing it still fills the dock — and a zoomed group refuses drops.
736    pub fn set_zoomed_out(&mut self, window: &mut Window, cx: &mut Context<Self>) {
737        self.set_zoom(None, window, cx);
738    }
739
740    pub fn is_zoomed(&self) -> bool {
741        self.zoomed.is_some()
742    }
743
744    /// The tab group filling the area, if a group is what is zoomed.
745    pub fn zoomed_group(&self) -> Option<NodeId> {
746        match self.zoomed {
747            Some(Zoomed::Group(node)) => Some(node),
748            _ => None,
749        }
750    }
751
752    /// The one place `self.zoomed` is written.
753    ///
754    /// Every write drives the container's own flag through the same call, and
755    /// the new target is recorded only if that container accepted it. So the
756    /// area cannot show a container the container does not think is zoomed,
757    /// and cannot leave a container flagged zoomed while showing something
758    /// else — the split state a group would carry as a permanent lock.
759    fn set_zoom(&mut self, zoomed: Option<Zoomed>, window: &mut Window, cx: &mut Context<Self>) {
760        if self.zoomed == zoomed {
761            return;
762        }
763
764        if let Some(previous) = self.zoomed {
765            self.drive_zoom(previous, false, window, cx);
766        }
767        let accepted = match zoomed {
768            Some(next) => self.drive_zoom(next, true, window, cx).then_some(next),
769            None => None,
770        };
771        self.zoomed = accepted;
772        cx.notify();
773    }
774
775    /// Ask one container to zoom in or out, and report whether it now agrees.
776    ///
777    /// A container that has already been left out of the cache — its node is
778    /// gone from the tree — has nothing to say and nothing to put back, so it
779    /// answers `false` and a zoom naming it is never installed.
780    fn drive_zoom(
781        &mut self,
782        zoomed: Zoomed,
783        zoom_in: bool,
784        window: &mut Window,
785        cx: &mut Context<Self>,
786    ) -> bool {
787        match zoomed {
788            Zoomed::Group(node) => {
789                let Some(group) = self.groups.get(&node).map(|cached| cached.entity.clone()) else {
790                    return false;
791                };
792                group.update(cx, |group, cx| {
793                    group.set_zoomed(zoom_in, window, cx);
794                    group.is_zoomed() == zoom_in
795                })
796            }
797        }
798    }
799
800    /// The container that fills the area when something is zoomed.
801    ///
802    /// The container, not the panel inside it: this is what keeps a zoomed
803    /// group's tab bar on screen.
804    fn zoomed_view(&self) -> Option<AnyView> {
805        match self.zoomed? {
806            Zoomed::Group(node) => Some(self.groups.get(&node)?.entity.clone().into()),
807        }
808    }
809}
810
811/// Persistence.
812impl DockArea {
813    /// Read a persisted layout, rebuilding every panel through
814    /// [`PanelRegistry`]. A panel this build does not know about becomes a
815    /// placeholder that carries the original [`PanelState`] forward, so the
816    /// next save does not erase it.
817    pub fn load(
818        &mut self,
819        state: DockAreaState,
820        window: &mut Window,
821        cx: &mut Context<Self>,
822    ) -> Result<()> {
823        self.version = state.version;
824        self.zoomed = None;
825        // Nothing in the old layout survives a load, so the caches are
826        // emptied rather than reconciled: every node id in the new trees is
827        // freshly minted and would miss the old cache anyway.
828        self.groups.clear();
829        self.splits.clear();
830        self.docks.clear();
831        // `self.panels` is deliberately *not* cleared: leaving the outgoing
832        // panels in it lets `reconcile` prune them, which is what tells them
833        // they were removed.
834
835        let dock_area = self.this.clone();
836        let renderer = self.renderer.clone();
837        let mut built = Vec::new();
838        self.center = {
839            let mut builder = RegistryPanelBuilder {
840                dock_area: dock_area.clone(),
841                renderer: renderer.clone(),
842                built: &mut built,
843                window,
844                cx,
845            };
846            PaneTree::from_state(&state.center, RootKind::Split, &mut builder)
847        };
848
849        for dock_state in [state.left_dock, state.right_dock, state.bottom_dock]
850            .into_iter()
851            .flatten()
852        {
853            let tree = {
854                let mut builder = RegistryPanelBuilder {
855                    dock_area: dock_area.clone(),
856                    renderer: renderer.clone(),
857                    built: &mut built,
858                    window,
859                    cx,
860                };
861                PaneTree::from_state(dock_state.panel(), RootKind::Any, &mut builder)
862            };
863            let mut dock = Dock::new(dock_state.size());
864            dock.set_open(dock_state.open());
865            self.docks
866                .insert(dock_state.placement(), DockRegion { tree, dock });
867        }
868
869        self.panels.extend(built);
870        self.reconcile(window, cx);
871        cx.emit(DockEvent::LayoutChanged);
872        Ok(())
873    }
874
875    /// Write the layout out.
876    ///
877    /// Slot sizes are resolved to concrete pixels first. The tree represents
878    /// an unconstrained slot as `None` and the writer emits `0.0` for it,
879    /// which *this* reader maps back to `None` — but an older build has no
880    /// notion of the sentinel and would construct a real zero-pixel panel from
881    /// it. Preference order is the split's measured size, then the tree's own
882    /// size, then [`PANEL_MIN_SIZE`] for a slot nothing has ever measured.
883    ///
884    /// The measurement wins because the tree does not track every change to
885    /// it. `ResizableState` only emits `Resized` from a finished drag, so that
886    /// is all the subscription in [`Self::split_entity`] writes back;
887    /// `adjust_to_container_size` rescales every slot silently on each window
888    /// resize, insert and remove. Preferring the tree would persist load-time
889    /// or last-drag pixels after a window resize, and worse, mix them: a slot
890    /// left `None` by a later insert would be filled from the current
891    /// measurement while its untouched siblings kept file-era numbers, so the
892    /// written ratio would match neither the file nor the screen. Reading the
893    /// measurement for every slot of a split writes one internally consistent
894    /// set, which is what the old `StackPanel::dump` did.
895    pub fn dump(&self, cx: &App) -> DockAreaState {
896        let source = LivePanels::new(&self.panels, cx);
897
898        DockAreaState {
899            version: self.version,
900            center: self.resolved_tree(&self.center, cx).to_state(&source),
901            left_dock: self.dump_dock(DockPlacement::Left, &source, cx),
902            right_dock: self.dump_dock(DockPlacement::Right, &source, cx),
903            bottom_dock: self.dump_dock(DockPlacement::Bottom, &source, cx),
904        }
905    }
906
907    fn dump_dock(
908        &self,
909        placement: DockPlacement,
910        source: &LivePanels<'_>,
911        cx: &App,
912    ) -> Option<DockState> {
913        let pane = self.docks.get(&placement)?;
914        Some(DockState::new(
915            self.resolved_tree(&pane.tree, cx).to_state(source),
916            placement,
917            pane.dock.size(),
918            pane.dock.is_open(),
919        ))
920    }
921
922    fn resolved_tree(&self, tree: &PaneTree, cx: &App) -> PaneTree {
923        let mut tree = tree.clone();
924        self.resolve_sizes(tree.root_mut(), cx);
925        tree
926    }
927
928    fn resolve_sizes(&self, node: &mut PaneNode, cx: &App) {
929        let measured = self
930            .splits
931            .get(&node.id())
932            .map(|cached| cached.entity.read(cx).sizes().clone())
933            .unwrap_or_default();
934
935        let NodeKind::Split {
936            children, sizes, ..
937        } = node.kind_mut()
938        else {
939            return;
940        };
941
942        for (ix, size) in sizes.iter_mut().enumerate() {
943            // A slot already holding zero is exactly as unsafe as an absent
944            // one: it is the same byte in the file and the same zero-pixel
945            // panel in an older build. So both the measurement and the stored
946            // value have to clear zero before they can be written.
947            let on_screen = measured.get(ix).copied().filter(|size| *size > px(0.));
948            let stored = (*size).filter(|size| *size > px(0.));
949            *size = Some(on_screen.or(stored).unwrap_or(PANEL_MIN_SIZE));
950        }
951
952        for child in children.iter_mut() {
953            self.resolve_sizes(child, cx);
954        }
955    }
956}
957
958/// Reconciliation.
959impl DockArea {
960    /// Apply one edit: bring the entity cache back in line and say so.
961    ///
962    /// `on_removed` is not fired from `EditResult::removed_panels` here.
963    /// [`Self::reconcile`] fires it instead, from the panels it prunes: that
964    /// is the same set for a plain removal, and it also covers the panels a
965    /// wholesale `set_center`, `set_dock`, `remove_dock` or `load` displaces,
966    /// which no `EditResult` describes at all. It is also the safer default —
967    /// a caller cannot forget a list it does not pass.
968    fn commit(&mut self, result: EditResult, window: &mut Window, cx: &mut Context<Self>) {
969        self.commit_changed(result.changed(), window, cx);
970    }
971
972    /// [`Self::commit`] for an edit that took more than one `EditResult`.
973    fn commit_changed(&mut self, changed: bool, window: &mut Window, cx: &mut Context<Self>) {
974        if !changed {
975            return;
976        }
977
978        self.reconcile(window, cx);
979        cx.emit(DockEvent::LayoutChanged);
980    }
981
982    /// Bring the entity cache in line with the trees.
983    ///
984    /// Because `NodeId` survives every edit and every normalization rule, a
985    /// steady-state pass creates and drops nothing; only genuinely new or dead
986    /// containers churn. That is what keeps a drag from resetting the state of
987    /// panels it did not touch.
988    fn reconcile(&mut self, window: &mut Window, cx: &mut Context<Self>) {
989        // Planned first, applied second: the plan borrows the trees, and
990        // applying it needs `&mut self` to fill the caches.
991        let mut plans = Vec::new();
992        plan_tree(&self.center, false, self.locked, &mut plans);
993        for pane in self.docks.values() {
994            plan_tree(&pane.tree, !pane.dock.is_open(), self.locked, &mut plans);
995        }
996
997        // Sets rather than vectors: these are membership tests, run once per
998        // cached entity and once per live panel, and a drag reaches this path
999        // on every mouse move.
1000        let mut live_nodes = HashSet::with_capacity(plans.len());
1001        let mut live_panels: HashSet<PanelId> = HashSet::new();
1002
1003        for plan in plans {
1004            live_nodes.insert(plan.node());
1005            match plan {
1006                ContainerPlan::Split {
1007                    node,
1008                    axis,
1009                    children,
1010                    sizes,
1011                } => {
1012                    let state = self.split_entity(node, cx);
1013                    let (previous, adopted) = self
1014                        .splits
1015                        .get(&node)
1016                        .map(|cached| (cached.children.clone(), cached.sizes.clone()))
1017                        .unwrap_or_default();
1018                    // Only a split the edit changed is handed anything. The
1019                    // state of every other split may legitimately disagree
1020                    // with its tree — a window resize rescales it silently —
1021                    // and pushing the tree's sizes back would move slots the
1022                    // edit never named. For a slot the tree leaves `None`, it
1023                    // would also un-pin the measurement the first layout pass
1024                    // resolved it to, and the whole split re-flexes.
1025                    if previous != children || adopted != sizes {
1026                        state.update(cx, |state, cx| {
1027                            sync_split_panels(state, &previous, &children, &sizes, cx);
1028                            state.sync_panels_count(axis, children.len(), cx);
1029                            // The tree is authoritative on how space divides,
1030                            // so its sizes land last — `insert_panel`
1031                            // renormalizes everything it touches, which would
1032                            // otherwise undo the share an edit just decided.
1033                            //
1034                            // What the tree decides is the *share*, not the
1035                            // pixel count. The file holds absolute pixels
1036                            // measured in whatever window last saved it, so
1037                            // restoring into a different one leaves their
1038                            // total off the container — and
1039                            // `adjust_to_container_size` rescales the state to
1040                            // the container on the very next pass. Adopting
1041                            // the raw numbers would re-assert the stale total,
1042                            // so hand over the share instead and both sides
1043                            // already agree.
1044                            state.adopt_sizes(&scale_sizes_to(state.container_size(), &sizes), cx);
1045                        });
1046                    }
1047                    if let Some(cached) = self.splits.get_mut(&node) {
1048                        cached.children = children;
1049                        cached.sizes = sizes;
1050                    }
1051                }
1052                ContainerPlan::Group {
1053                    node,
1054                    panels,
1055                    active_ix,
1056                    constraints,
1057                } => {
1058                    live_panels.extend(panels.iter().copied());
1059                    let views = self.views_of(&panels);
1060                    let group = self.group_entity(node, window, cx);
1061                    group.update(cx, |group, cx| {
1062                        // Every group must be told this. A group nobody has
1063                        // constrained stays `sealed()` and silently declines
1064                        // drags, drops and closes.
1065                        group.set_constraints(constraints, window, cx);
1066                        group.sync_from_tree(views, active_ix, window, cx);
1067                    });
1068                }
1069            }
1070        }
1071
1072        self.groups.retain(|node, _| live_nodes.contains(node));
1073        self.splits.retain(|node, _| live_nodes.contains(node));
1074
1075        let departed: Vec<Arc<dyn PanelView>> = self
1076            .panels
1077            .iter()
1078            .filter(|(panel, _)| !live_panels.contains(panel))
1079            .map(|(_, view)| view.clone())
1080            .collect();
1081        self.panels.retain(|panel, _| live_panels.contains(panel));
1082
1083        // A zoomed container fills the whole area, so one that has just left
1084        // the dock would otherwise keep filling it with nothing behind it.
1085        //
1086        // It is the container going away that ends the zoom, not a panel:
1087        // a group survives its displayed panel closing, and the next tab
1088        // takes over, still zoomed. The old `TabPanel::remove_panel` instead
1089        // emitted `ZoomOut` on every removal, which cleared the dock's zoom
1090        // even for a panel in some other tab panel entirely — and left the
1091        // zoomed `TabPanel` still flagged zoomed while the dock was not.
1092        let zoom_survives = match self.zoomed {
1093            Some(Zoomed::Group(node)) => self.groups.contains_key(&node),
1094            None => true,
1095        };
1096        if !zoom_survives {
1097            self.set_zoom(None, window, cx);
1098        }
1099
1100        cx.notify();
1101        // Last, so a panel reacting to this sees a dock that already agrees
1102        // with its trees.
1103        for view in departed {
1104            view.on_removed(window, cx);
1105        }
1106    }
1107
1108    /// The views for a group's panel ids, in tab order.
1109    fn views_of(&self, panels: &[PanelId]) -> Vec<Arc<dyn PanelView>> {
1110        debug_assert!(
1111            panels.iter().all(|panel| self.panels.contains_key(panel)),
1112            "every panel in a tree must have a live view; a missing one would \
1113             silently shift the group's active index"
1114        );
1115        panels
1116            .iter()
1117            .filter_map(|panel| self.panels.get(panel).cloned())
1118            .collect()
1119    }
1120
1121    fn group_entity(
1122        &mut self,
1123        node: NodeId,
1124        window: &mut Window,
1125        cx: &mut Context<Self>,
1126    ) -> Entity<TabGroup> {
1127        if let Some(cached) = self.groups.get(&node) {
1128            return cached.entity.clone();
1129        }
1130
1131        let renderer = self.renderer.tab_group_renderer();
1132        let entity = cx.new(|cx| TabGroup::new(node, window, cx).with_renderer(renderer));
1133        let subscription = cx.subscribe_in(&entity, window, Self::on_tab_group_event);
1134        self.groups.insert(
1135            node,
1136            Cached {
1137                entity: entity.clone(),
1138                _subscription: subscription,
1139            },
1140        );
1141        entity
1142    }
1143
1144    fn split_entity(&mut self, node: NodeId, cx: &mut Context<Self>) -> Entity<ResizableState> {
1145        if let Some(cached) = self.splits.get(&node) {
1146            return cached.entity.clone();
1147        }
1148
1149        let entity = cx.new(|_| ResizableState::default());
1150        // A drag on a resize handle changes only the measured sizes. Writing
1151        // them straight back keeps the tree describing the layout the user
1152        // arranged, which is what a later insert or removal scales from and
1153        // what a region with no live split entity is dumped from.
1154        //
1155        // It does not make the tree authoritative on slot sizes generally, and
1156        // `dump` does not treat it as such: only a finished drag arrives here,
1157        // while `adjust_to_container_size` rewrites the measurements silently
1158        // on every window resize. See [`Self::dump`].
1159        let subscription =
1160            cx.subscribe(&entity, move |this, state, _: &ResizablePanelEvent, cx| {
1161                let sizes: Vec<Option<Pixels>> = state
1162                    .read(cx)
1163                    .sizes()
1164                    .iter()
1165                    .map(|size| Some(*size))
1166                    .collect();
1167                let Some(region) = this.placement_of_node(node) else {
1168                    return;
1169                };
1170                let Some(tree) = this.tree_mut(region) else {
1171                    return;
1172                };
1173                if tree.set_sizes(node, sizes.clone()).changed() {
1174                    cx.emit(DockEvent::LayoutChanged);
1175                }
1176                // The state is where these came from, so the next reconcile
1177                // has nothing to hand it.
1178                if let Some(cached) = this.splits.get_mut(&node) {
1179                    cached.sizes = sizes;
1180                }
1181            });
1182        self.splits.insert(
1183            node,
1184            CachedSplit {
1185                entity: entity.clone(),
1186                children: Vec::new(),
1187                sizes: Vec::new(),
1188                _subscription: subscription,
1189            },
1190        );
1191        entity
1192    }
1193}
1194
1195/// Intents arriving from the containers.
1196impl DockArea {
1197    fn on_tab_group_event(
1198        &mut self,
1199        group: &Entity<TabGroup>,
1200        event: &TabGroupEvent,
1201        window: &mut Window,
1202        cx: &mut Context<Self>,
1203    ) {
1204        match event {
1205            TabGroupEvent::Drop { panel, target, .. } => {
1206                self.move_panel(*panel, *target, window, cx)
1207            }
1208            TabGroupEvent::DragDrop { item, target } => cx.emit(DockEvent::DragDrop {
1209                item: item.clone(),
1210                target: *target,
1211            }),
1212            TabGroupEvent::ClosePanel { panel } => self.remove_panel_id(*panel, window, cx),
1213            TabGroupEvent::ActiveChanged { ix } => {
1214                let node = group.read(cx).node();
1215                let Some(region) = self.placement_of_node(node) else {
1216                    return;
1217                };
1218                let Some(tree) = self.tree_mut(region) else {
1219                    return;
1220                };
1221                let result = tree.set_active(node, *ix);
1222                self.commit(result, window, cx);
1223            }
1224            TabGroupEvent::ZoomIn => {
1225                let node = group.read(cx).node();
1226                self.set_zoom(Some(Zoomed::Group(node)), window, cx);
1227            }
1228            // Only the group that is actually on screen can give the dock
1229            // back. A group told to zoom out to make room for another one
1230            // reports it too, and that report must not undo the zoom that
1231            // replaced it.
1232            TabGroupEvent::ZoomOut => {
1233                let node = group.read(cx).node();
1234                if self.zoomed == Some(Zoomed::Group(node)) {
1235                    self.set_zoom(None, window, cx);
1236                }
1237            }
1238        }
1239    }
1240}
1241
1242/// Region lookup.
1243impl DockArea {
1244    /// Feed every split's measured size back into the tree before an edit
1245    /// that has to divide space.
1246    ///
1247    /// Done here rather than continuously: the tree is the record of what the
1248    /// user arranged, and rewriting it on every layout pass would let a
1249    /// transient window size become the stored layout.
1250    fn adopt_measured_sizes(&mut self, placement: DockPlacement, cx: &App) {
1251        let measured: HashMap<NodeId, Vec<Pixels>> = self
1252            .splits
1253            .iter()
1254            // Only splits that have actually been laid out. A split created
1255            // earlier in this same edit has a zero container and its `sizes`
1256            // are whatever `insert_panel` left behind — adopting those would
1257            // freeze a placeholder ratio into the tree, and every later edit
1258            // would divide space according to it.
1259            .filter(|(_, cached)| cached.entity.read(cx).container_size() > Pixels::ZERO)
1260            .map(|(node, cached)| (*node, cached.entity.read(cx).sizes().clone()))
1261            .collect();
1262
1263        if let Some(tree) = self.tree_mut(placement) {
1264            tree.adopt_measured_sizes(&measured);
1265        }
1266    }
1267
1268    fn tree_mut(&mut self, placement: DockPlacement) -> Option<&mut PaneTree> {
1269        match placement {
1270            DockPlacement::Center => Some(&mut self.center),
1271            _ => self.docks.get_mut(&placement).map(|pane| &mut pane.tree),
1272        }
1273    }
1274
1275    /// Which region a container belongs to. Unambiguous because `NodeId`s are
1276    /// allocated globally rather than per tree.
1277    fn placement_of_node(&self, node: NodeId) -> Option<DockPlacement> {
1278        if self.center.find_node(node).is_some() {
1279            return Some(DockPlacement::Center);
1280        }
1281        self.docks
1282            .iter()
1283            .find(|(_, pane)| pane.tree.find_node(node).is_some())
1284            .map(|(placement, _)| *placement)
1285    }
1286
1287    fn placement_of_panel(&self, panel: PanelId) -> Option<DockPlacement> {
1288        if self.center.find_panel_node(panel).is_some() {
1289            return Some(DockPlacement::Center);
1290        }
1291        self.docks
1292            .iter()
1293            .find(|(_, pane)| pane.tree.find_panel_node(panel).is_some())
1294            .map(|(placement, _)| *placement)
1295    }
1296
1297    /// Resize one dock from a pointer position, clamped so neither this dock
1298    /// nor the one opposite is squeezed below its minimum.
1299    ///
1300    /// A collapsible bottom dock is the exception: it follows the pointer
1301    /// below the minimum down to its closed strip, so closing it by drag is
1302    /// one continuous motion. That size is only shown, and
1303    /// [`Self::end_dock_resize`] settles it on release.
1304    fn resize_dock(
1305        &mut self,
1306        placement: DockPlacement,
1307        pointer: Point<Pixels>,
1308        window: &mut Window,
1309        cx: &mut Context<Self>,
1310    ) {
1311        let opposite = match placement {
1312            DockPlacement::Left => self.dock_size(DockPlacement::Right),
1313            DockPlacement::Right => self.dock_size(DockPlacement::Left),
1314            _ => None,
1315        };
1316        // Sizing reads the pointer against the edge the dock physically sits on.
1317        let sizing = DockSizing::new(placement.physical(crate::LayoutDirection::global(cx)))
1318            .with_area_bounds(self.bounds)
1319            .with_opposite_dock_size(opposite.unwrap_or(px(0.)));
1320        let size = sizing
1321            .size_from_pointer(pointer)
1322            .min(sizing.clamp(Pixels::MAX));
1323
1324        let strip = self.renderer.closed_dock_extent(placement);
1325        let Some(pane) = self.docks.get_mut(&placement) else {
1326            return;
1327        };
1328        let was_open = pane.dock.is_open();
1329        if placement == DockPlacement::Bottom && pane.dock.is_collapsible() && size < PANEL_MIN_SIZE
1330        {
1331            pane.dock.set_open(size > strip);
1332            pane.dock.set_live_size(Some(size.max(strip)));
1333        } else {
1334            pane.dock.set_open(true);
1335            pane.dock.set_live_size(None);
1336            pane.dock.set_size(size);
1337        }
1338        if pane.dock.is_open() != was_open {
1339            self.reconcile(window, cx);
1340        }
1341        cx.notify();
1342    }
1343
1344    /// Settle a drag that ended below the minimum: nearer the closed strip it
1345    /// closes, nearer the minimum it opens at the minimum.
1346    fn end_dock_resize(
1347        &mut self,
1348        placement: DockPlacement,
1349        window: &mut Window,
1350        cx: &mut Context<Self>,
1351    ) {
1352        let strip = self.renderer.closed_dock_extent(placement);
1353        let Some(pane) = self.docks.get_mut(&placement) else {
1354            return;
1355        };
1356        let Some(size) = pane.dock.live_size() else {
1357            return;
1358        };
1359        pane.dock.set_live_size(None);
1360
1361        let open = size >= (strip + PANEL_MIN_SIZE) / 2.;
1362        if open {
1363            pane.dock.set_size(PANEL_MIN_SIZE);
1364        }
1365        if pane.dock.is_open() != open {
1366            pane.dock.set_open(open);
1367            self.reconcile(window, cx);
1368        }
1369        cx.notify();
1370    }
1371}
1372
1373/// Rendering.
1374impl DockArea {
1375    /// Lower one container to an element.
1376    fn render_node(&self, node: &PaneNode, window: &mut Window, cx: &mut App) -> AnyElement {
1377        match node.kind() {
1378            PaneRef::Split {
1379                axis,
1380                children,
1381                sizes,
1382            } => {
1383                let group = match axis {
1384                    Axis::Horizontal => h_resizable(("dock-split", node.id().as_u64())),
1385                    Axis::Vertical => v_resizable(("dock-split", node.id().as_u64())),
1386                };
1387                // A container whose every panel is hidden must not keep
1388                // occupying its slot. No renderer hook could supply this:
1389                // only the area can see the panels behind a node.
1390                let shown: Vec<bool> = children
1391                    .iter()
1392                    .map(|child| self.is_node_visible(child, cx))
1393                    .collect();
1394                // The slot that absorbs the leftover has to be one that is
1395                // actually drawn. A hidden slot renders nothing and grows
1396                // nothing, so making it the flexible one leaves every drawn
1397                // slot rigid and the split ends short of its container — the
1398                // empty strip this picks the *last shown* slot to avoid.
1399                let grows = shown.iter().rposition(|shown| *shown);
1400                let panels: Vec<_> = children
1401                    .iter()
1402                    .zip(sizes.iter())
1403                    .enumerate()
1404                    .map(|(ix, (child, size))| {
1405                        resizable_panel()
1406                            .visible(shown[ix])
1407                            .child(self.render_node(child, window, cx))
1408                            // `flex_none` is what makes the size stick.
1409                            // `ResizablePanel` sets `flex_grow: 1` on itself,
1410                            // so a slot given a size would otherwise treat it
1411                            // as a flex-basis and still absorb an equal share
1412                            // of the leftover — a 200px sidebar rendering
1413                            // 1075px wide in a 1950px split.
1414                            // The growth slot absorbs container growth. A
1415                            // drag records every measured size as pixels; if
1416                            // all of them became `flex_none`, a later viewport
1417                            // resize would leave an empty strip after the
1418                            // split instead of keeping the Dock filled.
1419                            .when_some(*size, |panel, size| {
1420                                panel
1421                                    .size(size)
1422                                    .when(Some(ix) != grows, |panel| panel.flex_none())
1423                            })
1424                    })
1425                    .collect();
1426
1427                let group = group
1428                    .when_some(self.splits.get(&node.id()), |group, cached| {
1429                        group.with_state(&cached.entity)
1430                    })
1431                    .with_handle_appearance({
1432                        let renderer = self.renderer.clone();
1433                        Rc::new(move |handle, window, cx| {
1434                            renderer.render_split_handle(handle, window, cx)
1435                        })
1436                    })
1437                    .children(panels);
1438
1439                self.renderer
1440                    .split_frame(node.id(), axis, window, cx)
1441                    // A split frame with no size collapses: base puts it
1442                    // between a `resizable_panel` and the resizable group, and
1443                    // between `center_frame` and the centre's root split, and
1444                    // neither parent sizes it. `size_full` and `flex_1` are
1445                    // belt and braces -- either alone passes every case I could
1446                    // construct, so this does not depend on which one wins in a
1447                    // given parent.
1448                    .size_full()
1449                    .flex_1()
1450                    .min_h(px(0.))
1451                    .overflow_hidden()
1452                    .child(group)
1453                    .into_any_element()
1454            }
1455            PaneRef::Tabs { .. } => match self.groups.get(&node.id()) {
1456                Some(cached) => cached.entity.clone().into_any_element(),
1457                None => Empty.into_any_element(),
1458            },
1459        }
1460    }
1461
1462    /// Whether anything in this container is on screen.
1463    ///
1464    /// Mirrors the old `StackPanel::render`, which asked each slot's
1465    /// `TabPanel::visible` — "does this group hold any visible panel?" — and
1466    /// hid the slot when it did not.
1467    fn is_node_visible(&self, node: &PaneNode, cx: &App) -> bool {
1468        let panels = LivePanels::new(&self.panels, cx);
1469        match node.kind() {
1470            PaneRef::Split { children, .. } => {
1471                children.iter().any(|child| self.is_node_visible(child, cx))
1472            }
1473            PaneRef::Tabs { panels: ids, .. } => ids.iter().any(|panel| panels.is_visible(*panel)),
1474        }
1475    }
1476
1477    fn render_dock(
1478        &self,
1479        placement: DockPlacement,
1480        window: &mut Window,
1481        cx: &mut App,
1482    ) -> Option<AnyElement> {
1483        let pane = self.docks.get(&placement)?;
1484        let dock = self.dock_context(placement, &pane.dock);
1485
1486        // A closed dock keeps what the renderer asks for: by default nothing
1487        // at the sides and a strip at the bottom so its tab bar stays
1488        // clickable. Nothing is drawn
1489        // for a dock with no extent, and the renderer is not asked for chrome
1490        // nobody can see.
1491        let size = if dock.is_open() {
1492            dock.size()
1493        } else {
1494            self.renderer.closed_dock_extent(placement)
1495        };
1496        if size <= px(0.) {
1497            return Some(div().into_any_element());
1498        }
1499
1500        let content = self.render_node(pane.tree.root(), window, cx);
1501        // The box is applied here rather than left to the renderer, and that is
1502        // the whole point of it being here. A dock's extent along its own axis
1503        // is not presentation -- it is what makes the dock a column beside the
1504        // centre instead of a block in the flow below it -- and a renderer that
1505        // did not know to state it produced a dock with no width, every pane
1506        // inside it shrunk to its content. `render_dock` on the renderer is a
1507        // chrome hook, so a renderer that draws nothing at all still gets a
1508        // dock that is the right shape.
1509        let chrome = self.renderer.render_dock(&dock, content, window, cx);
1510        Some(dock_frame(&dock, size).child(chrome).into_any_element())
1511    }
1512
1513    fn dock_context(&self, placement: DockPlacement, dock: &Dock) -> DockContext {
1514        let area = self.this.clone();
1515
1516        DockContext {
1517            placement,
1518            size: dock.live_size().unwrap_or(dock.size()),
1519            open: dock.is_open(),
1520            collapsible: dock.is_collapsible(),
1521            on_toggle: {
1522                let area = area.clone();
1523                Rc::new(move |window, cx| {
1524                    _ = area.update(cx, |area, cx| area.toggle_dock(placement, window, cx));
1525                })
1526            },
1527            on_resize: {
1528                let area = area.clone();
1529                Rc::new(move |pointer, window, cx| {
1530                    _ = area.update(cx, |area, cx| {
1531                        area.resize_dock(placement, pointer, window, cx)
1532                    });
1533                })
1534            },
1535            on_resize_end: Rc::new(move |window, cx| {
1536                _ = area.update(cx, |area, cx| area.end_dock_resize(placement, window, cx));
1537            }),
1538        }
1539    }
1540}
1541
1542impl EventEmitter<DockEvent> for DockArea {}
1543
1544impl Focusable for DockArea {
1545    fn focus_handle(&self, _: &App) -> FocusHandle {
1546        self.focus_handle.clone()
1547    }
1548}
1549
1550impl Render for DockArea {
1551    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1552        let area = cx.entity();
1553        let renderer = self.renderer.clone();
1554
1555        renderer
1556            .frame(window, cx)
1557            .test_support()
1558            // Structure, applied after the hook and not inside it. A dock area
1559            // lays its left dock, centre and right dock out in a row; a frame
1560            // that is not one stacks them down the window instead, which is
1561            // what every renderer that is not `DockSkin` used to get, because
1562            // the row lived in `DockSkin`'s override of this hook and the trait
1563            // default is a bare `div`.
1564            .relative()
1565            .size_full()
1566            .overflow_hidden()
1567            // Left dock on the start edge: the right edge in RTL.
1568            .flex_row_dir(cx)
1569            .on_prepaint(move |bounds, _, cx| {
1570                area.update(cx, |area, _| area.bounds = bounds);
1571            })
1572            .track_focus(&self.focus_handle)
1573            .map(|frame| match self.zoomed_view() {
1574                Some(view) => frame.child(view),
1575                None => frame
1576                    .when_some(
1577                        self.render_dock(DockPlacement::Left, window, cx),
1578                        ParentElement::child,
1579                    )
1580                    .child(
1581                        renderer
1582                            .center_frame(window, cx)
1583                            // Same reason as the frame above: the centre is
1584                            // whatever the side docks leave, in a column with
1585                            // the bottom dock. Without this it is neither, and
1586                            // shrinks to its content.
1587                            .flex()
1588                            .flex_1()
1589                            .flex_col()
1590                            .overflow_hidden()
1591                            .child(self.render_node(self.center.root(), window, cx))
1592                            .when_some(
1593                                self.render_dock(DockPlacement::Bottom, window, cx),
1594                                ParentElement::child,
1595                            ),
1596                    )
1597                    .when_some(
1598                        self.render_dock(DockPlacement::Right, window, cx),
1599                        ParentElement::child,
1600                    ),
1601            })
1602    }
1603}
1604
1605/// One container's worth of reconciliation work, snapshotted out of the tree.
1606enum ContainerPlan {
1607    Split {
1608        node: NodeId,
1609        axis: Axis,
1610        children: Vec<NodeId>,
1611        sizes: Vec<Option<Pixels>>,
1612    },
1613    Group {
1614        node: NodeId,
1615        panels: Vec<PanelId>,
1616        active_ix: usize,
1617        constraints: TabGroupConstraints,
1618    },
1619}
1620
1621impl ContainerPlan {
1622    fn node(&self) -> NodeId {
1623        match self {
1624            Self::Split { node, .. } | Self::Group { node, .. } => *node,
1625        }
1626    }
1627}
1628
1629/// Re-express slot sizes as shares of `container`, keeping their proportions.
1630///
1631/// Returns them unchanged unless every slot is constrained and both the
1632/// container and the recorded total are usable: an unconstrained slot is laid
1633/// out by flex and takes the leftover, so scaling only the constrained ones
1634/// would move a divider nothing asked to move.
1635fn scale_sizes_to(container: Pixels, sizes: &[Option<Pixels>]) -> Vec<Option<Pixels>> {
1636    let total: f32 = sizes.iter().flatten().map(|size| size.as_f32()).sum();
1637    if container <= px(0.) || total <= 0. || sizes.iter().any(Option::is_none) {
1638        return sizes.to_vec();
1639    }
1640
1641    let scale = container.as_f32() / total;
1642    sizes
1643        .iter()
1644        .map(|size| size.map(|size| px(size.as_f32() * scale)))
1645        .collect()
1646}
1647
1648/// Bring one split's `ResizableState` panel list from `previous` to `next`,
1649/// inserting and removing at the exact index rather than at the tail.
1650///
1651/// `ResizableState` treats the size handed to `insert_panel` as an initial
1652/// value only; from then on `panels[ix].size` is authoritative. So an
1653/// append-and-truncate sync leaves every survivor of a non-tail removal
1654/// wearing the width of whoever used to sit at its index — which is the most
1655/// ordinary edit in the dock, a drag that empties a group, and it is carried
1656/// into the save file by `resolve_sizes`.
1657fn sync_split_panels(
1658    state: &mut ResizableState,
1659    previous: &[NodeId],
1660    next: &[NodeId],
1661    sizes: &[Option<Pixels>],
1662    cx: &mut Context<ResizableState>,
1663) {
1664    let mut current = previous.to_vec();
1665
1666    // Removals from the tail, so the indices ahead of each removal stay valid.
1667    for ix in (0..current.len()).rev() {
1668        if !next.contains(&current[ix]) {
1669            if ix < state.sizes().len() {
1670                state.remove_panel(ix, cx);
1671            }
1672            current.remove(ix);
1673        }
1674    }
1675
1676    for (ix, node) in next.iter().enumerate() {
1677        if current.get(ix) == Some(node) {
1678            continue;
1679        }
1680        let at = ix.min(state.sizes().len());
1681        // Passed through as-is. The tree already decided this slot's share
1682        // when the panel was inserted — a drop halves the neighbour it landed
1683        // beside — so there is nothing to compute here, and nothing that
1684        // depends on a container this state may not have measured yet.
1685        state.insert_panel(sizes.get(ix).copied().flatten(), Some(at), cx);
1686        current.insert(at.min(current.len()), *node);
1687    }
1688
1689    debug_assert_eq!(
1690        current, next,
1691        "the split's panel list must end up mirroring its children exactly; \
1692         a reordering edit would need its own case here"
1693    );
1694}
1695
1696fn plan_tree(tree: &PaneTree, collapsed: bool, locked: bool, out: &mut Vec<ContainerPlan>) {
1697    // The root has nothing beside it by definition.
1698    plan_node(tree.root(), true, collapsed, locked, out);
1699}
1700
1701fn plan_node(
1702    node: &PaneNode,
1703    alone: bool,
1704    collapsed: bool,
1705    locked: bool,
1706    out: &mut Vec<ContainerPlan>,
1707) {
1708    match node.kind() {
1709        PaneRef::Split {
1710            axis,
1711            children,
1712            sizes,
1713        } => {
1714            out.push(ContainerPlan::Split {
1715                node: node.id(),
1716                axis,
1717                children: children.iter().map(PaneNode::id).collect(),
1718                sizes: sizes.to_vec(),
1719            });
1720            let children_alone = children.len() <= 1;
1721            for child in children {
1722                plan_node(child, children_alone, collapsed, locked, out);
1723            }
1724        }
1725        PaneRef::Tabs { panels, active_ix } => out.push(ContainerPlan::Group {
1726            node: node.id(),
1727            panels: panels.to_vec(),
1728            active_ix,
1729            constraints: TabGroupConstraints::in_split(alone)
1730                .dock_locked(locked)
1731                .collapsed(collapsed),
1732        }),
1733    }
1734}
1735
1736fn first_tab_group(node: &PaneNode) -> Option<NodeId> {
1737    match node.kind() {
1738        PaneRef::Tabs { .. } => Some(node.id()),
1739        PaneRef::Split { children, .. } => children.iter().find_map(first_tab_group),
1740    }
1741}
1742
1743fn target_node(target: &InsertTarget) -> NodeId {
1744    match target {
1745        InsertTarget::Tabs { node, .. } | InsertTarget::Split { node, .. } => *node,
1746    }
1747}
1748
1749/// Rebuilds panels out of persisted state through [`PanelRegistry`].
1750struct RegistryPanelBuilder<'a, 'w, 'c> {
1751    dock_area: WeakEntity<DockArea>,
1752    renderer: Rc<dyn DockAreaRenderer>,
1753    built: &'a mut Vec<(PanelId, Arc<dyn PanelView>)>,
1754    window: &'w mut Window,
1755    cx: &'c mut App,
1756}
1757
1758impl PanelBuilder for RegistryPanelBuilder<'_, '_, '_> {
1759    fn build(&mut self, state: &PanelState, info: &PanelInfo) -> PanelId {
1760        let context = PanelBuildContext::new(self.dock_area.clone(), state, info);
1761        let view =
1762            match PanelRegistry::build_panel(&state.panel_name, context, self.window, self.cx) {
1763                Some(view) => view,
1764                None => self
1765                    .renderer
1766                    .build_placeholder(state, self.window, self.cx)
1767                    .unwrap_or_else(|| {
1768                        Arc::new(self.cx.new(|cx| PlaceholderPanel::new(state.clone(), cx)))
1769                            as Arc<dyn PanelView>
1770                    }),
1771            };
1772
1773        let id = view.panel_id(self.cx);
1774        self.built.push((id, view));
1775        id
1776    }
1777}
1778
1779/// Stands in for a panel this build cannot construct.
1780///
1781/// It draws nothing — an "unknown panel" message is presentation and belongs
1782/// above this seam — but it keeps the original [`PanelState`] and hands it
1783/// back from [`Panel::dump`], so a layout written by a newer build survives a
1784/// load and save here instead of losing the panel.
1785struct PlaceholderPanel {
1786    state: PanelState,
1787    focus_handle: FocusHandle,
1788}
1789
1790impl PlaceholderPanel {
1791    fn new(state: PanelState, cx: &mut Context<Self>) -> Self {
1792        Self {
1793            state,
1794            focus_handle: cx.focus_handle(),
1795        }
1796    }
1797}
1798
1799impl Panel for PlaceholderPanel {
1800    fn panel_name(&self) -> &'static str {
1801        "InvalidPanel"
1802    }
1803
1804    fn dump(&self, _: &App) -> PanelState {
1805        self.state.clone()
1806    }
1807}
1808
1809impl EventEmitter<PanelEvent> for PlaceholderPanel {}
1810
1811impl Focusable for PlaceholderPanel {
1812    fn focus_handle(&self, _: &App) -> FocusHandle {
1813        self.focus_handle.clone()
1814    }
1815}
1816
1817impl Render for PlaceholderPanel {
1818    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1819        Empty
1820    }
1821}
1822
1823type DockToggleHandler = Rc<dyn Fn(&mut Window, &mut App)>;
1824type DockResizeHandler = Rc<dyn Fn(Point<Pixels>, &mut Window, &mut App)>;
1825
1826/// What a skin needs to draw one dock, and the callbacks it invokes rather
1827/// than reimplementing the open/close and clamping behavior.
1828#[derive(Clone)]
1829pub struct DockContext {
1830    placement: DockPlacement,
1831    size: Pixels,
1832    open: bool,
1833    collapsible: bool,
1834    on_toggle: DockToggleHandler,
1835    on_resize: DockResizeHandler,
1836    on_resize_end: DockToggleHandler,
1837}
1838
1839impl DockContext {
1840    pub fn placement(&self) -> DockPlacement {
1841        self.placement
1842    }
1843
1844    /// The dock's extent along its own axis: width for left/right, height for
1845    /// bottom.
1846    pub fn size(&self) -> Pixels {
1847        self.size
1848    }
1849
1850    pub fn is_open(&self) -> bool {
1851        self.open
1852    }
1853
1854    pub fn is_collapsible(&self) -> bool {
1855        self.collapsible
1856    }
1857
1858    pub fn toggle(&self, window: &mut Window, cx: &mut App) {
1859        (self.on_toggle)(window, cx);
1860    }
1861
1862    /// Resize from a pointer position in window coordinates. Base clamps it
1863    /// against the area bounds and the opposite dock.
1864    pub fn resize_to(&self, pointer: Point<Pixels>, window: &mut Window, cx: &mut App) {
1865        (self.on_resize)(pointer, window, cx);
1866    }
1867
1868    /// End a resize started with [`Self::resize_to`]. A bottom dock dragged
1869    /// below its minimum snaps shut or to the minimum, whichever is nearer.
1870    pub fn end_resize(&self, window: &mut Window, cx: &mut App) {
1871        (self.on_resize_end)(window, cx);
1872    }
1873}
1874
1875/// What a closed bottom dock keeps by default, so its tab bar stays
1876/// clickable. See [`DockAreaRenderer::closed_dock_extent`]. A
1877/// closed side dock keeps nothing: there is no tab bar left to click at zero
1878/// width, and reopening it is the application's to offer.
1879pub const CLOSED_BOTTOM_STRIP: Pixels = px(29.);
1880
1881/// The box a dock occupies: its extent along its own axis, full across, and
1882/// held at that size rather than stretched by the row it sits in.
1883///
1884/// Structural, not decorative, which is why it is built here and not in a
1885/// renderer. See [`DockArea::render_dock`].
1886pub fn dock_frame(dock: &DockContext, size: Pixels) -> Div {
1887    div()
1888        .flex()
1889        .flex_none()
1890        .relative()
1891        .overflow_hidden()
1892        .map(|this| match dock.placement() {
1893            DockPlacement::Left | DockPlacement::Right => this.flex_row().h_full().w(size),
1894            DockPlacement::Bottom => this.w_full().h(size),
1895            // Base never builds a dock for the centre.
1896            DockPlacement::Center => this,
1897        })
1898}
1899
1900/// Appearance for the dock area. Base draws none of it.
1901///
1902/// The frame hooks return the element itself rather than wrapping one, for the
1903/// same reason [`TabGroupRenderer`]'s do: base tracks focus and records the
1904/// area bounds on the very element the skin styles.
1905///
1906/// There is no separate `render_resize_handle` hook. A handle needs to be
1907/// positioned against the dock it resizes, and positioning is the skin's; the
1908/// skin draws it inside [`Self::render_dock`] and drives it through
1909/// [`DockContext::resize_to`].
1910#[allow(unused_variables)]
1911pub trait DockAreaRenderer: 'static {
1912    /// The area's outer frame, which base records its bounds on.
1913    /// Appearance only. The area is laid out as a row around whatever this
1914    /// returns, because that is what makes a dock a column beside the centre
1915    /// rather than a block above it, and a renderer cannot be expected to know
1916    /// it had a row to declare.
1917    fn frame(&self, window: &mut Window, cx: &mut App) -> Stateful<Div> {
1918        div().id("dock-area")
1919    }
1920
1921    /// One split container's frame, around base's resizable group.
1922    ///
1923    /// This one really is a wrapper, unlike the other frame hooks, and
1924    /// deliberately: base attaches nothing to it, so there is no hit area to
1925    /// separate from the painted area. It exists because the old `StackPanel`
1926    /// carried real appearance here — a background and an overflow clip — and
1927    /// without it a skin could style a dock and a tab group but nothing in
1928    /// between. `Stateful<Div>` rather than a plain one so the skin keeps a
1929    /// role, a tooltip, and scroll tracking.
1930    fn split_frame(
1931        &self,
1932        node: NodeId,
1933        axis: Axis,
1934        window: &mut Window,
1935        cx: &mut App,
1936    ) -> Stateful<Div> {
1937        div().id(("dock-split-frame", node.as_u64()))
1938    }
1939
1940    /// The column holding the center region and the bottom dock.
1941    /// Appearance only; see [`DockAreaRenderer::frame`]. The centre fills what
1942    /// the side docks leave and stacks with the bottom dock either way.
1943    fn center_frame(&self, window: &mut Window, cx: &mut App) -> Stateful<Div> {
1944        div().id("dock-area-center")
1945    }
1946
1947    /// The painted part of the divider between two slots of a split.
1948    ///
1949    /// `None` keeps base's own one-pixel line, so a skin that has no opinion
1950    /// about dividers implements nothing. The hit area, the cursor and the
1951    /// drag itself stay with base either way — this hook supplies appearance
1952    /// only, and is told the axis and whether the divider is being dragged.
1953    fn render_split_handle(
1954        &self,
1955        handle: &ResizeHandleContext,
1956        window: &mut Window,
1957        cx: &mut App,
1958    ) -> Option<AnyElement> {
1959        None
1960    }
1961
1962    /// How much a closed dock keeps along its own axis.
1963    ///
1964    /// The default keeps [`CLOSED_BOTTOM_STRIP`] for the bottom dock, so its
1965    /// tab bar stays clickable to reopen it, and nothing for a side dock. A
1966    /// skin whose application offers its own toggle can return `px(0.)` for
1967    /// the bottom dock too. The value also sets where a dragged bottom dock
1968    /// snaps shut.
1969    fn closed_dock_extent(&self, placement: DockPlacement) -> Pixels {
1970        match placement {
1971            DockPlacement::Bottom => CLOSED_BOTTOM_STRIP,
1972            _ => px(0.),
1973        }
1974    }
1975
1976    /// One dock's chrome around its content: the title strip, the collapse
1977    /// affordance, and the resize handle.
1978    ///
1979    /// Chrome only. The dock's own box -- its extent along its own axis, and
1980    /// the `flex_none` that holds it there -- is applied by
1981    /// [`DockArea::render_dock`] around whatever this returns, so a renderer
1982    /// cannot misplace a dock by not knowing to size it, and the default here
1983    /// can be what it is: the content, undecorated.
1984    fn render_dock(
1985        &self,
1986        dock: &DockContext,
1987        content: AnyElement,
1988        window: &mut Window,
1989        cx: &mut App,
1990    ) -> AnyElement {
1991        content
1992    }
1993
1994    /// The stand-in for a panel this build cannot construct — one whose
1995    /// `panel_name` no [`PanelRegistry`] builder answers to. `None` takes
1996    /// base's own placeholder, which draws nothing.
1997    ///
1998    /// The hook exists because a placeholder cannot be wrapped after the
1999    /// fact: presentation reaches base only through the handle a panel is
2000    /// registered behind, so whoever creates the panel decides what it can
2001    /// draw. An "unknown panel" message is presentation, so the skin creates
2002    /// that panel or does without one.
2003    ///
2004    /// A placeholder is what gets written back out on the next save, so one
2005    /// supplied here should answer [`Panel::dump`] with `state` unchanged —
2006    /// otherwise saving after a load erases the panel it stood in for. Base's
2007    /// own placeholder does; nothing here can enforce it of a skin's.
2008    fn build_placeholder(
2009        &self,
2010        state: &PanelState,
2011        window: &mut Window,
2012        cx: &mut App,
2013    ) -> Option<Arc<dyn PanelView>> {
2014        None
2015    }
2016
2017    fn tab_group_renderer(&self) -> Rc<dyn TabGroupRenderer>;
2018}
2019
2020/// The renderer an area starts with: the layout and nothing else.
2021struct BareDockArea;
2022
2023impl DockAreaRenderer for BareDockArea {
2024    fn tab_group_renderer(&self) -> Rc<dyn TabGroupRenderer> {
2025        Rc::new(BareTabGroup)
2026    }
2027}
2028
2029#[cfg(test)]
2030impl DockArea {
2031    /// Every cached container, as `(node, entity)`.
2032    ///
2033    /// Entity ids, not just node ids: node ids alone would compare equal even
2034    /// if every container entity had been torn down and rebuilt under the same
2035    /// key, which is exactly the failure the reconciliation contract exists to
2036    /// prevent.
2037    pub(crate) fn container_entity_ids(&self) -> Vec<(NodeId, gpui::EntityId)> {
2038        let mut ids: Vec<(NodeId, gpui::EntityId)> = self
2039            .groups
2040            .iter()
2041            .map(|(node, cached)| (*node, cached.entity.entity_id()))
2042            .chain(
2043                self.splits
2044                    .iter()
2045                    .map(|(node, cached)| (*node, cached.entity.entity_id())),
2046            )
2047            .collect();
2048        ids.sort();
2049        ids
2050    }
2051}
2052
2053#[cfg(test)]
2054mod tests {
2055    use gpui::{TestAppContext, VisualTestContext};
2056
2057    use std::{
2058        cell::{Cell, RefCell},
2059        rc::Rc,
2060    };
2061
2062    use super::*;
2063    use crate::dock::TabGroupContext;
2064    use crate::dock::test_support::{Log, PanelSignal, TestPanel, drain, drain_active, log_of};
2065
2066    /// The file holds pixels measured in whatever window last saved it, so its
2067    /// total is off the container the layout is restored into.
2068    #[test]
2069    fn slot_sizes_are_re_expressed_as_shares_of_the_container() {
2070        let scaled = scale_sizes_to(px(800.), &[Some(px(300.)), Some(px(100.))]);
2071
2072        assert_eq!(scaled, vec![Some(px(600.)), Some(px(200.))]);
2073    }
2074
2075    /// An unconstrained slot is laid out by flex and takes the leftover, so
2076    /// scaling only its siblings would move a divider nothing asked to move.
2077    #[test]
2078    fn an_unconstrained_slot_leaves_every_size_alone() {
2079        let sizes = [Some(px(300.)), None];
2080
2081        assert_eq!(scale_sizes_to(px(800.), &sizes), sizes.to_vec());
2082    }
2083
2084    /// Nothing to scale against before the first layout pass, or when the
2085    /// recorded sizes carry no length at all.
2086    #[test]
2087    fn an_unusable_container_or_total_leaves_every_size_alone() {
2088        let sizes = [Some(px(300.)), Some(px(100.))];
2089        assert_eq!(scale_sizes_to(px(0.), &sizes), sizes.to_vec());
2090
2091        let zeroed = [Some(px(0.)), Some(px(0.))];
2092        assert_eq!(scale_sizes_to(px(800.), &zeroed), zeroed.to_vec());
2093    }
2094
2095    fn setup(cx: &mut TestAppContext) -> (Entity<DockArea>, &mut VisualTestContext) {
2096        cx.update(|cx| {
2097            let _ = crate::Theme::global_mut(cx);
2098        });
2099        cx.add_window_view(|window, cx| DockArea::new("test-dock", None, window, cx))
2100    }
2101
2102    #[gpui::test]
2103    fn dock_size_change_emits_one_layout_event(cx: &mut TestAppContext) {
2104        let (area, cx) = setup(cx);
2105        cx.update(|window, cx| {
2106            area.update(cx, |area, cx| {
2107                area.set_dock(
2108                    DockPlacement::Left,
2109                    DockLayout::tabs().panel(TestPanel::new("Left", cx)),
2110                    window,
2111                    cx,
2112                );
2113            });
2114        });
2115
2116        let events = Rc::new(Cell::new(0));
2117        let observed = events.clone();
2118        let _subscription = cx.update(|window, cx| {
2119            window.subscribe(&area, cx, move |_, event: &DockEvent, _, _| {
2120                if matches!(event, DockEvent::LayoutChanged) {
2121                    observed.set(observed.get() + 1);
2122                }
2123            })
2124        });
2125
2126        cx.update(|window, cx| {
2127            area.update(cx, |area, cx| {
2128                area.set_dock_size(DockPlacement::Left, px(320.), window, cx);
2129                area.set_dock_size(DockPlacement::Left, px(320.), window, cx);
2130            });
2131        });
2132        assert_eq!(
2133            events.get(),
2134            1,
2135            "only an effective size change is persisted"
2136        );
2137    }
2138
2139    /// Two tab groups side by side, holding one logging panel each.
2140    fn two_groups<'a>(
2141        log: &Log,
2142        cx: &'a mut TestAppContext,
2143    ) -> (
2144        Entity<DockArea>,
2145        Entity<TestPanel>,
2146        &'a mut VisualTestContext,
2147    ) {
2148        let (area, cx) = setup(cx);
2149        let log = log.clone();
2150        let alpha = cx.update(|window, cx| {
2151            let alpha = TestPanel::logging("Alpha", &log, cx);
2152            let beta = TestPanel::logging("Beta", &log, cx);
2153            area.update(cx, |area, cx| {
2154                area.set_center(
2155                    DockLayout::h_split()
2156                        .child(DockLayout::tabs().panel(alpha.clone()), None)
2157                        .child(DockLayout::tabs().panel(beta), None),
2158                    window,
2159                    cx,
2160                );
2161            });
2162            alpha
2163        });
2164        (area, alpha, cx)
2165    }
2166
2167    /// The id of the center split's `ix`-th child container.
2168    fn child_node(area: &Entity<DockArea>, ix: usize, cx: &mut VisualTestContext) -> NodeId {
2169        cx.read(|cx| {
2170            let PaneRef::Split { children, .. } = area
2171                .read(cx)
2172                .layout(DockPlacement::Center)
2173                .unwrap()
2174                .root()
2175                .kind()
2176            else {
2177                panic!("the center root is a split");
2178            };
2179            children[ix].id()
2180        })
2181    }
2182
2183    fn panel_id_of(panel: &Entity<TestPanel>) -> PanelId {
2184        PanelId::from(panel.entity_id())
2185    }
2186
2187    fn move_alpha_into_the_other_group(
2188        area: &Entity<DockArea>,
2189        alpha: &Entity<TestPanel>,
2190        cx: &mut VisualTestContext,
2191    ) {
2192        let target = child_node(area, 1, cx);
2193        let alpha_id = panel_id_of(alpha);
2194        cx.update(|window, cx| {
2195            area.update(cx, |area, cx| {
2196                area.move_panel(
2197                    alpha_id,
2198                    InsertTarget::Tabs {
2199                        node: target,
2200                        ix: None,
2201                        activate: true,
2202                    },
2203                    window,
2204                    cx,
2205                );
2206            });
2207        });
2208        cx.run_until_parked();
2209    }
2210
2211    fn collect_sizes(state: &PanelState, out: &mut Vec<Pixels>) {
2212        if let PanelInfo::Stack { sizes, .. } = &state.info {
2213            out.extend(sizes.iter().copied());
2214        }
2215        for child in &state.children {
2216            collect_sizes(child, out);
2217        }
2218    }
2219
2220    fn register_test_panels(cx: &mut App) {
2221        for name in ["Alpha", "Beta", "Gamma"] {
2222            crate::dock::registry::register_panel(cx, name, move |_, _, cx| {
2223                Arc::new(TestPanel::new(name, cx)) as Arc<dyn PanelView>
2224            });
2225        }
2226    }
2227
2228    /// One tab group holding `names`, installed as the whole center.
2229    ///
2230    /// The `DockItem::tabs` the old `TabPanel` tests built is now a described
2231    /// layout the area reconciles, so the group entity is reached through the
2232    /// tree rather than handed back by the constructor.
2233    fn one_group<'a>(
2234        log: &Log,
2235        names: &[&'static str],
2236        active_ix: Option<usize>,
2237        cx: &'a mut TestAppContext,
2238    ) -> (
2239        Entity<DockArea>,
2240        Vec<Entity<TestPanel>>,
2241        &'a mut VisualTestContext,
2242    ) {
2243        let (area, cx) = setup(cx);
2244        let log = log.clone();
2245        let names = names.to_vec();
2246        let panels = cx.update(|window, cx| {
2247            let panels: Vec<_> = names
2248                .iter()
2249                .map(|name| TestPanel::logging(name, &log, cx))
2250                .collect();
2251            let layout = panels
2252                .iter()
2253                .fold(DockLayout::tabs(), |layout, panel| {
2254                    layout.panel(panel.clone())
2255                })
2256                .active_index(active_ix.unwrap_or(0));
2257            area.update(cx, |area, cx| area.set_center(layout, window, cx));
2258            panels
2259        });
2260        (area, panels, cx)
2261    }
2262
2263    /// The live group behind the center split's `ix`-th child.
2264    fn group_of(
2265        area: &Entity<DockArea>,
2266        ix: usize,
2267        cx: &mut VisualTestContext,
2268    ) -> Entity<TabGroup> {
2269        let node = child_node(area, ix, cx);
2270        cx.read(|cx| area.read(cx).groups.get(&node).unwrap().entity.clone())
2271    }
2272
2273    fn move_panel_into(
2274        area: &Entity<DockArea>,
2275        panel: PanelId,
2276        node: NodeId,
2277        ix: Option<usize>,
2278        activate: bool,
2279        cx: &mut VisualTestContext,
2280    ) {
2281        cx.update(|window, cx| {
2282            area.update(cx, |area, cx| {
2283                area.move_panel(panel, InsertTarget::Tabs { node, ix, activate }, window, cx);
2284            });
2285        });
2286        cx.run_until_parked();
2287    }
2288
2289    fn is_center_empty(area: &Entity<DockArea>, cx: &mut VisualTestContext) -> bool {
2290        cx.read(|cx| area.read(cx).is_empty(DockPlacement::Center, cx))
2291    }
2292
2293    #[gpui::test]
2294    fn a_layout_installs_and_dumps_back_to_the_same_state(cx: &mut TestAppContext) {
2295        let (area, cx) = setup(cx);
2296        cx.update(|window, cx| {
2297            let alpha = TestPanel::new("Alpha", cx);
2298            let beta = TestPanel::new("Beta", cx);
2299            area.update(cx, |area, cx| {
2300                area.set_center(
2301                    DockLayout::h_split()
2302                        .child(DockLayout::tabs().panel(alpha), Some(px(300.)))
2303                        .child(DockLayout::tabs().panel(beta), None),
2304                    window,
2305                    cx,
2306                );
2307            });
2308        });
2309
2310        let state = cx.read(|cx| area.read(cx).dump(cx));
2311        assert_eq!(state.center.panel_name, "StackPanel");
2312        assert_eq!(state.center.children.len(), 2);
2313        assert_eq!(state.center.children[0].children[0].panel_name, "Alpha");
2314        assert_eq!(state.center.children[1].children[0].panel_name, "Beta");
2315    }
2316
2317    #[gpui::test]
2318    fn moving_a_panel_reuses_its_entity(cx: &mut TestAppContext) {
2319        let log = log_of();
2320        let (area, alpha, cx) = two_groups(&log, cx);
2321        cx.run_until_parked();
2322        drain(&log);
2323
2324        let destination = child_node(&area, 1, cx);
2325        let destination_entity = cx.read(|cx| {
2326            area.read(cx)
2327                .groups
2328                .get(&destination)
2329                .unwrap()
2330                .entity
2331                .entity_id()
2332        });
2333
2334        move_alpha_into_the_other_group(&area, &alpha, cx);
2335
2336        assert_eq!(
2337            cx.read(|cx| area
2338                .read(cx)
2339                .groups
2340                .get(&destination)
2341                .unwrap()
2342                .entity
2343                .entity_id()),
2344            destination_entity,
2345            "the group the panel arrived in was reused, not rebuilt"
2346        );
2347
2348        // A liveness flag on the panel would not say this. The invariant is
2349        // that the panel is still in the tree and was never told it was
2350        // removed — which is exactly what `EditResult::removed_panels` encodes
2351        // by excluding moves.
2352        let alpha_id = panel_id_of(&alpha);
2353        assert!(
2354            cx.read(|cx| area
2355                .read(cx)
2356                .layout(DockPlacement::Center)
2357                .unwrap()
2358                .find_panel_node(alpha_id))
2359                .is_some(),
2360            "the moved panel is still in the tree"
2361        );
2362
2363        let state = cx.read(|cx| area.read(cx).dump(cx));
2364        // One child, not two: emptying the first group removes it, and a
2365        // `RootKind::Split` root is never collapsed, so what is left is a
2366        // one-child split root.
2367        assert_eq!(
2368            state.center.children.len(),
2369            1,
2370            "the emptied group collapsed out of the split"
2371        );
2372        assert_eq!(
2373            state.center.children[0].children.len(),
2374            2,
2375            "both panels now share the surviving group"
2376        );
2377    }
2378
2379    #[gpui::test]
2380    fn a_moved_panel_is_not_told_it_was_removed(cx: &mut TestAppContext) {
2381        let log = log_of();
2382        let (area, alpha, cx) = two_groups(&log, cx);
2383        cx.run_until_parked();
2384        drain(&log);
2385
2386        move_alpha_into_the_other_group(&area, &alpha, cx);
2387
2388        assert!(
2389            !drain(&log).contains(&("Alpha", PanelSignal::Removed)),
2390            "moving a panel between groups must never deliver on_removed"
2391        );
2392    }
2393
2394    #[gpui::test]
2395    fn removing_a_panel_does_tell_it_it_was_removed(cx: &mut TestAppContext) {
2396        // Without this, `a_moved_panel_is_not_told_it_was_removed` would pass
2397        // just as well against a `DockArea` that never calls `on_removed` at
2398        // all.
2399        let log = log_of();
2400        let (area, alpha, cx) = two_groups(&log, cx);
2401        cx.run_until_parked();
2402        drain(&log);
2403
2404        cx.update(|window, cx| {
2405            area.update(cx, |area, cx| area.remove_panel(alpha.clone(), window, cx));
2406        });
2407        cx.run_until_parked();
2408
2409        assert!(
2410            drain(&log).contains(&("Alpha", PanelSignal::Removed)),
2411            "a genuine removal must deliver on_removed"
2412        );
2413    }
2414
2415    #[gpui::test]
2416    fn reconciling_an_unchanged_tree_creates_no_entities(cx: &mut TestAppContext) {
2417        let log = log_of();
2418        let (area, _alpha, cx) = two_groups(&log, cx);
2419        cx.run_until_parked();
2420        drain(&log);
2421
2422        let before = cx.read(|cx| area.read(cx).container_entity_ids());
2423        cx.update(|window, cx| area.update(cx, |area, cx| area.reconcile(window, cx)));
2424        let after = cx.read(|cx| area.read(cx).container_entity_ids());
2425
2426        assert!(!before.is_empty(), "there were containers to preserve");
2427        assert_eq!(
2428            before, after,
2429            "a steady-state pass creates and drops nothing"
2430        );
2431        cx.run_until_parked();
2432        assert_eq!(
2433            drain(&log),
2434            vec![],
2435            "and no panel was re-added or re-activated by it"
2436        );
2437    }
2438
2439    #[gpui::test]
2440    fn a_loaded_layout_round_trips_through_dump(cx: &mut TestAppContext) {
2441        let (area, cx) = setup(cx);
2442        cx.update(|_, cx| register_test_panels(cx));
2443
2444        let json = include_str!("fixtures/nested_splits.json");
2445        let state: DockAreaState = serde_json::from_str(json).unwrap();
2446
2447        cx.update(|window, cx| {
2448            area.update(cx, |area, cx| area.load(state.clone(), window, cx).unwrap())
2449        });
2450        let dumped = cx.read(|cx| area.read(cx).dump(cx));
2451
2452        cx.update(|window, cx| {
2453            area.update(cx, |area, cx| {
2454                area.load(dumped.clone(), window, cx).unwrap()
2455            })
2456        });
2457        let again = cx.read(|cx| area.read(cx).dump(cx));
2458
2459        assert_eq!(dumped, again, "load/dump must reach a fixpoint");
2460        assert_eq!(
2461            dumped.center.children.len(),
2462            3,
2463            "the fixture's nesting is flattened, as the state layer already pins"
2464        );
2465        assert_eq!(dumped.center.children[0].children[0].panel_name, "Alpha");
2466    }
2467
2468    #[gpui::test]
2469    fn a_dumped_live_layout_has_no_zero_sizes(cx: &mut TestAppContext) {
2470        let (area, cx) = setup(cx);
2471        cx.update(|window, cx| {
2472            let alpha = TestPanel::new("Alpha", cx);
2473            let beta = TestPanel::new("Beta", cx);
2474            let gamma = TestPanel::new("Gamma", cx);
2475            area.update(cx, |area, cx| {
2476                area.set_center(
2477                    DockLayout::v_split()
2478                        // Unconstrained, which the tree stores as `None` and
2479                        // the writer would otherwise emit as 0.0.
2480                        .child(DockLayout::tabs().panel(alpha), None)
2481                        // Already zero. Resolving only the `None` slots would
2482                        // leave this one writing the same unsafe byte.
2483                        .child(DockLayout::tabs().panel(beta), Some(px(0.)))
2484                        .child(DockLayout::tabs().panel(gamma), Some(px(240.))),
2485                    window,
2486                    cx,
2487                );
2488            });
2489        });
2490
2491        let state = cx.read(|cx| area.read(cx).dump(cx));
2492        let mut sizes = Vec::new();
2493        collect_sizes(&state.center, &mut sizes);
2494
2495        assert!(!sizes.is_empty(), "the layout has slots to check");
2496        assert!(
2497            sizes.iter().all(|size| *size > px(0.)),
2498            "an older build reads a persisted 0.0 back as a real zero-pixel panel: {sizes:?}"
2499        );
2500    }
2501
2502    /// The tree only hears about slot sizes a drag finished on: the `Resized`
2503    /// subscription fires from `done_resizing`, while every window resize
2504    /// rescales `ResizableState::sizes()` silently. So `dump` reads the
2505    /// measurement for a split it has on screen, and this pins that it does —
2506    /// preferring the tree here would persist the described `300.0` after a
2507    /// layout pass has already rescaled that slot to fit the window.
2508    #[gpui::test]
2509    fn a_dumped_split_writes_the_sizes_it_is_actually_drawn_at(cx: &mut TestAppContext) {
2510        let (area, cx) = setup(cx);
2511        cx.update(|window, cx| {
2512            let alpha = TestPanel::new("Alpha", cx);
2513            let beta = TestPanel::new("Beta", cx);
2514            area.update(cx, |area, cx| {
2515                area.set_center(
2516                    DockLayout::h_split()
2517                        .child(DockLayout::tabs().panel(alpha), Some(px(300.)))
2518                        .child(DockLayout::tabs().panel(beta), Some(px(300.))),
2519                    window,
2520                    cx,
2521                );
2522            });
2523        });
2524        cx.run_until_parked();
2525
2526        let root = cx.read(|cx| {
2527            area.read(cx)
2528                .layout(DockPlacement::Center)
2529                .unwrap()
2530                .root()
2531                .id()
2532        });
2533        let measured = cx.read(|cx| area.read(cx).splits[&root].entity.read(cx).sizes().clone());
2534        assert_ne!(
2535            measured,
2536            vec![px(300.), px(300.)],
2537            "the split has to have been rescaled by a layout pass, or this \
2538             test cannot tell the two preferences apart"
2539        );
2540
2541        let state = cx.read(|cx| area.read(cx).dump(cx));
2542        let PanelInfo::Stack { sizes, .. } = &state.center.info else {
2543            panic!("the center writes a stack");
2544        };
2545        assert_eq!(
2546            sizes, &measured,
2547            "the written sizes are the ones on screen, not the ones the tree \
2548             was built from"
2549        );
2550    }
2551
2552    #[gpui::test]
2553    fn set_split_sizes_restores_a_share_and_reports_it(cx: &mut TestAppContext) {
2554        let (area, cx) = setup(cx);
2555        cx.update(|window, cx| {
2556            let alpha = TestPanel::new("Alpha", cx);
2557            let beta = TestPanel::new("Beta", cx);
2558            area.update(cx, |area, cx| {
2559                area.set_center(
2560                    DockLayout::h_split()
2561                        .child(DockLayout::tabs().panel(alpha), Some(px(300.)))
2562                        .child(DockLayout::tabs().panel(beta), Some(px(300.))),
2563                    window,
2564                    cx,
2565                );
2566            });
2567        });
2568        cx.run_until_parked();
2569
2570        let root = cx.read(|cx| {
2571            area.read(cx)
2572                .layout(DockPlacement::Center)
2573                .unwrap()
2574                .root()
2575                .id()
2576        });
2577        let events = Rc::new(Cell::new(0));
2578        let observed = events.clone();
2579        let _subscription = cx.update(|window, cx| {
2580            window.subscribe(&area, cx, move |_, event: &DockEvent, _, _| {
2581                if matches!(event, DockEvent::LayoutChanged) {
2582                    observed.set(observed.get() + 1);
2583                }
2584            })
2585        });
2586
2587        cx.update(|window, cx| {
2588            area.update(cx, |area, cx| {
2589                area.set_split_sizes(root, vec![px(100.), px(300.)], window, cx);
2590            });
2591        });
2592        cx.run_until_parked();
2593        assert_eq!(events.get(), 1);
2594        let measured = cx.read(|cx| area.read(cx).splits[&root].entity.read(cx).sizes().clone());
2595        let share = measured[0].as_f32() / (measured[0].as_f32() + measured[1].as_f32());
2596        assert!((share - 0.25).abs() < 0.01, "measured {measured:?}");
2597
2598        cx.update(|window, cx| {
2599            area.update(cx, |area, cx| {
2600                area.set_split_sizes(root, vec![px(10.)], window, cx);
2601            });
2602        });
2603        cx.run_until_parked();
2604        assert_eq!(events.get(), 1);
2605        let after = cx.read(|cx| area.read(cx).splits[&root].entity.read(cx).sizes().clone());
2606        assert_eq!(after, measured);
2607    }
2608
2609    /// A drop that splits carries no size — `TabGroup` builds
2610    /// `InsertTarget::Split { size: None }` — so the split has to decide one,
2611    /// and sharing the container equally is the decision. Passing the `None`
2612    /// straight to `ResizableState` instead makes the new slot the flexible
2613    /// one among fixed siblings, and it stops looking like a half.
2614    #[gpui::test]
2615    fn a_panel_dropped_beside_another_takes_half_the_split(cx: &mut TestAppContext) {
2616        let log = Log::default();
2617        let (area, panels, cx) = one_group(&log, &["Alpha", "Beta"], None, cx);
2618        let group = child_node(&area, 0, cx);
2619        let beta = panel_id_of(&panels[1]);
2620
2621        cx.update(|window, cx| {
2622            area.update(cx, |area, cx| {
2623                area.move_panel(
2624                    beta,
2625                    InsertTarget::Split {
2626                        node: group,
2627                        placement: Placement::Right,
2628                        size: None,
2629                    },
2630                    window,
2631                    cx,
2632                );
2633            });
2634        });
2635        cx.run_until_parked();
2636
2637        let root = cx.read(|cx| {
2638            area.read(cx)
2639                .layout(DockPlacement::Center)
2640                .unwrap()
2641                .root()
2642                .id()
2643        });
2644        let sizes = cx.read(|cx| area.read(cx).splits[&root].entity.read(cx).sizes().clone());
2645
2646        assert_eq!(sizes.len(), 2, "the drop splits the center in two");
2647        let (left, right) = (sizes[0].as_f32(), sizes[1].as_f32());
2648        assert!(
2649            (left - right).abs() <= (left + right) * 0.02,
2650            "the two halves must be within 2% of each other, got {left} and {right}"
2651        );
2652    }
2653
2654    /// Moving a panel this area does not own is a no-op, not a ghost insert.
2655    #[gpui::test]
2656    fn a_move_of_an_unowned_panel_is_ignored(cx: &mut TestAppContext) {
2657        let log = Log::default();
2658        let (area, _panels, cx) = one_group(&log, &["Alpha", "Beta"], None, cx);
2659        let group = child_node(&area, 0, cx);
2660        let before = cx.read(|cx| area.read(cx).dump(cx));
2661
2662        // A PanelId from nowhere, as if dropped from another DockArea.
2663        move_panel_into(&area, PanelId::from_u64(9_999_999), group, None, true, cx);
2664
2665        let after = cx.read(|cx| area.read(cx).dump(cx));
2666        assert_eq!(
2667            before, after,
2668            "an unowned panel move must not touch the tree"
2669        );
2670    }
2671
2672    /// The other drop geometry: a placement whose axis differs from the
2673    /// parent's wraps the target in a fresh split, so the sizes are decided
2674    /// by a `ResizableState` that has never been measured.
2675    #[gpui::test]
2676    fn a_panel_dropped_across_the_axis_still_takes_half(cx: &mut TestAppContext) {
2677        let log = Log::default();
2678        let (area, panels, cx) = one_group(&log, &["Alpha", "Beta"], None, cx);
2679        let group = child_node(&area, 0, cx);
2680        let beta = panel_id_of(&panels[1]);
2681
2682        cx.update(|window, cx| {
2683            area.update(cx, |area, cx| {
2684                area.move_panel(
2685                    beta,
2686                    InsertTarget::Split {
2687                        node: group,
2688                        placement: Placement::Bottom,
2689                        size: None,
2690                    },
2691                    window,
2692                    cx,
2693                );
2694            });
2695        });
2696        cx.run_until_parked();
2697
2698        // Dropping across the axis wraps the target in a new split, which
2699        // becomes the center root's only child — the root itself still holds
2700        // one slot.
2701        let wrapper = child_node(&area, 0, cx);
2702        let sizes = cx.read(|cx| {
2703            area.read(cx).splits[&wrapper]
2704                .entity
2705                .read(cx)
2706                .sizes()
2707                .clone()
2708        });
2709        assert_eq!(sizes.len(), 2, "the drop splits the group in two");
2710        let (top, bottom) = (sizes[0].as_f32(), sizes[1].as_f32());
2711        assert!(
2712            (top - bottom).abs() <= (top + bottom) * 0.02,
2713            "the two halves must be within 2% of each other, got {top} and {bottom}"
2714        );
2715    }
2716
2717    /// A drop into a split that already holds more than one slot, which is the
2718    /// shape a real workspace is in by the time anyone drags anything.
2719    #[gpui::test]
2720    fn a_panel_dropped_into_a_populated_split_takes_an_even_share(cx: &mut TestAppContext) {
2721        let (area, cx) = setup(cx);
2722        let panels = cx.update(|window, cx| {
2723            let alpha = TestPanel::new("Alpha", cx);
2724            let beta = TestPanel::new("Beta", cx);
2725            let gamma = TestPanel::new("Gamma", cx);
2726            area.update(cx, |area, cx| {
2727                area.set_center(
2728                    DockLayout::h_split()
2729                        .child(DockLayout::tabs().panel(alpha.clone()), Some(px(240.)))
2730                        .child(
2731                            DockLayout::tabs().panel(beta.clone()).panel(gamma.clone()),
2732                            None,
2733                        ),
2734                    window,
2735                    cx,
2736                );
2737            });
2738            vec![alpha, beta, gamma]
2739        });
2740        cx.run_until_parked();
2741
2742        let right = child_node(&area, 1, cx);
2743        let gamma = panel_id_of(&panels[2]);
2744        cx.update(|window, cx| {
2745            area.update(cx, |area, cx| {
2746                area.move_panel(
2747                    gamma,
2748                    InsertTarget::Split {
2749                        node: right,
2750                        placement: Placement::Right,
2751                        size: None,
2752                    },
2753                    window,
2754                    cx,
2755                );
2756            });
2757        });
2758        cx.run_until_parked();
2759
2760        let root = cx.read(|cx| {
2761            area.read(cx)
2762                .layout(DockPlacement::Center)
2763                .unwrap()
2764                .root()
2765                .id()
2766        });
2767        let sizes = cx.read(|cx| area.read(cx).splits[&root].entity.read(cx).sizes().clone());
2768        assert_eq!(sizes.len(), 3, "three slots side by side");
2769        let dropped = sizes[2].as_f32();
2770        let neighbour = sizes[1].as_f32();
2771        assert!(
2772            (dropped - neighbour).abs() <= (dropped + neighbour) * 0.02,
2773            "the dropped panel splits its neighbour evenly, got neighbour {neighbour} and dropped {dropped}"
2774        );
2775    }
2776
2777    /// A dock's root is usually a bare tab group, so a drop beside it takes
2778    /// the "wrap the target in a new split" path rather than the "insert into
2779    /// the existing split" one — and that split has never been measured.
2780    #[gpui::test]
2781    fn a_panel_dropped_beside_a_dock_takes_half(cx: &mut TestAppContext) {
2782        for placement in [DockPlacement::Bottom, DockPlacement::Left] {
2783            let (area, cx) = setup(cx);
2784            let dropped = cx.update(|window, cx| {
2785                let resident = TestPanel::new("Resident", cx);
2786                let dropped = TestPanel::new("Dropped", cx);
2787                area.update(cx, |area, cx| {
2788                    area.set_center(
2789                        DockLayout::tabs().panel(TestPanel::new("Center", cx)),
2790                        window,
2791                        cx,
2792                    );
2793                    area.set_dock(
2794                        placement,
2795                        DockLayout::tabs().panel(resident).panel(dropped.clone()),
2796                        window,
2797                        cx,
2798                    );
2799                    area.set_dock_size(placement, px(400.), window, cx);
2800                });
2801                dropped
2802            });
2803            cx.run_until_parked();
2804
2805            let group = cx.read(|cx| {
2806                area.read(cx)
2807                    .layout(placement)
2808                    .unwrap()
2809                    .find_panel_node(panel_id_of(&dropped))
2810                    .expect("both panels start in the dock's only group")
2811            });
2812
2813            cx.update(|window, cx| {
2814                area.update(cx, |area, cx| {
2815                    area.move_panel(
2816                        panel_id_of(&dropped),
2817                        InsertTarget::Split {
2818                            node: group,
2819                            placement: Placement::Bottom,
2820                            size: None,
2821                        },
2822                        window,
2823                        cx,
2824                    );
2825                });
2826            });
2827            cx.run_until_parked();
2828
2829            let split = cx.read(|cx| {
2830                let tree = area.read(cx).layout(placement).unwrap();
2831                let root = tree.root();
2832                match root.kind() {
2833                    PaneRef::Split { .. } => root.id(),
2834                    _ => panic!("the drop must have produced a split"),
2835                }
2836            });
2837            let sizes = cx.read(|cx| area.read(cx).splits[&split].entity.read(cx).sizes().clone());
2838
2839            assert_eq!(sizes.len(), 2, "{placement:?}: the drop splits in two");
2840            let (first, second) = (sizes[0].as_f32(), sizes[1].as_f32());
2841            assert!(
2842                (first - second).abs() <= (first + second) * 0.02,
2843                "{placement:?}: expected halves, got {first} and {second}"
2844            );
2845        }
2846    }
2847
2848    /// A slot given an explicit size keeps it on the frame after the first.
2849    ///
2850    /// The layout is laid out once with a flexible sibling, and the flexible
2851    /// slot's placeholder measurement used to drag the fixed one with it when
2852    /// the container was first measured — the layout visibly jumped once,
2853    /// then settled.
2854    #[gpui::test]
2855    fn an_explicit_slot_size_survives_the_first_layout_pass(cx: &mut TestAppContext) {
2856        let (area, cx) = setup(cx);
2857        cx.update(|window, cx| {
2858            let sidebar = TestPanel::new("Sidebar", cx);
2859            let content = TestPanel::new("Content", cx);
2860            area.update(cx, |area, cx| {
2861                area.set_center(
2862                    DockLayout::h_split()
2863                        .child(DockLayout::tabs().panel(sidebar), Some(px(200.)))
2864                        .child(DockLayout::tabs().panel(content), None),
2865                    window,
2866                    cx,
2867                );
2868            });
2869        });
2870        cx.run_until_parked();
2871
2872        let root = cx.read(|cx| {
2873            area.read(cx)
2874                .layout(DockPlacement::Center)
2875                .unwrap()
2876                .root()
2877                .id()
2878        });
2879        let sizes = cx.read(|cx| area.read(cx).splits[&root].entity.read(cx).sizes().clone());
2880
2881        // Within a couple of pixels of what was asked for — the measured
2882        // value carries the frame's own rounding. The bug this pins made it
2883        // 587px.
2884        let fixed = sizes
2885            .first()
2886            .copied()
2887            .expect("the split has slots")
2888            .as_f32();
2889        assert!(
2890            (fixed - 200.).abs() <= 4.,
2891            "the fixed slot keeps its 200px instead of being rescaled by the \
2892             flexible sibling's placeholder, got {fixed}"
2893        );
2894    }
2895
2896    /// A panel that draws a measurable box, so a test can read where a slot
2897    /// actually landed rather than what `ResizableState` believes about it.
2898    struct MeasuredPanel {
2899        name: &'static str,
2900        focus_handle: FocusHandle,
2901    }
2902
2903    impl MeasuredPanel {
2904        fn new(name: &'static str, cx: &mut App) -> Entity<Self> {
2905            cx.new(|cx| Self {
2906                name,
2907                focus_handle: cx.focus_handle(),
2908            })
2909        }
2910    }
2911
2912    impl Panel for MeasuredPanel {
2913        fn panel_name(&self) -> &'static str {
2914            self.name
2915        }
2916    }
2917
2918    impl EventEmitter<PanelEvent> for MeasuredPanel {}
2919
2920    impl Focusable for MeasuredPanel {
2921        fn focus_handle(&self, _: &App) -> FocusHandle {
2922            self.focus_handle.clone()
2923        }
2924    }
2925
2926    impl Render for MeasuredPanel {
2927        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2928            let name = self.name;
2929            div().size_full().debug_selector(move || name.into())
2930        }
2931    }
2932
2933    fn draw_frames(cx: &mut VisualTestContext, frames: usize) {
2934        for _ in 0..frames {
2935            cx.update(|window, cx| window.draw(cx).clear(cx));
2936        }
2937    }
2938
2939    /// Switching a tab edits one group, yet `commit` reconciles every
2940    /// container. Reconciling a split the edit did not touch re-adopted the
2941    /// tree's `None` for its flexible slot, un-pinning the size the first
2942    /// layout pass had measured for it, so the split re-flexed from scratch
2943    /// and its sized neighbour shrank. This is the dock example's left column
2944    /// getting shorter on every tab click in the bottom dock.
2945    #[gpui::test]
2946    fn switching_a_tab_leaves_an_untouched_split_where_it_was_drawn(cx: &mut TestAppContext) {
2947        let (area, cx) = setup(cx);
2948        cx.update(|window, cx| {
2949            area.update(cx, |area, cx| {
2950                area.set_center(
2951                    DockLayout::tabs().panel(TestPanel::new("Center", cx)),
2952                    window,
2953                    cx,
2954                );
2955                area.set_dock(
2956                    DockPlacement::Left,
2957                    DockLayout::v_split()
2958                        .child(
2959                            DockLayout::tabs().panel(MeasuredPanel::new("upper-left", cx)),
2960                            None,
2961                        )
2962                        .child(
2963                            DockLayout::tabs().panel(MeasuredPanel::new("lower-left", cx)),
2964                            Some(px(360.)),
2965                        ),
2966                    window,
2967                    cx,
2968                );
2969                area.set_dock_size(DockPlacement::Left, px(350.), window, cx);
2970                area.set_dock(
2971                    DockPlacement::Bottom,
2972                    DockLayout::tabs()
2973                        .panel(TestPanel::new("Tooltip", cx))
2974                        .panel(TestPanel::new("Icon", cx)),
2975                    window,
2976                    cx,
2977                );
2978                area.set_dock_size(DockPlacement::Bottom, px(200.), window, cx);
2979            });
2980        });
2981        cx.run_until_parked();
2982        draw_frames(cx, 3);
2983        let before = (
2984            cx.debug_bounds("upper-left").unwrap(),
2985            cx.debug_bounds("lower-left").unwrap(),
2986        );
2987
2988        let bottom = cx.read(|cx| {
2989            area.read(cx)
2990                .layout(DockPlacement::Bottom)
2991                .unwrap()
2992                .root()
2993                .id()
2994        });
2995        let group = cx.read(|cx| area.read(cx).groups[&bottom].entity.clone());
2996        cx.update(|window, cx| {
2997            group.update(cx, |group, cx| group.select_tab(1, window, cx));
2998        });
2999        cx.run_until_parked();
3000        draw_frames(cx, 3);
3001        let after = (
3002            cx.debug_bounds("upper-left").unwrap(),
3003            cx.debug_bounds("lower-left").unwrap(),
3004        );
3005
3006        assert_eq!(
3007            before, after,
3008            "a tab change in the bottom dock must not move the left split"
3009        );
3010    }
3011
3012    /// The other way a reconcile could move an untouched split: its file holds
3013    /// pixels measured in some other window, the first layout pass rescaled
3014    /// the state to the container it actually has, and handing the file's
3015    /// pixels back on a tab change slides the divider to a third position.
3016    #[gpui::test]
3017    fn switching_a_tab_keeps_a_restored_split_at_its_rescaled_share(cx: &mut TestAppContext) {
3018        let (area, cx) = setup(cx);
3019        cx.update(|window, cx| {
3020            area.update(cx, |area, cx| {
3021                area.set_center(
3022                    DockLayout::h_split()
3023                        .child(
3024                            DockLayout::tabs()
3025                                .panel(TestPanel::new("Alpha", cx))
3026                                .panel(TestPanel::new("Beta", cx)),
3027                            Some(px(620.)),
3028                        )
3029                        .child(
3030                            DockLayout::tabs().panel(MeasuredPanel::new("second", cx)),
3031                            Some(px(350.)),
3032                        ),
3033                    window,
3034                    cx,
3035                );
3036            });
3037        });
3038        cx.run_until_parked();
3039        draw_frames(cx, 3);
3040        // The second slot's box tells where the divider is: its left edge is
3041        // the first slot's width, and the two add up to the container.
3042        let before = cx.debug_bounds("second").unwrap();
3043        assert_ne!(
3044            before.right(),
3045            px(970.),
3046            "the window must not match the recorded total, or this test cannot \
3047             tell a rescaled split from the file's pixels"
3048        );
3049
3050        let group = group_of(&area, 0, cx);
3051        cx.update(|window, cx| {
3052            group.update(cx, |group, cx| group.select_tab(1, window, cx));
3053        });
3054        cx.run_until_parked();
3055        draw_frames(cx, 3);
3056        let after = cx.debug_bounds("second").unwrap();
3057
3058        assert_eq!(
3059            before, after,
3060            "a tab change must not hand the file's pixels back to the split"
3061        );
3062    }
3063
3064    /// The headline claim of the whole extraction, in one place: a layout
3065    /// written by the shipped dock loads into the tree world, draws, and saves
3066    /// back to a state the next load reproduces exactly.
3067    ///
3068    /// The fixture is a real user's file — a two-group center plus all three
3069    /// docks — and its panels are not registered here, so every leaf takes the
3070    /// placeholder path that carries the original `PanelState` forward. That
3071    /// is the load-bearing half: a build that dropped an unknown panel would
3072    /// still reach a fixpoint, so the region assertions below check the
3073    /// content is *there* before the fixpoint says it is stable.
3074    #[gpui::test]
3075    fn the_shipped_fixture_survives_a_load_dump_load_round_trip(cx: &mut TestAppContext) {
3076        let (area, cx) = setup(cx);
3077        let fixture: DockAreaState =
3078            serde_json::from_str(include_str!("fixtures/layout.json")).unwrap();
3079
3080        cx.update(|window, cx| area.update(cx, |area, cx| area.load(fixture, window, cx).unwrap()));
3081        cx.run_until_parked();
3082        let first = cx.read(|cx| area.read(cx).dump(cx));
3083
3084        assert_eq!(first.center.children.len(), 2, "the center's two groups");
3085        assert_eq!(first.center.children[0].children.len(), 15);
3086        assert_eq!(first.center.children[1].children.len(), 1);
3087        for dock in [&first.left_dock, &first.bottom_dock, &first.right_dock] {
3088            let dock = dock.as_ref().expect("all three docks are attached");
3089            assert!(dock.open());
3090            assert!(
3091                !dock.panel().children.is_empty(),
3092                "a dock that loaded empty would round-trip just as stably"
3093            );
3094        }
3095        assert_eq!(first.left_dock.as_ref().unwrap().size(), px(350.));
3096        assert_eq!(first.bottom_dock.as_ref().unwrap().size(), px(200.));
3097        assert_eq!(first.right_dock.as_ref().unwrap().size(), px(320.));
3098
3099        cx.update(|window, cx| {
3100            area.update(cx, |area, cx| area.load(first.clone(), window, cx).unwrap())
3101        });
3102        cx.run_until_parked();
3103        let second = cx.read(|cx| area.read(cx).dump(cx));
3104
3105        assert_eq!(second, first, "dump == dump(load(dump))");
3106    }
3107
3108    #[gpui::test]
3109    fn an_unregistered_panel_survives_a_load_and_save_round_trip(cx: &mut TestAppContext) {
3110        let (area, cx) = setup(cx);
3111        cx.update(|_, cx| register_test_panels(cx));
3112
3113        let json = include_str!("fixtures/unregistered_panel.json");
3114        let state: DockAreaState = serde_json::from_str(json).unwrap();
3115
3116        cx.update(|window, cx| area.update(cx, |area, cx| area.load(state, window, cx).unwrap()));
3117        let dumped = cx.read(|cx| area.read(cx).dump(cx));
3118
3119        let leaf = &dumped.center.children[0].children[0];
3120        assert_eq!(leaf.panel_name, "PanelFromTheFuture");
3121        assert_eq!(
3122            leaf.info,
3123            PanelInfo::panel(serde_json::json!({"keep": "me"})),
3124            "a panel this build cannot construct keeps its payload"
3125        );
3126    }
3127
3128    #[gpui::test]
3129    fn a_dock_carries_its_own_tree_and_survives_a_round_trip(cx: &mut TestAppContext) {
3130        let (area, cx) = setup(cx);
3131        cx.update(|window, cx| {
3132            let alpha = TestPanel::new("Alpha", cx);
3133            let beta = TestPanel::new("Beta", cx);
3134            area.update(cx, |area, cx| {
3135                area.set_center(DockLayout::tabs().panel(alpha), window, cx);
3136                area.set_dock(
3137                    DockPlacement::Left,
3138                    DockLayout::tabs().panel(beta),
3139                    window,
3140                    cx,
3141                );
3142            });
3143        });
3144
3145        // Node ids are globally allocated, so the center and the dock never
3146        // claim the same entity-cache slot.
3147        //
3148        // Comparing the two *roots* would not pin this: under a per-tree
3149        // counter the center's root is minted after its tab group and the
3150        // dock's is not, so the roots differ anyway. The collision is between
3151        // the two trees' tab-group nodes, and the property the cache actually
3152        // depends on is that no id is shared at all.
3153        let center_ids = cx.read(|cx| {
3154            area.read(cx)
3155                .layout(DockPlacement::Center)
3156                .unwrap()
3157                .node_ids()
3158        });
3159        let dock_ids = cx.read(|cx| {
3160            area.read(cx)
3161                .layout(DockPlacement::Left)
3162                .unwrap()
3163                .node_ids()
3164        });
3165        assert!(!center_ids.is_empty() && !dock_ids.is_empty());
3166        assert!(
3167            center_ids.iter().all(|id| !dock_ids.contains(id)),
3168            "every tree in one area must draw from one id space: \
3169             center {center_ids:?} vs left {dock_ids:?}"
3170        );
3171
3172        let state = cx.read(|cx| area.read(cx).dump(cx));
3173        let left = state.left_dock.clone().expect("the left dock is written");
3174        assert_eq!(left.placement(), DockPlacement::Left);
3175        assert!(left.open());
3176        assert_eq!(left.panel().children[0].panel_name, "Beta");
3177        assert!(state.right_dock.is_none());
3178    }
3179
3180    #[gpui::test]
3181    fn a_panel_moved_between_regions_keeps_its_active_state(cx: &mut TestAppContext) {
3182        let log = log_of();
3183        let (area, alpha, cx) = two_groups(&log, cx);
3184        cx.run_until_parked();
3185        // Alpha is the displayed tab of its own group, so it has been told
3186        // `true` exactly once.
3187        assert!(drain(&log).contains(&("Alpha", PanelSignal::Active(true))));
3188
3189        move_alpha_into_the_other_group(&area, &alpha, cx);
3190
3191        assert!(
3192            !drain(&log).contains(&("Alpha", PanelSignal::Active(true))),
3193            "a displayed panel dragged to another group must not be told `true` twice"
3194        );
3195    }
3196
3197    #[gpui::test]
3198    fn a_groups_close_intent_reaches_the_tree(cx: &mut TestAppContext) {
3199        // Nothing else here proves `DockArea` subscribes to `TabGroupEvent`
3200        // at all: a group reports intents and does nothing itself, so an
3201        // unsubscribed area is a dock region that silently does nothing.
3202        let log = log_of();
3203        let (area, alpha, cx) = two_groups(&log, cx);
3204        cx.run_until_parked();
3205        drain(&log);
3206
3207        let node = child_node(&area, 0, cx);
3208        let alpha_id = panel_id_of(&alpha);
3209        cx.update(|_, cx| {
3210            let group = area.read(cx).groups.get(&node).unwrap().entity.clone();
3211            group.update(cx, |group, cx| group.close_panel(alpha_id, cx));
3212        });
3213        cx.run_until_parked();
3214
3215        assert!(
3216            cx.read(|cx| area
3217                .read(cx)
3218                .layout(DockPlacement::Center)
3219                .unwrap()
3220                .find_panel_node(alpha_id))
3221                .is_none(),
3222            "the close intent was applied to the tree"
3223        );
3224        assert!(drain(&log).contains(&("Alpha", PanelSignal::Removed)));
3225    }
3226
3227    #[gpui::test]
3228    fn replacing_the_center_tells_the_panels_that_left(cx: &mut TestAppContext) {
3229        let log = log_of();
3230        let (area, _alpha, cx) = two_groups(&log, cx);
3231        cx.run_until_parked();
3232        drain(&log);
3233
3234        cx.update(|window, cx| {
3235            let gamma = TestPanel::new("Gamma", cx);
3236            area.update(cx, |area, cx| {
3237                area.set_center(DockLayout::tabs().panel(gamma), window, cx)
3238            });
3239        });
3240        cx.run_until_parked();
3241
3242        let seen = drain(&log);
3243        assert!(seen.contains(&("Alpha", PanelSignal::Removed)));
3244        assert!(seen.contains(&("Beta", PanelSignal::Removed)));
3245    }
3246
3247    #[gpui::test]
3248    fn closing_a_zoomed_panel_clears_the_zoom(cx: &mut TestAppContext) {
3249        let log = log_of();
3250        let (area, alpha, cx) = two_groups(&log, cx);
3251        cx.run_until_parked();
3252
3253        let node = child_node(&area, 0, cx);
3254        cx.update(|window, cx| area.update(cx, |area, cx| area.set_zoomed_in(node, window, cx)));
3255        assert!(cx.read(|cx| area.read(cx).is_zoomed()));
3256
3257        cx.update(|window, cx| {
3258            area.update(cx, |area, cx| area.remove_panel(alpha.clone(), window, cx))
3259        });
3260
3261        assert!(
3262            !cx.read(|cx| area.read(cx).is_zoomed()),
3263            "a zoomed panel that left the dock must not keep filling it"
3264        );
3265    }
3266
3267    /// The skin's stand-in for a panel this build cannot construct. It keeps
3268    /// the original state, which is the obligation
3269    /// [`DockAreaRenderer::build_placeholder`] documents.
3270    struct SkinPlaceholder {
3271        state: PanelState,
3272        focus_handle: FocusHandle,
3273    }
3274
3275    impl Panel for SkinPlaceholder {
3276        fn panel_name(&self) -> &'static str {
3277            "SkinPlaceholder"
3278        }
3279
3280        fn dump(&self, _: &App) -> PanelState {
3281            self.state.clone()
3282        }
3283    }
3284
3285    impl EventEmitter<PanelEvent> for SkinPlaceholder {}
3286
3287    impl Focusable for SkinPlaceholder {
3288        fn focus_handle(&self, _: &App) -> FocusHandle {
3289            self.focus_handle.clone()
3290        }
3291    }
3292
3293    impl Render for SkinPlaceholder {
3294        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3295            Empty
3296        }
3297    }
3298
3299    struct PlaceholderSkin {
3300        asked: Rc<std::cell::RefCell<Vec<String>>>,
3301    }
3302
3303    impl DockAreaRenderer for PlaceholderSkin {
3304        fn build_placeholder(
3305            &self,
3306            state: &PanelState,
3307            _: &mut Window,
3308            cx: &mut App,
3309        ) -> Option<Arc<dyn PanelView>> {
3310            self.asked.borrow_mut().push(state.panel_name.clone());
3311            let state = state.clone();
3312            Some(Arc::new(cx.new(|cx| SkinPlaceholder {
3313                state,
3314                focus_handle: cx.focus_handle(),
3315            })))
3316        }
3317
3318        fn tab_group_renderer(&self) -> Rc<dyn TabGroupRenderer> {
3319            Rc::new(BareTabGroup)
3320        }
3321    }
3322
3323    /// A panel no builder answers for becomes the skin's placeholder rather
3324    /// than base's draw-nothing one, so the "unknown panel" message the old
3325    /// `InvalidPanel` drew has somewhere to live.
3326    #[gpui::test]
3327    fn an_unbuildable_panel_becomes_the_skins_placeholder(cx: &mut TestAppContext) {
3328        cx.update(|cx| {
3329            let _ = crate::Theme::global_mut(cx);
3330        });
3331        let asked: Rc<std::cell::RefCell<Vec<String>>> = Rc::default();
3332        let skin = Rc::new(PlaceholderSkin {
3333            asked: asked.clone(),
3334        });
3335        let (area, cx) = cx.add_window_view(|window, cx| {
3336            DockArea::new("test-dock", None, window, cx).with_renderer(skin)
3337        });
3338
3339        // Nothing is registered, so the round trip cannot rebuild this panel.
3340        cx.update(|window, cx| {
3341            let ghost = TestPanel::new("Ghost", cx);
3342            area.update(cx, |area, cx| {
3343                area.set_center(DockLayout::tabs().panel(ghost), window, cx)
3344            });
3345        });
3346        let state = cx.read(|cx| area.read(cx).dump(cx));
3347        cx.update(|window, cx| area.update(cx, |area, cx| area.load(state, window, cx).unwrap()));
3348        cx.run_until_parked();
3349
3350        assert_eq!(*asked.borrow(), vec!["Ghost".to_string()]);
3351        assert_eq!(
3352            cx.read(|cx| area
3353                .read(cx)
3354                .panels
3355                .values()
3356                .map(|panel| panel.panel_name(cx))
3357                .collect::<Vec<_>>()),
3358            vec!["SkinPlaceholder"],
3359            "base installed the skin's placeholder, not its own"
3360        );
3361        assert_eq!(
3362            cx.read(|cx| area.read(cx).dump(cx)).center.children[0].children[0].panel_name,
3363            "Ghost",
3364            "and the unknown panel still survives the next save"
3365        );
3366    }
3367
3368    #[gpui::test]
3369    fn removing_a_non_tail_child_shifts_the_split_sizes_with_it(cx: &mut TestAppContext) {
3370        // `ResizableState` keeps the authoritative size on `panels[ix]`, so a
3371        // tail-truncating sync leaves the survivors of a non-tail removal
3372        // wearing their predecessors' widths.
3373        let log = log_of();
3374        let (area, cx) = setup(cx);
3375        let alpha = cx.update(|window, cx| {
3376            let alpha = TestPanel::logging("Alpha", &log, cx);
3377            let beta = TestPanel::logging("Beta", &log, cx);
3378            let gamma = TestPanel::logging("Gamma", &log, cx);
3379            area.update(cx, |area, cx| {
3380                area.set_center(
3381                    DockLayout::h_split()
3382                        .child(DockLayout::tabs().panel(alpha.clone()), Some(px(100.)))
3383                        .child(DockLayout::tabs().panel(beta), Some(px(200.)))
3384                        .child(DockLayout::tabs().panel(gamma), Some(px(300.))),
3385                    window,
3386                    cx,
3387                );
3388            });
3389            alpha
3390        });
3391
3392        let root = cx.read(|cx| {
3393            area.read(cx)
3394                .layout(DockPlacement::Center)
3395                .unwrap()
3396                .root()
3397                .id()
3398        });
3399        let split = cx.read(|cx| area.read(cx).splits.get(&root).unwrap().entity.clone());
3400        let sizes = |cx: &mut VisualTestContext| cx.read(|cx| split.read(cx).sizes().clone());
3401
3402        // Absolute widths are `ResizableState`'s business — it redistributes
3403        // against the measured container — so what is asserted is which slot
3404        // disappeared, through the ratio the survivors keep.
3405        let before = sizes(cx);
3406        assert_eq!(before.len(), 3);
3407        let kept_if_correct = before[1] / before[2];
3408        let kept_if_truncated = before[0] / before[1];
3409        assert!(
3410            (kept_if_correct - kept_if_truncated).abs() > 0.1,
3411            "the fixture must be able to tell the two outcomes apart"
3412        );
3413
3414        cx.update(|window, cx| area.update(cx, |area, cx| area.remove_panel(alpha, window, cx)));
3415
3416        let after = sizes(cx);
3417        assert_eq!(after.len(), 2);
3418        assert!(
3419            (after[0] / after[1] - kept_if_correct).abs() < 0.01,
3420            "the survivors kept their own proportions: slot 0 was removed, not \
3421             the tail — got {after:?} from {before:?}"
3422        );
3423    }
3424
3425    #[gpui::test]
3426    fn a_panel_moves_between_the_center_and_a_dock(cx: &mut TestAppContext) {
3427        let log = log_of();
3428        let (area, alpha, cx) = two_groups(&log, cx);
3429        cx.update(|window, cx| {
3430            let gamma = TestPanel::logging("Gamma", &log, cx);
3431            area.update(cx, |area, cx| {
3432                area.set_dock(
3433                    DockPlacement::Left,
3434                    DockLayout::tabs().panel(gamma),
3435                    window,
3436                    cx,
3437                );
3438            });
3439        });
3440        cx.run_until_parked();
3441        drain(&log);
3442
3443        let alpha_id = panel_id_of(&alpha);
3444        let dock_group = cx.read(|cx| {
3445            area.read(cx)
3446                .layout(DockPlacement::Left)
3447                .unwrap()
3448                .root()
3449                .id()
3450        });
3451
3452        cx.update(|window, cx| {
3453            area.update(cx, |area, cx| {
3454                area.move_panel(
3455                    alpha_id,
3456                    InsertTarget::Tabs {
3457                        node: dock_group,
3458                        ix: None,
3459                        activate: true,
3460                    },
3461                    window,
3462                    cx,
3463                );
3464            });
3465        });
3466        cx.run_until_parked();
3467
3468        assert!(
3469            cx.read(|cx| area
3470                .read(cx)
3471                .layout(DockPlacement::Center)
3472                .unwrap()
3473                .find_panel_node(alpha_id))
3474                .is_none(),
3475            "the panel left the center"
3476        );
3477        assert_eq!(
3478            cx.read(|cx| area
3479                .read(cx)
3480                .layout(DockPlacement::Left)
3481                .unwrap()
3482                .find_panel_node(alpha_id)),
3483            Some(dock_group),
3484            "and arrived in the dock's group"
3485        );
3486
3487        let seen = drain(&log);
3488        assert!(
3489            !seen.contains(&("Alpha", PanelSignal::Removed)),
3490            "crossing regions is still a move, not a removal"
3491        );
3492        assert!(
3493            !seen.contains(&("Alpha", PanelSignal::Active(true))),
3494            "and it was displayed in both, so it is not told `true` twice"
3495        );
3496    }
3497
3498    #[gpui::test]
3499    fn a_move_onto_an_unusable_target_leaves_no_stranded_panel(cx: &mut TestAppContext) {
3500        // `apply_insert` is a silent no-op when the target node's kind does
3501        // not match. Committing on the insert alone would early-return with
3502        // the panel already gone from the source tree but still in the view
3503        // map, for some later unrelated edit to prune and destroy.
3504        let log = log_of();
3505        let (area, _alpha, cx) = two_groups(&log, cx);
3506        let gamma = cx.update(|window, cx| {
3507            let gamma = TestPanel::logging("Gamma", &log, cx);
3508            area.update(cx, |area, cx| {
3509                area.set_dock(
3510                    DockPlacement::Left,
3511                    DockLayout::tabs().panel(gamma.clone()),
3512                    window,
3513                    cx,
3514                );
3515            });
3516            gamma
3517        });
3518        cx.run_until_parked();
3519        drain(&log);
3520
3521        let gamma_id = panel_id_of(&gamma);
3522        // The center root is a split, so a `Tabs` insert naming it does
3523        // nothing at all.
3524        let center_root = cx.read(|cx| {
3525            area.read(cx)
3526                .layout(DockPlacement::Center)
3527                .unwrap()
3528                .root()
3529                .id()
3530        });
3531
3532        cx.update(|window, cx| {
3533            area.update(cx, |area, cx| {
3534                area.move_panel(
3535                    gamma_id,
3536                    InsertTarget::Tabs {
3537                        node: center_root,
3538                        ix: None,
3539                        activate: true,
3540                    },
3541                    window,
3542                    cx,
3543                );
3544            });
3545        });
3546        cx.run_until_parked();
3547
3548        assert!(
3549            cx.read(|cx| area.read(cx).panel(gamma_id).is_none()),
3550            "the view map agrees with the trees straight away, rather than \
3551             carrying a panel that belongs to no tree"
3552        );
3553        assert!(
3554            drain(&log).contains(&("Gamma", PanelSignal::Removed)),
3555            "and the panel was told so at the point of the call"
3556        );
3557    }
3558
3559    #[gpui::test]
3560    fn an_all_hidden_container_reports_itself_invisible(cx: &mut TestAppContext) {
3561        // What the old `StackPanel::render` asked of each slot before hiding
3562        // it. `render_node` feeds this straight to `resizable_panel().visible`.
3563        let (area, cx) = setup(cx);
3564        let beta = cx.update(|window, cx| {
3565            let alpha = TestPanel::new("Alpha", cx);
3566            let beta = TestPanel::new("Beta", cx);
3567            area.update(cx, |area, cx| {
3568                area.set_center(
3569                    DockLayout::h_split()
3570                        .child(DockLayout::tabs().panel(alpha), None)
3571                        .child(DockLayout::tabs().panel(beta.clone()), None),
3572                    window,
3573                    cx,
3574                );
3575            });
3576            beta
3577        });
3578
3579        let visible = |ix: usize, cx: &mut VisualTestContext| {
3580            let node = child_node(&area, ix, cx);
3581            cx.read(|cx| {
3582                let area = area.read(cx);
3583                let tree = area.layout(DockPlacement::Center).unwrap();
3584                area.is_node_visible(tree.find_node(node).unwrap(), cx)
3585            })
3586        };
3587
3588        assert!(visible(0, cx) && visible(1, cx));
3589
3590        cx.update(|_, cx| beta.update(cx, |beta, cx| beta.set_visible(false, cx)));
3591
3592        assert!(visible(0, cx), "the visible group still holds its slot");
3593        assert!(
3594            !visible(1, cx),
3595            "a group whose every panel is hidden must give its slot up"
3596        );
3597    }
3598
3599    #[gpui::test]
3600    fn a_locked_area_seals_its_groups(cx: &mut TestAppContext) {
3601        let log = log_of();
3602        let (area, _alpha, cx) = two_groups(&log, cx);
3603        cx.run_until_parked();
3604
3605        let node = child_node(&area, 0, cx);
3606        let group = cx.read(|cx| area.read(cx).groups.get(&node).unwrap().entity.clone());
3607        assert!(
3608            cx.read(|cx| group.read(cx).is_closable(cx)),
3609            "an unlocked group's panel can be closed"
3610        );
3611
3612        cx.update(|window, cx| area.update(cx, |area, cx| area.set_locked(true, window, cx)));
3613
3614        assert!(
3615            !cx.read(|cx| group.read(cx).is_closable(cx)),
3616            "the lock reaches every group through the constraints push"
3617        );
3618    }
3619
3620    // The tests below were ported from `crates/component/src/dock/tab_panel.rs` when
3621    // the dock skin was rebuilt on this crate. They are the surviving record
3622    // of the `is_empty` semantics and the documented `set_active` contract.
3623
3624    /// An empty `StackPanel` used to dump as `PanelInfo::Panel`, the
3625    /// `PanelState` default, so restoring looked it up in `PanelRegistry` and
3626    /// failed.
3627    #[gpui::test]
3628    fn empty_center_round_trips_as_a_stack(cx: &mut TestAppContext) {
3629        let (area, cx) = setup(cx);
3630        let center = cx.read(|cx| area.read(cx).dump(cx).center);
3631
3632        assert_eq!(center.panel_name, "StackPanel");
3633        assert!(
3634            matches!(center.info, PanelInfo::Stack { .. }),
3635            "got {:?}",
3636            center.info
3637        );
3638    }
3639
3640    #[gpui::test]
3641    fn fresh_center_is_empty(cx: &mut TestAppContext) {
3642        let (area, cx) = setup(cx);
3643
3644        assert!(
3645            is_center_empty(&area, cx),
3646            "DockArea::new starts with an empty split centre"
3647        );
3648    }
3649
3650    #[gpui::test]
3651    fn center_holding_a_tab_group_is_not_empty(cx: &mut TestAppContext) {
3652        let log = log_of();
3653        let (area, _panels, cx) = one_group(&log, &["A", "B"], None, cx);
3654        cx.run_until_parked();
3655
3656        assert!(!is_center_empty(&area, cx));
3657    }
3658
3659    /// The tree still lists the group's node here until the last panel goes,
3660    /// so anything reading node counts rather than panels would report
3661    /// non-empty.
3662    #[gpui::test]
3663    fn center_is_empty_again_once_every_panel_is_removed(cx: &mut TestAppContext) {
3664        let log = log_of();
3665        let (area, panels, cx) = one_group(&log, &["A", "B"], None, cx);
3666        cx.run_until_parked();
3667
3668        for panel in panels {
3669            cx.update(|window, cx| {
3670                area.update(cx, |area, cx| area.remove_panel(panel.clone(), window, cx))
3671            });
3672        }
3673        cx.run_until_parked();
3674
3675        assert!(is_center_empty(&area, cx));
3676    }
3677
3678    #[gpui::test]
3679    fn center_is_not_empty_after_adding_to_a_tab_group(cx: &mut TestAppContext) {
3680        let (area, cx) = setup(cx);
3681        assert!(is_center_empty(&area, cx));
3682
3683        cx.update(|window, cx| {
3684            let alpha = TestPanel::new("Alpha", cx);
3685            area.update(cx, |area, cx| {
3686                area.add_panel(alpha, DockPlacement::Center, None, window, cx)
3687            });
3688        });
3689        cx.run_until_parked();
3690
3691        assert!(!is_center_empty(&area, cx));
3692    }
3693
3694    /// The pre-wrapped companion of `add_panel`, for a layer that hands base
3695    /// its own handle. The panel it registers is the very handle it was
3696    /// given, keyed by the id that handle reports.
3697    #[gpui::test]
3698    fn add_panel_view_registers_the_handle_it_was_given(cx: &mut TestAppContext) {
3699        let (area, cx) = setup(cx);
3700
3701        let view = cx.update(|window, cx| {
3702            let view: Arc<dyn PanelView> = Arc::new(TestPanel::new("Alpha", cx));
3703            area.update(cx, |area, cx| {
3704                area.add_panel_view(view.clone(), DockPlacement::Center, None, window, cx)
3705            });
3706            view
3707        });
3708        cx.run_until_parked();
3709
3710        let id = cx.read(|cx| view.panel_id(cx));
3711        assert!(
3712            cx.read(|cx| area
3713                .read(cx)
3714                .panel(id)
3715                .is_some_and(|stored| Arc::ptr_eq(stored, &view))),
3716            "the stored handle is the one that was handed over, under its own id"
3717        );
3718        assert!(!is_center_empty(&area, cx));
3719    }
3720
3721    /// Rendering skips invisible panels, so a centre holding only hidden ones
3722    /// draws nothing and counts as empty.
3723    #[gpui::test]
3724    fn center_holding_only_hidden_panels_is_empty(cx: &mut TestAppContext) {
3725        let log = log_of();
3726        let (area, panels, cx) = one_group(&log, &["A", "B"], None, cx);
3727        cx.run_until_parked();
3728        assert!(!is_center_empty(&area, cx));
3729
3730        cx.update(|_, cx| {
3731            for panel in &panels {
3732                panel.update(cx, |panel, cx| panel.set_visible(false, cx));
3733            }
3734        });
3735        cx.run_until_parked();
3736
3737        assert_eq!(
3738            cx.read(|cx| area
3739                .read(cx)
3740                .layout(DockPlacement::Center)
3741                .unwrap()
3742                .panels()
3743                .count()),
3744            2,
3745            "hiding a panel does not remove it from the tab group"
3746        );
3747        assert!(is_center_empty(&area, cx));
3748    }
3749
3750    #[gpui::test]
3751    fn single_panel_group_receives_initial_active(cx: &mut TestAppContext) {
3752        let log = log_of();
3753        let (_area, _panels, cx) = one_group(&log, &["A"], None, cx);
3754        cx.run_until_parked();
3755
3756        assert_eq!(drain_active(&log), [("A", true)]);
3757    }
3758
3759    #[gpui::test]
3760    fn multi_tab_construction_notifies_only_displayed_panel(cx: &mut TestAppContext) {
3761        let log = log_of();
3762        let (_area, _panels, cx) = one_group(&log, &["A", "B", "C"], None, cx);
3763        cx.run_until_parked();
3764
3765        // No false-then-true flip on A, no duplicate true, B/C silent.
3766        assert_eq!(drain_active(&log), [("A", true)]);
3767    }
3768
3769    #[gpui::test]
3770    fn active_index_restore_notifies_that_panel_only(cx: &mut TestAppContext) {
3771        let log = log_of();
3772        let (_area, _panels, cx) = one_group(&log, &["A", "B", "C"], Some(2), cx);
3773        cx.run_until_parked();
3774
3775        assert_eq!(drain_active(&log), [("C", true)]);
3776    }
3777
3778    #[gpui::test]
3779    fn switching_tabs_sends_false_then_true(cx: &mut TestAppContext) {
3780        let log = log_of();
3781        let (area, _panels, cx) = one_group(&log, &["A", "B"], None, cx);
3782        cx.run_until_parked();
3783        drain(&log);
3784
3785        let group = group_of(&area, 0, cx);
3786        cx.update(|window, cx| group.update(cx, |group, cx| group.select_tab(1, window, cx)));
3787        cx.run_until_parked();
3788
3789        assert_eq!(drain_active(&log), [("A", false), ("B", true)]);
3790    }
3791
3792    #[gpui::test]
3793    fn select_panel_displays_that_tab_where_it_sits(cx: &mut TestAppContext) {
3794        let log = log_of();
3795        let (area, panels, cx) = one_group(&log, &["A", "B", "C"], None, cx);
3796        cx.run_until_parked();
3797        drain(&log);
3798
3799        let b = panel_id_of(&panels[1]);
3800        cx.update(|window, cx| area.update(cx, |area, cx| area.select_panel(b, window, cx)));
3801        cx.run_until_parked();
3802
3803        assert_eq!(drain_active(&log), [("A", false), ("B", true)]);
3804        let (order, active_ix) = cx.read(|cx| {
3805            let tree = area.read(cx).layout(DockPlacement::Center).unwrap();
3806            let node = tree.find_panel_node(b).unwrap();
3807            match tree.find_node(node).unwrap().kind() {
3808                PaneRef::Tabs { panels, active_ix } => (panels.to_vec(), active_ix),
3809                PaneRef::Split { .. } => panic!("a tab group"),
3810            }
3811        });
3812        assert_eq!(active_ix, 1, "the selected tab is displayed");
3813        assert_eq!(
3814            order,
3815            panels.iter().map(panel_id_of).collect::<Vec<_>>(),
3816            "selecting a tab does not move it"
3817        );
3818    }
3819
3820    #[gpui::test]
3821    fn select_panel_is_silent_for_the_displayed_or_an_unknown_panel(cx: &mut TestAppContext) {
3822        let log = log_of();
3823        let (area, panels, cx) = one_group(&log, &["A", "B"], None, cx);
3824        cx.run_until_parked();
3825        drain(&log);
3826
3827        let a = panel_id_of(&panels[0]);
3828        let stranger = cx.update(|_, cx| panel_id_of(&TestPanel::logging("Z", &log, cx)));
3829        cx.update(|window, cx| {
3830            area.update(cx, |area, cx| {
3831                area.select_panel(a, window, cx);
3832                area.select_panel(stranger, window, cx);
3833            })
3834        });
3835        cx.run_until_parked();
3836
3837        assert_eq!(drain_active(&log), []);
3838    }
3839
3840    #[gpui::test]
3841    fn reselecting_active_tab_stays_silent(cx: &mut TestAppContext) {
3842        let log = log_of();
3843        let (area, _panels, cx) = one_group(&log, &["A", "B"], None, cx);
3844        cx.run_until_parked();
3845        drain(&log);
3846
3847        let group = group_of(&area, 0, cx);
3848        cx.update(|window, cx| group.update(cx, |group, cx| group.select_tab(0, window, cx)));
3849        cx.run_until_parked();
3850
3851        assert_eq!(drain_active(&log), []);
3852    }
3853
3854    /// The old `TabPanel::insert_panel_at` took a brand-new panel; the tree
3855    /// API inserts a panel that is already in the dock, so `C` arrives from a
3856    /// second group. It was a background tab there and so has been told
3857    /// nothing, which is what makes the arrival a genuine activation rather
3858    /// than a seeded handoff.
3859    #[gpui::test]
3860    fn inserting_at_active_ix_swaps_notifications(cx: &mut TestAppContext) {
3861        let log = log_of();
3862        let (area, cx) = setup(cx);
3863        let c = cx.update(|window, cx| {
3864            let a = TestPanel::logging("A", &log, cx);
3865            let b = TestPanel::logging("B", &log, cx);
3866            let x = TestPanel::logging("X", &log, cx);
3867            let c = TestPanel::logging("C", &log, cx);
3868            area.update(cx, |area, cx| {
3869                area.set_center(
3870                    DockLayout::h_split()
3871                        .child(DockLayout::tabs().panel(a).panel(b), None)
3872                        .child(DockLayout::tabs().panel(x).panel(c.clone()), None),
3873                    window,
3874                    cx,
3875                );
3876            });
3877            c
3878        });
3879        cx.run_until_parked();
3880        drain(&log);
3881
3882        let destination = child_node(&area, 0, cx);
3883        let c_id = panel_id_of(&c);
3884        move_panel_into(&area, c_id, destination, Some(0), true, cx);
3885
3886        assert_eq!(drain_active(&log), [("A", false), ("C", true)]);
3887        let group = group_of(&area, 0, cx);
3888        assert_eq!(cx.read(|cx| group.read(cx).active_ix()), 0);
3889        assert_eq!(
3890            cx.read(|cx| group.read(cx).panels()[0].panel_id(cx)),
3891            c_id,
3892            "the arriving panel took the slot it named"
3893        );
3894    }
3895
3896    #[gpui::test]
3897    fn removing_before_active_keeps_displayed_panel(cx: &mut TestAppContext) {
3898        let log = log_of();
3899        let (area, panels, cx) = one_group(&log, &["A", "B", "C"], None, cx);
3900        let group = group_of(&area, 0, cx);
3901        cx.update(|window, cx| group.update(cx, |group, cx| group.select_tab(1, window, cx)));
3902        cx.run_until_parked();
3903        drain(&log);
3904
3905        cx.update(|window, cx| {
3906            area.update(cx, |area, cx| {
3907                area.remove_panel(panels[0].clone(), window, cx)
3908            })
3909        });
3910        cx.run_until_parked();
3911
3912        assert_eq!(drain_active(&log), []);
3913        assert_eq!(cx.read(|cx| group.read(cx).active_ix()), 0);
3914        assert_eq!(
3915            cx.read(|cx| group.read(cx).panels()[0].panel_id(cx)),
3916            panel_id_of(&panels[1]),
3917            "the same panel is still displayed, at its new index"
3918        );
3919    }
3920
3921    /// Collapsing is now a dock closing, which is what
3922    /// `TabGroupConstraints::collapsed` carries.
3923    #[gpui::test]
3924    fn collapse_and_expand_notify_active_panel(cx: &mut TestAppContext) {
3925        let log = log_of();
3926        let (area, cx) = setup(cx);
3927        cx.update(|window, cx| {
3928            let a = TestPanel::logging("A", &log, cx);
3929            let b = TestPanel::logging("B", &log, cx);
3930            area.update(cx, |area, cx| {
3931                area.set_dock(
3932                    DockPlacement::Left,
3933                    DockLayout::tabs().panel(a).panel(b),
3934                    window,
3935                    cx,
3936                );
3937            });
3938        });
3939        cx.run_until_parked();
3940        drain(&log);
3941
3942        cx.update(|window, cx| {
3943            area.update(cx, |area, cx| {
3944                area.toggle_dock(DockPlacement::Left, window, cx)
3945            })
3946        });
3947        cx.run_until_parked();
3948        assert_eq!(drain_active(&log), [("A", false)]);
3949
3950        cx.update(|window, cx| {
3951            area.update(cx, |area, cx| {
3952                area.toggle_dock(DockPlacement::Left, window, cx)
3953            })
3954        });
3955        cx.run_until_parked();
3956        assert_eq!(drain_active(&log), [("A", true)]);
3957    }
3958
3959    #[gpui::test]
3960    fn background_add_is_silent_but_first_panel_is_not(cx: &mut TestAppContext) {
3961        let log = log_of();
3962        let (area, cx) = setup(cx);
3963        let d = cx.update(|window, cx| {
3964            let a = TestPanel::logging("A", &log, cx);
3965            let b = TestPanel::logging("B", &log, cx);
3966            let c = TestPanel::logging("C", &log, cx);
3967            let d = TestPanel::logging("D", &log, cx);
3968            area.update(cx, |area, cx| {
3969                area.set_center(
3970                    DockLayout::h_split()
3971                        .child(DockLayout::tabs().panel(a).panel(b), None)
3972                        .child(DockLayout::tabs().panel(c).panel(d.clone()), None),
3973                    window,
3974                    cx,
3975                );
3976            });
3977            d
3978        });
3979        cx.run_until_parked();
3980        drain(&log);
3981
3982        // D is a background tab in its own group and arrives as a background
3983        // tab in the other one, so nothing changes for anybody.
3984        let destination = child_node(&area, 0, cx);
3985        move_panel_into(&area, panel_id_of(&d), destination, None, false, cx);
3986        assert_eq!(drain_active(&log), []);
3987
3988        // The first panel of a region that had none is displayed regardless,
3989        // so it must be told.
3990        cx.update(|window, cx| {
3991            let e = TestPanel::logging("E", &log, cx);
3992            area.update(cx, |area, cx| {
3993                area.add_panel(e, DockPlacement::Left, None, window, cx)
3994            });
3995        });
3996        cx.run_until_parked();
3997        assert_eq!(drain_active(&log), [("E", true)]);
3998    }
3999
4000    #[gpui::test]
4001    fn drag_active_panel_to_other_group_stays_silent_for_it(cx: &mut TestAppContext) {
4002        let log = log_of();
4003        let (area, cx) = setup(cx);
4004        let a = cx.update(|window, cx| {
4005            let a = TestPanel::logging("A", &log, cx);
4006            let b = TestPanel::logging("B", &log, cx);
4007            let c = TestPanel::logging("C", &log, cx);
4008            area.update(cx, |area, cx| {
4009                area.set_center(
4010                    DockLayout::h_split()
4011                        .child(DockLayout::tabs().panel(a.clone()).panel(b), None)
4012                        .child(DockLayout::tabs().panel(c), None),
4013                    window,
4014                    cx,
4015                );
4016            });
4017            a
4018        });
4019        cx.run_until_parked();
4020        drain(&log);
4021
4022        // A was already told `true`; becoming the target's displayed tab must
4023        // not repeat it.
4024        let destination = child_node(&area, 1, cx);
4025        move_panel_into(&area, panel_id_of(&a), destination, None, true, cx);
4026
4027        // Two groups reconcile independently, so their deliveries interleave
4028        // in no guaranteed order; what is pinned is which ones happen.
4029        let seen = drain_active(&log);
4030        assert!(seen.contains(&("B", true)), "got {seen:?}");
4031        assert!(seen.contains(&("C", false)), "got {seen:?}");
4032        assert!(
4033            !seen.iter().any(|(name, _)| *name == "A"),
4034            "the moved panel was displayed before and after: {seen:?}"
4035        );
4036    }
4037
4038    #[gpui::test]
4039    fn drag_active_panel_to_background_slot_deactivates_it(cx: &mut TestAppContext) {
4040        let log = log_of();
4041        let (area, cx) = setup(cx);
4042        let a = cx.update(|window, cx| {
4043            let a = TestPanel::logging("A", &log, cx);
4044            let c = TestPanel::logging("C", &log, cx);
4045            let d = TestPanel::logging("D", &log, cx);
4046            area.update(cx, |area, cx| {
4047                area.set_center(
4048                    DockLayout::h_split()
4049                        .child(DockLayout::tabs().panel(a.clone()), None)
4050                        .child(DockLayout::tabs().panel(c).panel(d), None),
4051                    window,
4052                    cx,
4053                );
4054            });
4055            a
4056        });
4057        cx.run_until_parked();
4058        drain(&log);
4059
4060        // A was told `true` and becomes a background tab, so it gets one
4061        // `false`.
4062        let destination = child_node(&area, 1, cx);
4063        move_panel_into(&area, panel_id_of(&a), destination, None, false, cx);
4064
4065        assert_eq!(drain_active(&log), [("A", false)]);
4066    }
4067
4068    /// A skin that records what it was asked to draw.
4069    ///
4070    /// The chrome is the point: a tab bar is drawn by the *group*, and it does
4071    /// not run if the area renders the bare panel instead, so what lands in
4072    /// this log says which of the two is on screen — a question no reading of
4073    /// `is_zoomed()` can answer.
4074    struct RecordingSkin {
4075        tab_bars: Rc<RefCell<Vec<NodeId>>>,
4076    }
4077
4078    struct RecordingTabGroup {
4079        drawn: Rc<RefCell<Vec<NodeId>>>,
4080    }
4081
4082    impl DockAreaRenderer for RecordingSkin {
4083        fn tab_group_renderer(&self) -> Rc<dyn TabGroupRenderer> {
4084            Rc::new(RecordingTabGroup {
4085                drawn: self.tab_bars.clone(),
4086            })
4087        }
4088    }
4089
4090    impl TabGroupRenderer for RecordingTabGroup {
4091        fn render_tab_bar(
4092            &self,
4093            group: &TabGroupContext,
4094            _: &mut Window,
4095            _: &mut App,
4096        ) -> AnyElement {
4097            self.drawn.borrow_mut().push(group.node());
4098            Empty.into_any_element()
4099        }
4100    }
4101
4102    type DrawLog = Rc<RefCell<Vec<NodeId>>>;
4103
4104    /// [`setup`], with a skin that records the tab bars drawn.
4105    fn setup_recording(
4106        cx: &mut TestAppContext,
4107    ) -> (Entity<DockArea>, DrawLog, &mut VisualTestContext) {
4108        cx.update(|cx| {
4109            let _ = crate::Theme::global_mut(cx);
4110        });
4111        let tab_bars: DrawLog = Rc::default();
4112        let skin = Rc::new(RecordingSkin {
4113            tab_bars: tab_bars.clone(),
4114        });
4115        let (area, cx) = cx.add_window_view(|window, cx| {
4116            DockArea::new("test-dock", None, window, cx).with_renderer(skin)
4117        });
4118        (area, tab_bars, cx)
4119    }
4120
4121    fn zoom_signals(log: &Log) -> Vec<(&'static str, PanelSignal)> {
4122        drain(log)
4123            .into_iter()
4124            .filter(|(_, signal)| matches!(signal, PanelSignal::Zoomed(_)))
4125            .collect()
4126    }
4127
4128    /// The regression this exists for: zooming shows the *group*, tab bar and
4129    /// all, not the panel inside it.
4130    ///
4131    /// The old dock zoomed the whole `TabPanel` — every `subscribe_panel` call
4132    /// site handed it one — so the tab bar, the toolbar and the panel menu
4133    /// stayed on screen, and that is where the control that zooms back out
4134    /// lives. A zoom rendering the bare panel would still fill the area and
4135    /// still answer `is_zoomed()`; only the tab bar tells the two apart.
4136    #[gpui::test]
4137    fn a_zoomed_group_is_drawn_whole_rather_than_as_its_bare_panel(cx: &mut TestAppContext) {
4138        let log = log_of();
4139        let (area, tab_bars, cx) = setup_recording(cx);
4140        cx.update(|window, cx| {
4141            let alpha = TestPanel::logging("Alpha", &log, cx);
4142            let beta = TestPanel::logging("Beta", &log, cx);
4143            area.update(cx, |area, cx| {
4144                area.set_center(
4145                    DockLayout::h_split()
4146                        .child(DockLayout::tabs().panel(alpha), None)
4147                        .child(DockLayout::tabs().panel(beta), None),
4148                    window,
4149                    cx,
4150                );
4151            });
4152        });
4153        cx.run_until_parked();
4154
4155        let zoomed = child_node(&area, 0, cx);
4156        let other = child_node(&area, 1, cx);
4157        assert!(
4158            tab_bars.borrow().contains(&zoomed) && tab_bars.borrow().contains(&other),
4159            "both groups draw their own tab bar while nothing is zoomed"
4160        );
4161
4162        tab_bars.borrow_mut().clear();
4163        let group = group_of(&area, 0, cx);
4164        cx.update(|window, cx| group.update(cx, |group, cx| group.toggle_zoom(window, cx)));
4165        cx.run_until_parked();
4166
4167        assert!(
4168            tab_bars.borrow().contains(&zoomed),
4169            "a zoomed group is rendered whole: its own tab bar is still drawn, \
4170             which is exactly what the bare panel does not carry"
4171        );
4172        assert!(
4173            !tab_bars.borrow().contains(&other),
4174            "and it is the only thing on screen"
4175        );
4176    }
4177
4178    /// The area's zoom and the container's own flag are written together, so
4179    /// neither can be left believing something the other does not.
4180    ///
4181    /// A group left flagged zoomed reports itself locked for good, and a
4182    /// locked group refuses every drop.
4183    #[gpui::test]
4184    fn clearing_the_zoom_from_outside_puts_the_groups_own_flag_back(cx: &mut TestAppContext) {
4185        let log = log_of();
4186        let (area, _alpha, cx) = two_groups(&log, cx);
4187        cx.run_until_parked();
4188        drain(&log);
4189
4190        let node = child_node(&area, 0, cx);
4191        let group = group_of(&area, 0, cx);
4192        cx.update(|window, cx| group.update(cx, |group, cx| group.toggle_zoom(window, cx)));
4193        cx.run_until_parked();
4194        assert_eq!(cx.read(|cx| area.read(cx).zoomed_group()), Some(node));
4195        assert!(cx.read(|cx| group.read(cx).is_zoomed()));
4196        assert_eq!(
4197            zoom_signals(&log),
4198            vec![("Alpha", PanelSignal::Zoomed(true))]
4199        );
4200
4201        cx.update(|window, cx| area.update(cx, |area, cx| area.set_zoomed_out(window, cx)));
4202        cx.run_until_parked();
4203
4204        assert!(!cx.read(|cx| area.read(cx).is_zoomed()));
4205        assert!(
4206            !cx.read(|cx| group.read(cx).is_zoomed()),
4207            "a group left flagged zoomed would stay locked and refuse every drop"
4208        );
4209        assert!(
4210            cx.read(|cx| group.read(cx).context(cx).is_droppable()),
4211            "and the lock the zoom imposed is lifted with it"
4212        );
4213        assert_eq!(
4214            zoom_signals(&log),
4215            vec![("Alpha", PanelSignal::Zoomed(false))],
4216            "the panel hears the zoom end too, not just the group"
4217        );
4218    }
4219
4220    /// A group that refuses to zoom must not leave the area showing it as
4221    /// zoomed: the area records a zoom only once the container agrees.
4222    #[gpui::test]
4223    fn a_group_that_refuses_to_zoom_leaves_the_area_unzoomed(cx: &mut TestAppContext) {
4224        let log = log_of();
4225        let (area, alpha, cx) = two_groups(&log, cx);
4226        cx.run_until_parked();
4227        cx.update(|_, cx| alpha.update(cx, |panel, cx| panel.set_zoomable(false, cx)));
4228
4229        let node = child_node(&area, 0, cx);
4230        let group = group_of(&area, 0, cx);
4231        cx.update(|window, cx| area.update(cx, |area, cx| area.set_zoomed_in(node, window, cx)));
4232        cx.run_until_parked();
4233
4234        assert!(!cx.read(|cx| group.read(cx).is_zoomed()));
4235        assert!(
4236            !cx.read(|cx| area.read(cx).is_zoomed()),
4237            "the area must not fill itself with a group that never zoomed"
4238        );
4239    }
4240}