dock.rs

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