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;
 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 is_open(&self) -> bool {
179        self.is_open
180    }
181
182    pub fn has_focus(&self, cx: &WindowContext) -> bool {
183        self.visible_panel()
184            .map_or(false, |panel| panel.has_focus(cx))
185    }
186
187    pub fn panel_index_for_type<T: Panel>(&self) -> Option<usize> {
188        self.panel_entries
189            .iter()
190            .position(|entry| entry.panel.as_any().is::<T>())
191    }
192
193    pub fn panel_index_for_ui_name(&self, ui_name: &str, cx: &AppContext) -> Option<usize> {
194        self.panel_entries.iter().position(|entry| {
195            let panel = entry.panel.as_any();
196            cx.view_ui_name(panel.window_id(), panel.id()) == Some(ui_name)
197        })
198    }
199
200    pub fn active_panel_index(&self) -> usize {
201        self.active_panel_index
202    }
203
204    pub fn set_open(&mut self, open: bool, cx: &mut ViewContext<Self>) {
205        if open != self.is_open {
206            self.is_open = open;
207            if let Some(active_panel) = self.panel_entries.get(self.active_panel_index) {
208                active_panel.panel.set_active(open, cx);
209            }
210
211            cx.notify();
212        }
213    }
214
215    pub fn toggle_open(&mut self, cx: &mut ViewContext<Self>) {
216        self.set_open(!self.is_open, cx);
217        cx.notify();
218    }
219
220    pub fn set_panel_zoomed(
221        &mut self,
222        panel: &AnyViewHandle,
223        zoomed: bool,
224        cx: &mut ViewContext<Self>,
225    ) {
226        for entry in &mut self.panel_entries {
227            if entry.panel.as_any() == panel {
228                if zoomed != entry.panel.is_zoomed(cx) {
229                    entry.panel.set_zoomed(zoomed, cx);
230                }
231            } else if entry.panel.is_zoomed(cx) {
232                entry.panel.set_zoomed(false, cx);
233            }
234        }
235
236        cx.notify();
237    }
238
239    pub fn zoom_out(&mut self, cx: &mut ViewContext<Self>) {
240        for entry in &mut self.panel_entries {
241            if entry.panel.is_zoomed(cx) {
242                entry.panel.set_zoomed(false, cx);
243            }
244        }
245    }
246
247    pub fn add_panel<T: Panel>(&mut self, panel: ViewHandle<T>, cx: &mut ViewContext<Self>) {
248        let subscriptions = [
249            cx.observe(&panel, |_, _, cx| cx.notify()),
250            cx.subscribe(&panel, |this, panel, event, cx| {
251                if T::should_activate_on_event(event) {
252                    if let Some(ix) = this
253                        .panel_entries
254                        .iter()
255                        .position(|entry| entry.panel.id() == panel.id())
256                    {
257                        this.set_open(true, cx);
258                        this.activate_panel(ix, cx);
259                        cx.focus(&panel);
260                    }
261                } else if T::should_close_on_event(event)
262                    && this.visible_panel().map_or(false, |p| p.id() == panel.id())
263                {
264                    this.set_open(false, cx);
265                }
266            }),
267        ];
268
269        let dock_view_id = cx.view_id();
270        self.panel_entries.push(PanelEntry {
271            panel: Rc::new(panel),
272            context_menu: cx.add_view(|cx| {
273                let mut menu = ContextMenu::new(dock_view_id, cx);
274                menu.set_position_mode(OverlayPositionMode::Local);
275                menu
276            }),
277            _subscriptions: subscriptions,
278        });
279        cx.notify()
280    }
281
282    pub fn remove_panel<T: Panel>(&mut self, panel: &ViewHandle<T>, cx: &mut ViewContext<Self>) {
283        if let Some(panel_ix) = self
284            .panel_entries
285            .iter()
286            .position(|entry| entry.panel.id() == panel.id())
287        {
288            if panel_ix == self.active_panel_index {
289                self.active_panel_index = 0;
290                self.set_open(false, cx);
291            } else if panel_ix < self.active_panel_index {
292                self.active_panel_index -= 1;
293            }
294            self.panel_entries.remove(panel_ix);
295            cx.notify();
296        }
297    }
298
299    pub fn panels_len(&self) -> usize {
300        self.panel_entries.len()
301    }
302
303    pub fn activate_panel(&mut self, panel_ix: usize, cx: &mut ViewContext<Self>) {
304        if panel_ix != self.active_panel_index {
305            if let Some(active_panel) = self.panel_entries.get(self.active_panel_index) {
306                active_panel.panel.set_active(false, cx);
307            }
308
309            self.active_panel_index = panel_ix;
310            if let Some(active_panel) = self.panel_entries.get(self.active_panel_index) {
311                active_panel.panel.set_active(true, cx);
312            }
313
314            cx.notify();
315        }
316    }
317
318    pub fn visible_panel(&self) -> Option<&Rc<dyn PanelHandle>> {
319        let entry = self.visible_entry()?;
320        Some(&entry.panel)
321    }
322
323    pub fn active_panel(&self) -> Option<&Rc<dyn PanelHandle>> {
324        Some(&self.panel_entries.get(self.active_panel_index)?.panel)
325    }
326
327    fn visible_entry(&self) -> Option<&PanelEntry> {
328        if self.is_open {
329            self.panel_entries.get(self.active_panel_index)
330        } else {
331            None
332        }
333    }
334
335    pub fn zoomed_panel(&self, cx: &WindowContext) -> Option<Rc<dyn PanelHandle>> {
336        let entry = self.visible_entry()?;
337        if entry.panel.is_zoomed(cx) {
338            Some(entry.panel.clone())
339        } else {
340            None
341        }
342    }
343
344    pub fn panel_size(&self, panel: &dyn PanelHandle, cx: &WindowContext) -> Option<f32> {
345        self.panel_entries
346            .iter()
347            .find(|entry| entry.panel.id() == panel.id())
348            .map(|entry| entry.panel.size(cx))
349    }
350
351    pub fn active_panel_size(&self, cx: &WindowContext) -> Option<f32> {
352        if self.is_open {
353            self.panel_entries
354                .get(self.active_panel_index)
355                .map(|entry| entry.panel.size(cx))
356        } else {
357            None
358        }
359    }
360
361    pub fn resize_active_panel(&mut self, size: f32, cx: &mut ViewContext<Self>) {
362        if let Some(entry) = self.panel_entries.get_mut(self.active_panel_index) {
363            entry.panel.set_size(size, cx);
364            cx.notify();
365        }
366    }
367
368    pub fn render_placeholder(&self, cx: &WindowContext) -> AnyElement<Workspace> {
369        if let Some(active_entry) = self.visible_entry() {
370            Empty::new()
371                .into_any()
372                .contained()
373                .with_style(self.style(cx))
374                .resizable(
375                    self.position.to_resize_handle_side(),
376                    active_entry.panel.size(cx),
377                    |_, _, _| {},
378                )
379                .into_any()
380        } else {
381            Empty::new().into_any()
382        }
383    }
384
385    fn style(&self, cx: &WindowContext) -> ContainerStyle {
386        let theme = &settings::get::<ThemeSettings>(cx).theme;
387        let style = match self.position {
388            DockPosition::Left => theme.workspace.dock.left,
389            DockPosition::Bottom => theme.workspace.dock.bottom,
390            DockPosition::Right => theme.workspace.dock.right,
391        };
392        style
393    }
394}
395
396impl Entity for Dock {
397    type Event = ();
398}
399
400impl View for Dock {
401    fn ui_name() -> &'static str {
402        "Dock"
403    }
404
405    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
406        if let Some(active_entry) = self.visible_entry() {
407            let style = self.style(cx);
408            ChildView::new(active_entry.panel.as_any(), cx)
409                .contained()
410                .with_style(style)
411                .resizable(
412                    self.position.to_resize_handle_side(),
413                    active_entry.panel.size(cx),
414                    |dock: &mut Self, size, cx| dock.resize_active_panel(size, cx),
415                )
416                .into_any()
417        } else {
418            Empty::new().into_any()
419        }
420    }
421
422    fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
423        if cx.is_self_focused() {
424            if let Some(active_entry) = self.visible_entry() {
425                cx.focus(active_entry.panel.as_any());
426            } else {
427                cx.focus_parent();
428            }
429        }
430    }
431}
432
433impl PanelButtons {
434    pub fn new(
435        dock: ViewHandle<Dock>,
436        workspace: WeakViewHandle<Workspace>,
437        cx: &mut ViewContext<Self>,
438    ) -> Self {
439        cx.observe(&dock, |_, _, cx| cx.notify()).detach();
440        Self { dock, workspace }
441    }
442}
443
444impl Entity for PanelButtons {
445    type Event = ();
446}
447
448impl View for PanelButtons {
449    fn ui_name() -> &'static str {
450        "PanelButtons"
451    }
452
453    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
454        let theme = &settings::get::<ThemeSettings>(cx).theme;
455        let tooltip_style = theme.tooltip.clone();
456        let theme = &theme.workspace.status_bar.panel_buttons;
457        let button_style = theme.button.clone();
458        let dock = self.dock.read(cx);
459        let active_ix = dock.active_panel_index;
460        let is_open = dock.is_open;
461        let dock_position = dock.position;
462        let group_style = match dock_position {
463            DockPosition::Left => theme.group_left,
464            DockPosition::Bottom => theme.group_bottom,
465            DockPosition::Right => theme.group_right,
466        };
467        let menu_corner = match dock_position {
468            DockPosition::Left => AnchorCorner::BottomLeft,
469            DockPosition::Bottom | DockPosition::Right => AnchorCorner::BottomRight,
470        };
471
472        let panels = dock
473            .panel_entries
474            .iter()
475            .map(|item| (item.panel.clone(), item.context_menu.clone()))
476            .collect::<Vec<_>>();
477        Flex::row()
478            .with_children(panels.into_iter().enumerate().map(
479                |(panel_ix, (view, context_menu))| {
480                    let (tooltip, tooltip_action) = view.icon_tooltip(cx);
481                    Stack::new()
482                        .with_child(
483                            MouseEventHandler::<Self, _>::new(panel_ix, cx, |state, cx| {
484                                let is_active = is_open && panel_ix == active_ix;
485                                let style = button_style.style_for(state, is_active);
486                                Flex::row()
487                                    .with_child(
488                                        Svg::new(view.icon_path(cx))
489                                            .with_color(style.icon_color)
490                                            .constrained()
491                                            .with_width(style.icon_size)
492                                            .aligned(),
493                                    )
494                                    .with_children(if let Some(label) = view.icon_label(cx) {
495                                        Some(
496                                            Label::new(label, style.label.text.clone())
497                                                .contained()
498                                                .with_style(style.label.container)
499                                                .aligned(),
500                                        )
501                                    } else {
502                                        None
503                                    })
504                                    .constrained()
505                                    .with_height(style.icon_size)
506                                    .contained()
507                                    .with_style(style.container)
508                            })
509                            .with_cursor_style(CursorStyle::PointingHand)
510                            .on_click(MouseButton::Left, {
511                                move |_, this, cx| {
512                                    if let Some(workspace) = this.workspace.upgrade(cx) {
513                                        cx.window_context().defer(move |cx| {
514                                            workspace.update(cx, |workspace, cx| {
515                                                workspace.toggle_panel(dock_position, panel_ix, cx)
516                                            });
517                                        });
518                                    }
519                                }
520                            })
521                            .on_click(MouseButton::Right, {
522                                let view = view.clone();
523                                let menu = context_menu.clone();
524                                move |_, _, cx| {
525                                    const POSITIONS: [DockPosition; 3] = [
526                                        DockPosition::Left,
527                                        DockPosition::Right,
528                                        DockPosition::Bottom,
529                                    ];
530
531                                    menu.update(cx, |menu, cx| {
532                                        let items = POSITIONS
533                                            .into_iter()
534                                            .filter(|position| {
535                                                *position != dock_position
536                                                    && view.position_is_valid(*position, cx)
537                                            })
538                                            .map(|position| {
539                                                let view = view.clone();
540                                                ContextMenuItem::handler(
541                                                    format!("Dock {}", position.to_label()),
542                                                    move |cx| view.set_position(position, cx),
543                                                )
544                                            })
545                                            .collect();
546                                        menu.show(Default::default(), menu_corner, items, cx);
547                                    })
548                                }
549                            })
550                            .with_tooltip::<Self>(
551                                panel_ix,
552                                tooltip,
553                                tooltip_action,
554                                tooltip_style.clone(),
555                                cx,
556                            ),
557                        )
558                        .with_child(ChildView::new(&context_menu, cx))
559                },
560            ))
561            .contained()
562            .with_style(group_style)
563            .into_any()
564    }
565}
566
567impl StatusItemView for PanelButtons {
568    fn set_active_pane_item(
569        &mut self,
570        _: Option<&dyn crate::ItemHandle>,
571        _: &mut ViewContext<Self>,
572    ) {
573    }
574}
575
576#[cfg(test)]
577pub(crate) mod test {
578    use super::*;
579    use gpui::{ViewContext, WindowContext};
580
581    pub enum TestPanelEvent {
582        PositionChanged,
583        Activated,
584        Closed,
585        ZoomIn,
586        ZoomOut,
587        Focus,
588    }
589
590    pub struct TestPanel {
591        pub position: DockPosition,
592        pub zoomed: bool,
593        pub active: bool,
594        pub has_focus: bool,
595        pub size: f32,
596    }
597
598    impl TestPanel {
599        pub fn new(position: DockPosition) -> Self {
600            Self {
601                position,
602                zoomed: false,
603                active: false,
604                has_focus: false,
605                size: 300.,
606            }
607        }
608    }
609
610    impl Entity for TestPanel {
611        type Event = TestPanelEvent;
612    }
613
614    impl View for TestPanel {
615        fn ui_name() -> &'static str {
616            "TestPanel"
617        }
618
619        fn render(&mut self, _: &mut ViewContext<'_, '_, Self>) -> AnyElement<Self> {
620            Empty::new().into_any()
621        }
622
623        fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
624            self.has_focus = true;
625            cx.emit(TestPanelEvent::Focus);
626        }
627
628        fn focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {
629            self.has_focus = false;
630        }
631    }
632
633    impl Panel for TestPanel {
634        fn position(&self, _: &gpui::WindowContext) -> super::DockPosition {
635            self.position
636        }
637
638        fn position_is_valid(&self, _: super::DockPosition) -> bool {
639            true
640        }
641
642        fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
643            self.position = position;
644            cx.emit(TestPanelEvent::PositionChanged);
645        }
646
647        fn is_zoomed(&self, _: &WindowContext) -> bool {
648            self.zoomed
649        }
650
651        fn set_zoomed(&mut self, zoomed: bool, _cx: &mut ViewContext<Self>) {
652            self.zoomed = zoomed;
653        }
654
655        fn set_active(&mut self, active: bool, _cx: &mut ViewContext<Self>) {
656            self.active = active;
657        }
658
659        fn size(&self, _: &WindowContext) -> f32 {
660            self.size
661        }
662
663        fn set_size(&mut self, size: f32, _: &mut ViewContext<Self>) {
664            self.size = size;
665        }
666
667        fn icon_path(&self) -> &'static str {
668            "icons/test_panel.svg"
669        }
670
671        fn icon_tooltip(&self) -> (String, Option<Box<dyn Action>>) {
672            ("Test Panel".into(), None)
673        }
674
675        fn should_change_position_on_event(event: &Self::Event) -> bool {
676            matches!(event, TestPanelEvent::PositionChanged)
677        }
678
679        fn should_zoom_in_on_event(event: &Self::Event) -> bool {
680            matches!(event, TestPanelEvent::ZoomIn)
681        }
682
683        fn should_zoom_out_on_event(event: &Self::Event) -> bool {
684            matches!(event, TestPanelEvent::ZoomOut)
685        }
686
687        fn should_activate_on_event(event: &Self::Event) -> bool {
688            matches!(event, TestPanelEvent::Activated)
689        }
690
691        fn should_close_on_event(event: &Self::Event) -> bool {
692            matches!(event, TestPanelEvent::Closed)
693        }
694
695        fn has_focus(&self, _cx: &WindowContext) -> bool {
696            self.has_focus
697        }
698
699        fn is_focus_event(event: &Self::Event) -> bool {
700            matches!(event, TestPanelEvent::Focus)
701        }
702    }
703}