1use 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
38pub enum DockEvent {
40 LayoutChanged,
44 DragDrop { item: AnyDrag, target: DropTarget },
46}
47
48#[derive(Clone, Copy, PartialEq, Eq, Debug)]
58enum Zoomed {
59 Group(NodeId),
61 Tile { node: NodeId, panel: PanelId },
65}
66
67#[derive(Clone, Copy)]
70enum Added {
71 Anywhere(Option<Pixels>),
74 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
89struct DockRegion {
91 tree: PaneTree,
92 dock: Dock,
93}
94
95struct Cached<T> {
99 entity: Entity<T>,
100 _subscription: Subscription,
101}
102
103struct CachedSplit {
112 entity: Entity<ResizableState>,
113 children: Vec<NodeId>,
114 _subscription: Subscription,
115}
116
117pub 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 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 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 pub fn set_version(&mut self, version: Option<usize>, cx: &mut Context<Self>) {
197 self.version = version;
198 cx.notify();
199 }
200
201 pub fn bounds(&self) -> Bounds<Pixels> {
204 self.bounds
205 }
206
207 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 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 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 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 self.reconcile(window, cx);
249 }
250}
251
252impl DockArea {
254 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 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 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 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 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 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 self.reconcile(window, cx);
343 cx.emit(DockEvent::LayoutChanged);
344 }
345
346 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 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
391impl DockArea {
393 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 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 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 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 let previous = self.panels.insert(id, panel);
496
497 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 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 None => match first_tiles_canvas(tree.root()) {
541 Some(node) => InsertTarget::Tile {
542 node,
543 bounds: TileMeta::default().bounds,
544 },
545 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 self.restore_registration(id, previous);
563 return;
564 }
565 self.commit(result, window, cx);
566 }
567
568 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 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 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 if matches!(target, InsertTarget::Split { .. }) {
604 self.adopt_measured_sizes(destination, cx);
605 }
606
607 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 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 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
691impl DockArea {
702 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 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 pub fn zoomed_group(&self) -> Option<NodeId> {
726 match self.zoomed {
727 Some(Zoomed::Group(node)) => Some(node),
728 _ => None,
729 }
730 }
731
732 pub fn zoomed_tile(&self) -> Option<PanelId> {
734 match self.zoomed {
735 Some(Zoomed::Tile { panel, .. }) => Some(panel),
736 _ => None,
737 }
738 }
739
740 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 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 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
809impl DockArea {
811 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 self.groups.clear();
827 self.splits.clear();
828 self.tiles.clear();
829 self.docks.clear();
830 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 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 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
957impl DockArea {
959 fn commit(&mut self, result: EditResult, window: &mut Window, cx: &mut Context<Self>) {
968 self.commit_changed(result.changed(), window, cx);
969 }
970
971 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 fn reconcile(&mut self, window: &mut Window, cx: &mut Context<Self>) {
988 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 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 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 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 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 for view in departed {
1099 view.on_removed(window, cx);
1100 }
1101 }
1102
1103 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 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
1207impl 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 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 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
1307impl DockArea {
1309 fn adopt_measured_sizes(&mut self, placement: DockPlacement, cx: &App) {
1316 let measured: HashMap<NodeId, Vec<Pixels>> = self
1317 .splits
1318 .iter()
1319 .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 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 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
1387impl DockArea {
1389 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 let shown: Vec<bool> = children
1405 .iter()
1406 .map(|child| self.is_node_visible(child, cx))
1407 .collect();
1408 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 .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 .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 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 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 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 .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 .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
1612enum 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
1640fn 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 for ix in (0..current.len()).rev() {
1660 if !next.contains(¤t[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 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 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
1759struct 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
1789struct 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#[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 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 pub fn resize_to(&self, pointer: Point<Pixels>, window: &mut Window, cx: &mut App) {
1874 (self.on_resize)(pointer, window, cx);
1875 }
1876}
1877
1878pub const CLOSED_BOTTOM_STRIP: Pixels = px(29.);
1882
1883pub 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
1892pub 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 DockPlacement::Center => this,
1908 })
1909}
1910
1911#[allow(unused_variables)]
1922pub trait DockAreaRenderer: 'static {
1923 fn frame(&self, window: &mut Window, cx: &mut App) -> Stateful<Div> {
1929 div().id("dock-area")
1930 }
1931
1932 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 fn center_frame(&self, window: &mut Window, cx: &mut App) -> Stateful<Div> {
1955 div().id("dock-area-center")
1956 }
1957
1958 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 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 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
2019struct 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 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 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 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 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 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 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 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 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 .child(DockLayout::tabs().panel(alpha), None)
2460 .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 #[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 #[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 #[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 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 #[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 #[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 #[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 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 #[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 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 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 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 #[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 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 #[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 #[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 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 #[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 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 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 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 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 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 #[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 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 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 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 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 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 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 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 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 #[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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 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 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 let destination = child_node(&area, 1, cx);
4097 move_panel_into(&area, panel_id_of(&a), destination, None, true, cx);
4098
4099 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 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 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 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 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 #[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 #[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 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 #[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 #[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}