multi_workspace.rs

   1use anyhow::Result;
   2use gpui::PathPromptOptions;
   3use gpui::{
   4    AnyView, App, Context, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
   5    ManagedView, MouseButton, Pixels, Render, Subscription, Task, TaskExt, Tiling, Window,
   6    WindowId, actions, deferred, px,
   7};
   8use project::{DirectoryLister, DisableAiSettings, Project, ProjectGroupKey};
   9use remote::RemoteConnectionOptions;
  10use settings::Settings;
  11pub use settings::SidebarSide;
  12use std::collections::{HashMap, HashSet};
  13use std::future::Future;
  14use std::path::Path;
  15use std::path::PathBuf;
  16use ui::prelude::*;
  17use util::ResultExt;
  18use util::path_list::PathList;
  19use zed_actions::agents_sidebar::ToggleThreadSwitcher;
  20
  21use agent_settings::AgentSettings;
  22use settings::SidebarDockPosition;
  23use ui::{ContextMenu, right_click_menu};
  24
  25const SIDEBAR_RESIZE_HANDLE_SIZE: Pixels = px(6.0);
  26
  27use crate::open_remote_project_with_existing_connection;
  28use crate::{
  29    CloseIntent, CloseWindow, DockPosition, Event as WorkspaceEvent, Item, ModalView, OpenMode,
  30    Panel, Workspace, WorkspaceId, client_side_decorations,
  31    persistence::model::MultiWorkspaceState,
  32};
  33
  34actions!(
  35    multi_workspace,
  36    [
  37        /// Toggles the workspace switcher sidebar.
  38        ToggleWorkspaceSidebar,
  39        /// Closes the workspace sidebar.
  40        CloseWorkspaceSidebar,
  41        /// Moves focus to or from the workspace sidebar without closing it.
  42        FocusWorkspaceSidebar,
  43        /// Activates the next project in the sidebar.
  44        NextProject,
  45        /// Activates the previous project in the sidebar.
  46        PreviousProject,
  47        /// Activates the next thread in sidebar order.
  48        NextThread,
  49        /// Activates the previous thread in sidebar order.
  50        PreviousThread,
  51        /// Expands the thread list for the current project to show more threads.
  52        ShowMoreThreads,
  53        /// Collapses the thread list for the current project to show fewer threads.
  54        ShowFewerThreads,
  55        /// Creates a new thread in the current workspace.
  56        NewThread,
  57    ]
  58);
  59
  60#[derive(Default)]
  61pub struct SidebarRenderState {
  62    pub open: bool,
  63    pub side: SidebarSide,
  64}
  65
  66pub fn sidebar_side_context_menu(
  67    id: impl Into<ElementId>,
  68    cx: &App,
  69) -> ui::RightClickMenu<ContextMenu> {
  70    let current_position = AgentSettings::get_global(cx).sidebar_side;
  71    right_click_menu(id).menu(move |window, cx| {
  72        let fs = <dyn fs::Fs>::global(cx);
  73        ContextMenu::build(window, cx, move |mut menu, _, _cx| {
  74            let positions: [(SidebarDockPosition, &str); 2] = [
  75                (SidebarDockPosition::Left, "Left"),
  76                (SidebarDockPosition::Right, "Right"),
  77            ];
  78            for (position, label) in positions {
  79                let fs = fs.clone();
  80                menu = menu.toggleable_entry(
  81                    label,
  82                    position == current_position,
  83                    IconPosition::Start,
  84                    None,
  85                    move |_window, cx| {
  86                        settings::update_settings_file(fs.clone(), cx, move |settings, _cx| {
  87                            settings
  88                                .agent
  89                                .get_or_insert_default()
  90                                .set_sidebar_side(position);
  91                        });
  92                    },
  93                );
  94            }
  95            menu
  96        })
  97    })
  98}
  99
 100pub enum MultiWorkspaceEvent {
 101    ActiveWorkspaceChanged,
 102    WorkspaceAdded(Entity<Workspace>),
 103    WorkspaceRemoved(EntityId),
 104    WorktreePathAdded {
 105        old_main_paths: PathList,
 106        added_path: PathBuf,
 107    },
 108    WorktreePathRemoved {
 109        old_main_paths: PathList,
 110        removed_path: PathBuf,
 111    },
 112}
 113
 114pub enum SidebarEvent {
 115    SerializeNeeded,
 116}
 117
 118pub trait Sidebar: Focusable + Render + EventEmitter<SidebarEvent> + Sized {
 119    fn width(&self, cx: &App) -> Pixels;
 120    fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>);
 121    fn has_notifications(&self, cx: &App) -> bool;
 122    fn side(&self, _cx: &App) -> SidebarSide;
 123
 124    fn is_threads_list_view_active(&self) -> bool {
 125        true
 126    }
 127    /// Makes focus reset back to the search editor upon toggling the sidebar from outside
 128    fn prepare_for_focus(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
 129    /// Opens or cycles the thread switcher popup.
 130    fn toggle_thread_switcher(
 131        &mut self,
 132        _select_last: bool,
 133        _window: &mut Window,
 134        _cx: &mut Context<Self>,
 135    ) {
 136    }
 137
 138    /// Activates the next or previous project.
 139    fn cycle_project(&mut self, _forward: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
 140
 141    /// Activates the next or previous thread in sidebar order.
 142    fn cycle_thread(&mut self, _forward: bool, _window: &mut Window, _cx: &mut Context<Self>) {}
 143
 144    /// Return an opaque JSON blob of sidebar-specific state to persist.
 145    fn serialized_state(&self, _cx: &App) -> Option<String> {
 146        None
 147    }
 148
 149    /// Restore sidebar state from a previously-serialized blob.
 150    fn restore_serialized_state(
 151        &mut self,
 152        _state: &str,
 153        _window: &mut Window,
 154        _cx: &mut Context<Self>,
 155    ) {
 156    }
 157}
 158
 159pub trait SidebarHandle: 'static + Send + Sync {
 160    fn width(&self, cx: &App) -> Pixels;
 161    fn set_width(&self, width: Option<Pixels>, cx: &mut App);
 162    fn focus_handle(&self, cx: &App) -> FocusHandle;
 163    fn focus(&self, window: &mut Window, cx: &mut App);
 164    fn prepare_for_focus(&self, window: &mut Window, cx: &mut App);
 165    fn has_notifications(&self, cx: &App) -> bool;
 166    fn to_any(&self) -> AnyView;
 167    fn entity_id(&self) -> EntityId;
 168    fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App);
 169    fn cycle_project(&self, forward: bool, window: &mut Window, cx: &mut App);
 170    fn cycle_thread(&self, forward: bool, window: &mut Window, cx: &mut App);
 171
 172    fn is_threads_list_view_active(&self, cx: &App) -> bool;
 173
 174    fn side(&self, cx: &App) -> SidebarSide;
 175    fn serialized_state(&self, cx: &App) -> Option<String>;
 176    fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App);
 177}
 178
 179#[derive(Clone)]
 180pub struct DraggedSidebar;
 181
 182impl Render for DraggedSidebar {
 183    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 184        gpui::Empty
 185    }
 186}
 187
 188impl<T: Sidebar> SidebarHandle for Entity<T> {
 189    fn width(&self, cx: &App) -> Pixels {
 190        self.read(cx).width(cx)
 191    }
 192
 193    fn set_width(&self, width: Option<Pixels>, cx: &mut App) {
 194        self.update(cx, |this, cx| this.set_width(width, cx))
 195    }
 196
 197    fn focus_handle(&self, cx: &App) -> FocusHandle {
 198        self.read(cx).focus_handle(cx)
 199    }
 200
 201    fn focus(&self, window: &mut Window, cx: &mut App) {
 202        let handle = self.read(cx).focus_handle(cx);
 203        window.focus(&handle, cx);
 204    }
 205
 206    fn prepare_for_focus(&self, window: &mut Window, cx: &mut App) {
 207        self.update(cx, |this, cx| this.prepare_for_focus(window, cx));
 208    }
 209
 210    fn has_notifications(&self, cx: &App) -> bool {
 211        self.read(cx).has_notifications(cx)
 212    }
 213
 214    fn to_any(&self) -> AnyView {
 215        self.clone().into()
 216    }
 217
 218    fn entity_id(&self) -> EntityId {
 219        Entity::entity_id(self)
 220    }
 221
 222    fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App) {
 223        let entity = self.clone();
 224        window.defer(cx, move |window, cx| {
 225            entity.update(cx, |this, cx| {
 226                this.toggle_thread_switcher(select_last, window, cx);
 227            });
 228        });
 229    }
 230
 231    fn cycle_project(&self, forward: bool, window: &mut Window, cx: &mut App) {
 232        let entity = self.clone();
 233        window.defer(cx, move |window, cx| {
 234            entity.update(cx, |this, cx| {
 235                this.cycle_project(forward, window, cx);
 236            });
 237        });
 238    }
 239
 240    fn cycle_thread(&self, forward: bool, window: &mut Window, cx: &mut App) {
 241        let entity = self.clone();
 242        window.defer(cx, move |window, cx| {
 243            entity.update(cx, |this, cx| {
 244                this.cycle_thread(forward, window, cx);
 245            });
 246        });
 247    }
 248
 249    fn is_threads_list_view_active(&self, cx: &App) -> bool {
 250        self.read(cx).is_threads_list_view_active()
 251    }
 252
 253    fn side(&self, cx: &App) -> SidebarSide {
 254        self.read(cx).side(cx)
 255    }
 256
 257    fn serialized_state(&self, cx: &App) -> Option<String> {
 258        self.read(cx).serialized_state(cx)
 259    }
 260
 261    fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App) {
 262        self.update(cx, |this, cx| {
 263            this.restore_serialized_state(state, window, cx)
 264        })
 265    }
 266}
 267
 268/// Tracks which workspace the user is currently looking at.
 269///
 270/// `Persistent` workspaces live in the `workspaces` vec and are shown in the
 271/// sidebar. `Transient` workspaces exist outside the vec and are discarded
 272/// when the user switches away.
 273enum ActiveWorkspace {
 274    /// A persistent workspace, identified by index into the `workspaces` vec.
 275    Persistent(usize),
 276    /// A workspace not in the `workspaces` vec that will be discarded on
 277    /// switch or promoted to persistent when the sidebar is opened.
 278    Transient(Entity<Workspace>),
 279}
 280
 281impl ActiveWorkspace {
 282    fn transient_workspace(&self) -> Option<&Entity<Workspace>> {
 283        match self {
 284            Self::Transient(workspace) => Some(workspace),
 285            Self::Persistent(_) => None,
 286        }
 287    }
 288
 289    /// Sets the active workspace to transient, returning the previous
 290    /// transient workspace (if any).
 291    fn set_transient(&mut self, workspace: Entity<Workspace>) -> Option<Entity<Workspace>> {
 292        match std::mem::replace(self, Self::Transient(workspace)) {
 293            Self::Transient(old) => Some(old),
 294            Self::Persistent(_) => None,
 295        }
 296    }
 297
 298    /// Sets the active workspace to persistent at the given index,
 299    /// returning the previous transient workspace (if any).
 300    fn set_persistent(&mut self, index: usize) -> Option<Entity<Workspace>> {
 301        match std::mem::replace(self, Self::Persistent(index)) {
 302            Self::Transient(workspace) => Some(workspace),
 303            Self::Persistent(_) => None,
 304        }
 305    }
 306}
 307
 308pub struct MultiWorkspace {
 309    window_id: WindowId,
 310    workspaces: Vec<Entity<Workspace>>,
 311    active_workspace: ActiveWorkspace,
 312    project_group_keys: Vec<ProjectGroupKey>,
 313    workspace_group_keys: HashMap<EntityId, ProjectGroupKey>,
 314    sidebar: Option<Box<dyn SidebarHandle>>,
 315    sidebar_open: bool,
 316    sidebar_overlay: Option<AnyView>,
 317    pending_removal_tasks: Vec<Task<()>>,
 318    _serialize_task: Option<Task<()>>,
 319    _subscriptions: Vec<Subscription>,
 320    previous_focus_handle: Option<FocusHandle>,
 321}
 322
 323impl EventEmitter<MultiWorkspaceEvent> for MultiWorkspace {}
 324
 325impl MultiWorkspace {
 326    pub fn sidebar_side(&self, cx: &App) -> SidebarSide {
 327        self.sidebar
 328            .as_ref()
 329            .map_or(SidebarSide::Left, |s| s.side(cx))
 330    }
 331
 332    pub fn sidebar_render_state(&self, cx: &App) -> SidebarRenderState {
 333        SidebarRenderState {
 334            open: self.sidebar_open() && self.multi_workspace_enabled(cx),
 335            side: self.sidebar_side(cx),
 336        }
 337    }
 338
 339    pub fn new(workspace: Entity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 340        let release_subscription = cx.on_release(|this: &mut MultiWorkspace, _cx| {
 341            if let Some(task) = this._serialize_task.take() {
 342                task.detach();
 343            }
 344            for task in std::mem::take(&mut this.pending_removal_tasks) {
 345                task.detach();
 346            }
 347        });
 348        let quit_subscription = cx.on_app_quit(Self::app_will_quit);
 349        let settings_subscription = cx.observe_global_in::<settings::SettingsStore>(window, {
 350            let mut previous_disable_ai = DisableAiSettings::get_global(cx).disable_ai;
 351            move |this, window, cx| {
 352                if DisableAiSettings::get_global(cx).disable_ai != previous_disable_ai {
 353                    this.collapse_to_single_workspace(window, cx);
 354                    previous_disable_ai = DisableAiSettings::get_global(cx).disable_ai;
 355                }
 356            }
 357        });
 358        Self::subscribe_to_workspace(&workspace, window, cx);
 359        let weak_self = cx.weak_entity();
 360        workspace.update(cx, |workspace, cx| {
 361            workspace.set_multi_workspace(weak_self, cx);
 362        });
 363        Self {
 364            window_id: window.window_handle().window_id(),
 365            project_group_keys: Vec::new(),
 366            workspace_group_keys: HashMap::default(),
 367            workspaces: Vec::new(),
 368            active_workspace: ActiveWorkspace::Transient(workspace),
 369            sidebar: None,
 370            sidebar_open: false,
 371            sidebar_overlay: None,
 372            pending_removal_tasks: Vec::new(),
 373            _serialize_task: None,
 374            _subscriptions: vec![
 375                release_subscription,
 376                quit_subscription,
 377                settings_subscription,
 378            ],
 379            previous_focus_handle: None,
 380        }
 381    }
 382
 383    pub fn register_sidebar<T: Sidebar>(&mut self, sidebar: Entity<T>, cx: &mut Context<Self>) {
 384        self._subscriptions
 385            .push(cx.observe(&sidebar, |_this, _, cx| {
 386                cx.notify();
 387            }));
 388        self._subscriptions
 389            .push(cx.subscribe(&sidebar, |this, _, event, cx| match event {
 390                SidebarEvent::SerializeNeeded => {
 391                    this.serialize(cx);
 392                }
 393            }));
 394        self.sidebar = Some(Box::new(sidebar));
 395    }
 396
 397    pub fn sidebar(&self) -> Option<&dyn SidebarHandle> {
 398        self.sidebar.as_deref()
 399    }
 400
 401    pub fn set_sidebar_overlay(&mut self, overlay: Option<AnyView>, cx: &mut Context<Self>) {
 402        self.sidebar_overlay = overlay;
 403        cx.notify();
 404    }
 405
 406    pub fn sidebar_open(&self) -> bool {
 407        self.sidebar_open
 408    }
 409
 410    pub fn sidebar_has_notifications(&self, cx: &App) -> bool {
 411        self.sidebar
 412            .as_ref()
 413            .map_or(false, |s| s.has_notifications(cx))
 414    }
 415
 416    pub fn is_threads_list_view_active(&self, cx: &App) -> bool {
 417        self.sidebar
 418            .as_ref()
 419            .map_or(false, |s| s.is_threads_list_view_active(cx))
 420    }
 421
 422    pub fn multi_workspace_enabled(&self, cx: &App) -> bool {
 423        !DisableAiSettings::get_global(cx).disable_ai
 424    }
 425
 426    pub fn toggle_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 427        if !self.multi_workspace_enabled(cx) {
 428            return;
 429        }
 430
 431        if self.sidebar_open() {
 432            self.close_sidebar(window, cx);
 433        } else {
 434            self.previous_focus_handle = window.focused(cx);
 435            self.open_sidebar(cx);
 436            if let Some(sidebar) = &self.sidebar {
 437                sidebar.prepare_for_focus(window, cx);
 438                sidebar.focus(window, cx);
 439            }
 440        }
 441    }
 442
 443    pub fn close_sidebar_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 444        if !self.multi_workspace_enabled(cx) {
 445            return;
 446        }
 447
 448        if self.sidebar_open() {
 449            self.close_sidebar(window, cx);
 450        }
 451    }
 452
 453    pub fn focus_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 454        if !self.multi_workspace_enabled(cx) {
 455            return;
 456        }
 457
 458        if self.sidebar_open() {
 459            let sidebar_is_focused = self
 460                .sidebar
 461                .as_ref()
 462                .is_some_and(|s| s.focus_handle(cx).contains_focused(window, cx));
 463
 464            if sidebar_is_focused {
 465                self.restore_previous_focus(false, window, cx);
 466            } else {
 467                self.previous_focus_handle = window.focused(cx);
 468                if let Some(sidebar) = &self.sidebar {
 469                    sidebar.prepare_for_focus(window, cx);
 470                    sidebar.focus(window, cx);
 471                }
 472            }
 473        } else {
 474            self.previous_focus_handle = window.focused(cx);
 475            self.open_sidebar(cx);
 476            if let Some(sidebar) = &self.sidebar {
 477                sidebar.prepare_for_focus(window, cx);
 478                sidebar.focus(window, cx);
 479            }
 480        }
 481    }
 482
 483    pub fn open_sidebar(&mut self, cx: &mut Context<Self>) {
 484        self.sidebar_open = true;
 485        if let ActiveWorkspace::Transient(workspace) = &self.active_workspace {
 486            let workspace = workspace.clone();
 487            let index = self.promote_transient(workspace, cx);
 488            self.active_workspace = ActiveWorkspace::Persistent(index);
 489        }
 490        let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
 491        for workspace in self.workspaces.iter() {
 492            workspace.update(cx, |workspace, _cx| {
 493                workspace.set_sidebar_focus_handle(sidebar_focus_handle.clone());
 494            });
 495        }
 496        self.serialize(cx);
 497        cx.notify();
 498    }
 499
 500    pub fn close_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 501        self.sidebar_open = false;
 502        for workspace in self.workspaces.iter() {
 503            workspace.update(cx, |workspace, _cx| {
 504                workspace.set_sidebar_focus_handle(None);
 505            });
 506        }
 507        let sidebar_has_focus = self
 508            .sidebar
 509            .as_ref()
 510            .is_some_and(|s| s.focus_handle(cx).contains_focused(window, cx));
 511        if sidebar_has_focus {
 512            self.restore_previous_focus(true, window, cx);
 513        } else {
 514            self.previous_focus_handle.take();
 515        }
 516        self.serialize(cx);
 517        cx.notify();
 518    }
 519
 520    fn restore_previous_focus(&mut self, clear: bool, window: &mut Window, cx: &mut Context<Self>) {
 521        let focus_handle = if clear {
 522            self.previous_focus_handle.take()
 523        } else {
 524            self.previous_focus_handle.clone()
 525        };
 526
 527        if let Some(previous_focus) = focus_handle {
 528            previous_focus.focus(window, cx);
 529        } else {
 530            let pane = self.workspace().read(cx).active_pane().clone();
 531            window.focus(&pane.read(cx).focus_handle(cx), cx);
 532        }
 533    }
 534
 535    pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
 536        cx.spawn_in(window, async move |this, cx| {
 537            let workspaces = this.update(cx, |multi_workspace, _cx| {
 538                multi_workspace.workspaces().cloned().collect::<Vec<_>>()
 539            })?;
 540
 541            for workspace in workspaces {
 542                let should_continue = workspace
 543                    .update_in(cx, |workspace, window, cx| {
 544                        workspace.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 545                    })?
 546                    .await?;
 547                if !should_continue {
 548                    return anyhow::Ok(());
 549                }
 550            }
 551
 552            cx.update(|window, _cx| {
 553                window.remove_window();
 554            })?;
 555
 556            anyhow::Ok(())
 557        })
 558        .detach_and_log_err(cx);
 559    }
 560
 561    fn subscribe_to_workspace(
 562        workspace: &Entity<Workspace>,
 563        window: &Window,
 564        cx: &mut Context<Self>,
 565    ) {
 566        let project = workspace.read(cx).project().clone();
 567        cx.subscribe_in(&project, window, {
 568            let workspace = workspace.downgrade();
 569            move |this, _project, event, _window, cx| match event {
 570                project::Event::WorktreeAdded(_)
 571                | project::Event::WorktreeRemoved(_)
 572                | project::Event::WorktreeUpdatedRootRepoCommonDir(_) => {
 573                    if let Some(workspace) = workspace.upgrade() {
 574                        this.handle_workspace_key_change(&workspace, cx);
 575                    }
 576                }
 577                _ => {}
 578            }
 579        })
 580        .detach();
 581
 582        cx.subscribe_in(workspace, window, |this, workspace, event, window, cx| {
 583            if let WorkspaceEvent::Activate = event {
 584                this.activate(workspace.clone(), window, cx);
 585            }
 586        })
 587        .detach();
 588    }
 589
 590    fn handle_workspace_key_change(
 591        &mut self,
 592        workspace: &Entity<Workspace>,
 593        cx: &mut Context<Self>,
 594    ) {
 595        let workspace_id = workspace.entity_id();
 596        let old_key = self.project_group_key_for_workspace(workspace, cx);
 597        let new_key = workspace.read(cx).project_group_key(cx);
 598
 599        if new_key.path_list().paths().is_empty() || old_key == new_key {
 600            return;
 601        }
 602
 603        let active_workspace = self.workspace().clone();
 604
 605        self.set_workspace_group_key(workspace, new_key.clone());
 606
 607        let changed_root_paths = workspace.read(cx).root_paths(cx);
 608        let old_paths = old_key.path_list().paths();
 609        let new_paths = new_key.path_list().paths();
 610
 611        // Remove workspaces that already had the new key and have the same
 612        // root paths (true duplicates that this workspace is replacing).
 613        //
 614        // NOTE: These are dropped without prompting for unsaved changes because
 615        // the user explicitly added a folder that makes this workspace
 616        // identical to the duplicate — they are intentionally overwriting it.
 617        let duplicate_workspaces: Vec<Entity<Workspace>> = self
 618            .workspaces
 619            .iter()
 620            .filter(|ws| {
 621                ws.entity_id() != workspace_id
 622                    && self.project_group_key_for_workspace(ws, cx) == new_key
 623                    && ws.read(cx).root_paths(cx) == changed_root_paths
 624            })
 625            .cloned()
 626            .collect();
 627
 628        if duplicate_workspaces.contains(&active_workspace) {
 629            // The active workspace is among the duplicates — drop the
 630            // incoming workspace instead so the user stays where they are.
 631            self.detach_workspace(workspace, cx);
 632            self.workspaces.retain(|w| w != workspace);
 633        } else {
 634            for ws in &duplicate_workspaces {
 635                self.detach_workspace(ws, cx);
 636                self.workspaces.retain(|w| w != ws);
 637            }
 638        }
 639
 640        // Propagate folder adds/removes to linked worktree siblings
 641        // (different root paths, same old key) so they stay in the group.
 642        let group_workspaces: Vec<Entity<Workspace>> = self
 643            .workspaces
 644            .iter()
 645            .filter(|ws| {
 646                ws.entity_id() != workspace_id
 647                    && self.project_group_key_for_workspace(ws, cx) == old_key
 648            })
 649            .cloned()
 650            .collect();
 651
 652        for workspace in &group_workspaces {
 653            // Pre-set this to stop later WorktreeAdded events from triggering
 654            self.set_workspace_group_key(&workspace, new_key.clone());
 655
 656            let project = workspace.read(cx).project().clone();
 657
 658            for added_path in new_paths.iter().filter(|p| !old_paths.contains(p)) {
 659                project
 660                    .update(cx, |project, cx| {
 661                        project.find_or_create_worktree(added_path, true, cx)
 662                    })
 663                    .detach_and_log_err(cx);
 664            }
 665
 666            for removed_path in old_paths.iter().filter(|p| !new_paths.contains(p)) {
 667                project.update(cx, |project, cx| {
 668                    project.remove_worktree_for_main_worktree_path(removed_path, cx);
 669                });
 670            }
 671        }
 672
 673        // Restore the active workspace after removals may have shifted
 674        // the index. If the previously active workspace was removed,
 675        // fall back to the workspace whose key just changed.
 676        if let ActiveWorkspace::Persistent(_) = &self.active_workspace {
 677            let target = if self.workspaces.contains(&active_workspace) {
 678                &active_workspace
 679            } else {
 680                workspace
 681            };
 682            if let Some(new_index) = self.workspaces.iter().position(|ws| ws == target) {
 683                self.active_workspace = ActiveWorkspace::Persistent(new_index);
 684            }
 685        }
 686
 687        self.remove_stale_project_group_keys(cx);
 688
 689        let old_main_paths = old_key.path_list().clone();
 690        for added_path in new_paths.iter().filter(|p| !old_paths.contains(p)) {
 691            cx.emit(MultiWorkspaceEvent::WorktreePathAdded {
 692                old_main_paths: old_main_paths.clone(),
 693                added_path: added_path.clone(),
 694            });
 695        }
 696        for removed_path in old_paths.iter().filter(|p| !new_paths.contains(p)) {
 697            cx.emit(MultiWorkspaceEvent::WorktreePathRemoved {
 698                old_main_paths: old_main_paths.clone(),
 699                removed_path: removed_path.clone(),
 700            });
 701        }
 702
 703        self.serialize(cx);
 704        cx.notify();
 705    }
 706
 707    fn add_project_group_key(&mut self, project_group_key: ProjectGroupKey) {
 708        if project_group_key.path_list().paths().is_empty() {
 709            return;
 710        }
 711        if self.project_group_keys.contains(&project_group_key) {
 712            return;
 713        }
 714        // Store newest first so the vec is in "most recently added"
 715        self.project_group_keys.insert(0, project_group_key);
 716    }
 717
 718    pub(crate) fn set_workspace_group_key(
 719        &mut self,
 720        workspace: &Entity<Workspace>,
 721        project_group_key: ProjectGroupKey,
 722    ) {
 723        self.workspace_group_keys
 724            .insert(workspace.entity_id(), project_group_key.clone());
 725        self.add_project_group_key(project_group_key);
 726    }
 727
 728    pub fn project_group_key_for_workspace(
 729        &self,
 730        workspace: &Entity<Workspace>,
 731        cx: &App,
 732    ) -> ProjectGroupKey {
 733        self.workspace_group_keys
 734            .get(&workspace.entity_id())
 735            .cloned()
 736            .unwrap_or_else(|| workspace.read(cx).project_group_key(cx))
 737    }
 738
 739    fn remove_stale_project_group_keys(&mut self, cx: &App) {
 740        let workspace_keys: HashSet<ProjectGroupKey> = self
 741            .workspaces
 742            .iter()
 743            .map(|workspace| self.project_group_key_for_workspace(workspace, cx))
 744            .collect();
 745        self.project_group_keys
 746            .retain(|key| workspace_keys.contains(key));
 747    }
 748
 749    pub fn restore_project_group_keys(&mut self, keys: Vec<ProjectGroupKey>) {
 750        let mut restored: Vec<ProjectGroupKey> = Vec::with_capacity(keys.len());
 751        for key in keys {
 752            if key.path_list().paths().is_empty() {
 753                continue;
 754            }
 755            if !restored.contains(&key) {
 756                restored.push(key);
 757            }
 758        }
 759        for existing_key in &self.project_group_keys {
 760            if !restored.contains(existing_key) {
 761                restored.push(existing_key.clone());
 762            }
 763        }
 764        self.project_group_keys = restored;
 765    }
 766
 767    pub fn project_group_keys(&self) -> impl Iterator<Item = &ProjectGroupKey> {
 768        self.project_group_keys.iter()
 769    }
 770
 771    /// Returns the project groups, ordered by most recently added.
 772    pub fn project_groups(
 773        &self,
 774        cx: &App,
 775    ) -> impl Iterator<Item = (ProjectGroupKey, Vec<Entity<Workspace>>)> {
 776        let mut groups = self
 777            .project_group_keys
 778            .iter()
 779            .map(|key| (key.clone(), Vec::new()))
 780            .collect::<Vec<_>>();
 781        for workspace in &self.workspaces {
 782            let key = self.project_group_key_for_workspace(workspace, cx);
 783            if let Some((_, workspaces)) = groups.iter_mut().find(|(k, _)| k == &key) {
 784                workspaces.push(workspace.clone());
 785            }
 786        }
 787        groups.into_iter()
 788    }
 789
 790    pub fn workspaces_for_project_group(
 791        &self,
 792        project_group_key: &ProjectGroupKey,
 793        cx: &App,
 794    ) -> impl Iterator<Item = &Entity<Workspace>> {
 795        self.workspaces.iter().filter(move |workspace| {
 796            self.project_group_key_for_workspace(workspace, cx) == *project_group_key
 797        })
 798    }
 799
 800    pub fn remove_folder_from_project_group(
 801        &mut self,
 802        project_group_key: &ProjectGroupKey,
 803        path: &Path,
 804        cx: &mut Context<Self>,
 805    ) {
 806        let new_path_list = project_group_key.path_list().without_path(path);
 807        if new_path_list.is_empty() {
 808            return;
 809        }
 810
 811        let new_key = ProjectGroupKey::new(project_group_key.host(), new_path_list);
 812
 813        let workspaces: Vec<_> = self
 814            .workspaces_for_project_group(project_group_key, cx)
 815            .cloned()
 816            .collect();
 817
 818        self.add_project_group_key(new_key);
 819
 820        for workspace in workspaces {
 821            let project = workspace.read(cx).project().clone();
 822            project.update(cx, |project, cx| {
 823                project.remove_worktree_for_main_worktree_path(path, cx);
 824            });
 825        }
 826
 827        self.serialize(cx);
 828        cx.notify();
 829    }
 830
 831    pub fn prompt_to_add_folders_to_project_group(
 832        &mut self,
 833        key: &ProjectGroupKey,
 834        window: &mut Window,
 835        cx: &mut Context<Self>,
 836    ) {
 837        let paths = self.workspace().update(cx, |workspace, cx| {
 838            workspace.prompt_for_open_path(
 839                PathPromptOptions {
 840                    files: false,
 841                    directories: true,
 842                    multiple: true,
 843                    prompt: None,
 844                },
 845                DirectoryLister::Project(workspace.project().clone()),
 846                window,
 847                cx,
 848            )
 849        });
 850
 851        let key = key.clone();
 852        cx.spawn_in(window, async move |this, cx| {
 853            if let Some(new_paths) = paths.await.ok().flatten() {
 854                if !new_paths.is_empty() {
 855                    this.update(cx, |multi_workspace, cx| {
 856                        multi_workspace.add_folders_to_project_group(&key, new_paths, cx);
 857                    })?;
 858                }
 859            }
 860            anyhow::Ok(())
 861        })
 862        .detach_and_log_err(cx);
 863    }
 864
 865    pub fn add_folders_to_project_group(
 866        &mut self,
 867        project_group_key: &ProjectGroupKey,
 868        new_paths: Vec<PathBuf>,
 869        cx: &mut Context<Self>,
 870    ) {
 871        let mut all_paths: Vec<PathBuf> = project_group_key.path_list().paths().to_vec();
 872        all_paths.extend(new_paths.iter().cloned());
 873        let new_path_list = PathList::new(&all_paths);
 874        let new_key = ProjectGroupKey::new(project_group_key.host(), new_path_list);
 875
 876        let workspaces: Vec<_> = self
 877            .workspaces_for_project_group(project_group_key, cx)
 878            .cloned()
 879            .collect();
 880
 881        self.add_project_group_key(new_key);
 882
 883        for workspace in workspaces {
 884            let project = workspace.read(cx).project().clone();
 885            for path in &new_paths {
 886                project
 887                    .update(cx, |project, cx| {
 888                        project.find_or_create_worktree(path, true, cx)
 889                    })
 890                    .detach_and_log_err(cx);
 891            }
 892        }
 893
 894        self.serialize(cx);
 895        cx.notify();
 896    }
 897
 898    pub fn remove_project_group(
 899        &mut self,
 900        key: &ProjectGroupKey,
 901        window: &mut Window,
 902        cx: &mut Context<Self>,
 903    ) -> Task<Result<bool>> {
 904        let workspaces: Vec<_> = self
 905            .workspaces_for_project_group(key, cx)
 906            .cloned()
 907            .collect();
 908
 909        // Compute the neighbor while the key is still in the list.
 910        let neighbor_key = {
 911            let pos = self.project_group_keys.iter().position(|k| k == key);
 912            pos.and_then(|pos| {
 913                // Keys are in display order, so pos+1 is below
 914                // and pos-1 is above. Try below first.
 915                self.project_group_keys.get(pos + 1).or_else(|| {
 916                    pos.checked_sub(1)
 917                        .and_then(|i| self.project_group_keys.get(i))
 918                })
 919            })
 920            .cloned()
 921        };
 922
 923        // Now remove the key.
 924        self.project_group_keys.retain(|k| k != key);
 925
 926        self.remove(
 927            workspaces,
 928            move |this, window, cx| {
 929                if let Some(neighbor_key) = neighbor_key {
 930                    return this.find_or_create_local_workspace(
 931                        neighbor_key.path_list().clone(),
 932                        window,
 933                        cx,
 934                    );
 935                }
 936
 937                // No other project groups remain — create an empty workspace.
 938                let app_state = this.workspace().read(cx).app_state().clone();
 939                let project = Project::local(
 940                    app_state.client.clone(),
 941                    app_state.node_runtime.clone(),
 942                    app_state.user_store.clone(),
 943                    app_state.languages.clone(),
 944                    app_state.fs.clone(),
 945                    None,
 946                    project::LocalProjectFlags::default(),
 947                    cx,
 948                );
 949                let new_workspace =
 950                    cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
 951                Task::ready(Ok(new_workspace))
 952            },
 953            window,
 954            cx,
 955        )
 956    }
 957
 958    /// Finds an existing workspace whose root paths and host exactly match.
 959    pub fn workspace_for_paths(
 960        &self,
 961        path_list: &PathList,
 962        host: Option<&RemoteConnectionOptions>,
 963        cx: &App,
 964    ) -> Option<Entity<Workspace>> {
 965        self.workspaces
 966            .iter()
 967            .find(|ws| {
 968                let key = ws.read(cx).project_group_key(cx);
 969                key.host().as_ref() == host
 970                    && PathList::new(&ws.read(cx).root_paths(cx)) == *path_list
 971            })
 972            .cloned()
 973    }
 974
 975    /// Finds an existing workspace whose paths match, or creates a new one.
 976    ///
 977    /// For local projects (`host` is `None`), this delegates to
 978    /// [`Self::find_or_create_local_workspace`]. For remote projects, it
 979    /// tries an exact path match and, if no existing workspace is found,
 980    /// calls `connect_remote` to establish a connection and creates a new
 981    /// remote workspace.
 982    ///
 983    /// The `connect_remote` closure is responsible for any user-facing
 984    /// connection UI (e.g. password prompts). It receives the connection
 985    /// options and should return a [`Task`] that resolves to the
 986    /// [`RemoteClient`] session, or `None` if the connection was
 987    /// cancelled.
 988    pub fn find_or_create_workspace(
 989        &mut self,
 990        paths: PathList,
 991        host: Option<RemoteConnectionOptions>,
 992        provisional_project_group_key: Option<ProjectGroupKey>,
 993        connect_remote: impl FnOnce(
 994            RemoteConnectionOptions,
 995            &mut Window,
 996            &mut Context<Self>,
 997        ) -> Task<Result<Option<Entity<remote::RemoteClient>>>>
 998        + 'static,
 999        window: &mut Window,
1000        cx: &mut Context<Self>,
1001    ) -> Task<Result<Entity<Workspace>>> {
1002        if let Some(workspace) = self.workspace_for_paths(&paths, host.as_ref(), cx) {
1003            self.activate(workspace.clone(), window, cx);
1004            return Task::ready(Ok(workspace));
1005        }
1006
1007        let Some(connection_options) = host else {
1008            return self.find_or_create_local_workspace(paths, window, cx);
1009        };
1010
1011        let app_state = self.workspace().read(cx).app_state().clone();
1012        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
1013        let connect_task = connect_remote(connection_options.clone(), window, cx);
1014        let paths_vec = paths.paths().to_vec();
1015
1016        cx.spawn(async move |_this, cx| {
1017            let session = connect_task
1018                .await?
1019                .ok_or_else(|| anyhow::anyhow!("Remote connection was cancelled"))?;
1020
1021            let new_project = cx.update(|cx| {
1022                Project::remote(
1023                    session,
1024                    app_state.client.clone(),
1025                    app_state.node_runtime.clone(),
1026                    app_state.user_store.clone(),
1027                    app_state.languages.clone(),
1028                    app_state.fs.clone(),
1029                    true,
1030                    cx,
1031                )
1032            });
1033
1034            let window_handle =
1035                window_handle.ok_or_else(|| anyhow::anyhow!("Window is not a MultiWorkspace"))?;
1036
1037            open_remote_project_with_existing_connection(
1038                connection_options,
1039                new_project,
1040                paths_vec,
1041                app_state,
1042                window_handle,
1043                provisional_project_group_key,
1044                cx,
1045            )
1046            .await?;
1047
1048            window_handle.update(cx, |multi_workspace, window, cx| {
1049                let workspace = multi_workspace.workspace().clone();
1050                multi_workspace.add(workspace.clone(), window, cx);
1051                workspace
1052            })
1053        })
1054    }
1055
1056    /// Finds an existing workspace in this multi-workspace whose paths match,
1057    /// or creates a new one (deserializing its saved state from the database).
1058    /// Never searches other windows or matches workspaces with a superset of
1059    /// the requested paths.
1060    pub fn find_or_create_local_workspace(
1061        &mut self,
1062        path_list: PathList,
1063        window: &mut Window,
1064        cx: &mut Context<Self>,
1065    ) -> Task<Result<Entity<Workspace>>> {
1066        if let Some(workspace) = self.workspace_for_paths(&path_list, None, cx) {
1067            self.activate(workspace.clone(), window, cx);
1068            return Task::ready(Ok(workspace));
1069        }
1070
1071        if let Some(transient) = self.active_workspace.transient_workspace() {
1072            if transient.read(cx).project_group_key(cx).path_list() == &path_list {
1073                return Task::ready(Ok(transient.clone()));
1074            }
1075        }
1076
1077        let paths = path_list.paths().to_vec();
1078        let app_state = self.workspace().read(cx).app_state().clone();
1079        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
1080
1081        cx.spawn(async move |_this, cx| {
1082            let result = cx
1083                .update(|cx| {
1084                    Workspace::new_local(
1085                        paths,
1086                        app_state,
1087                        requesting_window,
1088                        None,
1089                        None,
1090                        OpenMode::Activate,
1091                        cx,
1092                    )
1093                })
1094                .await?;
1095            Ok(result.workspace)
1096        })
1097    }
1098
1099    pub fn workspace(&self) -> &Entity<Workspace> {
1100        match &self.active_workspace {
1101            ActiveWorkspace::Persistent(index) => &self.workspaces[*index],
1102            ActiveWorkspace::Transient(workspace) => workspace,
1103        }
1104    }
1105
1106    pub fn workspaces(&self) -> impl Iterator<Item = &Entity<Workspace>> {
1107        self.workspaces
1108            .iter()
1109            .chain(self.active_workspace.transient_workspace())
1110    }
1111
1112    /// Adds a workspace to this window as persistent without changing which
1113    /// workspace is active. Unlike `activate()`, this always inserts into the
1114    /// persistent list regardless of sidebar state — it's used for system-
1115    /// initiated additions like deserialization and worktree discovery.
1116    pub fn add(&mut self, workspace: Entity<Workspace>, window: &Window, cx: &mut Context<Self>) {
1117        self.insert_workspace(workspace, window, cx);
1118    }
1119
1120    /// Ensures the workspace is in the multiworkspace and makes it the active one.
1121    pub fn activate(
1122        &mut self,
1123        workspace: Entity<Workspace>,
1124        window: &mut Window,
1125        cx: &mut Context<Self>,
1126    ) {
1127        // Re-activating the current workspace is a no-op.
1128        if self.workspace() == &workspace {
1129            self.focus_active_workspace(window, cx);
1130            return;
1131        }
1132
1133        // Resolve where we're going.
1134        let new_index = if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
1135            Some(index)
1136        } else if self.sidebar_open {
1137            Some(self.insert_workspace(workspace.clone(), &*window, cx))
1138        } else {
1139            None
1140        };
1141
1142        // Transition the active workspace.
1143        if let Some(index) = new_index {
1144            if let Some(old) = self.active_workspace.set_persistent(index) {
1145                if self.sidebar_open {
1146                    self.promote_transient(old, cx);
1147                } else {
1148                    self.detach_workspace(&old, cx);
1149                }
1150            }
1151        } else {
1152            Self::subscribe_to_workspace(&workspace, window, cx);
1153            let weak_self = cx.weak_entity();
1154            workspace.update(cx, |workspace, cx| {
1155                workspace.set_multi_workspace(weak_self, cx);
1156            });
1157            if let Some(old) = self.active_workspace.set_transient(workspace) {
1158                self.detach_workspace(&old, cx);
1159            }
1160        }
1161
1162        cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
1163        self.serialize(cx);
1164        self.focus_active_workspace(window, cx);
1165        cx.notify();
1166    }
1167
1168    /// Promotes the currently active workspace to persistent if it is
1169    /// transient, so it is retained across workspace switches even when
1170    /// the sidebar is closed. No-op if the workspace is already persistent.
1171    pub fn retain_active_workspace(&mut self, cx: &mut Context<Self>) {
1172        if let ActiveWorkspace::Transient(workspace) = &self.active_workspace {
1173            let workspace = workspace.clone();
1174            let index = self.promote_transient(workspace, cx);
1175            self.active_workspace = ActiveWorkspace::Persistent(index);
1176            self.serialize(cx);
1177            cx.notify();
1178        }
1179    }
1180
1181    /// Promotes a former transient workspace into the persistent list.
1182    /// Returns the index of the newly inserted workspace.
1183    fn promote_transient(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) -> usize {
1184        let project_group_key = self.project_group_key_for_workspace(&workspace, cx);
1185        self.set_workspace_group_key(&workspace, project_group_key);
1186        self.workspaces.push(workspace.clone());
1187        cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
1188        self.workspaces.len() - 1
1189    }
1190
1191    /// Collapses to a single transient workspace, discarding all persistent
1192    /// workspaces. Used when multi-workspace is disabled (e.g. disable_ai).
1193    fn collapse_to_single_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1194        if self.sidebar_open {
1195            self.close_sidebar(window, cx);
1196        }
1197        let active = self.workspace().clone();
1198        for workspace in std::mem::take(&mut self.workspaces) {
1199            if workspace != active {
1200                self.detach_workspace(&workspace, cx);
1201            }
1202        }
1203        self.project_group_keys.clear();
1204        self.workspace_group_keys.clear();
1205        self.active_workspace = ActiveWorkspace::Transient(active);
1206        cx.notify();
1207    }
1208
1209    /// Inserts a workspace into the list if not already present. Returns the
1210    /// index of the workspace (existing or newly inserted). Does not change
1211    /// the active workspace index.
1212    fn insert_workspace(
1213        &mut self,
1214        workspace: Entity<Workspace>,
1215        window: &Window,
1216        cx: &mut Context<Self>,
1217    ) -> usize {
1218        if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
1219            index
1220        } else {
1221            let project_group_key = self.project_group_key_for_workspace(&workspace, cx);
1222
1223            Self::subscribe_to_workspace(&workspace, window, cx);
1224            self.sync_sidebar_to_workspace(&workspace, cx);
1225            let weak_self = cx.weak_entity();
1226            workspace.update(cx, |workspace, cx| {
1227                workspace.set_multi_workspace(weak_self, cx);
1228            });
1229
1230            self.set_workspace_group_key(&workspace, project_group_key);
1231            self.workspaces.push(workspace.clone());
1232            cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
1233            cx.notify();
1234            self.workspaces.len() - 1
1235        }
1236    }
1237
1238    /// Detaches a workspace: clears session state, DB binding, cached
1239    /// group key, and emits `WorkspaceRemoved`. The DB row is preserved
1240    /// so the workspace still appears in the recent-projects list.
1241    fn detach_workspace(&mut self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
1242        self.workspace_group_keys.remove(&workspace.entity_id());
1243        cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(workspace.entity_id()));
1244        workspace.update(cx, |workspace, _cx| {
1245            workspace.session_id.take();
1246            workspace._schedule_serialize_workspace.take();
1247            workspace._serialize_workspace_task.take();
1248        });
1249
1250        if let Some(workspace_id) = workspace.read(cx).database_id() {
1251            let db = crate::persistence::WorkspaceDb::global(cx);
1252            self.pending_removal_tasks.retain(|task| !task.is_ready());
1253            self.pending_removal_tasks
1254                .push(cx.background_spawn(async move {
1255                    db.set_session_binding(workspace_id, None, None)
1256                        .await
1257                        .log_err();
1258                }));
1259        }
1260    }
1261
1262    fn sync_sidebar_to_workspace(&self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
1263        if self.sidebar_open() {
1264            let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
1265            workspace.update(cx, |workspace, _| {
1266                workspace.set_sidebar_focus_handle(sidebar_focus_handle);
1267            });
1268        }
1269    }
1270
1271    pub(crate) fn serialize(&mut self, cx: &mut Context<Self>) {
1272        self._serialize_task = Some(cx.spawn(async move |this, cx| {
1273            let Some((window_id, state)) = this
1274                .read_with(cx, |this, cx| {
1275                    let state = MultiWorkspaceState {
1276                        active_workspace_id: this.workspace().read(cx).database_id(),
1277                        project_group_keys: this
1278                            .project_group_keys()
1279                            .cloned()
1280                            .map(Into::into)
1281                            .collect::<Vec<_>>(),
1282                        sidebar_open: this.sidebar_open,
1283                        sidebar_state: this.sidebar.as_ref().and_then(|s| s.serialized_state(cx)),
1284                    };
1285                    (this.window_id, state)
1286                })
1287                .ok()
1288            else {
1289                return;
1290            };
1291            let kvp = cx.update(|cx| db::kvp::KeyValueStore::global(cx));
1292            crate::persistence::write_multi_workspace_state(&kvp, window_id, state).await;
1293        }));
1294    }
1295
1296    /// Returns the in-flight serialization task (if any) so the caller can
1297    /// await it. Used by the quit handler to ensure pending DB writes
1298    /// complete before the process exits.
1299    pub fn flush_serialization(&mut self) -> Task<()> {
1300        self._serialize_task.take().unwrap_or(Task::ready(()))
1301    }
1302
1303    fn app_will_quit(&mut self, _cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
1304        let mut tasks: Vec<Task<()>> = Vec::new();
1305        if let Some(task) = self._serialize_task.take() {
1306            tasks.push(task);
1307        }
1308        tasks.extend(std::mem::take(&mut self.pending_removal_tasks));
1309
1310        async move {
1311            futures::future::join_all(tasks).await;
1312        }
1313    }
1314
1315    pub fn focus_active_workspace(&self, window: &mut Window, cx: &mut App) {
1316        // If a dock panel is zoomed, focus it instead of the center pane.
1317        // Otherwise, focusing the center pane triggers dismiss_zoomed_items_to_reveal
1318        // which closes the zoomed dock.
1319        let focus_handle = {
1320            let workspace = self.workspace().read(cx);
1321            let mut target = None;
1322            for dock in workspace.all_docks() {
1323                let dock = dock.read(cx);
1324                if dock.is_open() {
1325                    if let Some(panel) = dock.active_panel() {
1326                        if panel.is_zoomed(window, cx) {
1327                            target = Some(panel.panel_focus_handle(cx));
1328                            break;
1329                        }
1330                    }
1331                }
1332            }
1333            target.unwrap_or_else(|| {
1334                let pane = workspace.active_pane().clone();
1335                pane.read(cx).focus_handle(cx)
1336            })
1337        };
1338        window.focus(&focus_handle, cx);
1339    }
1340
1341    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
1342        self.workspace().read(cx).panel::<T>(cx)
1343    }
1344
1345    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
1346        self.workspace().read(cx).active_modal::<V>(cx)
1347    }
1348
1349    pub fn add_panel<T: Panel>(
1350        &mut self,
1351        panel: Entity<T>,
1352        window: &mut Window,
1353        cx: &mut Context<Self>,
1354    ) {
1355        self.workspace().update(cx, |workspace, cx| {
1356            workspace.add_panel(panel, window, cx);
1357        });
1358    }
1359
1360    pub fn focus_panel<T: Panel>(
1361        &mut self,
1362        window: &mut Window,
1363        cx: &mut Context<Self>,
1364    ) -> Option<Entity<T>> {
1365        self.workspace()
1366            .update(cx, |workspace, cx| workspace.focus_panel::<T>(window, cx))
1367    }
1368
1369    // used in a test
1370    pub fn toggle_modal<V: ModalView, B>(
1371        &mut self,
1372        window: &mut Window,
1373        cx: &mut Context<Self>,
1374        build: B,
1375    ) where
1376        B: FnOnce(&mut Window, &mut gpui::Context<V>) -> V,
1377    {
1378        self.workspace().update(cx, |workspace, cx| {
1379            workspace.toggle_modal(window, cx, build);
1380        });
1381    }
1382
1383    pub fn toggle_dock(
1384        &mut self,
1385        dock_side: DockPosition,
1386        window: &mut Window,
1387        cx: &mut Context<Self>,
1388    ) {
1389        self.workspace().update(cx, |workspace, cx| {
1390            workspace.toggle_dock(dock_side, window, cx);
1391        });
1392    }
1393
1394    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
1395        self.workspace().read(cx).active_item_as::<I>(cx)
1396    }
1397
1398    pub fn items_of_type<'a, T: Item>(
1399        &'a self,
1400        cx: &'a App,
1401    ) -> impl 'a + Iterator<Item = Entity<T>> {
1402        self.workspace().read(cx).items_of_type::<T>(cx)
1403    }
1404
1405    pub fn database_id(&self, cx: &App) -> Option<WorkspaceId> {
1406        self.workspace().read(cx).database_id()
1407    }
1408
1409    pub fn take_pending_removal_tasks(&mut self) -> Vec<Task<()>> {
1410        let tasks: Vec<Task<()>> = std::mem::take(&mut self.pending_removal_tasks)
1411            .into_iter()
1412            .filter(|task| !task.is_ready())
1413            .collect();
1414        tasks
1415    }
1416
1417    #[cfg(any(test, feature = "test-support"))]
1418    pub fn assert_project_group_key_integrity(&self, cx: &App) -> anyhow::Result<()> {
1419        let stored_keys: HashSet<&ProjectGroupKey> = self.project_group_keys().collect();
1420
1421        let workspace_group_keys: HashSet<&ProjectGroupKey> =
1422            self.workspace_group_keys.values().collect();
1423        let extra_keys = &workspace_group_keys - &stored_keys;
1424        anyhow::ensure!(
1425            extra_keys.is_empty(),
1426            "workspace_group_keys values not in project_group_keys: {:?}",
1427            extra_keys,
1428        );
1429
1430        let cached_ids: HashSet<EntityId> = self.workspace_group_keys.keys().copied().collect();
1431        let workspace_ids: HashSet<EntityId> =
1432            self.workspaces.iter().map(|ws| ws.entity_id()).collect();
1433        anyhow::ensure!(
1434            cached_ids == workspace_ids,
1435            "workspace_group_keys entity IDs don't match workspaces.\n\
1436             only in cache: {:?}\n\
1437             only in workspaces: {:?}",
1438            &cached_ids - &workspace_ids,
1439            &workspace_ids - &cached_ids,
1440        );
1441
1442        for workspace in self.workspaces() {
1443            let live_key = workspace.read(cx).project_group_key(cx);
1444            let cached_key = &self.workspace_group_keys[&workspace.entity_id()];
1445            anyhow::ensure!(
1446                *cached_key == live_key,
1447                "workspace {:?} has live key {:?} but cached key {:?}",
1448                workspace.entity_id(),
1449                live_key,
1450                cached_key,
1451            );
1452        }
1453
1454        Ok(())
1455    }
1456
1457    #[cfg(any(test, feature = "test-support"))]
1458    pub fn set_random_database_id(&mut self, cx: &mut Context<Self>) {
1459        self.workspace().update(cx, |workspace, _cx| {
1460            workspace.set_random_database_id();
1461        });
1462    }
1463
1464    #[cfg(any(test, feature = "test-support"))]
1465    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
1466        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
1467        Self::new(workspace, window, cx)
1468    }
1469
1470    #[cfg(any(test, feature = "test-support"))]
1471    pub fn test_add_workspace(
1472        &mut self,
1473        project: Entity<Project>,
1474        window: &mut Window,
1475        cx: &mut Context<Self>,
1476    ) -> Entity<Workspace> {
1477        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
1478        self.activate(workspace.clone(), window, cx);
1479        workspace
1480    }
1481
1482    #[cfg(any(test, feature = "test-support"))]
1483    pub fn create_test_workspace(
1484        &mut self,
1485        window: &mut Window,
1486        cx: &mut Context<Self>,
1487    ) -> Task<()> {
1488        let app_state = self.workspace().read(cx).app_state().clone();
1489        let project = Project::local(
1490            app_state.client.clone(),
1491            app_state.node_runtime.clone(),
1492            app_state.user_store.clone(),
1493            app_state.languages.clone(),
1494            app_state.fs.clone(),
1495            None,
1496            project::LocalProjectFlags::default(),
1497            cx,
1498        );
1499        let new_workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
1500        self.activate(new_workspace.clone(), window, cx);
1501
1502        let weak_workspace = new_workspace.downgrade();
1503        let db = crate::persistence::WorkspaceDb::global(cx);
1504        cx.spawn_in(window, async move |this, cx| {
1505            let workspace_id = db.next_id().await.unwrap();
1506            let workspace = weak_workspace.upgrade().unwrap();
1507            let task: Task<()> = this
1508                .update_in(cx, |this, window, cx| {
1509                    let session_id = workspace.read(cx).session_id();
1510                    let window_id = window.window_handle().window_id().as_u64();
1511                    workspace.update(cx, |workspace, _cx| {
1512                        workspace.set_database_id(workspace_id);
1513                    });
1514                    this.serialize(cx);
1515                    let db = db.clone();
1516                    cx.background_spawn(async move {
1517                        db.set_session_binding(workspace_id, session_id, Some(window_id))
1518                            .await
1519                            .log_err();
1520                    })
1521                })
1522                .unwrap();
1523            task.await
1524        })
1525    }
1526
1527    /// Removes one or more workspaces from this multi-workspace.
1528    ///
1529    /// If the active workspace is among those being removed,
1530    /// `fallback_workspace` is called **synchronously before the removal
1531    /// begins** to produce a `Task` that resolves to the workspace that
1532    /// should become active. The fallback must not be one of the
1533    /// workspaces being removed.
1534    ///
1535    /// Returns `true` if any workspaces were actually removed.
1536    pub fn remove(
1537        &mut self,
1538        workspaces: impl IntoIterator<Item = Entity<Workspace>>,
1539        fallback_workspace: impl FnOnce(
1540            &mut Self,
1541            &mut Window,
1542            &mut Context<Self>,
1543        ) -> Task<Result<Entity<Workspace>>>,
1544        window: &mut Window,
1545        cx: &mut Context<Self>,
1546    ) -> Task<Result<bool>> {
1547        let workspaces: Vec<_> = workspaces.into_iter().collect();
1548
1549        if workspaces.is_empty() {
1550            return Task::ready(Ok(false));
1551        }
1552
1553        let removing_active = workspaces.iter().any(|ws| ws == self.workspace());
1554        let original_active = self.workspace().clone();
1555
1556        let fallback_task = removing_active.then(|| fallback_workspace(self, window, cx));
1557
1558        cx.spawn_in(window, async move |this, cx| {
1559            // Prompt each workspace for unsaved changes. If any workspace
1560            // has dirty buffers, save_all_internal will emit Activate to
1561            // bring it into view before showing the save dialog.
1562            for workspace in &workspaces {
1563                let should_continue = workspace
1564                    .update_in(cx, |workspace, window, cx| {
1565                        workspace.save_all_internal(crate::SaveIntent::Close, window, cx)
1566                    })?
1567                    .await?;
1568
1569                if !should_continue {
1570                    return Ok(false);
1571                }
1572            }
1573
1574            // If we're removing the active workspace, await the
1575            // fallback and switch to it before tearing anything down.
1576            // Otherwise restore the original active workspace in case
1577            // prompting switched away from it.
1578            if let Some(fallback_task) = fallback_task {
1579                let new_active = fallback_task.await?;
1580
1581                this.update_in(cx, |this, window, cx| {
1582                    assert!(
1583                        !workspaces.contains(&new_active),
1584                        "fallback workspace must not be one of the workspaces being removed"
1585                    );
1586                    this.activate(new_active, window, cx);
1587                })?;
1588            } else {
1589                this.update_in(cx, |this, window, cx| {
1590                    if *this.workspace() != original_active {
1591                        this.activate(original_active, window, cx);
1592                    }
1593                })?;
1594            }
1595
1596            // Actually remove the workspaces.
1597            this.update_in(cx, |this, _, cx| {
1598                // Save a handle to the active workspace so we can restore
1599                // its index after the removals shift the vec around.
1600                let active_workspace = this.workspace().clone();
1601
1602                let mut removed_workspaces: Vec<Entity<Workspace>> = Vec::new();
1603
1604                this.workspaces.retain(|ws| {
1605                    if workspaces.contains(ws) {
1606                        removed_workspaces.push(ws.clone());
1607                        false
1608                    } else {
1609                        true
1610                    }
1611                });
1612
1613                for workspace in &removed_workspaces {
1614                    this.detach_workspace(workspace, cx);
1615                }
1616
1617                let removed_any = !removed_workspaces.is_empty();
1618
1619                if removed_any {
1620                    // Restore the active workspace index after removals.
1621                    if let Some(new_index) = this
1622                        .workspaces
1623                        .iter()
1624                        .position(|ws| ws == &active_workspace)
1625                    {
1626                        this.active_workspace = ActiveWorkspace::Persistent(new_index);
1627                    }
1628
1629                    this.serialize(cx);
1630                    cx.notify();
1631                }
1632
1633                Ok(removed_any)
1634            })?
1635        })
1636    }
1637
1638    pub fn open_project(
1639        &mut self,
1640        paths: Vec<PathBuf>,
1641        open_mode: OpenMode,
1642        window: &mut Window,
1643        cx: &mut Context<Self>,
1644    ) -> Task<Result<Entity<Workspace>>> {
1645        if self.multi_workspace_enabled(cx) {
1646            self.find_or_create_local_workspace(PathList::new(&paths), window, cx)
1647        } else {
1648            let workspace = self.workspace().clone();
1649            cx.spawn_in(window, async move |_this, cx| {
1650                let should_continue = workspace
1651                    .update_in(cx, |workspace, window, cx| {
1652                        workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx)
1653                    })?
1654                    .await?;
1655                if should_continue {
1656                    workspace
1657                        .update_in(cx, |workspace, window, cx| {
1658                            workspace.open_workspace_for_paths(open_mode, paths, window, cx)
1659                        })?
1660                        .await
1661                } else {
1662                    Ok(workspace)
1663                }
1664            })
1665        }
1666    }
1667}
1668
1669impl Render for MultiWorkspace {
1670    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1671        let multi_workspace_enabled = self.multi_workspace_enabled(cx);
1672        let sidebar_side = self.sidebar_side(cx);
1673        let sidebar_on_right = sidebar_side == SidebarSide::Right;
1674
1675        let sidebar: Option<AnyElement> = if multi_workspace_enabled && self.sidebar_open() {
1676            self.sidebar.as_ref().map(|sidebar_handle| {
1677                let weak = cx.weak_entity();
1678
1679                let sidebar_width = sidebar_handle.width(cx);
1680                let resize_handle = deferred(
1681                    div()
1682                        .id("sidebar-resize-handle")
1683                        .absolute()
1684                        .when(!sidebar_on_right, |el| {
1685                            el.right(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1686                        })
1687                        .when(sidebar_on_right, |el| {
1688                            el.left(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1689                        })
1690                        .top(px(0.))
1691                        .h_full()
1692                        .w(SIDEBAR_RESIZE_HANDLE_SIZE)
1693                        .cursor_col_resize()
1694                        .on_drag(DraggedSidebar, |dragged, _, _, cx| {
1695                            cx.stop_propagation();
1696                            cx.new(|_| dragged.clone())
1697                        })
1698                        .on_mouse_down(MouseButton::Left, |_, _, cx| {
1699                            cx.stop_propagation();
1700                        })
1701                        .on_mouse_up(MouseButton::Left, move |event, _, cx| {
1702                            if event.click_count == 2 {
1703                                weak.update(cx, |this, cx| {
1704                                    if let Some(sidebar) = this.sidebar.as_mut() {
1705                                        sidebar.set_width(None, cx);
1706                                    }
1707                                    this.serialize(cx);
1708                                })
1709                                .ok();
1710                                cx.stop_propagation();
1711                            } else {
1712                                weak.update(cx, |this, cx| {
1713                                    this.serialize(cx);
1714                                })
1715                                .ok();
1716                            }
1717                        })
1718                        .occlude(),
1719                );
1720
1721                div()
1722                    .id("sidebar-container")
1723                    .relative()
1724                    .h_full()
1725                    .w(sidebar_width)
1726                    .flex_shrink_0()
1727                    .child(sidebar_handle.to_any())
1728                    .child(resize_handle)
1729                    .into_any_element()
1730            })
1731        } else {
1732            None
1733        };
1734
1735        let (left_sidebar, right_sidebar) = if sidebar_on_right {
1736            (None, sidebar)
1737        } else {
1738            (sidebar, None)
1739        };
1740
1741        let ui_font = theme_settings::setup_ui_font(window, cx);
1742        let text_color = cx.theme().colors().text;
1743
1744        let workspace = self.workspace().clone();
1745        let workspace_key_context = workspace.update(cx, |workspace, cx| workspace.key_context(cx));
1746        let root = workspace.update(cx, |workspace, cx| workspace.actions(h_flex(), window, cx));
1747
1748        client_side_decorations(
1749            root.key_context(workspace_key_context)
1750                .relative()
1751                .size_full()
1752                .font(ui_font)
1753                .text_color(text_color)
1754                .on_action(cx.listener(Self::close_window))
1755                .when(self.multi_workspace_enabled(cx), |this| {
1756                    this.on_action(cx.listener(
1757                        |this: &mut Self, _: &ToggleWorkspaceSidebar, window, cx| {
1758                            this.toggle_sidebar(window, cx);
1759                        },
1760                    ))
1761                    .on_action(cx.listener(
1762                        |this: &mut Self, _: &CloseWorkspaceSidebar, window, cx| {
1763                            this.close_sidebar_action(window, cx);
1764                        },
1765                    ))
1766                    .on_action(cx.listener(
1767                        |this: &mut Self, _: &FocusWorkspaceSidebar, window, cx| {
1768                            this.focus_sidebar(window, cx);
1769                        },
1770                    ))
1771                    .on_action(cx.listener(
1772                        |this: &mut Self, action: &ToggleThreadSwitcher, window, cx| {
1773                            if let Some(sidebar) = &this.sidebar {
1774                                sidebar.toggle_thread_switcher(action.select_last, window, cx);
1775                            }
1776                        },
1777                    ))
1778                    .on_action(cx.listener(|this: &mut Self, _: &NextProject, window, cx| {
1779                        if let Some(sidebar) = &this.sidebar {
1780                            sidebar.cycle_project(true, window, cx);
1781                        }
1782                    }))
1783                    .on_action(
1784                        cx.listener(|this: &mut Self, _: &PreviousProject, window, cx| {
1785                            if let Some(sidebar) = &this.sidebar {
1786                                sidebar.cycle_project(false, window, cx);
1787                            }
1788                        }),
1789                    )
1790                    .on_action(cx.listener(|this: &mut Self, _: &NextThread, window, cx| {
1791                        if let Some(sidebar) = &this.sidebar {
1792                            sidebar.cycle_thread(true, window, cx);
1793                        }
1794                    }))
1795                    .on_action(cx.listener(
1796                        |this: &mut Self, _: &PreviousThread, window, cx| {
1797                            if let Some(sidebar) = &this.sidebar {
1798                                sidebar.cycle_thread(false, window, cx);
1799                            }
1800                        },
1801                    ))
1802                })
1803                .when(
1804                    self.sidebar_open() && self.multi_workspace_enabled(cx),
1805                    |this| {
1806                        this.on_drag_move(cx.listener(
1807                            move |this: &mut Self,
1808                                  e: &DragMoveEvent<DraggedSidebar>,
1809                                  window,
1810                                  cx| {
1811                                if let Some(sidebar) = &this.sidebar {
1812                                    let new_width = if sidebar_on_right {
1813                                        window.bounds().size.width - e.event.position.x
1814                                    } else {
1815                                        e.event.position.x
1816                                    };
1817                                    sidebar.set_width(Some(new_width), cx);
1818                                }
1819                            },
1820                        ))
1821                    },
1822                )
1823                .children(left_sidebar)
1824                .child(
1825                    div()
1826                        .flex()
1827                        .flex_1()
1828                        .size_full()
1829                        .overflow_hidden()
1830                        .child(self.workspace().clone()),
1831                )
1832                .children(right_sidebar)
1833                .child(self.workspace().read(cx).modal_layer.clone())
1834                .children(self.sidebar_overlay.as_ref().map(|view| {
1835                    deferred(div().absolute().size_full().inset_0().occlude().child(
1836                        v_flex().h(px(0.0)).top_20().items_center().child(
1837                            h_flex().occlude().child(view.clone()).on_mouse_down(
1838                                MouseButton::Left,
1839                                |_, _, cx| {
1840                                    cx.stop_propagation();
1841                                },
1842                            ),
1843                        ),
1844                    ))
1845                    .with_priority(2)
1846                })),
1847            window,
1848            cx,
1849            Tiling {
1850                left: !sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1851                right: sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1852                ..Tiling::default()
1853            },
1854        )
1855    }
1856}