1use crate::{StatusItemView, Workspace, WorkspaceBounds};
2use gpui2::{
3 elements::*, platform::CursorStyle, platform::MouseButton, Action, AnyViewHandle, AppContext,
4 Axis, Entity, Subscription, View, ViewContext, ViewHandle, WeakViewHandle, WindowContext,
5};
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8use std::rc::Rc;
9use theme2::ThemeSettings;
10
11pub trait Panel: View {
12 fn position(&self, cx: &WindowContext) -> DockPosition;
13 fn position_is_valid(&self, position: DockPosition) -> bool;
14 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>);
15 fn size(&self, cx: &WindowContext) -> f32;
16 fn set_size(&mut self, size: Option<f32>, cx: &mut ViewContext<Self>);
17 fn icon_path(&self, cx: &WindowContext) -> Option<&'static str>;
18 fn icon_tooltip(&self) -> (String, Option<Box<dyn Action>>);
19 fn icon_label(&self, _: &WindowContext) -> Option<String> {
20 None
21 }
22 fn should_change_position_on_event(_: &Self::Event) -> bool;
23 fn should_zoom_in_on_event(_: &Self::Event) -> bool {
24 false
25 }
26 fn should_zoom_out_on_event(_: &Self::Event) -> bool {
27 false
28 }
29 fn is_zoomed(&self, _cx: &WindowContext) -> bool {
30 false
31 }
32 fn set_zoomed(&mut self, _zoomed: bool, _cx: &mut ViewContext<Self>) {}
33 fn set_active(&mut self, _active: bool, _cx: &mut ViewContext<Self>) {}
34 fn should_activate_on_event(_: &Self::Event) -> bool {
35 false
36 }
37 fn should_close_on_event(_: &Self::Event) -> bool {
38 false
39 }
40 fn has_focus(&self, cx: &WindowContext) -> bool;
41 fn is_focus_event(_: &Self::Event) -> bool;
42}
43
44pub trait PanelHandle {
45 fn id(&self) -> usize;
46 fn position(&self, cx: &WindowContext) -> DockPosition;
47 fn position_is_valid(&self, position: DockPosition, cx: &WindowContext) -> bool;
48 fn set_position(&self, position: DockPosition, cx: &mut WindowContext);
49 fn is_zoomed(&self, cx: &WindowContext) -> bool;
50 fn set_zoomed(&self, zoomed: bool, cx: &mut WindowContext);
51 fn set_active(&self, active: bool, cx: &mut WindowContext);
52 fn size(&self, cx: &WindowContext) -> f32;
53 fn set_size(&self, size: Option<f32>, cx: &mut WindowContext);
54 fn icon_path(&self, cx: &WindowContext) -> Option<&'static str>;
55 fn icon_tooltip(&self, cx: &WindowContext) -> (String, Option<Box<dyn Action>>);
56 fn icon_label(&self, cx: &WindowContext) -> Option<String>;
57 fn has_focus(&self, cx: &WindowContext) -> bool;
58 fn as_any(&self) -> &AnyViewHandle;
59}
60
61impl<T> PanelHandle for ViewHandle<T>
62where
63 T: Panel,
64{
65 fn id(&self) -> usize {
66 self.id()
67 }
68
69 fn position(&self, cx: &WindowContext) -> DockPosition {
70 self.read(cx).position(cx)
71 }
72
73 fn position_is_valid(&self, position: DockPosition, cx: &WindowContext) -> bool {
74 self.read(cx).position_is_valid(position)
75 }
76
77 fn set_position(&self, position: DockPosition, cx: &mut WindowContext) {
78 self.update(cx, |this, cx| this.set_position(position, cx))
79 }
80
81 fn size(&self, cx: &WindowContext) -> f32 {
82 self.read(cx).size(cx)
83 }
84
85 fn set_size(&self, size: Option<f32>, cx: &mut WindowContext) {
86 self.update(cx, |this, cx| this.set_size(size, cx))
87 }
88
89 fn is_zoomed(&self, cx: &WindowContext) -> bool {
90 self.read(cx).is_zoomed(cx)
91 }
92
93 fn set_zoomed(&self, zoomed: bool, cx: &mut WindowContext) {
94 self.update(cx, |this, cx| this.set_zoomed(zoomed, cx))
95 }
96
97 fn set_active(&self, active: bool, cx: &mut WindowContext) {
98 self.update(cx, |this, cx| this.set_active(active, cx))
99 }
100
101 fn icon_path(&self, cx: &WindowContext) -> Option<&'static str> {
102 self.read(cx).icon_path(cx)
103 }
104
105 fn icon_tooltip(&self, cx: &WindowContext) -> (String, Option<Box<dyn Action>>) {
106 self.read(cx).icon_tooltip()
107 }
108
109 fn icon_label(&self, cx: &WindowContext) -> Option<String> {
110 self.read(cx).icon_label(cx)
111 }
112
113 fn has_focus(&self, cx: &WindowContext) -> bool {
114 self.read(cx).has_focus(cx)
115 }
116
117 fn as_any(&self) -> &AnyViewHandle {
118 self
119 }
120}
121
122impl From<&dyn PanelHandle> for AnyViewHandle {
123 fn from(val: &dyn PanelHandle) -> Self {
124 val.as_any().clone()
125 }
126}
127
128pub struct Dock {
129 position: DockPosition,
130 panel_entries: Vec<PanelEntry>,
131 is_open: bool,
132 active_panel_index: usize,
133}
134
135#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
136#[serde(rename_all = "lowercase")]
137pub enum DockPosition {
138 Left,
139 Bottom,
140 Right,
141}
142
143impl DockPosition {
144 fn to_label(&self) -> &'static str {
145 match self {
146 Self::Left => "left",
147 Self::Bottom => "bottom",
148 Self::Right => "right",
149 }
150 }
151
152 fn to_resize_handle_side(self) -> HandleSide {
153 match self {
154 Self::Left => HandleSide::Right,
155 Self::Bottom => HandleSide::Top,
156 Self::Right => HandleSide::Left,
157 }
158 }
159
160 pub fn axis(&self) -> Axis {
161 match self {
162 Self::Left | Self::Right => Axis::Horizontal,
163 Self::Bottom => Axis::Vertical,
164 }
165 }
166}
167
168struct PanelEntry {
169 panel: Rc<dyn PanelHandle>,
170 context_menu: ViewHandle<ContextMenu>,
171 _subscriptions: [Subscription; 2],
172}
173
174pub struct PanelButtons {
175 dock: ViewHandle<Dock>,
176 workspace: WeakViewHandle<Workspace>,
177}
178
179impl Dock {
180 pub fn new(position: DockPosition) -> Self {
181 Self {
182 position,
183 panel_entries: Default::default(),
184 active_panel_index: 0,
185 is_open: false,
186 }
187 }
188
189 pub fn position(&self) -> DockPosition {
190 self.position
191 }
192
193 pub fn is_open(&self) -> bool {
194 self.is_open
195 }
196
197 pub fn has_focus(&self, cx: &WindowContext) -> bool {
198 self.visible_panel()
199 .map_or(false, |panel| panel.has_focus(cx))
200 }
201
202 pub fn panel<T: Panel>(&self) -> Option<ViewHandle<T>> {
203 self.panel_entries
204 .iter()
205 .find_map(|entry| entry.panel.as_any().clone().downcast())
206 }
207
208 pub fn panel_index_for_type<T: Panel>(&self) -> Option<usize> {
209 self.panel_entries
210 .iter()
211 .position(|entry| entry.panel.as_any().is::<T>())
212 }
213
214 pub fn panel_index_for_ui_name(&self, ui_name: &str, cx: &AppContext) -> Option<usize> {
215 self.panel_entries.iter().position(|entry| {
216 let panel = entry.panel.as_any();
217 cx.view_ui_name(panel.window(), panel.id()) == Some(ui_name)
218 })
219 }
220
221 pub fn active_panel_index(&self) -> usize {
222 self.active_panel_index
223 }
224
225 pub(crate) fn set_open(&mut self, open: bool, cx: &mut ViewContext<Self>) {
226 if open != self.is_open {
227 self.is_open = open;
228 if let Some(active_panel) = self.panel_entries.get(self.active_panel_index) {
229 active_panel.panel.set_active(open, cx);
230 }
231
232 cx.notify();
233 }
234 }
235
236 pub fn set_panel_zoomed(
237 &mut self,
238 panel: &AnyViewHandle,
239 zoomed: bool,
240 cx: &mut ViewContext<Self>,
241 ) {
242 for entry in &mut self.panel_entries {
243 if entry.panel.as_any() == panel {
244 if zoomed != entry.panel.is_zoomed(cx) {
245 entry.panel.set_zoomed(zoomed, cx);
246 }
247 } else if entry.panel.is_zoomed(cx) {
248 entry.panel.set_zoomed(false, cx);
249 }
250 }
251
252 cx.notify();
253 }
254
255 pub fn zoom_out(&mut self, cx: &mut ViewContext<Self>) {
256 for entry in &mut self.panel_entries {
257 if entry.panel.is_zoomed(cx) {
258 entry.panel.set_zoomed(false, cx);
259 }
260 }
261 }
262
263 pub(crate) fn add_panel<T: Panel>(&mut self, panel: ViewHandle<T>, cx: &mut ViewContext<Self>) {
264 let subscriptions = [
265 cx.observe(&panel, |_, _, cx| cx.notify()),
266 cx.subscribe(&panel, |this, panel, event, cx| {
267 if T::should_activate_on_event(event) {
268 if let Some(ix) = this
269 .panel_entries
270 .iter()
271 .position(|entry| entry.panel.id() == panel.id())
272 {
273 this.set_open(true, cx);
274 this.activate_panel(ix, cx);
275 cx.focus(&panel);
276 }
277 } else if T::should_close_on_event(event)
278 && this.visible_panel().map_or(false, |p| p.id() == panel.id())
279 {
280 this.set_open(false, cx);
281 }
282 }),
283 ];
284
285 let dock_view_id = cx.view_id();
286 self.panel_entries.push(PanelEntry {
287 panel: Rc::new(panel),
288 context_menu: cx.add_view(|cx| {
289 let mut menu = ContextMenu::new(dock_view_id, cx);
290 menu.set_position_mode(OverlayPositionMode::Local);
291 menu
292 }),
293 _subscriptions: subscriptions,
294 });
295 cx.notify()
296 }
297
298 pub fn remove_panel<T: Panel>(&mut self, panel: &ViewHandle<T>, cx: &mut ViewContext<Self>) {
299 if let Some(panel_ix) = self
300 .panel_entries
301 .iter()
302 .position(|entry| entry.panel.id() == panel.id())
303 {
304 if panel_ix == self.active_panel_index {
305 self.active_panel_index = 0;
306 self.set_open(false, cx);
307 } else if panel_ix < self.active_panel_index {
308 self.active_panel_index -= 1;
309 }
310 self.panel_entries.remove(panel_ix);
311 cx.notify();
312 }
313 }
314
315 pub fn panels_len(&self) -> usize {
316 self.panel_entries.len()
317 }
318
319 pub fn activate_panel(&mut self, panel_ix: usize, cx: &mut ViewContext<Self>) {
320 if panel_ix != self.active_panel_index {
321 if let Some(active_panel) = self.panel_entries.get(self.active_panel_index) {
322 active_panel.panel.set_active(false, cx);
323 }
324
325 self.active_panel_index = panel_ix;
326 if let Some(active_panel) = self.panel_entries.get(self.active_panel_index) {
327 active_panel.panel.set_active(true, cx);
328 }
329
330 cx.notify();
331 }
332 }
333
334 pub fn visible_panel(&self) -> Option<&Rc<dyn PanelHandle>> {
335 let entry = self.visible_entry()?;
336 Some(&entry.panel)
337 }
338
339 pub fn active_panel(&self) -> Option<&Rc<dyn PanelHandle>> {
340 Some(&self.panel_entries.get(self.active_panel_index)?.panel)
341 }
342
343 fn visible_entry(&self) -> Option<&PanelEntry> {
344 if self.is_open {
345 self.panel_entries.get(self.active_panel_index)
346 } else {
347 None
348 }
349 }
350
351 pub fn zoomed_panel(&self, cx: &WindowContext) -> Option<Rc<dyn PanelHandle>> {
352 let entry = self.visible_entry()?;
353 if entry.panel.is_zoomed(cx) {
354 Some(entry.panel.clone())
355 } else {
356 None
357 }
358 }
359
360 pub fn panel_size(&self, panel: &dyn PanelHandle, cx: &WindowContext) -> Option<f32> {
361 self.panel_entries
362 .iter()
363 .find(|entry| entry.panel.id() == panel.id())
364 .map(|entry| entry.panel.size(cx))
365 }
366
367 pub fn active_panel_size(&self, cx: &WindowContext) -> Option<f32> {
368 if self.is_open {
369 self.panel_entries
370 .get(self.active_panel_index)
371 .map(|entry| entry.panel.size(cx))
372 } else {
373 None
374 }
375 }
376
377 pub fn resize_active_panel(&mut self, size: Option<f32>, cx: &mut ViewContext<Self>) {
378 if let Some(entry) = self.panel_entries.get_mut(self.active_panel_index) {
379 entry.panel.set_size(size, cx);
380 cx.notify();
381 }
382 }
383
384 pub fn render_placeholder(&self, cx: &WindowContext) -> AnyElement<Workspace> {
385 if let Some(active_entry) = self.visible_entry() {
386 Empty::new()
387 .into_any()
388 .contained()
389 .with_style(self.style(cx))
390 .resizable::<WorkspaceBounds>(
391 self.position.to_resize_handle_side(),
392 active_entry.panel.size(cx),
393 |_, _, _| {},
394 )
395 .into_any()
396 } else {
397 Empty::new().into_any()
398 }
399 }
400
401 fn style(&self, cx: &WindowContext) -> ContainerStyle {
402 let theme = &settings::get::<ThemeSettings>(cx).theme;
403 let style = match self.position {
404 DockPosition::Left => theme.workspace.dock.left,
405 DockPosition::Bottom => theme.workspace.dock.bottom,
406 DockPosition::Right => theme.workspace.dock.right,
407 };
408 style
409 }
410}
411
412impl Entity for Dock {
413 type Event = ();
414}
415
416impl View for Dock {
417 fn ui_name() -> &'static str {
418 "Dock"
419 }
420
421 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
422 if let Some(active_entry) = self.visible_entry() {
423 let style = self.style(cx);
424 ChildView::new(active_entry.panel.as_any(), cx)
425 .contained()
426 .with_style(style)
427 .resizable::<WorkspaceBounds>(
428 self.position.to_resize_handle_side(),
429 active_entry.panel.size(cx),
430 |dock: &mut Self, size, cx| dock.resize_active_panel(size, cx),
431 )
432 .into_any()
433 } else {
434 Empty::new().into_any()
435 }
436 }
437
438 fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
439 if cx.is_self_focused() {
440 if let Some(active_entry) = self.visible_entry() {
441 cx.focus(active_entry.panel.as_any());
442 } else {
443 cx.focus_parent();
444 }
445 }
446 }
447}
448
449impl PanelButtons {
450 pub fn new(
451 dock: ViewHandle<Dock>,
452 workspace: WeakViewHandle<Workspace>,
453 cx: &mut ViewContext<Self>,
454 ) -> Self {
455 cx.observe(&dock, |_, _, cx| cx.notify()).detach();
456 Self { dock, workspace }
457 }
458}
459
460impl Entity for PanelButtons {
461 type Event = ();
462}
463
464impl View for PanelButtons {
465 fn ui_name() -> &'static str {
466 "PanelButtons"
467 }
468
469 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
470 let theme = &settings::get::<ThemeSettings>(cx).theme;
471 let tooltip_style = theme.tooltip.clone();
472 let theme = &theme.workspace.status_bar.panel_buttons;
473 let button_style = theme.button.clone();
474 let dock = self.dock.read(cx);
475 let active_ix = dock.active_panel_index;
476 let is_open = dock.is_open;
477 let dock_position = dock.position;
478 let group_style = match dock_position {
479 DockPosition::Left => theme.group_left,
480 DockPosition::Bottom => theme.group_bottom,
481 DockPosition::Right => theme.group_right,
482 };
483 let menu_corner = match dock_position {
484 DockPosition::Left => AnchorCorner::BottomLeft,
485 DockPosition::Bottom | DockPosition::Right => AnchorCorner::BottomRight,
486 };
487
488 let panels = dock
489 .panel_entries
490 .iter()
491 .map(|item| (item.panel.clone(), item.context_menu.clone()))
492 .collect::<Vec<_>>();
493 Flex::row()
494 .with_children(panels.into_iter().enumerate().filter_map(
495 |(panel_ix, (view, context_menu))| {
496 let icon_path = view.icon_path(cx)?;
497 let is_active = is_open && panel_ix == active_ix;
498 let (tooltip, tooltip_action) = if is_active {
499 (
500 format!("Close {} dock", dock_position.to_label()),
501 Some(match dock_position {
502 DockPosition::Left => crate::ToggleLeftDock.boxed_clone(),
503 DockPosition::Bottom => crate::ToggleBottomDock.boxed_clone(),
504 DockPosition::Right => crate::ToggleRightDock.boxed_clone(),
505 }),
506 )
507 } else {
508 view.icon_tooltip(cx)
509 };
510 Some(
511 Stack::new()
512 .with_child(
513 MouseEventHandler::new::<Self, _>(panel_ix, cx, |state, cx| {
514 let style = button_style.in_state(is_active);
515
516 let style = style.style_for(state);
517 Flex::row()
518 .with_child(
519 Svg::new(icon_path)
520 .with_color(style.icon_color)
521 .constrained()
522 .with_width(style.icon_size)
523 .aligned(),
524 )
525 .with_children(if let Some(label) = view.icon_label(cx) {
526 Some(
527 Label::new(label, style.label.text.clone())
528 .contained()
529 .with_style(style.label.container)
530 .aligned(),
531 )
532 } else {
533 None
534 })
535 .constrained()
536 .with_height(style.icon_size)
537 .contained()
538 .with_style(style.container)
539 })
540 .with_cursor_style(CursorStyle::PointingHand)
541 .on_click(MouseButton::Left, {
542 let tooltip_action =
543 tooltip_action.as_ref().map(|action| action.boxed_clone());
544 move |_, this, cx| {
545 if let Some(tooltip_action) = &tooltip_action {
546 let window = cx.window();
547 let view_id = this.workspace.id();
548 let tooltip_action = tooltip_action.boxed_clone();
549 cx.spawn(|_, mut cx| async move {
550 window.dispatch_action(
551 view_id,
552 &*tooltip_action,
553 &mut cx,
554 );
555 })
556 .detach();
557 }
558 }
559 })
560 .on_click(MouseButton::Right, {
561 let view = view.clone();
562 let menu = context_menu.clone();
563 move |_, _, cx| {
564 const POSITIONS: [DockPosition; 3] = [
565 DockPosition::Left,
566 DockPosition::Right,
567 DockPosition::Bottom,
568 ];
569
570 menu.update(cx, |menu, cx| {
571 let items = POSITIONS
572 .into_iter()
573 .filter(|position| {
574 *position != dock_position
575 && view.position_is_valid(*position, cx)
576 })
577 .map(|position| {
578 let view = view.clone();
579 ContextMenuItem::handler(
580 format!("Dock {}", position.to_label()),
581 move |cx| view.set_position(position, cx),
582 )
583 })
584 .collect();
585 menu.show(Default::default(), menu_corner, items, cx);
586 })
587 }
588 })
589 .with_tooltip::<Self>(
590 panel_ix,
591 tooltip,
592 tooltip_action,
593 tooltip_style.clone(),
594 cx,
595 ),
596 )
597 .with_child(ChildView::new(&context_menu, cx)),
598 )
599 },
600 ))
601 .contained()
602 .with_style(group_style)
603 .into_any()
604 }
605}
606
607impl StatusItemView for PanelButtons {
608 fn set_active_pane_item(
609 &mut self,
610 _: Option<&dyn crate::ItemHandle>,
611 _: &mut ViewContext<Self>,
612 ) {
613 }
614}
615
616#[cfg(any(test, feature = "test-support"))]
617pub mod test {
618 use super::*;
619 use gpui2::{ViewContext, WindowContext};
620
621 #[derive(Debug)]
622 pub enum TestPanelEvent {
623 PositionChanged,
624 Activated,
625 Closed,
626 ZoomIn,
627 ZoomOut,
628 Focus,
629 }
630
631 pub struct TestPanel {
632 pub position: DockPosition,
633 pub zoomed: bool,
634 pub active: bool,
635 pub has_focus: bool,
636 pub size: f32,
637 }
638
639 impl TestPanel {
640 pub fn new(position: DockPosition) -> Self {
641 Self {
642 position,
643 zoomed: false,
644 active: false,
645 has_focus: false,
646 size: 300.,
647 }
648 }
649 }
650
651 impl Entity for TestPanel {
652 type Event = TestPanelEvent;
653 }
654
655 impl View for TestPanel {
656 fn ui_name() -> &'static str {
657 "TestPanel"
658 }
659
660 fn render(&mut self, _: &mut ViewContext<'_, '_, Self>) -> AnyElement<Self> {
661 Empty::new().into_any()
662 }
663
664 fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
665 self.has_focus = true;
666 cx.emit(TestPanelEvent::Focus);
667 }
668
669 fn focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {
670 self.has_focus = false;
671 }
672 }
673
674 impl Panel for TestPanel {
675 fn position(&self, _: &gpui::WindowContext) -> super::DockPosition {
676 self.position
677 }
678
679 fn position_is_valid(&self, _: super::DockPosition) -> bool {
680 true
681 }
682
683 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
684 self.position = position;
685 cx.emit(TestPanelEvent::PositionChanged);
686 }
687
688 fn is_zoomed(&self, _: &WindowContext) -> bool {
689 self.zoomed
690 }
691
692 fn set_zoomed(&mut self, zoomed: bool, _cx: &mut ViewContext<Self>) {
693 self.zoomed = zoomed;
694 }
695
696 fn set_active(&mut self, active: bool, _cx: &mut ViewContext<Self>) {
697 self.active = active;
698 }
699
700 fn size(&self, _: &WindowContext) -> f32 {
701 self.size
702 }
703
704 fn set_size(&mut self, size: Option<f32>, _: &mut ViewContext<Self>) {
705 self.size = size.unwrap_or(300.);
706 }
707
708 fn icon_path(&self, _: &WindowContext) -> Option<&'static str> {
709 Some("icons/test_panel.svg")
710 }
711
712 fn icon_tooltip(&self) -> (String, Option<Box<dyn Action>>) {
713 ("Test Panel".into(), None)
714 }
715
716 fn should_change_position_on_event(event: &Self::Event) -> bool {
717 matches!(event, TestPanelEvent::PositionChanged)
718 }
719
720 fn should_zoom_in_on_event(event: &Self::Event) -> bool {
721 matches!(event, TestPanelEvent::ZoomIn)
722 }
723
724 fn should_zoom_out_on_event(event: &Self::Event) -> bool {
725 matches!(event, TestPanelEvent::ZoomOut)
726 }
727
728 fn should_activate_on_event(event: &Self::Event) -> bool {
729 matches!(event, TestPanelEvent::Activated)
730 }
731
732 fn should_close_on_event(event: &Self::Event) -> bool {
733 matches!(event, TestPanelEvent::Closed)
734 }
735
736 fn has_focus(&self, _cx: &WindowContext) -> bool {
737 self.has_focus
738 }
739
740 fn is_focus_event(event: &Self::Event) -> bool {
741 matches!(event, TestPanelEvent::Focus)
742 }
743 }
744}