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            bounds: Default::default(),
538            display: Default::default(),
539        };
540
541        let fs = FakeFs::new(cx.background());
542        let project = Project::test(fs, [], cx).await;
543
544        let (_, _workspace) = cx.add_window(|cx| {
545            Workspace::new(
546                Some(serialized_workspace),
547                0,
548                project.clone(),
549                default_item_factory,
550                cx,
551            )
552        });
553
554        cx.foreground().run_until_parked();
555        //Should terminate
556    }
557
558    #[gpui::test]
559    async fn test_dock_hides_when_pane_empty(cx: &mut TestAppContext) {
560        let mut cx = DockTestContext::new(cx).await;
561
562        // Closing the last item in the dock hides the dock
563        cx.move_dock(DockAnchor::Right);
564        let old_items = cx.dock_items();
565        assert!(!old_items.is_empty());
566        cx.close_dock_items().await;
567        cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Right));
568
569        // Reopening the dock adds a new item
570        cx.move_dock(DockAnchor::Right);
571        let new_items = cx.dock_items();
572        assert!(!new_items.is_empty());
573        assert!(new_items
574            .into_iter()
575            .all(|new_item| !old_items.contains(&new_item)));
576    }
577
578    #[gpui::test]
579    async fn test_dock_panel_collisions(cx: &mut TestAppContext) {
580        let mut cx = DockTestContext::new(cx).await;
581
582        // Dock closes when expanded for either panel
583        cx.move_dock(DockAnchor::Expanded);
584        cx.open_sidebar(SidebarSide::Left);
585        cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Expanded));
586        cx.close_sidebar(SidebarSide::Left);
587        cx.move_dock(DockAnchor::Expanded);
588        cx.open_sidebar(SidebarSide::Right);
589        cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Expanded));
590
591        // Dock closes in the right position if the right sidebar is opened
592        cx.move_dock(DockAnchor::Right);
593        cx.open_sidebar(SidebarSide::Left);
594        cx.assert_dock_position(DockPosition::Shown(DockAnchor::Right));
595        cx.open_sidebar(SidebarSide::Right);
596        cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Right));
597        cx.close_sidebar(SidebarSide::Right);
598
599        // Dock in bottom position ignores sidebars
600        cx.move_dock(DockAnchor::Bottom);
601        cx.open_sidebar(SidebarSide::Left);
602        cx.open_sidebar(SidebarSide::Right);
603        cx.assert_dock_position(DockPosition::Shown(DockAnchor::Bottom));
604
605        // Opening the dock in the right position closes the right sidebar
606        cx.move_dock(DockAnchor::Right);
607        cx.assert_sidebar_closed(SidebarSide::Right);
608    }
609
610    #[gpui::test]
611    async fn test_focusing_panes_shows_and_hides_dock(cx: &mut TestAppContext) {
612        let mut cx = DockTestContext::new(cx).await;
613
614        // Focusing an item not in the dock when expanded hides the dock
615        let center_item = cx.add_item_to_center_pane();
616        cx.move_dock(DockAnchor::Expanded);
617        let dock_item = cx
618            .dock_items()
619            .get(0)
620            .cloned()
621            .expect("Dock should have an item at this point");
622        center_item.update(&mut cx, |_, cx| cx.focus_self());
623        cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Expanded));
624
625        // Focusing an item not in the dock when not expanded, leaves the dock open but inactive
626        cx.move_dock(DockAnchor::Right);
627        center_item.update(&mut cx, |_, cx| cx.focus_self());
628        cx.assert_dock_position(DockPosition::Shown(DockAnchor::Right));
629        cx.assert_dock_pane_inactive();
630        cx.assert_workspace_pane_active();
631
632        // Focusing an item in the dock activates it's pane
633        dock_item.update(&mut cx, |_, cx| cx.focus_self());
634        cx.assert_dock_position(DockPosition::Shown(DockAnchor::Right));
635        cx.assert_dock_pane_active();
636        cx.assert_workspace_pane_inactive();
637    }
638
639    #[gpui::test]
640    async fn test_toggle_dock_focus(cx: &mut TestAppContext) {
641        let cx = DockTestContext::new(cx).await;
642
643        cx.move_dock(DockAnchor::Right);
644        cx.assert_dock_pane_active();
645        cx.hide_dock();
646        cx.move_dock(DockAnchor::Right);
647        cx.assert_dock_pane_active();
648    }
649
650    #[gpui::test]
651    async fn test_activate_next_and_prev_pane(cx: &mut TestAppContext) {
652        let mut cx = DockTestContext::new(cx).await;
653
654        cx.move_dock(DockAnchor::Right);
655        cx.assert_dock_pane_active();
656
657        cx.update_workspace(|workspace, cx| workspace.activate_next_pane(cx));
658        cx.assert_dock_pane_active();
659
660        cx.update_workspace(|workspace, cx| workspace.activate_previous_pane(cx));
661        cx.assert_dock_pane_active();
662    }
663
664    struct DockTestContext<'a> {
665        pub cx: &'a mut TestAppContext,
666        pub window_id: usize,
667        pub workspace: ViewHandle<Workspace>,
668    }
669
670    impl<'a> DockTestContext<'a> {
671        pub async fn new(cx: &'a mut TestAppContext) -> DockTestContext<'a> {
672            Settings::test_async(cx);
673            let fs = FakeFs::new(cx.background());
674
675            cx.update(|cx| init(cx));
676            let project = Project::test(fs, [], cx).await;
677            let (window_id, workspace) = cx.add_window(|cx| {
678                Workspace::new(Default::default(), 0, project, default_item_factory, cx)
679            });
680
681            workspace.update(cx, |workspace, cx| {
682                let left_panel = cx.add_view(|_| TestItem::new());
683                workspace.left_sidebar().update(cx, |sidebar, cx| {
684                    sidebar.add_item(
685                        "icons/folder_tree_16.svg",
686                        "Left Test Panel".to_string(),
687                        left_panel.clone(),
688                        cx,
689                    );
690                });
691
692                let right_panel = cx.add_view(|_| TestItem::new());
693                workspace.right_sidebar().update(cx, |sidebar, cx| {
694                    sidebar.add_item(
695                        "icons/folder_tree_16.svg",
696                        "Right Test Panel".to_string(),
697                        right_panel.clone(),
698                        cx,
699                    );
700                });
701            });
702
703            Self {
704                cx,
705                window_id,
706                workspace,
707            }
708        }
709
710        pub fn workspace<F, T>(&self, read: F) -> T
711        where
712            F: FnOnce(&Workspace, &AppContext) -> T,
713        {
714            self.workspace.read_with(self.cx, read)
715        }
716
717        pub fn update_workspace<F, T>(&mut self, update: F) -> T
718        where
719            F: FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,
720        {
721            self.workspace.update(self.cx, update)
722        }
723
724        pub fn sidebar<F, T>(&self, sidebar_side: SidebarSide, read: F) -> T
725        where
726            F: FnOnce(&Sidebar, &AppContext) -> T,
727        {
728            self.workspace(|workspace, cx| {
729                let sidebar = match sidebar_side {
730                    SidebarSide::Left => workspace.left_sidebar(),
731                    SidebarSide::Right => workspace.right_sidebar(),
732                }
733                .read(cx);
734
735                read(sidebar, cx)
736            })
737        }
738
739        pub fn center_pane_handle(&self) -> ViewHandle<Pane> {
740            self.workspace(|workspace, cx| {
741                workspace
742                    .last_active_center_pane
743                    .clone()
744                    .and_then(|pane| pane.upgrade(cx))
745                    .unwrap_or_else(|| workspace.center.panes()[0].clone())
746            })
747        }
748
749        pub fn add_item_to_center_pane(&mut self) -> ViewHandle<TestItem> {
750            self.update_workspace(|workspace, cx| {
751                let item = cx.add_view(|_| TestItem::new());
752                let pane = workspace
753                    .last_active_center_pane
754                    .clone()
755                    .and_then(|pane| pane.upgrade(cx))
756                    .unwrap_or_else(|| workspace.center.panes()[0].clone());
757                Pane::add_item(
758                    workspace,
759                    &pane,
760                    Box::new(item.clone()),
761                    true,
762                    true,
763                    None,
764                    cx,
765                );
766                item
767            })
768        }
769
770        pub fn dock_pane<F, T>(&self, read: F) -> T
771        where
772            F: FnOnce(&Pane, &AppContext) -> T,
773        {
774            self.workspace(|workspace, cx| {
775                let dock_pane = workspace.dock_pane().read(cx);
776                read(dock_pane, cx)
777            })
778        }
779
780        pub fn move_dock(&self, anchor: DockAnchor) {
781            self.cx.dispatch_action(self.window_id, MoveDock(anchor));
782        }
783
784        pub fn hide_dock(&self) {
785            self.cx.dispatch_action(self.window_id, HideDock);
786        }
787
788        pub fn open_sidebar(&mut self, sidebar_side: SidebarSide) {
789            if !self.sidebar(sidebar_side, |sidebar, _| sidebar.is_open()) {
790                self.update_workspace(|workspace, cx| workspace.toggle_sidebar(sidebar_side, cx));
791            }
792        }
793
794        pub fn close_sidebar(&mut self, sidebar_side: SidebarSide) {
795            if self.sidebar(sidebar_side, |sidebar, _| sidebar.is_open()) {
796                self.update_workspace(|workspace, cx| workspace.toggle_sidebar(sidebar_side, cx));
797            }
798        }
799
800        pub fn dock_items(&self) -> Vec<ViewHandle<TestItem>> {
801            self.dock_pane(|pane, cx| {
802                pane.items()
803                    .map(|item| {
804                        item.act_as::<TestItem>(cx)
805                            .expect("Dock Test Context uses TestItems in the dock")
806                    })
807                    .collect()
808            })
809        }
810
811        pub async fn close_dock_items(&mut self) {
812            self.update_workspace(|workspace, cx| {
813                Pane::close_items(workspace, workspace.dock_pane().clone(), cx, |_| true)
814            })
815            .await
816            .expect("Could not close dock items")
817        }
818
819        pub fn assert_dock_position(&self, expected_position: DockPosition) {
820            self.workspace(|workspace, _| assert_eq!(workspace.dock.position, expected_position));
821        }
822
823        pub fn assert_sidebar_closed(&self, sidebar_side: SidebarSide) {
824            assert!(!self.sidebar(sidebar_side, |sidebar, _| sidebar.is_open()));
825        }
826
827        pub fn assert_workspace_pane_active(&self) {
828            assert!(self
829                .center_pane_handle()
830                .read_with(self.cx, |pane, _| pane.is_active()));
831        }
832
833        pub fn assert_workspace_pane_inactive(&self) {
834            assert!(!self
835                .center_pane_handle()
836                .read_with(self.cx, |pane, _| pane.is_active()));
837        }
838
839        pub fn assert_dock_pane_active(&self) {
840            assert!(self.dock_pane(|pane, _| pane.is_active()))
841        }
842
843        pub fn assert_dock_pane_inactive(&self) {
844            assert!(!self.dock_pane(|pane, _| pane.is_active()))
845        }
846    }
847
848    impl<'a> Deref for DockTestContext<'a> {
849        type Target = gpui::TestAppContext;
850
851        fn deref(&self) -> &Self::Target {
852            self.cx
853        }
854    }
855
856    impl<'a> DerefMut for DockTestContext<'a> {
857        fn deref_mut(&mut self) -> &mut Self::Target {
858            &mut self.cx
859        }
860    }
861
862    impl<'a> UpdateView for DockTestContext<'a> {
863        fn update_view<T, S>(
864            &mut self,
865            handle: &ViewHandle<T>,
866            update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
867        ) -> S
868        where
869            T: View,
870        {
871            handle.update(self.cx, update)
872        }
873    }
874}