dock.rs

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