dock.rs

  1use collections::HashMap;
  2use gpui::{
  3    actions,
  4    elements::{ChildView, Container, Empty, MouseEventHandler, ParentElement, Side, Stack, Svg},
  5    geometry::vector::Vector2F,
  6    impl_internal_actions, Border, CursorStyle, Element, ElementBox, Entity, MouseButton,
  7    MutableAppContext, RenderContext, SizeConstraint, View, ViewContext, ViewHandle,
  8    WeakViewHandle,
  9};
 10use serde::Deserialize;
 11use settings::{DockAnchor, Settings};
 12use theme::Theme;
 13
 14use crate::{
 15    handle_dropped_item, sidebar::SidebarSide, ItemHandle, Pane, StatusItemView, Workspace,
 16};
 17
 18#[derive(PartialEq, Clone, Deserialize)]
 19pub struct MoveDock(pub DockAnchor);
 20
 21#[derive(PartialEq, Clone)]
 22pub struct AddDefaultItemToDock;
 23
 24actions!(
 25    dock,
 26    [
 27        FocusDock,
 28        HideDock,
 29        AnchorDockRight,
 30        AnchorDockBottom,
 31        ExpandDock,
 32        MoveActiveItemToDock,
 33    ]
 34);
 35impl_internal_actions!(dock, [MoveDock, AddDefaultItemToDock]);
 36
 37pub fn init(cx: &mut MutableAppContext) {
 38    cx.add_action(Dock::focus_dock);
 39    cx.add_action(Dock::hide_dock);
 40    cx.add_action(Dock::move_dock);
 41    cx.add_action(
 42        |workspace: &mut Workspace, _: &AnchorDockRight, cx: &mut ViewContext<Workspace>| {
 43            Dock::move_dock(workspace, &MoveDock(DockAnchor::Right), cx)
 44        },
 45    );
 46    cx.add_action(
 47        |workspace: &mut Workspace, _: &AnchorDockBottom, cx: &mut ViewContext<Workspace>| {
 48            Dock::move_dock(workspace, &MoveDock(DockAnchor::Bottom), cx)
 49        },
 50    );
 51    cx.add_action(
 52        |workspace: &mut Workspace, _: &ExpandDock, cx: &mut ViewContext<Workspace>| {
 53            Dock::move_dock(workspace, &MoveDock(DockAnchor::Expanded), cx)
 54        },
 55    );
 56    cx.add_action(
 57        |workspace: &mut Workspace, _: &MoveActiveItemToDock, cx: &mut ViewContext<Workspace>| {
 58            if let Some(active_item) = workspace.active_item(cx) {
 59                let item_id = active_item.id();
 60
 61                let from = workspace.active_pane();
 62                let to = workspace.dock_pane();
 63                if from.id() == to.id() {
 64                    return;
 65                }
 66
 67                let destination_index = to.read(cx).items_len() + 1;
 68
 69                Pane::move_item(
 70                    workspace,
 71                    from.clone(),
 72                    to.clone(),
 73                    item_id,
 74                    destination_index,
 75                    cx,
 76                );
 77            }
 78        },
 79    );
 80}
 81
 82#[derive(Copy, Clone, PartialEq, Eq, Debug)]
 83pub enum DockPosition {
 84    Shown(DockAnchor),
 85    Hidden(DockAnchor),
 86}
 87
 88impl Default for DockPosition {
 89    fn default() -> Self {
 90        DockPosition::Hidden(Default::default())
 91    }
 92}
 93
 94pub fn icon_for_dock_anchor(anchor: DockAnchor) -> &'static str {
 95    match anchor {
 96        DockAnchor::Right => "icons/dock_right_12.svg",
 97        DockAnchor::Bottom => "icons/dock_bottom_12.svg",
 98        DockAnchor::Expanded => "icons/dock_modal_12.svg",
 99    }
