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