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