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.active_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.active_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 active_panel(&self) -> Option<&Rc<dyn PanelHandle>> {
319        let entry = self.active_entry()?;
320        Some(&entry.panel)
321    }
322
323    fn active_entry(&self) -> Option<&PanelEntry> {
324        if self.is_open {
325            self.panel_entries.get(self.active_panel_index)
326        } else {
327            None
328        }
329    }
330
331    pub fn zoomed_panel(&self, cx: &WindowContext) -> Option<Rc<dyn PanelHandle>> {
332        let entry = self.active_entry()?;
333        if entry.panel.is_zoomed(cx) {
334            Some(entry.panel.clone())
335        } else {
336            None
337        }
338    }
339
340    pub fn panel_size(&self, panel: &dyn PanelHandle, cx: &WindowContext) -> Option<f32> {
341        self.panel_entries
342            .iter()
343            .find(|entry| entry.panel.id() == panel.id())
344            .map(|entry| entry.panel.size(cx))
345    }
346
347    pub fn active_panel_size(&self, cx: &WindowContext) -> Option<f32> {
348        if self.is_open {
349            self.panel_entries
350                .get(self.active_panel_index)
351                .map(|entry| entry.panel.size(cx))
352        } else {
353            None
354        }
355    }
356
357    pub fn resize_active_panel(&mut self, size: f32, cx: &mut ViewContext<Self>) {
358        if let Some(entry) = self.panel_entries.get_mut(self.active_panel_index) {
359            entry.panel.set_size(size, cx);
360            cx.notify();
361        }
362    }
363
364    pub fn render_placeholder(&self, cx: &WindowContext) -> AnyElement<Workspace> {
365        if let Some(active_entry) = self.active_entry() {
366            Empty::new()
367                .into_any()
368                .contained()
369                .with_style(self.style(cx))
370                .resizable(
371                    self.position.to_resize_handle_side(),
372                    active_entry.panel.size(cx),
373                    |_, _, _| {},
374                )
375                .into_any()
376        } else {
377            Empty::new().into_any()
378        }
379    }
380
381    fn style(&self, cx: &WindowContext) -> ContainerStyle {
382        let theme = &settings::get::<ThemeSettings>(cx).theme;
383        let style = match self.position {
384            DockPosition::Left => theme.workspace.dock.left,
385            DockPosition::Bottom => theme.workspace.dock.bottom,
386            DockPosition::Right => theme.workspace.dock.right,
387        };
388        style
389    }
390}
391
392impl Entity for Dock {
393    type Event = ();
394}
395
396impl View for Dock {
397    fn ui_name() -> &'static str {
398        "Dock"
399    }
400
401    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
402        if let Some(active_entry) = self.active_entry() {
403            let style = self.style(cx);
404            ChildView::new(active_entry.panel.as_any(), cx)
405                .contained()
406                .with_style(style)
407                .resizable(
408                    self.position.to_resize_handle_side(),
409                    active_entry.panel.size(cx),
410                    |dock: &mut Self, size, cx| dock.resize_active_panel(size, cx),
411                )
412                .into_any()
413        } else {
414            Empty::new().into_any()
415        }
416    }
417
418    fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
419        if cx.is_self_focused() {
420            if let Some(active_entry) = self.active_entry() {
421                cx.focus(active_entry.panel.as_any());
422            } else {
423                cx.focus_parent();
424            }
425        }
426    }
427}
428
429impl PanelButtons {
430    pub fn new(
431        dock: ViewHandle<Dock>,
432        workspace: WeakViewHandle<Workspace>,
433        cx: &mut ViewContext<Self>,
434    ) -> Self {
435        cx.observe(&dock, |_, _, cx| cx.notify()).detach();
436        Self { dock, workspace }
437    }
438}
439
440impl Entity for PanelButtons {
441    type Event = ();
442}
443
444impl View for PanelButtons {
445    fn ui_name() -> &'static str {
446        "PanelButtons"
447    }
448
449    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
450        let theme = &settings::get::<ThemeSettings>(cx).theme;
451        let tooltip_style = theme.tooltip.clone();
452        let theme = &theme.workspace.status_bar.panel_buttons;
453        let button_style = theme.button.clone();
454        let dock = self.dock.read(cx);
455        let active_ix = dock.active_panel_index;
456        let is_open = dock.is_open;
457        let dock_position = dock.position;
458        let group_style = match dock_position {
459            DockPosition::Left => theme.group_left,
460            DockPosition::Bottom => theme.group_bottom,
461            DockPosition::Right => theme.group_right,
462        };
463        let menu_corner = match dock_position {
464            DockPosition::Left => AnchorCorner::BottomLeft,
465            DockPosition::Bottom | DockPosition::Right => AnchorCorner::BottomRight,
466        };
467
468        let panels = dock
469            .panel_entries
470            .iter()
471            .map(|item| (item.panel.clone(), item.context_menu.clone()))
472            .collect::<Vec<_>>();
473        Flex::row()
474            .with_children(panels.into_iter().enumerate().map(
475                |(panel_ix, (view, context_menu))| {
476                    let (tooltip, tooltip_action) = view.icon_tooltip(cx);
477                    Stack::new()
478                        .with_child(
479                            MouseEventHandler::<Self, _>::new(panel_ix, cx, |state, cx| {
480                                let is_active = is_open && panel_ix == active_ix;
481                                let style = button_style.style_for(state, is_active);
482                                Flex::row()
483                                    .with_child(
484                                        Svg::new(view.icon_path(cx))
485                                            .with_color(style.icon_color)
486                                            .constrained()
487                                            .with_width(style.icon_size)
488                                            .aligned(),
489                                    )
490                                    .with_children(if let Some(label) = view.icon_label(cx) {
491                                        Some(
492                                            Label::new(label, style.label.text.clone())
493                                                .contained()
494                                                .with_style(style.label.container)
495                                                .aligned(),
496                                        )
497                                    } else {
498                                        None
499                                    })
500                                    .constrained()
501                                    .with_height(style.icon_size)
502                                    .contained()
503                                    .with_style(style.container)
504                            })
505                            .with_cursor_style(CursorStyle::PointingHand)
506                            .on_click(MouseButton::Left, {
507                                move |_, this, cx| {
508                                    if let Some(workspace) = this.workspace.upgrade(cx) {
509                                        cx.window_context().defer(move |cx| {
510                                            workspace.update(cx, |workspace, cx| {
511                                                workspace.toggle_panel(dock_position, panel_ix, cx)
512                                            });
513                                        });
514                                    }
515                                }
516                            })
517                            .on_click(MouseButton::Right, {
518                                let view = view.clone();
519                                let menu = context_menu.clone();
520                                move |_, _, cx| {
521                                    const POSITIONS: [DockPosition; 3] = [
522                                        DockPosition::Left,
523                                        DockPosition::Right,
524                                        DockPosition::Bottom,
525                                    ];
526
527                                    menu.update(cx, |menu, cx| {
528                                        let items = POSITIONS
529                                            .into_iter()
530                                            .filter(|position| {
531                                                *position != dock_position
532                                                    && view.position_is_valid(*position, cx)
533                                            })
534                                            .map(|position| {
535                                                let view = view.clone();
536                                                ContextMenuItem::handler(
537                                                    format!("Dock {}", position.to_label()),
538                                                    move |cx| view.set_position(position, cx),
539                                                )
540                                            })
541                                            .collect();
542                                        menu.show(Default::default(), menu_corner, items, cx);
543                                    })
544                                }
545                            })
546                            .with_tooltip::<Self>(
547                                panel_ix,
548                                tooltip,
549                                tooltip_action,
550                                tooltip_style.clone(),
551                                cx,
552                            ),
553                        )
554                        .with_child(ChildView::new(&context_menu, cx))
555                },
556            ))
557            .contained()
558            .with_style(group_style)
559            .into_any()
560    }
561}
562
563impl StatusItemView for PanelButtons {
564    fn set_active_pane_item(
565        &mut self,
566        _: Option<&dyn crate::ItemHandle>,
567        _: &mut ViewContext<Self>,
568    ) {
569    }
570}
571
572#[cfg(test)]
573pub(crate) mod test {
574    use super::*;
575    use gpui::{ViewContext, WindowContext};
576
577    pub enum TestPanelEvent {
578        PositionChanged,
579        Activated,
580        Closed,
581        ZoomIn,
582        ZoomOut,
583        Focus,
584    }
585
586    pub struct TestPanel {
587        pub position: DockPosition,
588        pub zoomed: bool,
589        pub active: bool,
590        pub has_focus: bool,
591        pub size: f32,
592    }
593
594    impl TestPanel {
595        pub fn new(position: DockPosition) -> Self {
596            Self {
597                position,
598                zoomed: false,
599                active: false,
600                has_focus: false,
601                size: 300.,
602            }
603        }
604    }
605
606    impl Entity for TestPanel {
607        type Event = TestPanelEvent;
608    }
609
610    impl View for TestPanel {
611        fn ui_name() -> &'static str {
612            "TestPanel"
613        }
614
615        fn render(&mut self, _: &mut ViewContext<'_, '_, Self>) -> AnyElement<Self> {
616            Empty::new().into_any()
617        }
618
619        fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
620            self.has_focus = true;
621            cx.emit(TestPanelEvent::Focus);
622        }
623
624        fn focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {
625            self.has_focus = false;
626        }
627    }
628
629    impl Panel for TestPanel {
630        fn position(&self, _: &gpui::WindowContext) -> super::DockPosition {
631            self.position
632        }
633
634        fn position_is_valid(&self, _: super::DockPosition) -> bool {
635            true
636        }
637
638        fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
639            self.position = position;
640            cx.emit(TestPanelEvent::PositionChanged);
641        }
642
643        fn is_zoomed(&self, _: &WindowContext) -> bool {
644            self.zoomed
645        }
646
647        fn set_zoomed(&mut self, zoomed: bool, _cx: &mut ViewContext<Self>) {
648            self.zoomed = zoomed;
649        }
650
651        fn set_active(&mut self, active: bool, _cx: &mut ViewContext<Self>) {
652            self.active = active;
653        }
654
655        fn size(&self, _: &WindowContext) -> f32 {
656            self.size
657        }
658
659        fn set_size(&mut self, size: f32, _: &mut ViewContext<Self>) {
660            self.size = size;
661        }
662
663        fn icon_path(&self) -> &'static str {
664            "icons/test_panel.svg"
665        }
666
667        fn icon_tooltip(&self) -> (String, Option<Box<dyn Action>>) {
668            ("Test Panel".into(), None)
669        }
670
671        fn should_change_position_on_event(event: &Self::Event) -> bool {
672            matches!(event, TestPanelEvent::PositionChanged)
673        }
674
675        fn should_zoom_in_on_event(event: &Self::Event) -> bool {
676            matches!(event, TestPanelEvent::ZoomIn)
677        }
678
679        fn should_zoom_out_on_event(event: &Self::Event) -> bool {
680            matches!(event, TestPanelEvent::ZoomOut)
681        }
682
683        fn should_activate_on_event(event: &Self::Event) -> bool {
684            matches!(event, TestPanelEvent::Activated)
685        }
686
687        fn should_close_on_event(event: &Self::Event) -> bool {
688            matches!(event, TestPanelEvent::Closed)
689        }
690
691        fn has_focus(&self, _cx: &WindowContext) -> bool {
692            self.has_focus
693        }
694
695        fn is_focus_event(event: &Self::Event) -> bool {
696            matches!(event, TestPanelEvent::Focus)
697        }
698    }
699}