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, _: &AppContext) -> Option<String> {
 20        None
 21    }
 22    fn should_change_position_on_event(_: &Self::Event) -> bool;
 23    fn should_activate_on_event(&self, _: &Self::Event, _: &AppContext) -> bool;
 24    fn should_close_on_event(&self, _: &Self::Event, _: &AppContext) -> bool;
 25}
 26
 27pub trait PanelHandle {
 28    fn id(&self) -> usize;
 29    fn position(&self, cx: &WindowContext) -> DockPosition;
 30    fn position_is_valid(&self, position: DockPosition, cx: &WindowContext) -> bool;
 31    fn set_position(&self, position: DockPosition, cx: &mut WindowContext);
 32    fn default_size(&self, cx: &WindowContext) -> f32;
 33    fn icon_path(&self, cx: &WindowContext) -> &'static str;
 34    fn icon_tooltip(&self, cx: &WindowContext) -> String;
 35    fn icon_label(&self, cx: &WindowContext) -> Option<String>;
 36    fn is_focused(&self, cx: &WindowContext) -> bool;
 37    fn as_any(&self) -> &AnyViewHandle;
 38}
 39
 40impl<T> PanelHandle for ViewHandle<T>
 41where
 42    T: Panel,
 43{
 44    fn id(&self) -> usize {
 45        self.id()
 46    }
 47
 48    fn position(&self, cx: &WindowContext) -> DockPosition {
 49        self.read(cx).position(cx)
 50    }
 51
 52    fn position_is_valid(&self, position: DockPosition, cx: &WindowContext) -> bool {
 53        self.read(cx).position_is_valid(position)
 54    }
 55
 56    fn set_position(&self, position: DockPosition, cx: &mut WindowContext) {
 57        self.update(cx, |this, cx| this.set_position(position, cx))
 58    }
 59
 60    fn default_size(&self, cx: &WindowContext) -> f32 {
 61        self.read(cx).default_size(cx)
 62    }
 63
 64    fn icon_path(&self, cx: &WindowContext) -> &'static str {
 65        self.read(cx).icon_path()
 66    }
 67
 68    fn icon_tooltip(&self, cx: &WindowContext) -> String {
 69        self.read(cx).icon_tooltip()
 70    }
 71
 72    fn icon_label(&self, cx: &WindowContext) -> Option<String> {
 73        self.read(cx).icon_label(cx)
 74    }
 75
 76    fn is_focused(&self, cx: &WindowContext) -> bool {
 77        ViewHandle::is_focused(self, cx)
 78    }
 79
 80    fn as_any(&self) -> &AnyViewHandle {
 81        self
 82    }
 83}
 84
 85impl From<&dyn PanelHandle> for AnyViewHandle {
 86    fn from(val: &dyn PanelHandle) -> Self {
 87        val.as_any().clone()
 88    }
 89}
 90
 91pub struct Dock {
 92    position: DockPosition,
 93    panel_entries: Vec<PanelEntry>,
 94    is_open: bool,
 95    active_panel_index: usize,
 96}
 97
 98#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
 99pub enum DockPosition {
100    Left,
101    Bottom,
102    Right,
103}
104
105impl DockPosition {
106    fn to_label(&self) -> &'static str {
107        match self {
108            Self::Left => "left",
109            Self::Bottom => "bottom",
110            Self::Right => "right",
111        }
112    }
113
114    fn to_resize_handle_side(self) -> HandleSide {
115        match self {
116            Self::Left => HandleSide::Right,
117            Self::Bottom => HandleSide::Top,
118            Self::Right => HandleSide::Left,
119        }
120    }
121
122    pub fn axis(&self) -> Axis {
123        match self {
124            Self::Left | Self::Right => Axis::Horizontal,
125            Self::Bottom => Axis::Vertical,
126        }
127    }
128}
129
130struct PanelEntry {
131    panel: Rc<dyn PanelHandle>,
132    size: f32,
133    context_menu: ViewHandle<ContextMenu>,
134    _subscriptions: [Subscription; 2],
135}
136
137pub struct PanelButtons {
138    dock: ViewHandle<Dock>,
139    workspace: WeakViewHandle<Workspace>,
140}
141
142#[derive(Clone, Debug, Deserialize, PartialEq)]
143pub struct TogglePanel {
144    pub dock_position: DockPosition,
145    pub panel_index: usize,
146}
147
148impl_actions!(workspace, [TogglePanel]);
149
150impl Dock {
151    pub fn new(position: DockPosition) -> Self {
152        Self {
153            position,
154            panel_entries: Default::default(),
155            active_panel_index: 0,
156            is_open: false,
157        }
158    }
159
160    pub fn is_open(&self) -> bool {
161        self.is_open
162    }
163
164    pub fn active_panel_index(&self) -> usize {
165        self.active_panel_index
166    }
167
168    pub fn set_open(&mut self, open: bool, cx: &mut ViewContext<Self>) {
169        if open != self.is_open {
170            self.is_open = open;
171            cx.notify();
172        }
173    }
174
175    pub fn toggle_open(&mut self, cx: &mut ViewContext<Self>) {
176        self.is_open = !self.is_open;
177        cx.notify();
178    }
179
180    pub fn add_panel<T: Panel>(&mut self, panel: ViewHandle<T>, cx: &mut ViewContext<Self>) {
181        let subscriptions = [
182            cx.observe(&panel, |_, _, cx| cx.notify()),
183            cx.subscribe(&panel, |this, view, event, cx| {
184                if view.read(cx).should_activate_on_event(event, cx) {
185                    if let Some(ix) = this
186                        .panel_entries
187                        .iter()
188                        .position(|entry| entry.panel.id() == view.id())
189                    {
190                        this.activate_panel(ix, cx);
191                    }
192                } else if view.read(cx).should_close_on_event(event, cx) {
193                    this.set_open(false, cx);
194                }
195            }),
196        ];
197
198        let dock_view_id = cx.view_id();
199        let size = panel.default_size(cx);
200        self.panel_entries.push(PanelEntry {
201            panel: Rc::new(panel),
202            size,
203            context_menu: cx.add_view(|cx| {
204                let mut menu = ContextMenu::new(dock_view_id, cx);
205                menu.set_position_mode(OverlayPositionMode::Local);
206                menu
207            }),
208            _subscriptions: subscriptions,
209        });
210        cx.notify()
211    }
212
213    pub fn remove_panel<T: Panel>(&mut self, panel: &ViewHandle<T>, cx: &mut ViewContext<Self>) {
214        if let Some(panel_ix) = self
215            .panel_entries
216            .iter()
217            .position(|entry| entry.panel.id() == panel.id())
218        {
219            if panel_ix == self.active_panel_index {
220                self.active_panel_index = 0;
221                self.set_open(false, cx);
222            } else if panel_ix < self.active_panel_index {
223                self.active_panel_index -= 1;
224            }
225            self.panel_entries.remove(panel_ix);
226            cx.notify();
227        }
228    }
229
230    pub fn panels_len(&self) -> usize {
231        self.panel_entries.len()
232    }
233
234    pub fn activate_panel(&mut self, panel_ix: usize, cx: &mut ViewContext<Self>) {
235        self.active_panel_index = panel_ix;
236        cx.notify();
237    }
238
239    pub fn toggle_panel(&mut self, panel_ix: usize, cx: &mut ViewContext<Self>) {
240        if self.active_panel_index == panel_ix {
241            self.is_open = false;
242        } else {
243            self.active_panel_index = panel_ix;
244        }
245        cx.notify();
246    }
247
248    pub fn active_panel(&self) -> Option<&Rc<dyn PanelHandle>> {
249        if self.is_open {
250            self.panel_entries
251                .get(self.active_panel_index)
252                .map(|entry| &entry.panel)
253        } else {
254            None
255        }
256    }
257
258    pub fn panel_size(&self, panel: &dyn PanelHandle) -> Option<f32> {
259        self.panel_entries
260            .iter()
261            .find(|entry| entry.panel.id() == panel.id())
262            .map(|entry| entry.size)
263    }
264
265    pub fn resize_panel(&mut self, panel: &dyn PanelHandle, size: f32) {
266        let entry = self
267            .panel_entries
268            .iter_mut()
269            .find(|entry| entry.panel.id() == panel.id());
270        if let Some(entry) = entry {
271            entry.size = size;
272        }
273    }
274
275    pub fn active_panel_size(&self) -> Option<f32> {
276        if self.is_open {
277            self.panel_entries
278                .get(self.active_panel_index)
279                .map(|entry| entry.size)
280        } else {
281            None
282        }
283    }
284
285    pub fn resize_active_panel(&mut self, size: f32, cx: &mut ViewContext<Self>) {
286        if let Some(entry) = self.panel_entries.get_mut(self.active_panel_index) {
287            entry.size = size;
288            cx.notify();
289        }
290    }
291}
292
293impl Entity for Dock {
294    type Event = ();
295}
296
297impl View for Dock {
298    fn ui_name() -> &'static str {
299        "Dock"
300    }
301
302    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
303        if let Some(active_panel) = self.active_panel() {
304            let size = self.active_panel_size().unwrap();
305            let style = &cx.global::<Settings>().theme.workspace.dock;
306            ChildView::new(active_panel.as_any(), cx)
307                .contained()
308                .with_style(style.container)
309                .resizable(
310                    self.position.to_resize_handle_side(),
311                    size,
312                    |dock: &mut Self, size, cx| {
313                        dock.resize_active_panel(size, cx);
314                    },
315                )
316                .into_any()
317        } else {
318            Empty::new().into_any()
319        }
320    }
321}
322
323impl PanelButtons {
324    pub fn new(
325        dock: ViewHandle<Dock>,
326        workspace: WeakViewHandle<Workspace>,
327        cx: &mut ViewContext<Self>,
328    ) -> Self {
329        cx.observe(&dock, |_, _, cx| cx.notify()).detach();
330        Self { dock, workspace }
331    }
332}
333
334impl Entity for PanelButtons {
335    type Event = ();
336}
337
338impl View for PanelButtons {
339    fn ui_name() -> &'static str {
340        "PanelButtons"
341    }
342
343    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
344        let theme = &cx.global::<Settings>().theme;
345        let tooltip_style = theme.tooltip.clone();
346        let theme = &theme.workspace.status_bar.panel_buttons;
347        let button_style = theme.button.clone();
348        let dock = self.dock.read(cx);
349        let active_ix = dock.active_panel_index;
350        let is_open = dock.is_open;
351        let dock_position = dock.position;
352        let group_style = match dock_position {
353            DockPosition::Left => theme.group_left,
354            DockPosition::Bottom => theme.group_bottom,
355            DockPosition::Right => theme.group_right,
356        };
357        let menu_corner = match dock_position {
358            DockPosition::Left => AnchorCorner::BottomLeft,
359            DockPosition::Bottom | DockPosition::Right => AnchorCorner::BottomRight,
360        };
361
362        let panels = dock
363            .panel_entries
364            .iter()
365            .map(|item| (item.panel.clone(), item.context_menu.clone()))
366            .collect::<Vec<_>>();
367        Flex::row()
368            .with_children(
369                panels
370                    .into_iter()
371                    .enumerate()
372                    .map(|(ix, (view, context_menu))| {
373                        let action = TogglePanel {
374                            dock_position,
375                            panel_index: ix,
376                        };
377
378                        Stack::new()
379                            .with_child(
380                                MouseEventHandler::<Self, _>::new(ix, cx, |state, cx| {
381                                    let is_active = is_open && ix == active_ix;
382                                    let style = button_style.style_for(state, is_active);
383                                    Flex::row()
384                                        .with_child(
385                                            Svg::new(view.icon_path(cx))
386                                                .with_color(style.icon_color)
387                                                .constrained()
388                                                .with_width(style.icon_size)
389                                                .aligned(),
390                                        )
391                                        .with_children(if let Some(label) = view.icon_label(cx) {
392                                            Some(
393                                                Label::new(label, style.label.text.clone())
394                                                    .contained()
395                                                    .with_style(style.label.container)
396                                                    .aligned(),
397                                            )
398                                        } else {
399                                            None
400                                        })
401                                        .constrained()
402                                        .with_height(style.icon_size)
403                                        .contained()
404                                        .with_style(style.container)
405                                })
406                                .with_cursor_style(CursorStyle::PointingHand)
407                                .on_click(MouseButton::Left, {
408                                    let action = action.clone();
409                                    move |_, this, cx| {
410                                        if let Some(workspace) = this.workspace.upgrade(cx) {
411                                            let action = action.clone();
412                                            cx.window_context().defer(move |cx| {
413                                                workspace.update(cx, |workspace, cx| {
414                                                    workspace.toggle_panel(&action, cx)
415                                                });
416                                            });
417                                        }
418                                    }
419                                })
420                                .on_click(MouseButton::Right, {
421                                    let view = view.clone();
422                                    let menu = context_menu.clone();
423                                    move |_, _, cx| {
424                                        const POSITIONS: [DockPosition; 3] = [
425                                            DockPosition::Left,
426                                            DockPosition::Right,
427                                            DockPosition::Bottom,
428                                        ];
429
430                                        menu.update(cx, |menu, cx| {
431                                            let items = POSITIONS
432                                                .into_iter()
433                                                .filter(|position| {
434                                                    *position != dock_position
435                                                        && view.position_is_valid(*position, cx)
436                                                })
437                                                .map(|position| {
438                                                    let view = view.clone();
439                                                    ContextMenuItem::handler(
440                                                        format!("Dock {}", position.to_label()),
441                                                        move |cx| view.set_position(position, cx),
442                                                    )
443                                                })
444                                                .collect();
445                                            menu.show(Default::default(), menu_corner, items, cx);
446                                        })
447                                    }
448                                })
449                                .with_tooltip::<Self>(
450                                    ix,
451                                    view.icon_tooltip(cx),
452                                    Some(Box::new(action)),
453                                    tooltip_style.clone(),
454                                    cx,
455                                ),
456                            )
457                            .with_child(ChildView::new(&context_menu, cx))
458                    }),
459            )
460            .contained()
461            .with_style(group_style)
462            .into_any()
463    }
464}
465
466impl StatusItemView for PanelButtons {
467    fn set_active_pane_item(
468        &mut self,
469        _: Option<&dyn crate::ItemHandle>,
470        _: &mut ViewContext<Self>,
471    ) {
472    }
473}
474
475#[cfg(test)]
476pub(crate) mod test {
477    use super::*;
478    use gpui::Entity;
479
480    pub enum TestPanelEvent {
481        PositionChanged,
482        Activated,
483        Closed,
484    }
485
486    pub struct TestPanel {
487        pub position: DockPosition,
488    }
489
490    impl Entity for TestPanel {
491        type Event = TestPanelEvent;
492    }
493
494    impl View for TestPanel {
495        fn ui_name() -> &'static str {
496            "TestPanel"
497        }
498
499        fn render(&mut self, _: &mut ViewContext<'_, '_, Self>) -> AnyElement<Self> {
500            Empty::new().into_any()
501        }
502    }
503
504    impl Panel for TestPanel {
505        fn position(&self, _: &gpui::WindowContext) -> super::DockPosition {
506            self.position
507        }
508
509        fn position_is_valid(&self, _: super::DockPosition) -> bool {
510            true
511        }
512
513        fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
514            self.position = position;
515            cx.emit(TestPanelEvent::PositionChanged);
516        }
517
518        fn default_size(&self, _: &WindowContext) -> f32 {
519            match self.position.axis() {
520                Axis::Horizontal => 300.,
521                Axis::Vertical => 200.,
522            }
523        }
524
525        fn icon_path(&self) -> &'static str {
526            "icons/test_panel.svg"
527        }
528
529        fn icon_tooltip(&self) -> String {
530            "Test Panel".into()
531        }
532
533        fn should_change_position_on_event(event: &Self::Event) -> bool {
534            matches!(event, TestPanelEvent::PositionChanged)
535        }
536
537        fn should_activate_on_event(&self, event: &Self::Event, _: &gpui::AppContext) -> bool {
538            matches!(event, TestPanelEvent::Activated)
539        }
540
541        fn should_close_on_event(&self, event: &Self::Event, _: &gpui::AppContext) -> bool {
542            matches!(event, TestPanelEvent::Closed)
543        }
544    }
545}