multi_workspace.rs

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