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