dock.rs

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