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