multi_workspace.rs

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