dock.rs

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