multi_workspace.rs

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