100}
101
102impl DockPosition {
103    pub fn is_visible(&self) -> bool {
104        match self {
105            DockPosition::Shown(_) => true,
106            DockPosition::Hidden(_) => false,
107        }
108    }
109
110    pub fn anchor(&self) -> DockAnchor {
111        match self {
112            DockPosition::Shown(anchor) | DockPosition::Hidden(anchor) => *anchor,
113        }
114    }
115
116    fn hide(self) -> Self {
117        match self {
118            DockPosition::Shown(anchor) => DockPosition::Hidden(anchor),
119            DockPosition::Hidden(_) => self,
120        }
121    }
122
123    fn show(self) -> Self {
124        match self {
125            DockPosition::Hidden(anchor) => DockPosition::Shown(anchor),
126            DockPosition::Shown(_) => self,
127        }
128    }
129}
130
131pub type DockDefaultItemFactory =
132    fn(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Option<Box<dyn ItemHandle>>;
133
134pub struct Dock {
135    position: DockPosition,
136    panel_sizes: HashMap<DockAnchor, f32>,
137    pane: ViewHandle<Pane>,
138    default_item_factory: DockDefaultItemFactory,
139}
140
141impl Dock {
142    pub fn new(
143        default_item_factory: DockDefaultItemFactory,
144        cx: &mut ViewContext<Workspace>,
145    ) -> Self {
146        let position = DockPosition::Hidden(cx.global::<Settings>().default_dock_anchor);
147
148        let pane = cx.add_view(|cx| Pane::new(Some(position.anchor()), cx));
149        pane.update(cx, |pane, cx| {
150            pane.set_active(false, cx);
151        });
152        let pane_id = pane.id();
153        cx.subscribe(&pane, move |workspace, _, event, cx| {
154            workspace.handle_pane_event(pane_id, event, cx);
155        })
156        .detach();
157
158        Self {
159            pane,
160            panel_sizes: Default::default(),
161            position,
162            default_item_factory,
163        }
164    }
165
166    pub fn pane(&self) -> &ViewHandle<Pane> {
167        &self.pane
168    }
169
170    pub fn visible_pane(&self) -> Option<&ViewHandle<Pane>> {
171        self.position.is_visible().then(|| self.pane())
172    }
173
174    pub fn is_anchored_at(&self, anchor: DockAnchor) -> bool {
175        self.position.is_visible() && self.position.anchor() == anchor
176    }
177
178    pub(crate) fn set_dock_position(
179        workspace: &mut Workspace,
180        new_position: DockPosition,
181        cx: &mut ViewContext<Workspace>,
182    ) {
183        workspace.dock.position = new_position;
184        // Tell the pane about the new anchor position
185        workspace.dock.pane.update(cx, |pane, cx| {
186            pane.set_docked(Some(new_position.anchor()), cx)
187        });
188
189        if workspace.dock.position.is_visible() {
190            // Close the right sidebar if the dock is on the right side and the right sidebar is open
191            if workspace.dock.position.anchor() == DockAnchor::Right {
192                if workspace.right_sidebar().read(cx).is_open() {
193                    workspace.toggle_sidebar(SidebarSide::Right, cx);
194                }
195            }
196
197            // Ensure that the pane has at least one item or construct a default item to put in it
198            let pane = workspace.dock.pane.clone();
199            if pane.read(cx).items().next().is_none() {
200                if let Some(item_to_add) = (workspace.dock.default_item_factory)(workspace, cx) {
201                    Pane::add_item(workspace, &pane, item_to_add, true, true, None, cx);
202                } else {
203                    workspace.dock.position = workspace.dock.position.hide();
204                }
205            } else {
206                cx.focus(pane);
207            }
208        } else if let Some(last_active_center_pane) = workspace
209            .last_active_center_pane
210            .as_ref()
211            .and_then(|pane| pane.upgrade(cx))
212        {
213            cx.focus(last_active_center_pane);
214        }
215        cx.emit(crate::Event::DockAnchorChanged);
216        workspace.serialize_workspace(cx);
217        cx.notify();
218    }
219
220    pub fn hide(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
221        Self::set_dock_position(workspace, workspace.dock.position.hide(), cx);
222    }
223
224    pub fn show(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
225        Self::set_dock_position(workspace, workspace.dock.position.show(), cx);
226    }
227
228    pub fn hide_on_sidebar_shown(
229        workspace: &mut Workspace,
230        sidebar_side: SidebarSide,
231        cx: &mut ViewContext<Workspace>,
232    ) {
233        if (sidebar_side == SidebarSide::Right && workspace.dock.is_anchored_at(DockAnchor::Right))
234            || workspace.dock.is_anchored_at(DockAnchor::Expanded)
235        {
236            Self::hide(workspace, cx);
237        }
238    }
239
240    fn focus_dock(workspace: &mut Workspace, _: &FocusDock, cx: &mut ViewContext<Workspace>) {
241        Self::set_dock_position(workspace, workspace.dock.position.show(), cx);
242    }
243
244    fn hide_dock(workspace: &mut Workspace, _: &HideDock, cx: &mut ViewContext<Workspace>) {
245        Self::set_dock_position(workspace, workspace.dock.position.hide(), cx);
246    }
247
248    fn move_dock(
249        workspace: &mut Workspace,
250        &MoveDock(new_anchor): &MoveDock,
251        cx: &mut ViewContext<Workspace>,
252    ) {
253        Self::set_dock_position(workspace, DockPosition::Shown(new_anchor), cx);
254    }
255
256    pub fn render(
257        &self,
258        theme: &Theme,
259        anchor: DockAnchor,
260        cx: &mut RenderContext<Workspace>,
261    ) -> Option<ElementBox> {
262        let style = &theme.workspace.dock;
263
264        self.position
265            .is_visible()
266            .then(|| self.position.anchor())
267            .filter(|current_anchor| *current_anchor == anchor)
268            .map(|anchor| match anchor {
269                DockAnchor::Bottom | DockAnchor::Right => {
270                    let mut panel_style = style.panel.clone();
271                    let (resize_side, initial_size) = if anchor == DockAnchor::Bottom {
272                        panel_style.border = Border {
273                            top: true,
274                            bottom: false,
275                            left: false,
276                            right: false,
277                            ..panel_style.border
278                        };
279
280                        (Side::Top, style.initial_size_bottom)
281                    } else {
282                        panel_style.border = Border {
283                            top: false,
284                            bottom: false,
285                            left: true,
286                            right: false,
287                            ..panel_style.border
288                        };
289                        (Side::Left, style.initial_size_right)
290                    };
291
292                    enum DockResizeHandle {}
293
294                    let resizable = Container::new(ChildView::new(self.pane.clone(), cx).boxed())
295                        .with_style(panel_style)
296                        .with_resize_handle::<DockResizeHandle, _>(
297                            resize_side as usize,
298                            resize_side,
299                            4.,
300                            self.panel_sizes
301                                .get(&anchor)
302                                .copied()
303                                .unwrap_or(initial_size),
304                            cx,
305                        );
306
307                    let size = resizable.current_size();
308                    let workspace = cx.handle();
309                    cx.defer(move |cx| {
310                        if let Some(workspace) = workspace.upgrade(cx) {
311                            workspace.update(cx, |workspace, _| {
312                                workspace.dock.panel_sizes.insert(anchor, size);
313                            })
314                        }
315                    });
316
317                    if anchor == DockAnchor::Right {
318                        resizable
319                            .constrained()
320                            .dynamically(|constraint, cx| {
321                                SizeConstraint::new(
322                                    Vector2F::new(20., constraint.min.y()),
323                                    Vector2F::new(cx.window_size.x() * 0.8, constraint.max.y()),
324                                )
325                            })
326                            .boxed()
327                    } else {
328                        resizable
329                            .constrained()
330                            .dynamically(|constraint, cx| {
331                                SizeConstraint::new(
332                                    Vector2F::new(constraint.min.x(), 50.),
333                                    Vector2F::new(constraint.max.x(), cx.window_size.y() * 0.8),
334                                )
335                            })
336                            .boxed()
337                    }
338                }
339                DockAnchor::Expanded => {
340                    enum ExpandedDockWash {}
341                    enum ExpandedDockPane {}
342                    Stack::new()
343                        .with_child(
344                            // Render wash under the dock which when clicked hides it
345                            MouseEventHandler::<ExpandedDockWash>::new(0, cx, |_, _| {
346                                Empty::new()
347                                    .contained()
348                                    .with_background_color(style.wash_color)
349                                    .boxed()
350                            })
351                            .capture_all()
352                            .on_down(MouseButton::Left, |_, cx| {
353                                cx.dispatch_action(HideDock);
354                            })
355                            .with_cursor_style(CursorStyle::Arrow)
356                            .boxed(),
357                        )
358                        .with_child(
359                            MouseEventHandler::<ExpandedDockPane>::new(0, cx, |_state, cx| {
360                                ChildView::new(&self.pane, cx).boxed()
361                            })
362                            // Make sure all events directly under the dock pane
363                            // are captured
364                            .capture_all()
365                            .contained()
366                            .with_style(style.maximized)
367                            .boxed(),
368                        )
369                        .boxed()
370                }
371            })
372    }
373
374    pub fn position(&self) -> DockPosition {
375        self.position
376    }
377}
378
379pub struct ToggleDockButton {
380    workspace: WeakViewHandle<Workspace>,
381}
382
383impl ToggleDockButton {
384    pub fn new(workspace: ViewHandle<Workspace>, cx: &mut ViewContext<Self>) -> Self {
385        // When dock moves, redraw so that the icon and toggle status matches.
386        cx.subscribe(&workspace, |_, _, _, cx| cx.notify()).detach();
387
388        Self {
389            workspace: workspace.downgrade(),
390        }
391    }
392}
393
394impl Entity for ToggleDockButton {
395    type Event = ();
396}
397
398impl View for ToggleDockButton {
399    fn ui_name() -> &'static str {
400        "Dock Toggle"
401    }
402
403    fn render(&mut self, cx: &mut gpui::RenderContext<'_, Self>) -> ElementBox {
404        let workspace = self.workspace.upgrade(cx);
405
406        if workspace.is_none() {
407            return Empty::new().boxed();
408        }
409
410        let workspace = workspace.unwrap();
411        let dock_position = workspace.read(cx).dock.position;
412
413        let theme = cx.global::<Settings>().theme.clone();
414
415        let button = MouseEventHandler::<Self>::new(0, cx, {
416            let theme = theme.clone();
417            move |state, _| {
418                let style = theme
419                    .workspace
420                    .status_bar
421                    .sidebar_buttons
422                    .item
423                    .style_for(state, dock_position.is_visible());
424
425                Svg::new(icon_for_dock_anchor(dock_position.anchor()))
426                    .with_color(style.icon_color)
427                    .constrained()
428                    .with_width(style.icon_size)
429                    .with_height(style.icon_size)
430                    .contained()
431                    .with_style(style.container)
432                    .boxed()
433            }
434        })
435        .with_cursor_style(CursorStyle::PointingHand)
436        .on_up(MouseButton::Left, move |event, cx| {
437            let dock_pane = workspace.read(cx.app).dock_pane();
438            let drop_index = dock_pane.read(cx.app).items_len() + 1;
439            handle_dropped_item(event, &dock_pane.downgrade(), drop_index, false, None, cx);
440        });
441
442        if dock_position.is_visible() {
443            button
444                .on_click(MouseButton::Left, |_, cx| {
445                    cx.dispatch_action(HideDock);
446                })
447                .with_tooltip::<Self, _>(
448                    0,
449                    "Hide Dock".into(),
450                    Some(Box::new(HideDock)),
451                    theme.tooltip.clone(),
452                    cx,
453                )
454        } else {
455            button
456                .on_click(MouseButton::Left, |_, cx| {
457                    cx.dispatch_action(FocusDock);
458                })
459                .with_tooltip::<Self, _>(
460                    0,
461                    "Focus Dock".into(),
462                    Some(Box::new(FocusDock)),
463                    theme.tooltip.clone(),
464                    cx,
465                )
466        }
467        .boxed()
468    }
469}
470
471impl StatusItemView for ToggleDockButton {
472    fn set_active_pane_item(
473        &mut self,
474        _active_pane_item: Option<&dyn crate::ItemHandle>,
475        _cx: &mut ViewContext<Self>,
476    ) {
477        //Not applicable
478    }
479}
480
481#[cfg(test)]
482mod tests {
483    use std::{
484        ops::{Deref, DerefMut},
485        path::PathBuf,
486    };
487
488    use gpui::{AppContext, TestAppContext, UpdateView, ViewContext};
489    use project::{FakeFs, Project};
490    use settings::Settings;
491
492    use super::*;
493    use crate::{
494        dock,
495        item::{self, test::TestItem},
496        persistence::model::{
497            SerializedItem, SerializedPane, SerializedPaneGroup, SerializedWorkspace,
498        },
499        register_deserializable_item,
500        sidebar::Sidebar,
501        ItemHandle, Workspace,
502    };
503
504    pub fn default_item_factory(
505        _workspace: &mut Workspace,
506        cx: &mut ViewContext<Workspace>,
507    ) -> Option<Box<dyn ItemHandle>> {
508        Some(Box::new(cx.add_view(|_| TestItem::new())))
509    }
510
511    #[gpui::test]
512    async fn test_dock_workspace_infinite_loop(cx: &mut TestAppContext) {
513        cx.foreground().forbid_parking();
514        Settings::test_async(cx);
515
516        cx.update(|cx| {
517            register_deserializable_item::<item::test::TestItem>(cx);
518        });
519
520        let serialized_workspace = SerializedWorkspace {
521            id: 0,
522            location: Vec::<PathBuf>::new().into(),
523            dock_position: dock::DockPosition::Shown(DockAnchor::Expanded),
524            center_group: SerializedPaneGroup::Pane(SerializedPane {
525                active: false,
526                children: vec![],
527            }),
528            dock_pane: SerializedPane {
529                active: true,
530                children: vec![SerializedItem {
531                    active: true,
532                    item_id: 0,
533                    kind: "TestItem".into(),
534                }],
535            },
536            left_sidebar_open: false,
537        };
538
539        let fs = FakeFs::new(cx.background());
540        let project = Project::test(fs, [], cx).await;
541
542        let (_, _workspace) = cx.add_window(|cx| {
543            Workspace::new(
544                Some(serialized_workspace),
545                0,
546                project.clone(),
547                default_item_factory,
548                cx,
549            )
550        });
551
552        cx.foreground().run_until_parked();
553        //Should terminate
554    }
555
556    #[gpui::test]
557    async fn test_dock_hides_when_pane_empty(cx: &mut TestAppContext) {
558        let mut cx = DockTestContext::new(cx).await;
559
560        // Closing the last item in the dock hides the dock
561        cx.move_dock(DockAnchor::Right);
562        let old_items = cx.dock_items();
563        assert!(!old_items.is_empty());
564        cx.close_dock_items().await;
565        cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Right));
566
567        // Reopening the dock adds a new item
568        cx.move_dock(DockAnchor::Right);
569        let new_items = cx.dock_items();
570        assert!(!new_items.is_empty());
571        assert!(new_items
572            .into_iter()
573            .all(|new_item| !old_items.contains(&new_item)));
574    }
575
576    #[gpui::test]
577    async fn test_dock_panel_collisions(cx: &mut TestAppContext) {
578        let mut cx = DockTestContext::new(cx).await;
579
580        // Dock closes when expanded for either panel
581        cx.move_dock(DockAnchor::Expanded);
582        cx.open_sidebar(SidebarSide::Left);
583        cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Expanded));
584        cx.close_sidebar(SidebarSide::Left);
585        cx.move_dock(DockAnchor::Expanded);
586        cx.open_sidebar(SidebarSide::Right);
587        cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Expanded));
588
589        // Dock closes in the right position if the right sidebar is opened
590        cx.move_dock(DockAnchor::Right);
591        cx.open_sidebar(SidebarSide::Left);
592        cx.assert_dock_position(DockPosition::Shown(DockAnchor::Right));
593        cx.open_sidebar(SidebarSide::Right);
594        cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Right));
595        cx.close_sidebar(SidebarSide::Right);
596
597        // Dock in bottom position ignores sidebars
598        cx.move_dock(DockAnchor::Bottom);
599        cx.open_sidebar(SidebarSide::Left);
600        cx.open_sidebar(SidebarSide::Right);
601        cx.assert_dock_position(DockPosition::Shown(DockAnchor::Bottom));
602
603        // Opening the dock in the right position closes the right sidebar
604        cx.move_dock(DockAnchor::Right);
605        cx.assert_sidebar_closed(SidebarSide::Right);
606    }
607
608    #[gpui::test]
609    async fn test_focusing_panes_shows_and_hides_dock(cx: &mut TestAppContext) {
610        let mut cx = DockTestContext::new(cx).await;
611
612        // Focusing an item not in the dock when expanded hides the dock
613        let center_item = cx.add_item_to_center_pane();
614        cx.move_dock(DockAnchor::Expanded);
615        let dock_item = cx
616            .dock_items()
617            .get(0)
618            .cloned()
619            .expect("Dock should have an item at this point");
620        center_item.update(&mut cx, |_, cx| cx.focus_self());
621        cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Expanded));
622
623        // Focusing an item not in the dock when not expanded, leaves the dock open but inactive
624        cx.move_dock(DockAnchor::Right);
625        center_item.update(&mut cx, |_, cx| cx.focus_self());
626        cx.assert_dock_position(DockPosition::Shown(DockAnchor::Right));
627        cx.assert_dock_pane_inactive();
628        cx.assert_workspace_pane_active();
629
630        // Focusing an item in the dock activates it's pane
631        dock_item.update(&mut cx, |_, cx| cx.focus_self());
632        cx.assert_dock_position(DockPosition::Shown(DockAnchor::Right));
633        cx.assert_dock_pane_active();
634        cx.assert_workspace_pane_inactive();
635    }
636
637    #[gpui::test]
638    async fn test_toggle_dock_focus(cx: &mut TestAppContext) {
639        let cx = DockTestContext::new(cx).await;
640
641        cx.move_dock(DockAnchor::Right);
642        cx.assert_dock_pane_active();
643        cx.hide_dock();
644        cx.move_dock(DockAnchor::Right);
645        cx.assert_dock_pane_active();
646    }
647
648    #[gpui::test]
649    async fn test_activate_next_and_prev_pane(cx: &mut TestAppContext) {
650        let mut cx = DockTestContext::new(cx).await;
651
652        cx.move_dock(DockAnchor::Right);
653        cx.assert_dock_pane_active();
654
655        cx.update_workspace(|workspace, cx| workspace.activate_next_pane(cx));
656        cx.assert_dock_pane_active();
657
658        cx.update_workspace(|workspace, cx| workspace.activate_previous_pane(cx));
659        cx.assert_dock_pane_active();
660    }
661
662    struct DockTestContext<'a> {
663        pub cx: &'a mut TestAppContext,
664        pub window_id: usize,
665        pub workspace: ViewHandle<Workspace>,
666    }
667
668    impl<'a> DockTestContext<'a> {
669        pub async fn new(cx: &'a mut TestAppContext) -> DockTestContext<'a> {
670            Settings::test_async(cx);
671            let fs = FakeFs::new(cx.background());
672
673            cx.update(|cx| init(cx));
674            let project = Project::test(fs, [], cx).await;
675            let (window_id, workspace) = cx.add_window(|cx| {
676                Workspace::new(Default::default(), 0, project, default_item_factory, cx)
677            });
678
679            workspace.update(cx, |workspace, cx| {
680                let left_panel = cx.add_view(|_| TestItem::new());
681                workspace.left_sidebar().update(cx, |sidebar, cx| {
682                    sidebar.add_item(
683                        "icons/folder_tree_16.svg",
684                        "Left Test Panel".to_string(),
685                        left_panel.clone(),
686                        cx,
687                    );
688                });
689
690                let right_panel = cx.add_view(|_| TestItem::new());
691                workspace.right_sidebar().update(cx, |sidebar, cx| {
692                    sidebar.add_item(
693                        "icons/folder_tree_16.svg",
694                        "Right Test Panel".to_string(),
695                        right_panel.clone(),
696                        cx,
697                    );
698                });
699            });
700
701            Self {
702                cx,
703                window_id,
704                workspace,
705            }
706        }
707
708        pub fn workspace<F, T>(&self, read: F) -> T
709        where
710            F: FnOnce(&Workspace, &AppContext) -> T,
711        {
712            self.workspace.read_with(self.cx, read)
713        }
714
715        pub fn update_workspace<F, T>(&mut self, update: F) -> T
716        where
717            F: FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,
718        {
719            self.workspace.update(self.cx, update)
720        }
721
722        pub fn sidebar<F, T>(&self, sidebar_side: SidebarSide, read: F) -> T
723        where
724            F: FnOnce(&Sidebar, &AppContext) -> T,
725        {
726            self.workspace(|workspace, cx| {
727                let sidebar = match sidebar_side {
728                    SidebarSide::Left => workspace.left_sidebar(),
729                    SidebarSide::Right => workspace.right_sidebar(),
730                }
731                .read(cx);
732
733                read(sidebar, cx)
734            })
735        }
736
737        pub fn center_pane_handle(&self) -> ViewHandle<Pane> {
738            self.workspace(|workspace, cx| {
739                workspace
740                    .last_active_center_pane
741                    .clone()
742                    .and_then(|pane| pane.upgrade(cx))
743                    .unwrap_or_else(|| workspace.center.panes()[0].clone())
744            })
745        }
746
747        pub fn add_item_to_center_pane(&mut self) -> ViewHandle<TestItem> {
748            self.update_workspace(|workspace, cx| {
749                let item = cx.add_view(|_| TestItem::new());
750                let pane = workspace
751                    .last_active_center_pane
752                    .clone()
753                    .and_then(|pane| pane.upgrade(cx))
754                    .unwrap_or_else(|| workspace.center.panes()[0].clone());
755                Pane::add_item(
756                    workspace,
757                    &pane,
758                    Box::new(item.clone()),
759                    true,
760                    true,
761                    None,
762                    cx,
763                );
764                item
765            })
766        }
767
768        pub fn dock_pane<F, T>(&self, read: F) -> T
769        where
770            F: FnOnce(&Pane, &AppContext) -> T,
771        {
772            self.workspace(|workspace, cx| {
773                let dock_pane = workspace.dock_pane().read(cx);
774                read(dock_pane, cx)
775            })
776        }
777
778        pub fn move_dock(&self, anchor: DockAnchor) {
779            self.cx.dispatch_action(self.window_id, MoveDock(anchor));
780        }
781
782        pub fn hide_dock(&self) {
783            self.cx.dispatch_action(self.window_id, HideDock);
784        }
785
786        pub fn open_sidebar(&mut self, sidebar_side: SidebarSide) {
787            if !self.sidebar(sidebar_side, |sidebar, _| sidebar.is_open()) {
788                self.update_workspace(|workspace, cx| workspace.toggle_sidebar(sidebar_side, cx));
789            }
790        }
791
792        pub fn close_sidebar(&mut self, sidebar_side: SidebarSide) {
793            if self.sidebar(sidebar_side, |sidebar, _| sidebar.is_open()) {
794                self.update_workspace(|workspace, cx| workspace.toggle_sidebar(sidebar_side, cx));
795            }
796        }
797
798        pub fn dock_items(&self) -> Vec<ViewHandle<TestItem>> {
799            self.dock_pane(|pane, cx| {
800                pane.items()
801                    .map(|item| {
802                        item.act_as::<TestItem>(cx)
803                            .expect("Dock Test Context uses TestItems in the dock")
804                    })
805                    .collect()
806            })
807        }
808
809        pub async fn close_dock_items(&mut self) {
810            self.update_workspace(|workspace, cx| {
811                Pane::close_items(workspace, workspace.dock_pane().clone(), cx, |_| true)
812            })
813            .await
814            .expect("Could not close dock items")
815        }
816
817        pub fn assert_dock_position(&self, expected_position: DockPosition) {
818            self.workspace(|workspace, _| assert_eq!(workspace.dock.position, expected_position));
819        }
820
821        pub fn assert_sidebar_closed(&self, sidebar_side: SidebarSide) {
822            assert!(!self.sidebar(sidebar_side, |sidebar, _| sidebar.is_open()));
823        }
824
825        pub fn assert_workspace_pane_active(&self) {
826            assert!(self
827                .center_pane_handle()
828                .read_with(self.cx, |pane, _| pane.is_active()));
829        }
830
831        pub fn assert_workspace_pane_inactive(&self) {
832            assert!(!self
833                .center_pane_handle()
834                .read_with(self.cx, |pane, _| pane.is_active()));
835        }
836
837        pub fn assert_dock_pane_active(&self) {
838            assert!(self.dock_pane(|pane, _| pane.is_active()))
839        }
840
841        pub fn assert_dock_pane_inactive(&self) {
842            assert!(!self.dock_pane(|pane, _| pane.is_active()))
843        }
844    }
845
846    impl<'a> Deref for DockTestContext<'a> {
847        type Target = gpui::TestAppContext;
848
849        fn deref(&self) -> &Self::Target {
850            self.cx
851        }
852    }
853
854    impl<'a> DerefMut for DockTestContext<'a> {
855        fn deref_mut(&mut self) -> &mut Self::Target {
856            &mut self.cx
857        }
858    }
859
860    impl<'a> UpdateView for DockTestContext<'a> {
861        fn update_view<T, S>(
862            &mut self,
863            handle: &ViewHandle<T>,
864            update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
865        ) -> S
866        where
867            T: View,
868        {
869            handle.update(self.cx, update)
870        }
871    }
872}