multi_workspace.rs

   1use anyhow::Result;
   2use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
   3use gpui::{
   4    AnyView, App, Context, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
   5    ManagedView, MouseButton, Pixels, Render, Subscription, Task, Tiling, Window, WindowId,
   6    actions, deferred, px,
   7};
   8use project::DisableAiSettings;
   9#[cfg(any(test, feature = "test-support"))]
  10use project::Project;
  11use settings::Settings;
  12pub use settings::SidebarSide;
  13use std::future::Future;
  14use std::path::PathBuf;
  15use std::sync::Arc;
  16use ui::prelude::*;
  17use util::ResultExt;
  18use zed_actions::agents_sidebar::{MoveWorkspaceToNewWindow, ToggleThreadSwitcher};
  19
  20use agent_settings::AgentSettings;
  21use settings::SidebarDockPosition;
  22use ui::{ContextMenu, right_click_menu};
  23
  24const SIDEBAR_RESIZE_HANDLE_SIZE: Pixels = px(6.0);
  25
  26use crate::{
  27    CloseIntent, CloseWindow, DockPosition, Event as WorkspaceEvent, Item, ModalView, OpenMode,
  28    Panel, Workspace, WorkspaceId, client_side_decorations,
  29};
  30
  31actions!(
  32    multi_workspace,
  33    [
  34        /// Toggles the workspace switcher sidebar.
  35        ToggleWorkspaceSidebar,
  36        /// Closes the workspace sidebar.
  37        CloseWorkspaceSidebar,
  38        /// Moves focus to or from the workspace sidebar without closing it.
  39        FocusWorkspaceSidebar,
  40        /// Switches to the next workspace.
  41        NextWorkspace,
  42        /// Switches to the previous workspace.
  43        PreviousWorkspace,
  44    ]
  45);
  46
  47#[derive(Default)]
  48pub struct SidebarRenderState {
  49    pub open: bool,
  50    pub side: SidebarSide,
  51}
  52
  53pub fn sidebar_side_context_menu(
  54    id: impl Into<ElementId>,
  55    cx: &App,
  56) -> ui::RightClickMenu<ContextMenu> {
  57    let current_position = AgentSettings::get_global(cx).sidebar_side;
  58    right_click_menu(id).menu(move |window, cx| {
  59        let fs = <dyn fs::Fs>::global(cx);
  60        ContextMenu::build(window, cx, move |mut menu, _, _cx| {
  61            let positions: [(SidebarDockPosition, &str); 2] = [
  62                (SidebarDockPosition::Left, "Left"),
  63                (SidebarDockPosition::Right, "Right"),
  64            ];
  65            for (position, label) in positions {
  66                let fs = fs.clone();
  67                menu = menu.toggleable_entry(
  68                    label,
  69                    position == current_position,
  70                    IconPosition::Start,
  71                    None,
  72                    move |_window, cx| {
  73                        settings::update_settings_file(fs.clone(), cx, move |settings, _cx| {
  74                            settings
  75                                .agent
  76                                .get_or_insert_default()
  77                                .set_sidebar_side(position);
  78                        });
  79                    },
  80                );
  81            }
  82            menu
  83        })
  84    })
  85}
  86
  87pub enum MultiWorkspaceEvent {
  88    ActiveWorkspaceChanged,
  89    WorkspaceAdded(Entity<Workspace>),
  90    WorkspaceRemoved(EntityId),
  91}
  92
  93pub enum SidebarEvent {
  94    SerializeNeeded,
  95}
  96
  97pub trait Sidebar: Focusable + Render + EventEmitter<SidebarEvent> + Sized {
  98    fn width(&self, cx: &App) -> Pixels;
  99    fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>);
 100    fn has_notifications(&self, cx: &App) -> bool;
 101    fn side(&self, _cx: &App) -> SidebarSide;
 102
 103    fn is_threads_list_view_active(&self) -> bool {
 104        true
 105    }
 106    /// Makes focus reset back to the search editor upon toggling the sidebar from outside
 107    fn prepare_for_focus(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
 108    /// Opens or cycles the thread switcher popup.
 109    fn toggle_thread_switcher(
 110        &mut self,
 111        _select_last: bool,
 112        _window: &mut Window,
 113        _cx: &mut Context<Self>,
 114    ) {
 115    }
 116
 117    /// Return an opaque JSON blob of sidebar-specific state to persist.
 118    fn serialized_state(&self, _cx: &App) -> Option<String> {
 119        None
 120    }
 121
 122    /// Restore sidebar state from a previously-serialized blob.
 123    fn restore_serialized_state(
 124        &mut self,
 125        _state: &str,
 126        _window: &mut Window,
 127        _cx: &mut Context<Self>,
 128    ) {
 129    }
 130}
 131
 132pub trait SidebarHandle: 'static + Send + Sync {
 133    fn width(&self, cx: &App) -> Pixels;
 134    fn set_width(&self, width: Option<Pixels>, cx: &mut App);
 135    fn focus_handle(&self, cx: &App) -> FocusHandle;
 136    fn focus(&self, window: &mut Window, cx: &mut App);
 137    fn prepare_for_focus(&self, window: &mut Window, cx: &mut App);
 138    fn has_notifications(&self, cx: &App) -> bool;
 139    fn to_any(&self) -> AnyView;
 140    fn entity_id(&self) -> EntityId;
 141    fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App);
 142
 143    fn is_threads_list_view_active(&self, cx: &App) -> bool;
 144
 145    fn side(&self, cx: &App) -> SidebarSide;
 146    fn serialized_state(&self, cx: &App) -> Option<String>;
 147    fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App);
 148}
 149
 150#[derive(Clone)]
 151pub struct DraggedSidebar;
 152
 153impl Render for DraggedSidebar {
 154    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 155        gpui::Empty
 156    }
 157}
 158
 159impl<T: Sidebar> SidebarHandle for Entity<T> {
 160    fn width(&self, cx: &App) -> Pixels {
 161        self.read(cx).width(cx)
 162    }
 163
 164    fn set_width(&self, width: Option<Pixels>, cx: &mut App) {
 165        self.update(cx, |this, cx| this.set_width(width, cx))
 166    }
 167
 168    fn focus_handle(&self, cx: &App) -> FocusHandle {
 169        self.read(cx).focus_handle(cx)
 170    }
 171
 172    fn focus(&self, window: &mut Window, cx: &mut App) {
 173        let handle = self.read(cx).focus_handle(cx);
 174        window.focus(&handle, cx);
 175    }
 176
 177    fn prepare_for_focus(&self, window: &mut Window, cx: &mut App) {
 178        self.update(cx, |this, cx| this.prepare_for_focus(window, cx));
 179    }
 180
 181    fn has_notifications(&self, cx: &App) -> bool {
 182        self.read(cx).has_notifications(cx)
 183    }
 184
 185    fn to_any(&self) -> AnyView {
 186        self.clone().into()
 187    }
 188
 189    fn entity_id(&self) -> EntityId {
 190        Entity::entity_id(self)
 191    }
 192
 193    fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App) {
 194        let entity = self.clone();
 195        window.defer(cx, move |window, cx| {
 196            entity.update(cx, |this, cx| {
 197                this.toggle_thread_switcher(select_last, window, cx);
 198            });
 199        });
 200    }
 201
 202    fn is_threads_list_view_active(&self, cx: &App) -> bool {
 203        self.read(cx).is_threads_list_view_active()
 204    }
 205
 206    fn side(&self, cx: &App) -> SidebarSide {
 207        self.read(cx).side(cx)
 208    }
 209
 210    fn serialized_state(&self, cx: &App) -> Option<String> {
 211        self.read(cx).serialized_state(cx)
 212    }
 213
 214    fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App) {
 215        self.update(cx, |this, cx| {
 216            this.restore_serialized_state(state, window, cx)
 217        })
 218    }
 219}
 220
 221pub struct MultiWorkspace {
 222    window_id: WindowId,
 223    workspaces: Vec<Entity<Workspace>>,
 224    active_workspace_index: usize,
 225    sidebar: Option<Box<dyn SidebarHandle>>,
 226    sidebar_open: bool,
 227    sidebar_overlay: Option<AnyView>,
 228    pending_removal_tasks: Vec<Task<()>>,
 229    _serialize_task: Option<Task<()>>,
 230    _subscriptions: Vec<Subscription>,
 231}
 232
 233impl EventEmitter<MultiWorkspaceEvent> for MultiWorkspace {}
 234
 235impl MultiWorkspace {
 236    pub fn sidebar_side(&self, cx: &App) -> SidebarSide {
 237        self.sidebar
 238            .as_ref()
 239            .map_or(SidebarSide::Left, |s| s.side(cx))
 240    }
 241
 242    pub fn sidebar_render_state(&self, cx: &App) -> SidebarRenderState {
 243        SidebarRenderState {
 244            open: self.sidebar_open() && self.multi_workspace_enabled(cx),
 245            side: self.sidebar_side(cx),
 246        }
 247    }
 248
 249    pub fn new(workspace: Entity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 250        let release_subscription = cx.on_release(|this: &mut MultiWorkspace, _cx| {
 251            if let Some(task) = this._serialize_task.take() {
 252                task.detach();
 253            }
 254            for task in std::mem::take(&mut this.pending_removal_tasks) {
 255                task.detach();
 256            }
 257        });
 258        let quit_subscription = cx.on_app_quit(Self::app_will_quit);
 259        let settings_subscription =
 260            cx.observe_global_in::<settings::SettingsStore>(window, |this, window, cx| {
 261                if DisableAiSettings::get_global(cx).disable_ai && this.sidebar_open {
 262                    this.close_sidebar(window, cx);
 263                }
 264            });
 265        Self::subscribe_to_workspace(&workspace, window, cx);
 266        let weak_self = cx.weak_entity();
 267        workspace.update(cx, |workspace, cx| {
 268            workspace.set_multi_workspace(weak_self, cx);
 269        });
 270        Self {
 271            window_id: window.window_handle().window_id(),
 272            workspaces: vec![workspace],
 273            active_workspace_index: 0,
 274            sidebar: None,
 275            sidebar_open: false,
 276            sidebar_overlay: None,
 277            pending_removal_tasks: Vec::new(),
 278            _serialize_task: None,
 279            _subscriptions: vec![
 280                release_subscription,
 281                quit_subscription,
 282                settings_subscription,
 283            ],
 284        }
 285    }
 286
 287    pub fn register_sidebar<T: Sidebar>(&mut self, sidebar: Entity<T>, cx: &mut Context<Self>) {
 288        self._subscriptions
 289            .push(cx.observe(&sidebar, |_this, _, cx| {
 290                cx.notify();
 291            }));
 292        self._subscriptions
 293            .push(cx.subscribe(&sidebar, |this, _, event, cx| match event {
 294                SidebarEvent::SerializeNeeded => {
 295                    this.serialize(cx);
 296                }
 297            }));
 298        self.sidebar = Some(Box::new(sidebar));
 299    }
 300
 301    pub fn sidebar(&self) -> Option<&dyn SidebarHandle> {
 302        self.sidebar.as_deref()
 303    }
 304
 305    pub fn set_sidebar_overlay(&mut self, overlay: Option<AnyView>, cx: &mut Context<Self>) {
 306        self.sidebar_overlay = overlay;
 307        cx.notify();
 308    }
 309
 310    pub fn sidebar_open(&self) -> bool {
 311        self.sidebar_open
 312    }
 313
 314    pub fn sidebar_has_notifications(&self, cx: &App) -> bool {
 315        self.sidebar
 316            .as_ref()
 317            .map_or(false, |s| s.has_notifications(cx))
 318    }
 319
 320    pub fn is_threads_list_view_active(&self, cx: &App) -> bool {
 321        self.sidebar
 322            .as_ref()
 323            .map_or(false, |s| s.is_threads_list_view_active(cx))
 324    }
 325
 326    pub fn multi_workspace_enabled(&self, cx: &App) -> bool {
 327        cx.has_flag::<AgentV2FeatureFlag>() && !DisableAiSettings::get_global(cx).disable_ai
 328    }
 329
 330    pub fn toggle_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 331        if !self.multi_workspace_enabled(cx) {
 332            return;
 333        }
 334
 335        if self.sidebar_open {
 336            self.close_sidebar(window, cx);
 337        } else {
 338            self.open_sidebar(cx);
 339            if let Some(sidebar) = &self.sidebar {
 340                sidebar.prepare_for_focus(window, cx);
 341                sidebar.focus(window, cx);
 342            }
 343        }
 344    }
 345
 346    pub fn close_sidebar_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 347        if !self.multi_workspace_enabled(cx) {
 348            return;
 349        }
 350
 351        if self.sidebar_open {
 352            self.close_sidebar(window, cx);
 353        }
 354    }
 355
 356    pub fn focus_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 357        if !self.multi_workspace_enabled(cx) {
 358            return;
 359        }
 360
 361        if self.sidebar_open {
 362            let sidebar_is_focused = self
 363                .sidebar
 364                .as_ref()
 365                .is_some_and(|s| s.focus_handle(cx).contains_focused(window, cx));
 366
 367            if sidebar_is_focused {
 368                let pane = self.workspace().read(cx).active_pane().clone();
 369                let pane_focus = pane.read(cx).focus_handle(cx);
 370                window.focus(&pane_focus, cx);
 371            } else if let Some(sidebar) = &self.sidebar {
 372                sidebar.prepare_for_focus(window, cx);
 373                sidebar.focus(window, cx);
 374            }
 375        } else {
 376            self.open_sidebar(cx);
 377            if let Some(sidebar) = &self.sidebar {
 378                sidebar.prepare_for_focus(window, cx);
 379                sidebar.focus(window, cx);
 380            }
 381        }
 382    }
 383
 384    pub fn open_sidebar(&mut self, cx: &mut Context<Self>) {
 385        self.sidebar_open = true;
 386        let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
 387        for workspace in &self.workspaces {
 388            workspace.update(cx, |workspace, _cx| {
 389                workspace.set_sidebar_focus_handle(sidebar_focus_handle.clone());
 390            });
 391        }
 392        self.serialize(cx);
 393        cx.notify();
 394    }
 395
 396    pub fn close_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 397        self.sidebar_open = false;
 398        for workspace in &self.workspaces {
 399            workspace.update(cx, |workspace, _cx| {
 400                workspace.set_sidebar_focus_handle(None);
 401            });
 402        }
 403        let pane = self.workspace().read(cx).active_pane().clone();
 404        let pane_focus = pane.read(cx).focus_handle(cx);
 405        window.focus(&pane_focus, cx);
 406        self.serialize(cx);
 407        cx.notify();
 408    }
 409
 410    pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
 411        cx.spawn_in(window, async move |this, cx| {
 412            let workspaces = this.update(cx, |multi_workspace, _cx| {
 413                multi_workspace.workspaces().to_vec()
 414            })?;
 415
 416            for workspace in workspaces {
 417                let should_continue = workspace
 418                    .update_in(cx, |workspace, window, cx| {
 419                        workspace.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 420                    })?
 421                    .await?;
 422                if !should_continue {
 423                    return anyhow::Ok(());
 424                }
 425            }
 426
 427            cx.update(|window, _cx| {
 428                window.remove_window();
 429            })?;
 430
 431            anyhow::Ok(())
 432        })
 433        .detach_and_log_err(cx);
 434    }
 435
 436    fn subscribe_to_workspace(
 437        workspace: &Entity<Workspace>,
 438        window: &Window,
 439        cx: &mut Context<Self>,
 440    ) {
 441        cx.subscribe_in(workspace, window, |this, workspace, event, window, cx| {
 442            if let WorkspaceEvent::Activate = event {
 443                this.activate(workspace.clone(), window, cx);
 444            }
 445        })
 446        .detach();
 447    }
 448
 449    pub fn workspace(&self) -> &Entity<Workspace> {
 450        &self.workspaces[self.active_workspace_index]
 451    }
 452
 453    pub fn workspaces(&self) -> &[Entity<Workspace>] {
 454        &self.workspaces
 455    }
 456
 457    pub fn active_workspace_index(&self) -> usize {
 458        self.active_workspace_index
 459    }
 460
 461    /// Adds a workspace to this window without changing which workspace is
 462    /// active.
 463    pub fn add(&mut self, workspace: Entity<Workspace>, window: &Window, cx: &mut Context<Self>) {
 464        if !self.multi_workspace_enabled(cx) {
 465            self.set_single_workspace(workspace, cx);
 466            return;
 467        }
 468
 469        self.insert_workspace(workspace, window, cx);
 470    }
 471
 472    /// Ensures the workspace is in the multiworkspace and makes it the active one.
 473    pub fn activate(
 474        &mut self,
 475        workspace: Entity<Workspace>,
 476        window: &mut Window,
 477        cx: &mut Context<Self>,
 478    ) {
 479        if !self.multi_workspace_enabled(cx) {
 480            self.set_single_workspace(workspace, cx);
 481            return;
 482        }
 483
 484        let index = self.insert_workspace(workspace, &*window, cx);
 485        let changed = self.active_workspace_index != index;
 486        self.active_workspace_index = index;
 487        if changed {
 488            cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
 489            self.serialize(cx);
 490        }
 491        self.focus_active_workspace(window, cx);
 492        cx.notify();
 493    }
 494
 495    /// Replaces the currently active workspace with a new one. If the
 496    /// workspace is already in the list, this just switches to it.
 497    pub fn replace(
 498        &mut self,
 499        workspace: Entity<Workspace>,
 500        window: &Window,
 501        cx: &mut Context<Self>,
 502    ) {
 503        if !self.multi_workspace_enabled(cx) {
 504            self.set_single_workspace(workspace, cx);
 505            return;
 506        }
 507
 508        if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
 509            let changed = self.active_workspace_index != index;
 510            self.active_workspace_index = index;
 511            if changed {
 512                cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
 513                self.serialize(cx);
 514            }
 515            cx.notify();
 516            return;
 517        }
 518
 519        let old_workspace = std::mem::replace(
 520            &mut self.workspaces[self.active_workspace_index],
 521            workspace.clone(),
 522        );
 523
 524        let old_entity_id = old_workspace.entity_id();
 525        self.detach_workspace(&old_workspace, cx);
 526
 527        Self::subscribe_to_workspace(&workspace, window, cx);
 528        self.sync_sidebar_to_workspace(&workspace, cx);
 529
 530        cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(old_entity_id));
 531        cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
 532        cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
 533        self.serialize(cx);
 534        cx.notify();
 535    }
 536
 537    fn set_single_workspace(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) {
 538        self.workspaces[0] = workspace;
 539        self.active_workspace_index = 0;
 540        cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
 541        cx.notify();
 542    }
 543
 544    /// Inserts a workspace into the list if not already present. Returns the
 545    /// index of the workspace (existing or newly inserted). Does not change
 546    /// the active workspace index.
 547    fn insert_workspace(
 548        &mut self,
 549        workspace: Entity<Workspace>,
 550        window: &Window,
 551        cx: &mut Context<Self>,
 552    ) -> usize {
 553        if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
 554            index
 555        } else {
 556            Self::subscribe_to_workspace(&workspace, window, cx);
 557            self.sync_sidebar_to_workspace(&workspace, cx);
 558            let weak_self = cx.weak_entity();
 559            workspace.update(cx, |workspace, cx| {
 560                workspace.set_multi_workspace(weak_self, cx);
 561            });
 562            self.workspaces.push(workspace.clone());
 563            cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
 564            cx.notify();
 565            self.workspaces.len() - 1
 566        }
 567    }
 568
 569    /// Clears session state and DB binding for a workspace that is being
 570    /// removed or replaced. The DB row is preserved so the workspace still
 571    /// appears in the recent-projects list.
 572    fn detach_workspace(&mut self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
 573        workspace.update(cx, |workspace, _cx| {
 574            workspace.session_id.take();
 575            workspace._schedule_serialize_workspace.take();
 576            workspace._serialize_workspace_task.take();
 577        });
 578
 579        if let Some(workspace_id) = workspace.read(cx).database_id() {
 580            let db = crate::persistence::WorkspaceDb::global(cx);
 581            self.pending_removal_tasks.retain(|task| !task.is_ready());
 582            self.pending_removal_tasks
 583                .push(cx.background_spawn(async move {
 584                    db.set_session_binding(workspace_id, None, None)
 585                        .await
 586                        .log_err();
 587                }));
 588        }
 589    }
 590
 591    fn sync_sidebar_to_workspace(&self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
 592        if self.sidebar_open {
 593            let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
 594            workspace.update(cx, |workspace, _| {
 595                workspace.set_sidebar_focus_handle(sidebar_focus_handle);
 596            });
 597        }
 598    }
 599
 600    fn cycle_workspace(&mut self, delta: isize, window: &mut Window, cx: &mut Context<Self>) {
 601        let count = self.workspaces.len() as isize;
 602        if count <= 1 {
 603            return;
 604        }
 605        let current = self.active_workspace_index as isize;
 606        let next = ((current + delta).rem_euclid(count)) as usize;
 607        let workspace = self.workspaces[next].clone();
 608        self.activate(workspace, window, cx);
 609    }
 610
 611    fn next_workspace(&mut self, _: &NextWorkspace, window: &mut Window, cx: &mut Context<Self>) {
 612        self.cycle_workspace(1, window, cx);
 613    }
 614
 615    fn previous_workspace(
 616        &mut self,
 617        _: &PreviousWorkspace,
 618        window: &mut Window,
 619        cx: &mut Context<Self>,
 620    ) {
 621        self.cycle_workspace(-1, window, cx);
 622    }
 623
 624    pub(crate) fn serialize(&mut self, cx: &mut Context<Self>) {
 625        self._serialize_task = Some(cx.spawn(async move |this, cx| {
 626            let Some((window_id, state)) = this
 627                .read_with(cx, |this, cx| {
 628                    let state = crate::persistence::model::MultiWorkspaceState {
 629                        active_workspace_id: this.workspace().read(cx).database_id(),
 630                        sidebar_open: this.sidebar_open,
 631                        sidebar_state: this.sidebar.as_ref().and_then(|s| s.serialized_state(cx)),
 632                    };
 633                    (this.window_id, state)
 634                })
 635                .ok()
 636            else {
 637                return;
 638            };
 639            let kvp = cx.update(|cx| db::kvp::KeyValueStore::global(cx));
 640            crate::persistence::write_multi_workspace_state(&kvp, window_id, state).await;
 641        }));
 642    }
 643
 644    /// Returns the in-flight serialization task (if any) so the caller can
 645    /// await it. Used by the quit handler to ensure pending DB writes
 646    /// complete before the process exits.
 647    pub fn flush_serialization(&mut self) -> Task<()> {
 648        self._serialize_task.take().unwrap_or(Task::ready(()))
 649    }
 650
 651    fn app_will_quit(&mut self, _cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
 652        let mut tasks: Vec<Task<()>> = Vec::new();
 653        if let Some(task) = self._serialize_task.take() {
 654            tasks.push(task);
 655        }
 656        tasks.extend(std::mem::take(&mut self.pending_removal_tasks));
 657
 658        async move {
 659            futures::future::join_all(tasks).await;
 660        }
 661    }
 662
 663    pub fn focus_active_workspace(&self, window: &mut Window, cx: &mut App) {
 664        // If a dock panel is zoomed, focus it instead of the center pane.
 665        // Otherwise, focusing the center pane triggers dismiss_zoomed_items_to_reveal
 666        // which closes the zoomed dock.
 667        let focus_handle = {
 668            let workspace = self.workspace().read(cx);
 669            let mut target = None;
 670            for dock in workspace.all_docks() {
 671                let dock = dock.read(cx);
 672                if dock.is_open() {
 673                    if let Some(panel) = dock.active_panel() {
 674                        if panel.is_zoomed(window, cx) {
 675                            target = Some(panel.panel_focus_handle(cx));
 676                            break;
 677                        }
 678                    }
 679                }
 680            }
 681            target.unwrap_or_else(|| {
 682                let pane = workspace.active_pane().clone();
 683                pane.read(cx).focus_handle(cx)
 684            })
 685        };
 686        window.focus(&focus_handle, cx);
 687    }
 688
 689    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 690        self.workspace().read(cx).panel::<T>(cx)
 691    }
 692
 693    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 694        self.workspace().read(cx).active_modal::<V>(cx)
 695    }
 696
 697    pub fn add_panel<T: Panel>(
 698        &mut self,
 699        panel: Entity<T>,
 700        window: &mut Window,
 701        cx: &mut Context<Self>,
 702    ) {
 703        self.workspace().update(cx, |workspace, cx| {
 704            workspace.add_panel(panel, window, cx);
 705        });
 706    }
 707
 708    pub fn focus_panel<T: Panel>(
 709        &mut self,
 710        window: &mut Window,
 711        cx: &mut Context<Self>,
 712    ) -> Option<Entity<T>> {
 713        self.workspace()
 714            .update(cx, |workspace, cx| workspace.focus_panel::<T>(window, cx))
 715    }
 716
 717    // used in a test
 718    pub fn toggle_modal<V: ModalView, B>(
 719        &mut self,
 720        window: &mut Window,
 721        cx: &mut Context<Self>,
 722        build: B,
 723    ) where
 724        B: FnOnce(&mut Window, &mut gpui::Context<V>) -> V,
 725    {
 726        self.workspace().update(cx, |workspace, cx| {
 727            workspace.toggle_modal(window, cx, build);
 728        });
 729    }
 730
 731    pub fn toggle_dock(
 732        &mut self,
 733        dock_side: DockPosition,
 734        window: &mut Window,
 735        cx: &mut Context<Self>,
 736    ) {
 737        self.workspace().update(cx, |workspace, cx| {
 738            workspace.toggle_dock(dock_side, window, cx);
 739        });
 740    }
 741
 742    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 743        self.workspace().read(cx).active_item_as::<I>(cx)
 744    }
 745
 746    pub fn items_of_type<'a, T: Item>(
 747        &'a self,
 748        cx: &'a App,
 749    ) -> impl 'a + Iterator<Item = Entity<T>> {
 750        self.workspace().read(cx).items_of_type::<T>(cx)
 751    }
 752
 753    pub fn database_id(&self, cx: &App) -> Option<WorkspaceId> {
 754        self.workspace().read(cx).database_id()
 755    }
 756
 757    pub fn take_pending_removal_tasks(&mut self) -> Vec<Task<()>> {
 758        let tasks: Vec<Task<()>> = std::mem::take(&mut self.pending_removal_tasks)
 759            .into_iter()
 760            .filter(|task| !task.is_ready())
 761            .collect();
 762        tasks
 763    }
 764
 765    #[cfg(any(test, feature = "test-support"))]
 766    pub fn set_random_database_id(&mut self, cx: &mut Context<Self>) {
 767        self.workspace().update(cx, |workspace, _cx| {
 768            workspace.set_random_database_id();
 769        });
 770    }
 771
 772    #[cfg(any(test, feature = "test-support"))]
 773    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 774        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
 775        Self::new(workspace, window, cx)
 776    }
 777
 778    #[cfg(any(test, feature = "test-support"))]
 779    pub fn test_add_workspace(
 780        &mut self,
 781        project: Entity<Project>,
 782        window: &mut Window,
 783        cx: &mut Context<Self>,
 784    ) -> Entity<Workspace> {
 785        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
 786        self.activate(workspace.clone(), window, cx);
 787        workspace
 788    }
 789
 790    #[cfg(any(test, feature = "test-support"))]
 791    pub fn create_test_workspace(
 792        &mut self,
 793        window: &mut Window,
 794        cx: &mut Context<Self>,
 795    ) -> Task<()> {
 796        let app_state = self.workspace().read(cx).app_state().clone();
 797        let project = Project::local(
 798            app_state.client.clone(),
 799            app_state.node_runtime.clone(),
 800            app_state.user_store.clone(),
 801            app_state.languages.clone(),
 802            app_state.fs.clone(),
 803            None,
 804            project::LocalProjectFlags::default(),
 805            cx,
 806        );
 807        let new_workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
 808        self.activate(new_workspace.clone(), window, cx);
 809
 810        let weak_workspace = new_workspace.downgrade();
 811        let db = crate::persistence::WorkspaceDb::global(cx);
 812        cx.spawn_in(window, async move |this, cx| {
 813            let workspace_id = db.next_id().await.unwrap();
 814            let workspace = weak_workspace.upgrade().unwrap();
 815            let task: Task<()> = this
 816                .update_in(cx, |this, window, cx| {
 817                    let session_id = workspace.read(cx).session_id();
 818                    let window_id = window.window_handle().window_id().as_u64();
 819                    workspace.update(cx, |workspace, _cx| {
 820                        workspace.set_database_id(workspace_id);
 821                    });
 822                    this.serialize(cx);
 823                    let db = db.clone();
 824                    cx.background_spawn(async move {
 825                        db.set_session_binding(workspace_id, session_id, Some(window_id))
 826                            .await
 827                            .log_err();
 828                    })
 829                })
 830                .unwrap();
 831            task.await
 832        })
 833    }
 834
 835    pub fn remove(
 836        &mut self,
 837        workspace: &Entity<Workspace>,
 838        window: &mut Window,
 839        cx: &mut Context<Self>,
 840    ) -> bool {
 841        let Some(index) = self.workspaces.iter().position(|w| w == workspace) else {
 842            return false;
 843        };
 844        if self.workspaces.len() <= 1 {
 845            return false;
 846        }
 847
 848        let removed_workspace = self.workspaces.remove(index);
 849
 850        if self.active_workspace_index >= self.workspaces.len() {
 851            self.active_workspace_index = self.workspaces.len() - 1;
 852        } else if self.active_workspace_index > index {
 853            self.active_workspace_index -= 1;
 854        }
 855
 856        self.detach_workspace(&removed_workspace, cx);
 857
 858        self.serialize(cx);
 859        self.focus_active_workspace(window, cx);
 860        cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(
 861            removed_workspace.entity_id(),
 862        ));
 863        cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
 864        cx.notify();
 865
 866        true
 867    }
 868
 869    pub fn move_workspace_to_new_window(
 870        &mut self,
 871        workspace: &Entity<Workspace>,
 872        window: &mut Window,
 873        cx: &mut Context<Self>,
 874    ) {
 875        let workspace = workspace.clone();
 876        if !self.remove(&workspace, window, cx) {
 877            return;
 878        }
 879
 880        let app_state: Arc<crate::AppState> = workspace.read(cx).app_state().clone();
 881
 882        cx.defer(move |cx| {
 883            let options = (app_state.build_window_options)(None, cx);
 884
 885            let Ok(window) = cx.open_window(options, |window, cx| {
 886                cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 887            }) else {
 888                return;
 889            };
 890
 891            let _ = window.update(cx, |_, window, _| {
 892                window.activate_window();
 893            });
 894        });
 895    }
 896
 897    fn move_active_workspace_to_new_window(
 898        &mut self,
 899        _: &MoveWorkspaceToNewWindow,
 900        window: &mut Window,
 901        cx: &mut Context<Self>,
 902    ) {
 903        let workspace = self.workspace().clone();
 904        self.move_workspace_to_new_window(&workspace, window, cx);
 905    }
 906
 907    pub fn open_project(
 908        &mut self,
 909        paths: Vec<PathBuf>,
 910        open_mode: OpenMode,
 911        window: &mut Window,
 912        cx: &mut Context<Self>,
 913    ) -> Task<Result<Entity<Workspace>>> {
 914        let workspace = self.workspace().clone();
 915
 916        let needs_close_prompt =
 917            open_mode == OpenMode::Replace || !self.multi_workspace_enabled(cx);
 918        let open_mode = if self.multi_workspace_enabled(cx) {
 919            open_mode
 920        } else {
 921            OpenMode::Replace
 922        };
 923
 924        if needs_close_prompt {
 925            cx.spawn_in(window, async move |_this, cx| {
 926                let should_continue = workspace
 927                    .update_in(cx, |workspace, window, cx| {
 928                        workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx)
 929                    })?
 930                    .await?;
 931                if should_continue {
 932                    workspace
 933                        .update_in(cx, |workspace, window, cx| {
 934                            workspace.open_workspace_for_paths(open_mode, paths, window, cx)
 935                        })?
 936                        .await
 937                } else {
 938                    Ok(workspace)
 939                }
 940            })
 941        } else {
 942            workspace.update(cx, |workspace, cx| {
 943                workspace.open_workspace_for_paths(open_mode, paths, window, cx)
 944            })
 945        }
 946    }
 947}
 948
 949impl Render for MultiWorkspace {
 950    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 951        let multi_workspace_enabled = self.multi_workspace_enabled(cx);
 952        let sidebar_side = self.sidebar_side(cx);
 953        let sidebar_on_right = sidebar_side == SidebarSide::Right;
 954
 955        let sidebar: Option<AnyElement> = if multi_workspace_enabled && self.sidebar_open() {
 956            self.sidebar.as_ref().map(|sidebar_handle| {
 957                let weak = cx.weak_entity();
 958
 959                let sidebar_width = sidebar_handle.width(cx);
 960                let resize_handle = deferred(
 961                    div()
 962                        .id("sidebar-resize-handle")
 963                        .absolute()
 964                        .when(!sidebar_on_right, |el| {
 965                            el.right(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
 966                        })
 967                        .when(sidebar_on_right, |el| {
 968                            el.left(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
 969                        })
 970                        .top(px(0.))
 971                        .h_full()
 972                        .w(SIDEBAR_RESIZE_HANDLE_SIZE)
 973                        .cursor_col_resize()
 974                        .on_drag(DraggedSidebar, |dragged, _, _, cx| {
 975                            cx.stop_propagation();
 976                            cx.new(|_| dragged.clone())
 977                        })
 978                        .on_mouse_down(MouseButton::Left, |_, _, cx| {
 979                            cx.stop_propagation();
 980                        })
 981                        .on_mouse_up(MouseButton::Left, move |event, _, cx| {
 982                            if event.click_count == 2 {
 983                                weak.update(cx, |this, cx| {
 984                                    if let Some(sidebar) = this.sidebar.as_mut() {
 985                                        sidebar.set_width(None, cx);
 986                                    }
 987                                    this.serialize(cx);
 988                                })
 989                                .ok();
 990                                cx.stop_propagation();
 991                            } else {
 992                                weak.update(cx, |this, cx| {
 993                                    this.serialize(cx);
 994                                })
 995                                .ok();
 996                            }
 997                        })
 998                        .occlude(),
 999                );
1000
1001                div()
1002                    .id("sidebar-container")
1003                    .relative()
1004                    .h_full()
1005                    .w(sidebar_width)
1006                    .flex_shrink_0()
1007                    .child(sidebar_handle.to_any())
1008                    .child(resize_handle)
1009                    .into_any_element()
1010            })
1011        } else {
1012            None
1013        };
1014
1015        let (left_sidebar, right_sidebar) = if sidebar_on_right {
1016            (None, sidebar)
1017        } else {
1018            (sidebar, None)
1019        };
1020
1021        let ui_font = theme_settings::setup_ui_font(window, cx);
1022        let text_color = cx.theme().colors().text;
1023
1024        let workspace = self.workspace().clone();
1025        let workspace_key_context = workspace.update(cx, |workspace, cx| workspace.key_context(cx));
1026        let root = workspace.update(cx, |workspace, cx| workspace.actions(h_flex(), window, cx));
1027
1028        client_side_decorations(
1029            root.key_context(workspace_key_context)
1030                .relative()
1031                .size_full()
1032                .font(ui_font)
1033                .text_color(text_color)
1034                .on_action(cx.listener(Self::close_window))
1035                .when(self.multi_workspace_enabled(cx), |this| {
1036                    this.on_action(cx.listener(
1037                        |this: &mut Self, _: &ToggleWorkspaceSidebar, window, cx| {
1038                            this.toggle_sidebar(window, cx);
1039                        },
1040                    ))
1041                    .on_action(cx.listener(
1042                        |this: &mut Self, _: &CloseWorkspaceSidebar, window, cx| {
1043                            this.close_sidebar_action(window, cx);
1044                        },
1045                    ))
1046                    .on_action(cx.listener(
1047                        |this: &mut Self, _: &FocusWorkspaceSidebar, window, cx| {
1048                            this.focus_sidebar(window, cx);
1049                        },
1050                    ))
1051                    .on_action(cx.listener(Self::next_workspace))
1052                    .on_action(cx.listener(Self::previous_workspace))
1053                    .on_action(cx.listener(Self::move_active_workspace_to_new_window))
1054                    .on_action(cx.listener(
1055                        |this: &mut Self, action: &ToggleThreadSwitcher, window, cx| {
1056                            if let Some(sidebar) = &this.sidebar {
1057                                sidebar.toggle_thread_switcher(action.select_last, window, cx);
1058                            }
1059                        },
1060                    ))
1061                })
1062                .when(
1063                    self.sidebar_open() && self.multi_workspace_enabled(cx),
1064                    |this| {
1065                        this.on_drag_move(cx.listener(
1066                            move |this: &mut Self,
1067                                  e: &DragMoveEvent<DraggedSidebar>,
1068                                  window,
1069                                  cx| {
1070                                if let Some(sidebar) = &this.sidebar {
1071                                    let new_width = if sidebar_on_right {
1072                                        window.bounds().size.width - e.event.position.x
1073                                    } else {
1074                                        e.event.position.x
1075                                    };
1076                                    sidebar.set_width(Some(new_width), cx);
1077                                }
1078                            },
1079                        ))
1080                    },
1081                )
1082                .children(left_sidebar)
1083                .child(
1084                    div()
1085                        .flex()
1086                        .flex_1()
1087                        .size_full()
1088                        .overflow_hidden()
1089                        .child(self.workspace().clone()),
1090                )
1091                .children(right_sidebar)
1092                .child(self.workspace().read(cx).modal_layer.clone())
1093                .children(self.sidebar_overlay.as_ref().map(|view| {
1094                    deferred(div().absolute().size_full().inset_0().occlude().child(
1095                        v_flex().h(px(0.0)).top_20().items_center().child(
1096                            h_flex().occlude().child(view.clone()).on_mouse_down(
1097                                MouseButton::Left,
1098                                |_, _, cx| {
1099                                    cx.stop_propagation();
1100                                },
1101                            ),
1102                        ),
1103                    ))
1104                    .with_priority(2)
1105                })),
1106            window,
1107            cx,
1108            Tiling {
1109                left: !sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1110                right: sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1111                ..Tiling::default()
1112            },
1113        )
1114    }
1115}