dock.rs

  1use crate::persistence::model::DockData;
  2use crate::{status_bar::StatusItemView, Workspace};
  3use crate::{DraggedDock, Event, Pane};
  4use client::proto;
  5use gpui::{
  6    deferred, div, px, Action, AnyView, App, Axis, Context, Corner, Entity, EntityId, EventEmitter,
  7    FocusHandle, Focusable, IntoElement, KeyContext, MouseButton, MouseDownEvent, MouseUpEvent,
  8    ParentElement, Render, SharedString, StyleRefinement, Styled, Subscription, WeakEntity, Window,
  9};
 10use schemars::JsonSchema;
 11use serde::{Deserialize, Serialize};
 12use settings::SettingsStore;
 13use std::sync::Arc;
 14use ui::{h_flex, ContextMenu, Divider, DividerColor, IconButton, Tooltip};
 15use ui::{prelude::*, right_click_menu};
 16
 17pub(crate) const RESIZE_HANDLE_SIZE: Pixels = Pixels(6.);
 18
 19pub enum PanelEvent {
 20    ZoomIn,
 21    ZoomOut,
 22    Activate,
 23    Close,
 24}
 25
 26pub use proto::PanelId;
 27
 28pub trait Panel: Focusable + EventEmitter<PanelEvent> + Render + Sized {
 29    fn persistent_name() -> &'static str;
 30    fn position(&self, window: &Window, cx: &App) -> DockPosition;
 31    fn position_is_valid(&self, position: DockPosition) -> bool;
 32    fn set_position(&mut self, position: DockPosition, window: &mut Window, cx: &mut Context<Self>);
 33    fn size(&self, window: &Window, cx: &App) -> Pixels;
 34    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>);
 35    fn icon(&self, window: &Window, cx: &App) -> Option<ui::IconName>;
 36    fn icon_tooltip(&self, window: &Window, cx: &App) -> Option<&'static str>;
 37    fn toggle_action(&self) -> Box<dyn Action>;
 38    fn icon_label(&self, _window: &Window, _: &App) -> Option<String> {
 39        None
 40    }
 41    fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
 42        false
 43    }
 44    fn starts_open(&self, _window: &Window, _cx: &App) -> bool {
 45        false
 46    }
 47    fn set_zoomed(&mut self, _zoomed: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
 48    fn set_active(&mut self, _active: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
 49    fn pane(&self) -> Option<Entity<Pane>> {
 50        None
 51    }
 52    fn remote_id() -> Option<proto::PanelId> {
 53        None
 54    }
 55    fn activation_priority(&self) -> u32;
 56}
 57
 58pub trait PanelHandle: Send + Sync {
 59    fn panel_id(&self) -> EntityId;
 60    fn persistent_name(&self) -> &'static str;
 61    fn position(&self, window: &Window, cx: &App) -> DockPosition;
 62    fn position_is_valid(&self, position: DockPosition, cx: &App) -> bool;
 63    fn set_position(&self, position: DockPosition, window: &mut Window, cx: &mut App);
 64    fn is_zoomed(&self, window: &Window, cx: &App) -> bool;
 65    fn set_zoomed(&self, zoomed: bool, window: &mut Window, cx: &mut App);
 66    fn set_active(&self, active: bool, window: &mut Window, cx: &mut App);
 67    fn remote_id(&self) -> Option<proto::PanelId>;
 68    fn pane(&self, cx: &App) -> Option<Entity<Pane>>;
 69    fn size(&self, window: &Window, cx: &App) -> Pixels;
 70    fn set_size(&self, size: Option<Pixels>, window: &mut Window, cx: &mut App);
 71    fn icon(&self, window: &Window, cx: &App) -> Option<ui::IconName>;
 72    fn icon_tooltip(&self, window: &Window, cx: &App) -> Option<&'static str>;
 73    fn toggle_action(&self, window: &Window, cx: &App) -> Box<dyn Action>;
 74    fn icon_label(&self, window: &Window, cx: &App) -> Option<String>;
 75    fn panel_focus_handle(&self, cx: &App) -> FocusHandle;
 76    fn to_any(&self) -> AnyView;
 77    fn activation_priority(&self, cx: &App) -> u32;
 78    fn move_to_next_position(&self, window: &mut Window, cx: &mut App) {
 79        let current_position = self.position(window, cx);
 80        let next_position = [
 81            DockPosition::Left,
 82            DockPosition::Bottom,
 83            DockPosition::Right,
 84        ]
 85        .into_iter()
 86        .filter(|position| self.position_is_valid(*position, cx))
 87        .skip_while(|valid_position| *valid_position != current_position)
 88        .nth(1)
 89        .unwrap_or(DockPosition::Left);
 90
 91        self.set_position(next_position, window, cx);
 92    }
 93}
 94
 95impl<T> PanelHandle for Entity<T>
 96where
 97    T: Panel,
 98{
 99    fn panel_id(&self) -> EntityId {
100        Entity::entity_id(self)
101    }
102
103    fn persistent_name(&self) -> &'static str {
104        T::persistent_name()
105    }
106
107    fn position(&self, window: &Window, cx: &App) -> DockPosition {
108        self.read(cx).position(window, cx)
109    }
110
111    fn position_is_valid(&self, position: DockPosition, cx: &App) -> bool {
112        self.read(cx).position_is_valid(position)
113    }
114
115    fn set_position(&self, position: DockPosition, window: &mut Window, cx: &mut App) {
116        self.update(cx, |this, cx| this.set_position(position, window, cx))
117    }
118
119    fn is_zoomed(&self, window: &Window, cx: &App) -> bool {
120        self.read(cx).is_zoomed(window, cx)
121    }
122
123    fn set_zoomed(&self, zoomed: bool, window: &mut Window, cx: &mut App) {
124        self.update(cx, |this, cx| this.set_zoomed(zoomed, window, cx))
125    }
126
127    fn set_active(&self, active: bool, window: &mut Window, cx: &mut App) {
128        self.update(cx, |this, cx| this.set_active(active, window, cx))
129    }
130
131    fn pane(&self, cx: &App) -> Option<Entity<Pane>> {
132        self.read(cx).pane()
133    }
134
135    fn remote_id(&self) -> Option<PanelId> {
136        T::remote_id()
137    }
138
139    fn size(&self, window: &Window, cx: &App) -> Pixels {
140        self.read(cx).size(window, cx)
141    }
142
143    fn set_size(&self, size: Option<Pixels>, window: &mut Window, cx: &mut App) {
144        self.update(cx, |this, cx| this.set_size(size, window, cx))
145    }
146
147    fn icon(&self, window: &Window, cx: &App) -> Option<ui::IconName> {
148        self.read(cx).icon(window, cx)
149    }
150
151    fn icon_tooltip(&self, window: &Window, cx: &App) -> Option<&'static str> {
152        self.read(cx).icon_tooltip(window, cx)
153    }
154
155    fn toggle_action(&self, _: &Window, cx: &App) -> Box<dyn Action> {
156        self.read(cx).toggle_action()
157    }
158
159    fn icon_label(&self, window: &Window, cx: &App) -> Option<String> {
160        self.read(cx).icon_label(window, cx)
161    }
162
163    fn to_any(&self) -> AnyView {
164        self.clone().into()
165    }
166
167    fn panel_focus_handle(&self, cx: &App) -> FocusHandle {
168        self.read(cx).focus_handle(cx).clone()
169    }
170
171    fn activation_priority(&self, cx: &App) -> u32 {
172        self.read(cx).activation_priority()
173    }
174}
175
176impl From<&dyn PanelHandle> for AnyView {
177    fn from(val: &dyn PanelHandle) -> Self {
178        val.to_any()
179    }
180}
181
182/// A container with a fixed [`DockPosition`] adjacent to a certain widown edge.
183/// Can contain multiple panels and show/hide itself with all contents.
184pub struct Dock {
185    position: DockPosition,
186    panel_entries: Vec<PanelEntry>,
187    workspace: WeakEntity<Workspace>,
188    is_open: bool,
189    active_panel_index: Option<usize>,
190    focus_handle: FocusHandle,
191    pub(crate) serialized_dock: Option<DockData>,
192    resizeable: bool,
193    _subscriptions: [Subscription; 2],
194}
195
196impl Focusable for Dock {
197    fn focus_handle(&self, _: &App) -> FocusHandle {
198        self.focus_handle.clone()
199    }
200}
201
202#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
203#[serde(rename_all = "lowercase")]
204pub enum DockPosition {
205    Left,
206    Bottom,
207    Right,
208}
209
210impl DockPosition {
211    fn label(&self) -> &'static str {
212        match self {
213            Self::Left => "left",
214            Self::Bottom => "bottom",
215            Self::Right => "right",
216        }
217    }
218
219    pub fn axis(&self) -> Axis {
220        match self {
221            Self::Left | Self::Right => Axis::Horizontal,
222            Self::Bottom => Axis::Vertical,
223        }
224    }
225}
226
227struct PanelEntry {
228    panel: Arc<dyn PanelHandle>,
229    _subscriptions: [Subscription; 3],
230}
231
232pub struct PanelButtons {
233    dock: Entity<Dock>,
234}
235
236impl Dock {
237    pub fn new(
238        position: DockPosition,
239        window: &mut Window,
240        cx: &mut Context<Workspace>,
241    ) -> Entity<Self> {
242        let focus_handle = cx.focus_handle();
243        let workspace = cx.entity().clone();
244        let dock = cx.new(|cx| {
245            let focus_subscription =
246                cx.on_focus(&focus_handle, window, |dock: &mut Dock, window, cx| {
247                    if let Some(active_entry) = dock.active_panel_entry() {
248                        active_entry.panel.panel_focus_handle(cx).focus(window)
249                    }
250                });
251            let zoom_subscription = cx.subscribe(&workspace, |dock, workspace, e: &Event, cx| {
252                if matches!(e, Event::ZoomChanged) {
253                    let is_zoomed = workspace.read(cx).zoomed.is_some();
254                    dock.resizeable = !is_zoomed;
255                }
256            });
257            Self {
258                position,
259                workspace: workspace.downgrade(),
260                panel_entries: Default::default(),
261                active_panel_index: None,
262                is_open: false,
263                focus_handle: focus_handle.clone(),
264                _subscriptions: [focus_subscription, zoom_subscription],
265                serialized_dock: None,
266                resizeable: true,
267            }
268        });
269
270        cx.on_focus_in(&focus_handle, window, {
271            let dock = dock.downgrade();
272            move |workspace, window, cx| {
273                let Some(dock) = dock.upgrade() else {
274                    return;
275                };
276                let Some(panel) = dock.read(cx).active_panel() else {
277                    return;
278                };
279                if panel.is_zoomed(window, cx) {
280                    workspace.zoomed = Some(panel.to_any().downgrade());
281                    workspace.zoomed_position = Some(position);
282                } else {
283                    workspace.zoomed = None;
284                    workspace.zoomed_position = None;
285                }
286                cx.emit(Event::ZoomChanged);
287                workspace.dismiss_zoomed_items_to_reveal(Some(position), window, cx);
288                workspace.update_active_view_for_followers(window, cx)
289            }
290        })
291        .detach();
292
293        cx.observe_in(&dock, window, move |workspace, dock, window, cx| {
294            if dock.read(cx).is_open() {
295                if let Some(panel) = dock.read(cx).active_panel() {
296                    if panel.is_zoomed(window, cx) {
297                        workspace.zoomed = Some(panel.to_any().downgrade());
298                        workspace.zoomed_position = Some(position);
299                        cx.emit(Event::ZoomChanged);
300                        return;
301                    }
302                }
303            }
304            if workspace.zoomed_position == Some(position) {
305                workspace.zoomed = None;
306                workspace.zoomed_position = None;
307                cx.emit(Event::ZoomChanged);
308            }
309        })
310        .detach();
311
312        dock
313    }
314
315    pub fn position(&self) -> DockPosition {
316        self.position
317    }
318
319    pub fn is_open(&self) -> bool {
320        self.is_open
321    }
322
323    pub fn panel<T: Panel>(&self) -> Option<Entity<T>> {
324        self.panel_entries
325            .iter()
326            .find_map(|entry| entry.panel.to_any().clone().downcast().ok())
327    }
328
329    pub fn panel_index_for_type<T: Panel>(&self) -> Option<usize> {
330        self.panel_entries
331            .iter()
332            .position(|entry| entry.panel.to_any().downcast::<T>().is_ok())
333    }
334
335    pub fn panel_index_for_persistent_name(&self, ui_name: &str, _cx: &App) -> Option<usize> {
336        self.panel_entries
337            .iter()
338            .position(|entry| entry.panel.persistent_name() == ui_name)
339    }
340
341    pub fn panel_index_for_proto_id(&self, panel_id: PanelId) -> Option<usize> {
342        self.panel_entries
343            .iter()
344            .position(|entry| entry.panel.remote_id() == Some(panel_id))
345    }
346
347    fn active_panel_entry(&self) -> Option<&PanelEntry> {
348        self.active_panel_index
349            .and_then(|index| self.panel_entries.get(index))
350    }
351
352    pub(crate) fn set_open(&mut self, open: bool, window: &mut Window, cx: &mut Context<Self>) {
353        if open != self.is_open {
354            self.is_open = open;
355            if let Some(active_panel) = self.active_panel_entry() {
356                active_panel.panel.set_active(open, window, cx);
357            }
358
359            cx.notify();
360        }
361    }
362
363    pub fn set_panel_zoomed(
364        &mut self,
365        panel: &AnyView,
366        zoomed: bool,
367        window: &mut Window,
368        cx: &mut Context<Self>,
369    ) {
370        for entry in &mut self.panel_entries {
371            if entry.panel.panel_id() == panel.entity_id() {
372                if zoomed != entry.panel.is_zoomed(window, cx) {
373                    entry.panel.set_zoomed(zoomed, window, cx);
374                }
375            } else if entry.panel.is_zoomed(window, cx) {
376                entry.panel.set_zoomed(false, window, cx);
377            }
378        }
379
380        self.workspace
381            .update(cx, |workspace, cx| {
382                workspace.serialize_workspace(window, cx);
383            })
384            .ok();
385        cx.notify();
386    }
387
388    pub fn zoom_out(&mut self, window: &mut Window, cx: &mut Context<Self>) {
389        for entry in &mut self.panel_entries {
390            if entry.panel.is_zoomed(window, cx) {
391                entry.panel.set_zoomed(false, window, cx);
392            }
393        }
394    }
395
396    pub(crate) fn add_panel<T: Panel>(
397        &mut self,
398        panel: Entity<T>,
399        workspace: WeakEntity<Workspace>,
400        window: &mut Window,
401        cx: &mut Context<Self>,
402    ) -> usize {
403        let subscriptions = [
404            cx.observe(&panel, |_, _, cx| cx.notify()),
405            cx.observe_global_in::<SettingsStore>(window, {
406                let workspace = workspace.clone();
407                let panel = panel.clone();
408
409                move |this, window, cx| {
410                    let new_position = panel.read(cx).position(window, cx);
411                    if new_position == this.position {
412                        return;
413                    }
414
415                    let Ok(new_dock) = workspace.update(cx, |workspace, cx| {
416                        if panel.is_zoomed(window, cx) {
417                            workspace.zoomed_position = Some(new_position);
418                        }
419                        match new_position {
420                            DockPosition::Left => &workspace.left_dock,
421                            DockPosition::Bottom => &workspace.bottom_dock,
422                            DockPosition::Right => &workspace.right_dock,
423                        }
424                        .clone()
425                    }) else {
426                        return;
427                    };
428
429                    let was_visible = this.is_open()
430                        && this.visible_panel().map_or(false, |active_panel| {
431                            active_panel.panel_id() == Entity::entity_id(&panel)
432                        });
433
434                    this.remove_panel(&panel, window, cx);
435
436                    new_dock.update(cx, |new_dock, cx| {
437                        new_dock.remove_panel(&panel, window, cx);
438                        let index =
439                            new_dock.add_panel(panel.clone(), workspace.clone(), window, cx);
440                        if was_visible {
441                            new_dock.set_open(true, window, cx);
442                            new_dock.activate_panel(index, window, cx);
443                        }
444                    });
445                }
446            }),
447            cx.subscribe_in(
448                &panel,
449                window,
450                move |this, panel, event, window, cx| match event {
451                    PanelEvent::ZoomIn => {
452                        this.set_panel_zoomed(&panel.to_any(), true, window, cx);
453                        if !PanelHandle::panel_focus_handle(panel, cx).contains_focused(window, cx)
454                        {
455                            window.focus(&panel.focus_handle(cx));
456                        }
457                        workspace
458                            .update(cx, |workspace, cx| {
459                                workspace.zoomed = Some(panel.downgrade().into());
460                                workspace.zoomed_position =
461                                    Some(panel.read(cx).position(window, cx));
462                                cx.emit(Event::ZoomChanged);
463                            })
464                            .ok();
465                    }
466                    PanelEvent::ZoomOut => {
467                        this.set_panel_zoomed(&panel.to_any(), false, window, cx);
468                        workspace
469                            .update(cx, |workspace, cx| {
470                                if workspace.zoomed_position == Some(this.position) {
471                                    workspace.zoomed = None;
472                                    workspace.zoomed_position = None;
473                                    cx.emit(Event::ZoomChanged);
474                                }
475                                cx.notify();
476                            })
477                            .ok();
478                    }
479                    PanelEvent::Activate => {
480                        if let Some(ix) = this
481                            .panel_entries
482                            .iter()
483                            .position(|entry| entry.panel.panel_id() == Entity::entity_id(panel))
484                        {
485                            this.set_open(true, window, cx);
486                            this.activate_panel(ix, window, cx);
487                            window.focus(&panel.read(cx).focus_handle(cx));
488                        }
489                    }
490                    PanelEvent::Close => {
491                        if this
492                            .visible_panel()
493                            .map_or(false, |p| p.panel_id() == Entity::entity_id(panel))
494                        {
495                            this.set_open(false, window, cx);
496                        }
497                    }
498                },
499            ),
500        ];
501
502        let index = match self
503            .panel_entries
504            .binary_search_by_key(&panel.read(cx).activation_priority(), |entry| {
505                entry.panel.activation_priority(cx)
506            }) {
507            Ok(ix) => ix,
508            Err(ix) => ix,
509        };
510        if let Some(active_index) = self.active_panel_index.as_mut() {
511            if *active_index >= index {
512                *active_index += 1;
513            }
514        }
515        self.panel_entries.insert(
516            index,
517            PanelEntry {
518                panel: Arc::new(panel.clone()),
519                _subscriptions: subscriptions,
520            },
521        );
522
523        self.restore_state(window, cx);
524        if panel.read(cx).starts_open(window, cx) {
525            self.activate_panel(index, window, cx);
526            self.set_open(true, window, cx);
527        }
528
529        cx.notify();
530        index
531    }
532
533    pub fn restore_state(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
534        if let Some(serialized) = self.serialized_dock.clone() {
535            if let Some(active_panel) = serialized.active_panel {
536                if let Some(idx) = self.panel_index_for_persistent_name(active_panel.as_str(), cx) {
537                    self.activate_panel(idx, window, cx);
538                }
539            }
540
541            if serialized.zoom {
542                if let Some(panel) = self.active_panel() {
543                    panel.set_zoomed(true, window, cx)
544                }
545            }
546            self.set_open(serialized.visible, window, cx);
547            return true;
548        }
549        false
550    }
551
552    pub fn remove_panel<T: Panel>(
553        &mut self,
554        panel: &Entity<T>,
555        window: &mut Window,
556        cx: &mut Context<Self>,
557    ) {
558        if let Some(panel_ix) = self
559            .panel_entries
560            .iter()
561            .position(|entry| entry.panel.panel_id() == Entity::entity_id(panel))
562        {
563            if let Some(active_panel_index) = self.active_panel_index.as_mut() {
564                match panel_ix.cmp(active_panel_index) {
565                    std::cmp::Ordering::Less => {
566                        *active_panel_index -= 1;
567                    }
568                    std::cmp::Ordering::Equal => {
569                        self.active_panel_index = None;
570                        self.set_open(false, window, cx);
571                    }
572                    std::cmp::Ordering::Greater => {}
573                }
574            }
575            self.panel_entries.remove(panel_ix);
576            cx.notify();
577        }
578    }
579
580    pub fn panels_len(&self) -> usize {
581        self.panel_entries.len()
582    }
583
584    pub fn activate_panel(&mut self, panel_ix: usize, window: &mut Window, cx: &mut Context<Self>) {
585        if Some(panel_ix) != self.active_panel_index {
586            if let Some(active_panel) = self.active_panel_entry() {
587                active_panel.panel.set_active(false, window, cx);
588            }
589
590            self.active_panel_index = Some(panel_ix);
591            if let Some(active_panel) = self.active_panel_entry() {
592                active_panel.panel.set_active(true, window, cx);
593            }
594
595            cx.notify();
596        }
597    }
598
599    pub fn visible_panel(&self) -> Option<&Arc<dyn PanelHandle>> {
600        let entry = self.visible_entry()?;
601        Some(&entry.panel)
602    }
603
604    pub fn active_panel(&self) -> Option<&Arc<dyn PanelHandle>> {
605        let panel_entry = self.active_panel_entry()?;
606        Some(&panel_entry.panel)
607    }
608
609    fn visible_entry(&self) -> Option<&PanelEntry> {
610        if self.is_open {
611            self.active_panel_entry()
612        } else {
613            None
614        }
615    }
616
617    pub fn zoomed_panel(&self, window: &Window, cx: &App) -> Option<Arc<dyn PanelHandle>> {
618        let entry = self.visible_entry()?;
619        if entry.panel.is_zoomed(window, cx) {
620            Some(entry.panel.clone())
621        } else {
622            None
623        }
624    }
625
626    pub fn panel_size(&self, panel: &dyn PanelHandle, window: &Window, cx: &App) -> Option<Pixels> {
627        self.panel_entries
628            .iter()
629            .find(|entry| entry.panel.panel_id() == panel.panel_id())
630            .map(|entry| entry.panel.size(window, cx))
631    }
632
633    pub fn active_panel_size(&self, window: &Window, cx: &App) -> Option<Pixels> {
634        if self.is_open {
635            self.active_panel_entry()
636                .map(|entry| entry.panel.size(window, cx))
637        } else {
638            None
639        }
640    }
641
642    pub fn resize_active_panel(
643        &mut self,
644        size: Option<Pixels>,
645        window: &mut Window,
646        cx: &mut Context<Self>,
647    ) {
648        if let Some(entry) = self.active_panel_entry() {
649            let size = size.map(|size| size.max(RESIZE_HANDLE_SIZE).round());
650
651            entry.panel.set_size(size, window, cx);
652            cx.notify();
653        }
654    }
655
656    pub fn toggle_action(&self) -> Box<dyn Action> {
657        match self.position {
658            DockPosition::Left => crate::ToggleLeftDock.boxed_clone(),
659            DockPosition::Bottom => crate::ToggleBottomDock.boxed_clone(),
660            DockPosition::Right => crate::ToggleRightDock.boxed_clone(),
661        }
662    }
663
664    fn dispatch_context() -> KeyContext {
665        let mut dispatch_context = KeyContext::new_with_defaults();
666        dispatch_context.add("Dock");
667
668        dispatch_context
669    }
670
671    pub fn clamp_panel_size(&mut self, max_size: Pixels, window: &mut Window, cx: &mut App) {
672        let max_size = px((max_size.0 - RESIZE_HANDLE_SIZE.0).abs());
673        for panel in self.panel_entries.iter().map(|entry| &entry.panel) {
674            if panel.size(window, cx) > max_size {
675                panel.set_size(Some(max_size.max(RESIZE_HANDLE_SIZE)), window, cx);
676            }
677        }
678    }
679}
680
681impl Render for Dock {
682    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
683        let dispatch_context = Self::dispatch_context();
684        if let Some(entry) = self.visible_entry() {
685            let size = entry.panel.size(window, cx);
686
687            let position = self.position;
688            let create_resize_handle = || {
689                let handle = div()
690                    .id("resize-handle")
691                    .on_drag(DraggedDock(position), |dock, _, _, cx| {
692                        cx.stop_propagation();
693                        cx.new(|_| dock.clone())
694                    })
695                    .on_mouse_down(
696                        MouseButton::Left,
697                        cx.listener(|_, _: &MouseDownEvent, _, cx| {
698                            cx.stop_propagation();
699                        }),
700                    )
701                    .on_mouse_up(
702                        MouseButton::Left,
703                        cx.listener(|dock, e: &MouseUpEvent, window, cx| {
704                            if e.click_count == 2 {
705                                dock.resize_active_panel(None, window, cx);
706                                dock.workspace
707                                    .update(cx, |workspace, cx| {
708                                        workspace.serialize_workspace(window, cx);
709                                    })
710                                    .ok();
711                                cx.stop_propagation();
712                            }
713                        }),
714                    )
715                    .occlude();
716                match self.position() {
717                    DockPosition::Left => deferred(
718                        handle
719                            .absolute()
720                            .right(-RESIZE_HANDLE_SIZE / 2.)
721                            .top(px(0.))
722                            .h_full()
723                            .w(RESIZE_HANDLE_SIZE)
724                            .cursor_col_resize(),
725                    ),
726                    DockPosition::Bottom => deferred(
727                        handle
728                            .absolute()
729                            .top(-RESIZE_HANDLE_SIZE / 2.)
730                            .left(px(0.))
731                            .w_full()
732                            .h(RESIZE_HANDLE_SIZE)
733                            .cursor_row_resize(),
734                    ),
735                    DockPosition::Right => deferred(
736                        handle
737                            .absolute()
738                            .top(px(0.))
739                            .left(-RESIZE_HANDLE_SIZE / 2.)
740                            .h_full()
741                            .w(RESIZE_HANDLE_SIZE)
742                            .cursor_col_resize(),
743                    ),
744                }
745            };
746
747            div()
748                .key_context(dispatch_context)
749                .track_focus(&self.focus_handle(cx))
750                .flex()
751                .bg(cx.theme().colors().panel_background)
752                .border_color(cx.theme().colors().border)
753                .overflow_hidden()
754                .map(|this| match self.position().axis() {
755                    Axis::Horizontal => this.w(size).h_full().flex_row(),
756                    Axis::Vertical => this.h(size).w_full().flex_col(),
757                })
758                .map(|this| match self.position() {
759                    DockPosition::Left => this.border_r_1(),
760                    DockPosition::Right => this.border_l_1(),
761                    DockPosition::Bottom => this.border_t_1(),
762                })
763                .child(
764                    div()
765                        .map(|this| match self.position().axis() {
766                            Axis::Horizontal => this.min_w(size).h_full(),
767                            Axis::Vertical => this.min_h(size).w_full(),
768                        })
769                        .child(
770                            entry
771                                .panel
772                                .to_any()
773                                .cached(StyleRefinement::default().v_flex().size_full()),
774                        ),
775                )
776                .when(self.resizeable, |this| this.child(create_resize_handle()))
777        } else {
778            div()
779                .key_context(dispatch_context)
780                .track_focus(&self.focus_handle(cx))
781        }
782    }
783}
784
785impl PanelButtons {
786    pub fn new(dock: Entity<Dock>, cx: &mut Context<Self>) -> Self {
787        cx.observe(&dock, |_, _, cx| cx.notify()).detach();
788        Self { dock }
789    }
790}
791
792impl Render for PanelButtons {
793    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
794        let dock = self.dock.read(cx);
795        let active_index = dock.active_panel_index;
796        let is_open = dock.is_open;
797        let dock_position = dock.position;
798
799        let (menu_anchor, menu_attach) = match dock.position {
800            DockPosition::Left => (Corner::BottomLeft, Corner::TopLeft),
801            DockPosition::Bottom | DockPosition::Right => (Corner::BottomRight, Corner::TopRight),
802        };
803
804        let buttons: Vec<_> = dock
805            .panel_entries
806            .iter()
807            .enumerate()
808            .filter_map(|(i, entry)| {
809                let icon = entry.panel.icon(window, cx)?;
810                let icon_tooltip = entry.panel.icon_tooltip(window, cx)?;
811                let name = entry.panel.persistent_name();
812                let panel = entry.panel.clone();
813
814                let is_active_button = Some(i) == active_index && is_open;
815                let (action, tooltip) = if is_active_button {
816                    let action = dock.toggle_action();
817
818                    let tooltip: SharedString =
819                        format!("Close {} dock", dock.position.label()).into();
820
821                    (action, tooltip)
822                } else {
823                    let action = entry.panel.toggle_action(window, cx);
824
825                    (action, icon_tooltip.into())
826                };
827
828                Some(
829                    right_click_menu(name)
830                        .menu(move |window, cx| {
831                            const POSITIONS: [DockPosition; 3] = [
832                                DockPosition::Left,
833                                DockPosition::Right,
834                                DockPosition::Bottom,
835                            ];
836
837                            ContextMenu::build(window, cx, |mut menu, _, cx| {
838                                for position in POSITIONS {
839                                    if position != dock_position
840                                        && panel.position_is_valid(position, cx)
841                                    {
842                                        let panel = panel.clone();
843                                        menu = menu.entry(
844                                            format!("Dock {}", position.label()),
845                                            None,
846                                            move |window, cx| {
847                                                panel.set_position(position, window, cx);
848                                            },
849                                        )
850                                    }
851                                }
852                                menu
853                            })
854                        })
855                        .anchor(menu_anchor)
856                        .attach(menu_attach)
857                        .trigger(
858                            IconButton::new(name, icon)
859                                .icon_size(IconSize::Small)
860                                .toggle_state(is_active_button)
861                                .on_click({
862                                    let action = action.boxed_clone();
863                                    move |_, window, cx| {
864                                        window.dispatch_action(action.boxed_clone(), cx)
865                                    }
866                                })
867                                .tooltip(move |window, cx| {
868                                    Tooltip::for_action(tooltip.clone(), &*action, window, cx)
869                                }),
870                        ),
871                )
872            })
873            .collect();
874
875        let has_buttons = !buttons.is_empty();
876        h_flex()
877            .gap_1()
878            .children(buttons)
879            .when(has_buttons && dock.position == DockPosition::Left, |this| {
880                this.child(Divider::vertical().color(DividerColor::Border))
881            })
882    }
883}
884
885impl StatusItemView for PanelButtons {
886    fn set_active_pane_item(
887        &mut self,
888        _active_pane_item: Option<&dyn crate::ItemHandle>,
889        _window: &mut Window,
890        _cx: &mut Context<Self>,
891    ) {
892        // Nothing to do, panel buttons don't depend on the active center item
893    }
894}
895
896#[cfg(any(test, feature = "test-support"))]
897pub mod test {
898    use super::*;
899    use gpui::{actions, div, App, Context, Window};
900
901    pub struct TestPanel {
902        pub position: DockPosition,
903        pub zoomed: bool,
904        pub active: bool,
905        pub focus_handle: FocusHandle,
906        pub size: Pixels,
907    }
908    actions!(test, [ToggleTestPanel]);
909
910    impl EventEmitter<PanelEvent> for TestPanel {}
911
912    impl TestPanel {
913        pub fn new(position: DockPosition, cx: &mut App) -> Self {
914            Self {
915                position,
916                zoomed: false,
917                active: false,
918                focus_handle: cx.focus_handle(),
919                size: px(300.),
920            }
921        }
922    }
923
924    impl Render for TestPanel {
925        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
926            div().id("test").track_focus(&self.focus_handle(cx))
927        }
928    }
929
930    impl Panel for TestPanel {
931        fn persistent_name() -> &'static str {
932            "TestPanel"
933        }
934
935        fn position(&self, _window: &Window, _: &App) -> super::DockPosition {
936            self.position
937        }
938
939        fn position_is_valid(&self, _: super::DockPosition) -> bool {
940            true
941        }
942
943        fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
944            self.position = position;
945            cx.update_global::<SettingsStore, _>(|_, _| {});
946        }
947
948        fn size(&self, _window: &Window, _: &App) -> Pixels {
949            self.size
950        }
951
952        fn set_size(&mut self, size: Option<Pixels>, _window: &mut Window, _: &mut Context<Self>) {
953            self.size = size.unwrap_or(px(300.));
954        }
955
956        fn icon(&self, _window: &Window, _: &App) -> Option<ui::IconName> {
957            None
958        }
959
960        fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
961            None
962        }
963
964        fn toggle_action(&self) -> Box<dyn Action> {
965            ToggleTestPanel.boxed_clone()
966        }
967
968        fn is_zoomed(&self, _window: &Window, _: &App) -> bool {
969            self.zoomed
970        }
971
972        fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, _cx: &mut Context<Self>) {
973            self.zoomed = zoomed;
974        }
975
976        fn set_active(&mut self, active: bool, _window: &mut Window, _cx: &mut Context<Self>) {
977            self.active = active;
978        }
979
980        fn activation_priority(&self) -> u32 {
981            100
982        }
983    }
984
985    impl Focusable for TestPanel {
986        fn focus_handle(&self, _cx: &App) -> FocusHandle {
987            self.focus_handle.clone()
988        }
989    }
990}