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