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
174 .last_active_center_pane
175 .as_ref()
176 .and_then(|pane| pane.upgrade(cx))
177 {
178 cx.focus(last_active_center_pane);
179 }
180 cx.emit(crate::Event::DockAnchorChanged);
181 cx.notify();
182 }
183
184 pub fn hide(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
185 Self::set_dock_position(workspace, workspace.dock.position.hide(), cx);
186 }
187
188 pub fn show(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
189 Self::set_dock_position(workspace, workspace.dock.position.show(), cx);
190 }
191
192 pub fn hide_on_sidebar_shown(
193 workspace: &mut Workspace,
194 sidebar_side: SidebarSide,
195 cx: &mut ViewContext<Workspace>,
196 ) {
197 if (sidebar_side == SidebarSide::Right && workspace.dock.is_anchored_at(DockAnchor::Right))
198 || workspace.dock.is_anchored_at(DockAnchor::Expanded)
199 {
200 Self::hide(workspace, cx);
201 }
202 }
203
204 fn focus_dock(workspace: &mut Workspace, _: &FocusDock, cx: &mut ViewContext<Workspace>) {
205 Self::set_dock_position(workspace, workspace.dock.position.show(), cx);
206 }
207
208 fn hide_dock(workspace: &mut Workspace, _: &HideDock, cx: &mut ViewContext<Workspace>) {
209 Self::set_dock_position(workspace, workspace.dock.position.hide(), cx);
210 }
211
212 fn move_dock(
213 workspace: &mut Workspace,
214 &MoveDock(new_anchor): &MoveDock,
215 cx: &mut ViewContext<Workspace>,
216 ) {
217 Self::set_dock_position(workspace, DockPosition::Shown(new_anchor), cx);
218 }
219
220 pub fn render(
221 &self,
222 theme: &Theme,
223 anchor: DockAnchor,
224 cx: &mut RenderContext<Workspace>,
225 ) -> Option<ElementBox> {
226 let style = &theme.workspace.dock;
227
228 self.position
229 .is_visible()
230 .then(|| self.position.anchor())
231 .filter(|current_anchor| *current_anchor == anchor)
232 .map(|anchor| match anchor {
233 DockAnchor::Bottom | DockAnchor::Right => {
234 let mut panel_style = style.panel.clone();
235 let (resize_side, initial_size) = if anchor == DockAnchor::Bottom {
236 panel_style.border = Border {
237 top: true,
238 bottom: false,
239 left: false,
240 right: false,
241 ..panel_style.border
242 };
243
244 (Side::Top, style.initial_size_bottom)
245 } else {
246 panel_style.border = Border {
247 top: false,
248 bottom: false,
249 left: true,
250 right: false,
251 ..panel_style.border
252 };
253 (Side::Left, style.initial_size_right)
254 };
255
256 enum DockResizeHandle {}
257
258 let resizable = Container::new(ChildView::new(self.pane.clone(), cx).boxed())
259 .with_style(panel_style)
260 .with_resize_handle::<DockResizeHandle, _>(
261 resize_side as usize,
262 resize_side,
263 4.,
264 self.panel_sizes
265 .get(&anchor)
266 .copied()
267 .unwrap_or(initial_size),
268 cx,
269 );
270
271 let size = resizable.current_size();
272 let workspace = cx.handle();
273 cx.defer(move |cx| {
274 if let Some(workspace) = workspace.upgrade(cx) {
275 workspace.update(cx, |workspace, _| {
276 workspace.dock.panel_sizes.insert(anchor, size);
277 })
278 }
279 });
280
281 resizable.flex(5., false).boxed()
282 }
283 DockAnchor::Expanded => {
284 enum ExpandedDockWash {}
285 enum ExpandedDockPane {}
286 Container::new(
287 MouseEventHandler::<ExpandedDockWash>::new(0, cx, |_state, cx| {
288 MouseEventHandler::<ExpandedDockPane>::new(0, cx, |_state, cx| {
289 ChildView::new(&self.pane, cx).boxed()
290 })
291 .capture_all()
292 .contained()
293 .with_style(style.maximized)
294 .boxed()
295 })
296 .capture_all()
297 .on_down(MouseButton::Left, |_, cx| {
298 cx.dispatch_action(HideDock);
299 })
300 .with_cursor_style(CursorStyle::Arrow)
301 .boxed(),
302 )
303 .with_background_color(style.wash_color)
304 .boxed()
305 }
306 })
307 }
308}
309
310pub struct ToggleDockButton {
311 workspace: WeakViewHandle<Workspace>,
312}
313
314impl ToggleDockButton {
315 pub fn new(workspace: ViewHandle<Workspace>, cx: &mut ViewContext<Self>) -> Self {
316 // When dock moves, redraw so that the icon and toggle status matches.
317 cx.subscribe(&workspace, |_, _, _, cx| cx.notify()).detach();
318
319 Self {
320 workspace: workspace.downgrade(),
321 }
322 }
323}
324
325impl Entity for ToggleDockButton {
326 type Event = ();
327}
328
329impl View for ToggleDockButton {
330 fn ui_name() -> &'static str {
331 "Dock Toggle"
332 }
333
334 fn render(&mut self, cx: &mut gpui::RenderContext<'_, Self>) -> ElementBox {
335 let workspace = self.workspace.upgrade(cx);
336
337 if workspace.is_none() {
338 return Empty::new().boxed();
339 }
340
341 let dock_position = workspace.unwrap().read(cx).dock.position;
342
343 let theme = cx.global::<Settings>().theme.clone();
344 let button = MouseEventHandler::<Self>::new(0, cx, {
345 let theme = theme.clone();
346 move |state, _| {
347 let style = theme
348 .workspace
349 .status_bar
350 .sidebar_buttons
351 .item
352 .style_for(state, dock_position.is_visible());
353
354 Svg::new(icon_for_dock_anchor(dock_position.anchor()))
355 .with_color(style.icon_color)
356 .constrained()
357 .with_width(style.icon_size)
358 .with_height(style.icon_size)
359 .contained()
360 .with_style(style.container)
361 .boxed()
362 }
363 })
364 .with_cursor_style(CursorStyle::PointingHand);
365
366 if dock_position.is_visible() {
367 button
368 .on_click(MouseButton::Left, |_, cx| {
369 cx.dispatch_action(HideDock);
370 })
371 .with_tooltip::<Self, _>(
372 0,
373 "Hide Dock".into(),
374 Some(Box::new(HideDock)),
375 theme.tooltip.clone(),
376 cx,
377 )
378 } else {
379 button
380 .on_click(MouseButton::Left, |_, cx| {
381 cx.dispatch_action(FocusDock);
382 })
383 .with_tooltip::<Self, _>(
384 0,
385 "Focus Dock".into(),
386 Some(Box::new(FocusDock)),
387 theme.tooltip.clone(),
388 cx,
389 )
390 }
391 .boxed()
392 }
393}
394
395impl StatusItemView for ToggleDockButton {
396 fn set_active_pane_item(
397 &mut self,
398 _active_pane_item: Option<&dyn crate::ItemHandle>,
399 _cx: &mut ViewContext<Self>,
400 ) {
401 //Not applicable
402 }
403}
404
405#[cfg(test)]
406mod tests {
407 use std::ops::{Deref, DerefMut};
408
409 use gpui::{AppContext, TestAppContext, UpdateView, ViewContext};
410 use project::{FakeFs, Project};
411 use settings::Settings;
412
413 use super::*;
414 use crate::{sidebar::Sidebar, tests::TestItem, ItemHandle, Workspace};
415
416 pub fn default_item_factory(
417 _workspace: &mut Workspace,
418 cx: &mut ViewContext<Workspace>,
419 ) -> Box<dyn ItemHandle> {
420 Box::new(cx.add_view(|_| TestItem::new()))
421 }
422
423 #[gpui::test]
424 async fn test_dock_hides_when_pane_empty(cx: &mut TestAppContext) {
425 let mut cx = DockTestContext::new(cx).await;
426
427 // Closing the last item in the dock hides the dock
428 cx.move_dock(DockAnchor::Right);
429 let old_items = cx.dock_items();
430 assert!(!old_items.is_empty());
431 cx.close_dock_items().await;
432 cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Right));
433
434 // Reopening the dock adds a new item
435 cx.move_dock(DockAnchor::Right);
436 let new_items = cx.dock_items();
437 assert!(!new_items.is_empty());
438 assert!(new_items
439 .into_iter()
440 .all(|new_item| !old_items.contains(&new_item)));
441 }
442
443 #[gpui::test]
444 async fn test_dock_panel_collisions(cx: &mut TestAppContext) {
445 let mut cx = DockTestContext::new(cx).await;
446
447 // Dock closes when expanded for either panel
448 cx.move_dock(DockAnchor::Expanded);
449 cx.open_sidebar(SidebarSide::Left);
450 cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Expanded));
451 cx.close_sidebar(SidebarSide::Left);
452 cx.move_dock(DockAnchor::Expanded);
453 cx.open_sidebar(SidebarSide::Right);
454 cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Expanded));
455
456 // Dock closes in the right position if the right sidebar is opened
457 cx.move_dock(DockAnchor::Right);
458 cx.open_sidebar(SidebarSide::Left);
459 cx.assert_dock_position(DockPosition::Shown(DockAnchor::Right));
460 cx.open_sidebar(SidebarSide::Right);
461 cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Right));
462 cx.close_sidebar(SidebarSide::Right);
463
464 // Dock in bottom position ignores sidebars
465 cx.move_dock(DockAnchor::Bottom);
466 cx.open_sidebar(SidebarSide::Left);
467 cx.open_sidebar(SidebarSide::Right);
468 cx.assert_dock_position(DockPosition::Shown(DockAnchor::Bottom));
469
470 // Opening the dock in the right position closes the right sidebar
471 cx.move_dock(DockAnchor::Right);
472 cx.assert_sidebar_closed(SidebarSide::Right);
473 }
474
475 #[gpui::test]
476 async fn test_focusing_panes_shows_and_hides_dock(cx: &mut TestAppContext) {
477 let mut cx = DockTestContext::new(cx).await;
478
479 // Focusing an item not in the dock when expanded hides the dock
480 let center_item = cx.add_item_to_center_pane();
481 cx.move_dock(DockAnchor::Expanded);
482 let dock_item = cx
483 .dock_items()
484 .get(0)
485 .cloned()
486 .expect("Dock should have an item at this point");
487 center_item.update(&mut cx, |_, cx| cx.focus_self());
488 cx.assert_dock_position(DockPosition::Hidden(DockAnchor::Expanded));
489
490 // Focusing an item not in the dock when not expanded, leaves the dock open but inactive
491 cx.move_dock(DockAnchor::Right);
492 center_item.update(&mut cx, |_, cx| cx.focus_self());
493 cx.assert_dock_position(DockPosition::Shown(DockAnchor::Right));
494 cx.assert_dock_pane_inactive();
495 cx.assert_workspace_pane_active();
496
497 // Focusing an item in the dock activates it's pane
498 dock_item.update(&mut cx, |_, cx| cx.focus_self());
499 cx.assert_dock_position(DockPosition::Shown(DockAnchor::Right));
500 cx.assert_dock_pane_active();
501 cx.assert_workspace_pane_inactive();
502 }
503
504 #[gpui::test]
505 async fn test_toggle_dock_focus(cx: &mut TestAppContext) {
506 let cx = DockTestContext::new(cx).await;
507
508 cx.move_dock(DockAnchor::Right);
509 cx.assert_dock_pane_active();
510 cx.hide_dock();
511 cx.move_dock(DockAnchor::Right);
512 cx.assert_dock_pane_active();
513 }
514
515 struct DockTestContext<'a> {
516 pub cx: &'a mut TestAppContext,
517 pub window_id: usize,
518 pub workspace: ViewHandle<Workspace>,
519 }
520
521 impl<'a> DockTestContext<'a> {
522 pub async fn new(cx: &'a mut TestAppContext) -> DockTestContext<'a> {
523 Settings::test_async(cx);
524 let fs = FakeFs::new(cx.background());
525
526 cx.update(|cx| init(cx));
527 let project = Project::test(fs, [], cx).await;
528 let (window_id, workspace) =
529 cx.add_window(|cx| Workspace::new(project, default_item_factory, cx));
530
531 workspace.update(cx, |workspace, cx| {
532 let left_panel = cx.add_view(|_| TestItem::new());
533 workspace.left_sidebar().update(cx, |sidebar, cx| {
534 sidebar.add_item(
535 "icons/folder_tree_16.svg",
536 "Left Test Panel".to_string(),
537 left_panel.clone(),
538 cx,
539 );
540 });
541
542 let right_panel = cx.add_view(|_| TestItem::new());
543 workspace.right_sidebar().update(cx, |sidebar, cx| {
544 sidebar.add_item(
545 "icons/folder_tree_16.svg",
546 "Right Test Panel".to_string(),
547 right_panel.clone(),
548 cx,
549 );
550 });
551 });
552
553 Self {
554 cx,
555 window_id,
556 workspace,
557 }
558 }
559
560 pub fn workspace<F, T>(&self, read: F) -> T
561 where
562 F: FnOnce(&Workspace, &AppContext) -> T,
563 {
564 self.workspace.read_with(self.cx, read)
565 }
566
567 pub fn update_workspace<F, T>(&mut self, update: F) -> T
568 where
569 F: FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,
570 {
571 self.workspace.update(self.cx, update)
572 }
573
574 pub fn sidebar<F, T>(&self, sidebar_side: SidebarSide, read: F) -> T
575 where
576 F: FnOnce(&Sidebar, &AppContext) -> T,
577 {
578 self.workspace(|workspace, cx| {
579 let sidebar = match sidebar_side {
580 SidebarSide::Left => workspace.left_sidebar(),
581 SidebarSide::Right => workspace.right_sidebar(),
582 }
583 .read(cx);
584
585 read(sidebar, cx)
586 })
587 }
588
589 pub fn center_pane_handle(&self) -> ViewHandle<Pane> {
590 self.workspace(|workspace, cx| {
591 workspace
592 .last_active_center_pane
593 .clone()
594 .and_then(|pane| pane.upgrade(cx))
595 .unwrap_or_else(|| workspace.center.panes()[0].clone())
596 })
597 }
598
599 pub fn add_item_to_center_pane(&mut self) -> ViewHandle<TestItem> {
600 self.update_workspace(|workspace, cx| {
601 let item = cx.add_view(|_| TestItem::new());
602 let pane = workspace
603 .last_active_center_pane
604 .clone()
605 .and_then(|pane| pane.upgrade(cx))
606 .unwrap_or_else(|| workspace.center.panes()[0].clone());
607 Pane::add_item(
608 workspace,
609 &pane,
610 Box::new(item.clone()),
611 true,
612 true,
613 None,
614 cx,
615 );
616 item
617 })
618 }
619
620 pub fn dock_pane<F, T>(&self, read: F) -> T
621 where
622 F: FnOnce(&Pane, &AppContext) -> T,
623 {
624 self.workspace(|workspace, cx| {
625 let dock_pane = workspace.dock_pane().read(cx);
626 read(dock_pane, cx)
627 })
628 }
629
630 pub fn move_dock(&self, anchor: DockAnchor) {
631 self.cx.dispatch_action(self.window_id, MoveDock(anchor));
632 }
633
634 pub fn hide_dock(&self) {
635 self.cx.dispatch_action(self.window_id, HideDock);
636 }
637
638 pub fn open_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 close_sidebar(&mut self, sidebar_side: SidebarSide) {
645 if self.sidebar(sidebar_side, |sidebar, _| sidebar.is_open()) {
646 self.update_workspace(|workspace, cx| workspace.toggle_sidebar(sidebar_side, cx));
647 }
648 }
649
650 pub fn dock_items(&self) -> Vec<ViewHandle<TestItem>> {
651 self.dock_pane(|pane, cx| {
652 pane.items()
653 .map(|item| {
654 item.act_as::<TestItem>(cx)
655 .expect("Dock Test Context uses TestItems in the dock")
656 })
657 .collect()
658 })
659 }
660
661 pub async fn close_dock_items(&mut self) {
662 self.update_workspace(|workspace, cx| {
663 Pane::close_items(workspace, workspace.dock_pane().clone(), cx, |_| true)
664 })
665 .await
666 .expect("Could not close dock items")
667 }
668
669 pub fn assert_dock_position(&self, expected_position: DockPosition) {
670 self.workspace(|workspace, _| assert_eq!(workspace.dock.position, expected_position));
671 }
672
673 pub fn assert_sidebar_closed(&self, sidebar_side: SidebarSide) {
674 assert!(!self.sidebar(sidebar_side, |sidebar, _| sidebar.is_open()));
675 }
676
677 pub fn assert_workspace_pane_active(&self) {
678 assert!(self
679 .center_pane_handle()
680 .read_with(self.cx, |pane, _| pane.is_active()));
681 }
682
683 pub fn assert_workspace_pane_inactive(&self) {
684 assert!(!self
685 .center_pane_handle()
686 .read_with(self.cx, |pane, _| pane.is_active()));
687 }
688
689 pub fn assert_dock_pane_active(&self) {
690 assert!(self.dock_pane(|pane, _| pane.is_active()))
691 }
692
693 pub fn assert_dock_pane_inactive(&self) {
694 assert!(!self.dock_pane(|pane, _| pane.is_active()))
695 }
696 }
697
698 impl<'a> Deref for DockTestContext<'a> {
699 type Target = gpui::TestAppContext;
700
701 fn deref(&self) -> &Self::Target {
702 self.cx
703 }
704 }
705
706 impl<'a> DerefMut for DockTestContext<'a> {
707 fn deref_mut(&mut self) -> &mut Self::Target {
708 &mut self.cx
709 }
710 }
711
712 impl<'a> UpdateView for DockTestContext<'a> {
713 fn update_view<T, S>(
714 &mut self,
715 handle: &ViewHandle<T>,
716 update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
717 ) -> S
718 where
719 T: View,
720 {
721 handle.update(self.cx, update)
722 }
723 }
724}