multi_workspace.rs

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