multi_workspace.rs

   1use anyhow::Result;
   2use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
   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};
   8#[cfg(any(test, feature = "test-support"))]
   9use project::Project;
  10use project::{DisableAiSettings, ProjectGroupKey};
  11use settings::Settings;
  12pub use settings::SidebarSide;
  13use std::future::Future;
  14use std::path::PathBuf;
  15use std::sync::Arc;
  16use ui::prelude::*;
  17use util::ResultExt;
  18use zed_actions::agents_sidebar::{MoveWorkspaceToNewWindow, ToggleThreadSwitcher};
  19
  20use agent_settings::AgentSettings;
  21use settings::SidebarDockPosition;
  22use ui::{ContextMenu, right_click_menu};
  23
  24const SIDEBAR_RESIZE_HANDLE_SIZE: Pixels = px(6.0);
  25
  26use crate::{
  27    CloseIntent, CloseWindow, DockPosition, Event as WorkspaceEvent, Item, ModalView, OpenMode,
  28    Panel, Workspace, WorkspaceId, client_side_decorations,
  29    persistence::model::MultiWorkspaceState,
  30};
  31
  32actions!(
  33    multi_workspace,
  34    [
  35        /// Toggles the workspace switcher sidebar.
  36        ToggleWorkspaceSidebar,
  37        /// Closes the workspace sidebar.
  38        CloseWorkspaceSidebar,
  39        /// Moves focus to or from the workspace sidebar without closing it.
  40        FocusWorkspaceSidebar,
  41        /// Switches to the next workspace.
  42        NextWorkspace,
  43        /// Switches to the previous workspace.
  44        PreviousWorkspace,
  45    ]
  46);
  47
  48#[derive(Default)]
  49pub struct SidebarRenderState {
  50    pub open: bool,
  51    pub side: SidebarSide,
  52}
  53
  54pub fn sidebar_side_context_menu(
  55    id: impl Into<ElementId>,
  56    cx: &App,
  57) -> ui::RightClickMenu<ContextMenu> {
  58    let current_position = AgentSettings::get_global(cx).sidebar_side;
  59    right_click_menu(id).menu(move |window, cx| {
  60        let fs = <dyn fs::Fs>::global(cx);
  61        ContextMenu::build(window, cx, move |mut menu, _, _cx| {
  62            let positions: [(SidebarDockPosition, &str); 2] = [
  63                (SidebarDockPosition::Left, "Left"),
  64                (SidebarDockPosition::Right, "Right"),
  65            ];
  66            for (position, label) in positions {
  67                let fs = fs.clone();
  68                menu = menu.toggleable_entry(
  69                    label,
  70                    position == current_position,
  71                    IconPosition::Start,
  72                    None,
  73                    move |_window, cx| {
  74                        settings::update_settings_file(fs.clone(), cx, move |settings, _cx| {
  75                            settings
  76                                .agent
  77                                .get_or_insert_default()
  78                                .set_sidebar_side(position);
  79                        });
  80                    },
  81                );
  82            }
  83            menu
  84        })
  85    })
  86}
  87
  88pub enum MultiWorkspaceEvent {
  89    ActiveWorkspaceChanged,
  90    WorkspaceAdded(Entity<Workspace>),
  91    WorkspaceRemoved(EntityId),
  92}
  93
  94pub enum SidebarEvent {
  95    SerializeNeeded,
  96}
  97
  98pub trait Sidebar: Focusable + Render + EventEmitter<SidebarEvent> + Sized {
  99    fn width(&self, cx: &App) -> Pixels;
 100    fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>);
 101    fn has_notifications(&self, cx: &App) -> bool;
 102    fn side(&self, _cx: &App) -> SidebarSide;
 103
 104    fn is_threads_list_view_active(&self) -> bool {
 105        true
 106    }
 107    /// Makes focus reset back to the search editor upon toggling the sidebar from outside
 108    fn prepare_for_focus(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
 109    /// Opens or cycles the thread switcher popup.
 110    fn toggle_thread_switcher(
 111        &mut self,
 112        _select_last: bool,
 113        _window: &mut Window,
 114        _cx: &mut Context<Self>,
 115    ) {
 116    }
 117
 118    /// Return an opaque JSON blob of sidebar-specific state to persist.
 119    fn serialized_state(&self, _cx: &App) -> Option<String> {
 120        None
 121    }
 122
 123    /// Restore sidebar state from a previously-serialized blob.
 124    fn restore_serialized_state(
 125        &mut self,
 126        _state: &str,
 127        _window: &mut Window,
 128        _cx: &mut Context<Self>,
 129    ) {
 130    }
 131}
 132
 133pub trait SidebarHandle: 'static + Send + Sync {
 134    fn width(&self, cx: &App) -> Pixels;
 135    fn set_width(&self, width: Option<Pixels>, cx: &mut App);
 136    fn focus_handle(&self, cx: &App) -> FocusHandle;
 137    fn focus(&self, window: &mut Window, cx: &mut App);
 138    fn prepare_for_focus(&self, window: &mut Window, cx: &mut App);
 139    fn has_notifications(&self, cx: &App) -> bool;
 140    fn to_any(&self) -> AnyView;
 141    fn entity_id(&self) -> EntityId;
 142    fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App);
 143
 144    fn is_threads_list_view_active(&self, cx: &App) -> bool;
 145
 146    fn side(&self, cx: &App) -> SidebarSide;
 147    fn serialized_state(&self, cx: &App) -> Option<String>;
 148    fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App);
 149}
 150
 151#[derive(Clone)]
 152pub struct DraggedSidebar;
 153
 154impl Render for DraggedSidebar {
 155    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 156        gpui::Empty
 157    }
 158}
 159
 160impl<T: Sidebar> SidebarHandle for Entity<T> {
 161    fn width(&self, cx: &App) -> Pixels {
 162        self.read(cx).width(cx)
 163    }
 164
 165    fn set_width(&self, width: Option<Pixels>, cx: &mut App) {
 166        self.update(cx, |this, cx| this.set_width(width, cx))
 167    }
 168
 169    fn focus_handle(&self, cx: &App) -> FocusHandle {
 170        self.read(cx).focus_handle(cx)
 171    }
 172
 173    fn focus(&self, window: &mut Window, cx: &mut App) {
 174        let handle = self.read(cx).focus_handle(cx);
 175        window.focus(&handle, cx);
 176    }
 177
 178    fn prepare_for_focus(&self, window: &mut Window, cx: &mut App) {
 179        self.update(cx, |this, cx| this.prepare_for_focus(window, cx));
 180    }
 181
 182    fn has_notifications(&self, cx: &App) -> bool {
 183        self.read(cx).has_notifications(cx)
 184    }
 185
 186    fn to_any(&self) -> AnyView {
 187        self.clone().into()
 188    }
 189
 190    fn entity_id(&self) -> EntityId {
 191        Entity::entity_id(self)
 192    }
 193
 194    fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App) {
 195        let entity = self.clone();
 196        window.defer(cx, move |window, cx| {
 197            entity.update(cx, |this, cx| {
 198                this.toggle_thread_switcher(select_last, window, cx);
 199            });
 200        });
 201    }
 202
 203    fn is_threads_list_view_active(&self, cx: &App) -> bool {
 204        self.read(cx).is_threads_list_view_active()
 205    }
 206
 207    fn side(&self, cx: &App) -> SidebarSide {
 208        self.read(cx).side(cx)
 209    }
 210
 211    fn serialized_state(&self, cx: &App) -> Option<String> {
 212        self.read(cx).serialized_state(cx)
 213    }
 214
 215    fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App) {
 216        self.update(cx, |this, cx| {
 217            this.restore_serialized_state(state, window, cx)
 218        })
 219    }
 220}
 221
 222pub struct MultiWorkspace {
 223    window_id: WindowId,
 224    workspaces: Vec<Entity<Workspace>>,
 225    active_workspace_index: usize,
 226    project_group_keys: Vec<ProjectGroupKey>,
 227    sidebar: Option<Box<dyn SidebarHandle>>,
 228    sidebar_open: bool,
 229    sidebar_overlay: Option<AnyView>,
 230    pending_removal_tasks: Vec<Task<()>>,
 231    _serialize_task: Option<Task<()>>,
 232    _subscriptions: Vec<Subscription>,
 233}
 234
 235impl EventEmitter<MultiWorkspaceEvent> for MultiWorkspace {}
 236
 237impl MultiWorkspace {
 238    pub fn sidebar_side(&self, cx: &App) -> SidebarSide {
 239        self.sidebar
 240            .as_ref()
 241            .map_or(SidebarSide::Left, |s| s.side(cx))
 242    }
 243
 244    pub fn sidebar_render_state(&self, cx: &App) -> SidebarRenderState {
 245        SidebarRenderState {
 246            open: self.sidebar_open() && self.multi_workspace_enabled(cx),
 247            side: self.sidebar_side(cx),
 248        }
 249    }
 250
 251    pub fn new(workspace: Entity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 252        let release_subscription = cx.on_release(|this: &mut MultiWorkspace, _cx| {
 253            if let Some(task) = this._serialize_task.take() {
 254                task.detach();
 255            }
 256            for task in std::mem::take(&mut this.pending_removal_tasks) {
 257                task.detach();
 258            }
 259        });
 260        let quit_subscription = cx.on_app_quit(Self::app_will_quit);
 261        let settings_subscription =
 262            cx.observe_global_in::<settings::SettingsStore>(window, |this, window, cx| {
 263                if DisableAiSettings::get_global(cx).disable_ai && this.sidebar_open {
 264                    this.close_sidebar(window, cx);
 265                }
 266            });
 267        Self::subscribe_to_workspace(&workspace, window, cx);
 268        let weak_self = cx.weak_entity();
 269        workspace.update(cx, |workspace, cx| {
 270            workspace.set_multi_workspace(weak_self, cx);
 271        });
 272        Self {
 273            window_id: window.window_handle().window_id(),
 274            project_group_keys: vec![workspace.read(cx).project_group_key(cx)],
 275            workspaces: vec![workspace],
 276            active_workspace_index: 0,
 277            sidebar: None,
 278            sidebar_open: false,
 279            sidebar_overlay: None,
 280            pending_removal_tasks: Vec::new(),
 281            _serialize_task: None,
 282            _subscriptions: vec![
 283                release_subscription,
 284                quit_subscription,
 285                settings_subscription,
 286            ],
 287        }
 288    }
 289
 290    pub fn register_sidebar<T: Sidebar>(&mut self, sidebar: Entity<T>, cx: &mut Context<Self>) {
 291        self._subscriptions
 292            .push(cx.observe(&sidebar, |_this, _, cx| {
 293                cx.notify();
 294            }));
 295        self._subscriptions
 296            .push(cx.subscribe(&sidebar, |this, _, event, cx| match event {
 297                SidebarEvent::SerializeNeeded => {
 298                    this.serialize(cx);
 299                }
 300            }));
 301        self.sidebar = Some(Box::new(sidebar));
 302    }
 303
 304    pub fn sidebar(&self) -> Option<&dyn SidebarHandle> {
 305        self.sidebar.as_deref()
 306    }
 307
 308    pub fn window_id(&self) -> WindowId {
 309        self.window_id
 310    }
 311
 312    pub fn set_sidebar_overlay(&mut self, overlay: Option<AnyView>, cx: &mut Context<Self>) {
 313        self.sidebar_overlay = overlay;
 314        cx.notify();
 315    }
 316
 317    pub fn sidebar_open(&self) -> bool {
 318        self.sidebar_open
 319    }
 320
 321    pub fn sidebar_has_notifications(&self, cx: &App) -> bool {
 322        self.sidebar
 323            .as_ref()
 324            .map_or(false, |s| s.has_notifications(cx))
 325    }
 326
 327    pub fn is_threads_list_view_active(&self, cx: &App) -> bool {
 328        self.sidebar
 329            .as_ref()
 330            .map_or(false, |s| s.is_threads_list_view_active(cx))
 331    }
 332
 333    pub fn multi_workspace_enabled(&self, cx: &App) -> bool {
 334        cx.has_flag::<AgentV2FeatureFlag>() && !DisableAiSettings::get_global(cx).disable_ai
 335    }
 336
 337    pub fn toggle_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 338        if !self.multi_workspace_enabled(cx) {
 339            return;
 340        }
 341
 342        if self.sidebar_open {
 343            self.close_sidebar(window, cx);
 344        } else {
 345            self.open_sidebar(cx);
 346            if let Some(sidebar) = &self.sidebar {
 347                sidebar.prepare_for_focus(window, cx);
 348                sidebar.focus(window, cx);
 349            }
 350        }
 351    }
 352
 353    pub fn close_sidebar_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 354        if !self.multi_workspace_enabled(cx) {
 355            return;
 356        }
 357
 358        if self.sidebar_open {
 359            self.close_sidebar(window, cx);
 360        }
 361    }
 362
 363    pub fn focus_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 364        if !self.multi_workspace_enabled(cx) {
 365            return;
 366        }
 367
 368        if self.sidebar_open {
 369            let sidebar_is_focused = self
 370                .sidebar
 371                .as_ref()
 372                .is_some_and(|s| s.focus_handle(cx).contains_focused(window, cx));
 373
 374            if sidebar_is_focused {
 375                let pane = self.workspace().read(cx).active_pane().clone();
 376                let pane_focus = pane.read(cx).focus_handle(cx);
 377                window.focus(&pane_focus, cx);
 378            } else if let Some(sidebar) = &self.sidebar {
 379                sidebar.prepare_for_focus(window, cx);
 380                sidebar.focus(window, cx);
 381            }
 382        } else {
 383            self.open_sidebar(cx);
 384            if let Some(sidebar) = &self.sidebar {
 385                sidebar.prepare_for_focus(window, cx);
 386                sidebar.focus(window, cx);
 387            }
 388        }
 389    }
 390
 391    pub fn open_sidebar(&mut self, cx: &mut Context<Self>) {
 392        self.sidebar_open = true;
 393        let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
 394        for workspace in &self.workspaces {
 395            workspace.update(cx, |workspace, _cx| {
 396                workspace.set_sidebar_focus_handle(sidebar_focus_handle.clone());
 397            });
 398        }
 399        self.serialize(cx);
 400        cx.notify();
 401    }
 402
 403    pub fn close_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 404        self.sidebar_open = false;
 405        for workspace in &self.workspaces {
 406            workspace.update(cx, |workspace, _cx| {
 407                workspace.set_sidebar_focus_handle(None);
 408            });
 409        }
 410        let pane = self.workspace().read(cx).active_pane().clone();
 411        let pane_focus = pane.read(cx).focus_handle(cx);
 412        window.focus(&pane_focus, cx);
 413        self.serialize(cx);
 414        cx.notify();
 415    }
 416
 417    pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
 418        cx.spawn_in(window, async move |this, cx| {
 419            let workspaces = this.update(cx, |multi_workspace, _cx| {
 420                multi_workspace.workspaces().to_vec()
 421            })?;
 422
 423            for workspace in workspaces {
 424                let should_continue = workspace
 425                    .update_in(cx, |workspace, window, cx| {
 426                        workspace.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 427                    })?
 428                    .await?;
 429                if !should_continue {
 430                    return anyhow::Ok(());
 431                }
 432            }
 433
 434            cx.update(|window, _cx| {
 435                window.remove_window();
 436            })?;
 437
 438            anyhow::Ok(())
 439        })
 440        .detach_and_log_err(cx);
 441    }
 442
 443    fn subscribe_to_workspace(
 444        workspace: &Entity<Workspace>,
 445        window: &Window,
 446        cx: &mut Context<Self>,
 447    ) {
 448        let project = workspace.read(cx).project().clone();
 449        cx.subscribe_in(&project, window, {
 450            let workspace = workspace.downgrade();
 451            move |this, _project, event, _window, cx| match event {
 452                project::Event::WorktreeAdded(_) | project::Event::WorktreeRemoved(_) => {
 453                    if let Some(workspace) = workspace.upgrade() {
 454                        this.add_project_group_key(workspace.read(cx).project_group_key(cx));
 455                    }
 456                }
 457                _ => {}
 458            }
 459        })
 460        .detach();
 461
 462        cx.subscribe_in(workspace, window, |this, workspace, event, window, cx| {
 463            if let WorkspaceEvent::Activate = event {
 464                this.activate(workspace.clone(), window, cx);
 465            }
 466        })
 467        .detach();
 468    }
 469
 470    pub fn add_project_group_key(&mut self, project_group_key: ProjectGroupKey) {
 471        if self.project_group_keys.contains(&project_group_key) {
 472            return;
 473        }
 474        self.project_group_keys.push(project_group_key);
 475    }
 476
 477    pub fn project_group_keys(&self) -> impl Iterator<Item = &ProjectGroupKey> {
 478        self.project_group_keys.iter()
 479    }
 480
 481    /// Returns the project groups, ordered by most recently added.
 482    pub fn project_groups(
 483        &self,
 484        cx: &App,
 485    ) -> impl Iterator<Item = (ProjectGroupKey, Vec<Entity<Workspace>>)> {
 486        let mut groups = self
 487            .project_group_keys
 488            .iter()
 489            .rev()
 490            .map(|key| (key.clone(), Vec::new()))
 491            .collect::<Vec<_>>();
 492        for workspace in &self.workspaces {
 493            let key = workspace.read(cx).project_group_key(cx);
 494            if let Some((_, workspaces)) = groups.iter_mut().find(|(k, _)| k == &key) {
 495                workspaces.push(workspace.clone());
 496            }
 497        }
 498        groups.into_iter()
 499    }
 500
 501    pub fn workspace(&self) -> &Entity<Workspace> {
 502        &self.workspaces[self.active_workspace_index]
 503    }
 504
 505    pub fn workspaces(&self) -> &[Entity<Workspace>] {
 506        &self.workspaces
 507    }
 508
 509    pub fn active_workspace_index(&self) -> usize {
 510        self.active_workspace_index
 511    }
 512
 513    /// Adds a workspace to this window without changing which workspace is
 514    /// active.
 515    pub fn add(&mut self, workspace: Entity<Workspace>, window: &Window, cx: &mut Context<Self>) {
 516        if !self.multi_workspace_enabled(cx) {
 517            self.set_single_workspace(workspace, cx);
 518            return;
 519        }
 520
 521        self.insert_workspace(workspace, window, cx);
 522    }
 523
 524    /// Ensures the workspace is in the multiworkspace and makes it the active one.
 525    pub fn activate(
 526        &mut self,
 527        workspace: Entity<Workspace>,
 528        window: &mut Window,
 529        cx: &mut Context<Self>,
 530    ) {
 531        if !self.multi_workspace_enabled(cx) {
 532            self.set_single_workspace(workspace, cx);
 533            return;
 534        }
 535
 536        let index = self.insert_workspace(workspace, &*window, cx);
 537        let changed = self.active_workspace_index != index;
 538        self.active_workspace_index = index;
 539        if changed {
 540            cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
 541            self.serialize(cx);
 542        }
 543        self.focus_active_workspace(window, cx);
 544        cx.notify();
 545    }
 546
 547    fn set_single_workspace(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) {
 548        self.workspaces[0] = workspace;
 549        self.active_workspace_index = 0;
 550        cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
 551        cx.notify();
 552    }
 553
 554    /// Inserts a workspace into the list if not already present. Returns the
 555    /// index of the workspace (existing or newly inserted). Does not change
 556    /// the active workspace index.
 557    fn insert_workspace(
 558        &mut self,
 559        workspace: Entity<Workspace>,
 560        window: &Window,
 561        cx: &mut Context<Self>,
 562    ) -> usize {
 563        if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
 564            index
 565        } else {
 566            let project_group_key = workspace.read(cx).project().read(cx).project_group_key(cx);
 567
 568            Self::subscribe_to_workspace(&workspace, window, cx);
 569            self.sync_sidebar_to_workspace(&workspace, cx);
 570            let weak_self = cx.weak_entity();
 571            workspace.update(cx, |workspace, cx| {
 572                workspace.set_multi_workspace(weak_self, cx);
 573            });
 574
 575            self.add_project_group_key(project_group_key);
 576            self.workspaces.push(workspace.clone());
 577            cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
 578            cx.notify();
 579            self.workspaces.len() - 1
 580        }
 581    }
 582
 583    /// Clears session state and DB binding for a workspace that is being
 584    /// removed or replaced. The DB row is preserved so the workspace still
 585    /// appears in the recent-projects list.
 586    fn detach_workspace(&mut self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
 587        workspace.update(cx, |workspace, _cx| {
 588            workspace.session_id.take();
 589            workspace._schedule_serialize_workspace.take();
 590            workspace._serialize_workspace_task.take();
 591        });
 592
 593        if let Some(workspace_id) = workspace.read(cx).database_id() {
 594            let db = crate::persistence::WorkspaceDb::global(cx);
 595            self.pending_removal_tasks.retain(|task| !task.is_ready());
 596            self.pending_removal_tasks
 597                .push(cx.background_spawn(async move {
 598                    db.set_session_binding(workspace_id, None, None)
 599                        .await
 600                        .log_err();
 601                }));
 602        }
 603    }
 604
 605    fn sync_sidebar_to_workspace(&self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
 606        if self.sidebar_open {
 607            let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
 608            workspace.update(cx, |workspace, _| {
 609                workspace.set_sidebar_focus_handle(sidebar_focus_handle);
 610            });
 611        }
 612    }
 613
 614    fn cycle_workspace(&mut self, delta: isize, window: &mut Window, cx: &mut Context<Self>) {
 615        let count = self.workspaces.len() as isize;
 616        if count <= 1 {
 617            return;
 618        }
 619        let current = self.active_workspace_index as isize;
 620        let next = ((current + delta).rem_euclid(count)) as usize;
 621        let workspace = self.workspaces[next].clone();
 622        self.activate(workspace, window, cx);
 623    }
 624
 625    fn next_workspace(&mut self, _: &NextWorkspace, window: &mut Window, cx: &mut Context<Self>) {
 626        self.cycle_workspace(1, window, cx);
 627    }
 628
 629    fn previous_workspace(
 630        &mut self,
 631        _: &PreviousWorkspace,
 632        window: &mut Window,
 633        cx: &mut Context<Self>,
 634    ) {
 635        self.cycle_workspace(-1, window, cx);
 636    }
 637
 638    pub(crate) fn serialize(&mut self, cx: &mut Context<Self>) {
 639        self._serialize_task = Some(cx.spawn(async move |this, cx| {
 640            let Some((window_id, state)) = this
 641                .read_with(cx, |this, cx| {
 642                    let state = MultiWorkspaceState {
 643                        active_workspace_id: this.workspace().read(cx).database_id(),
 644                        project_group_keys: this
 645                            .project_group_keys()
 646                            .cloned()
 647                            .map(Into::into)
 648                            .collect::<Vec<_>>(),
 649                        sidebar_open: this.sidebar_open,
 650                        sidebar_state: this.sidebar.as_ref().and_then(|s| s.serialized_state(cx)),
 651                    };
 652                    (this.window_id, state)
 653                })
 654                .ok()
 655            else {
 656                return;
 657            };
 658            let kvp = cx.update(|cx| db::kvp::KeyValueStore::global(cx));
 659            crate::persistence::write_multi_workspace_state(&kvp, window_id, state).await;
 660        }));
 661    }
 662
 663    /// Returns the in-flight serialization task (if any) so the caller can
 664    /// await it. Used by the quit handler to ensure pending DB writes
 665    /// complete before the process exits.
 666    pub fn flush_serialization(&mut self) -> Task<()> {
 667        self._serialize_task.take().unwrap_or(Task::ready(()))
 668    }
 669
 670    fn app_will_quit(&mut self, _cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
 671        let mut tasks: Vec<Task<()>> = Vec::new();
 672        if let Some(task) = self._serialize_task.take() {
 673            tasks.push(task);
 674        }
 675        tasks.extend(std::mem::take(&mut self.pending_removal_tasks));
 676
 677        async move {
 678            futures::future::join_all(tasks).await;
 679        }
 680    }
 681
 682    pub fn focus_active_workspace(&self, window: &mut Window, cx: &mut App) {
 683        // If a dock panel is zoomed, focus it instead of the center pane.
 684        // Otherwise, focusing the center pane triggers dismiss_zoomed_items_to_reveal
 685        // which closes the zoomed dock.
 686        let focus_handle = {
 687            let workspace = self.workspace().read(cx);
 688            let mut target = None;
 689            for dock in workspace.all_docks() {
 690                let dock = dock.read(cx);
 691                if dock.is_open() {
 692                    if let Some(panel) = dock.active_panel() {
 693                        if panel.is_zoomed(window, cx) {
 694                            target = Some(panel.panel_focus_handle(cx));
 695                            break;
 696                        }
 697                    }
 698                }
 699            }
 700            target.unwrap_or_else(|| {
 701                let pane = workspace.active_pane().clone();
 702                pane.read(cx).focus_handle(cx)
 703            })
 704        };
 705        window.focus(&focus_handle, cx);
 706    }
 707
 708    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 709        self.workspace().read(cx).panel::<T>(cx)
 710    }
 711
 712    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 713        self.workspace().read(cx).active_modal::<V>(cx)
 714    }
 715
 716    pub fn add_panel<T: Panel>(
 717        &mut self,
 718        panel: Entity<T>,
 719        window: &mut Window,
 720        cx: &mut Context<Self>,
 721    ) {
 722        self.workspace().update(cx, |workspace, cx| {
 723            workspace.add_panel(panel, window, cx);
 724        });
 725    }
 726
 727    pub fn focus_panel<T: Panel>(
 728        &mut self,
 729        window: &mut Window,
 730        cx: &mut Context<Self>,
 731    ) -> Option<Entity<T>> {
 732        self.workspace()
 733            .update(cx, |workspace, cx| workspace.focus_panel::<T>(window, cx))
 734    }
 735
 736    // used in a test
 737    pub fn toggle_modal<V: ModalView, B>(
 738        &mut self,
 739        window: &mut Window,
 740        cx: &mut Context<Self>,
 741        build: B,
 742    ) where
 743        B: FnOnce(&mut Window, &mut gpui::Context<V>) -> V,
 744    {
 745        self.workspace().update(cx, |workspace, cx| {
 746            workspace.toggle_modal(window, cx, build);
 747        });
 748    }
 749
 750    pub fn toggle_dock(
 751        &mut self,
 752        dock_side: DockPosition,
 753        window: &mut Window,
 754        cx: &mut Context<Self>,
 755    ) {
 756        self.workspace().update(cx, |workspace, cx| {
 757            workspace.toggle_dock(dock_side, window, cx);
 758        });
 759    }
 760
 761    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 762        self.workspace().read(cx).active_item_as::<I>(cx)
 763    }
 764
 765    pub fn items_of_type<'a, T: Item>(
 766        &'a self,
 767        cx: &'a App,
 768    ) -> impl 'a + Iterator<Item = Entity<T>> {
 769        self.workspace().read(cx).items_of_type::<T>(cx)
 770    }
 771
 772    pub fn database_id(&self, cx: &App) -> Option<WorkspaceId> {
 773        self.workspace().read(cx).database_id()
 774    }
 775
 776    pub fn take_pending_removal_tasks(&mut self) -> Vec<Task<()>> {
 777        let tasks: Vec<Task<()>> = std::mem::take(&mut self.pending_removal_tasks)
 778            .into_iter()
 779            .filter(|task| !task.is_ready())
 780            .collect();
 781        tasks
 782    }
 783
 784    #[cfg(any(test, feature = "test-support"))]
 785    pub fn set_random_database_id(&mut self, cx: &mut Context<Self>) {
 786        self.workspace().update(cx, |workspace, _cx| {
 787            workspace.set_random_database_id();
 788        });
 789    }
 790
 791    #[cfg(any(test, feature = "test-support"))]
 792    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 793        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
 794        Self::new(workspace, window, cx)
 795    }
 796
 797    #[cfg(any(test, feature = "test-support"))]
 798    pub fn test_add_workspace(
 799        &mut self,
 800        project: Entity<Project>,
 801        window: &mut Window,
 802        cx: &mut Context<Self>,
 803    ) -> Entity<Workspace> {
 804        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
 805        self.activate(workspace.clone(), window, cx);
 806        workspace
 807    }
 808
 809    #[cfg(any(test, feature = "test-support"))]
 810    pub fn create_test_workspace(
 811        &mut self,
 812        window: &mut Window,
 813        cx: &mut Context<Self>,
 814    ) -> Task<()> {
 815        let app_state = self.workspace().read(cx).app_state().clone();
 816        let project = Project::local(
 817            app_state.client.clone(),
 818            app_state.node_runtime.clone(),
 819            app_state.user_store.clone(),
 820            app_state.languages.clone(),
 821            app_state.fs.clone(),
 822            None,
 823            project::LocalProjectFlags::default(),
 824            cx,
 825        );
 826        let new_workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
 827        self.activate(new_workspace.clone(), window, cx);
 828
 829        let weak_workspace = new_workspace.downgrade();
 830        let db = crate::persistence::WorkspaceDb::global(cx);
 831        cx.spawn_in(window, async move |this, cx| {
 832            let workspace_id = db.next_id().await.unwrap();
 833            let workspace = weak_workspace.upgrade().unwrap();
 834            let task: Task<()> = this
 835                .update_in(cx, |this, window, cx| {
 836                    let session_id = workspace.read(cx).session_id();
 837                    let window_id = window.window_handle().window_id().as_u64();
 838                    workspace.update(cx, |workspace, _cx| {
 839                        workspace.set_database_id(workspace_id);
 840                    });
 841                    this.serialize(cx);
 842                    let db = db.clone();
 843                    cx.background_spawn(async move {
 844                        db.set_session_binding(workspace_id, session_id, Some(window_id))
 845                            .await
 846                            .log_err();
 847                    })
 848                })
 849                .unwrap();
 850            task.await
 851        })
 852    }
 853
 854    pub fn remove(
 855        &mut self,
 856        workspace: &Entity<Workspace>,
 857        window: &mut Window,
 858        cx: &mut Context<Self>,
 859    ) -> bool {
 860        let Some(index) = self.workspaces.iter().position(|w| w == workspace) else {
 861            return false;
 862        };
 863        if self.workspaces.len() <= 1 {
 864            return false;
 865        }
 866
 867        let removed_workspace = self.workspaces.remove(index);
 868
 869        if self.active_workspace_index >= self.workspaces.len() {
 870            self.active_workspace_index = self.workspaces.len() - 1;
 871        } else if self.active_workspace_index > index {
 872            self.active_workspace_index -= 1;
 873        }
 874
 875        self.detach_workspace(&removed_workspace, cx);
 876
 877        self.serialize(cx);
 878        self.focus_active_workspace(window, cx);
 879        cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(
 880            removed_workspace.entity_id(),
 881        ));
 882        cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
 883        cx.notify();
 884
 885        true
 886    }
 887
 888    pub fn move_workspace_to_new_window(
 889        &mut self,
 890        workspace: &Entity<Workspace>,
 891        window: &mut Window,
 892        cx: &mut Context<Self>,
 893    ) {
 894        let workspace = workspace.clone();
 895        if !self.remove(&workspace, window, cx) {
 896            return;
 897        }
 898
 899        let app_state: Arc<crate::AppState> = workspace.read(cx).app_state().clone();
 900
 901        cx.defer(move |cx| {
 902            let options = (app_state.build_window_options)(None, cx);
 903
 904            let Ok(window) = cx.open_window(options, |window, cx| {
 905                cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 906            }) else {
 907                return;
 908            };
 909
 910            let _ = window.update(cx, |_, window, _| {
 911                window.activate_window();
 912            });
 913        });
 914    }
 915
 916    // TODO: Move group to a new window?
 917    fn move_active_workspace_to_new_window(
 918        &mut self,
 919        _: &MoveWorkspaceToNewWindow,
 920        window: &mut Window,
 921        cx: &mut Context<Self>,
 922    ) {
 923        let workspace = self.workspace().clone();
 924        self.move_workspace_to_new_window(&workspace, window, cx);
 925    }
 926
 927    pub fn open_project(
 928        &mut self,
 929        paths: Vec<PathBuf>,
 930        open_mode: OpenMode,
 931        window: &mut Window,
 932        cx: &mut Context<Self>,
 933    ) -> Task<Result<Entity<Workspace>>> {
 934        let workspace = self.workspace().clone();
 935
 936        let needs_close_prompt = !self.multi_workspace_enabled(cx);
 937        let open_mode = if self.multi_workspace_enabled(cx) {
 938            open_mode
 939        } else {
 940            OpenMode::Activate
 941        };
 942
 943        if needs_close_prompt {
 944            cx.spawn_in(window, async move |_this, cx| {
 945                let should_continue = workspace
 946                    .update_in(cx, |workspace, window, cx| {
 947                        workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx)
 948                    })?
 949                    .await?;
 950                if should_continue {
 951                    workspace
 952                        .update_in(cx, |workspace, window, cx| {
 953                            workspace.open_workspace_for_paths(open_mode, paths, window, cx)
 954                        })?
 955                        .await
 956                } else {
 957                    Ok(workspace)
 958                }
 959            })
 960        } else {
 961            workspace.update(cx, |workspace, cx| {
 962                workspace.open_workspace_for_paths(open_mode, paths, window, cx)
 963            })
 964        }
 965    }
 966}
 967
 968impl Render for MultiWorkspace {
 969    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 970        let multi_workspace_enabled = self.multi_workspace_enabled(cx);
 971        let sidebar_side = self.sidebar_side(cx);
 972        let sidebar_on_right = sidebar_side == SidebarSide::Right;
 973
 974        let sidebar: Option<AnyElement> = if multi_workspace_enabled && self.sidebar_open() {
 975            self.sidebar.as_ref().map(|sidebar_handle| {
 976                let weak = cx.weak_entity();
 977
 978                let sidebar_width = sidebar_handle.width(cx);
 979                let resize_handle = deferred(
 980                    div()
 981                        .id("sidebar-resize-handle")
 982                        .absolute()
 983                        .when(!sidebar_on_right, |el| {
 984                            el.right(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
 985                        })
 986                        .when(sidebar_on_right, |el| {
 987                            el.left(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
 988                        })
 989                        .top(px(0.))
 990                        .h_full()
 991                        .w(SIDEBAR_RESIZE_HANDLE_SIZE)
 992                        .cursor_col_resize()
 993                        .on_drag(DraggedSidebar, |dragged, _, _, cx| {
 994                            cx.stop_propagation();
 995                            cx.new(|_| dragged.clone())
 996                        })
 997                        .on_mouse_down(MouseButton::Left, |_, _, cx| {
 998                            cx.stop_propagation();
 999                        })
1000                        .on_mouse_up(MouseButton::Left, move |event, _, cx| {
1001                            if event.click_count == 2 {
1002                                weak.update(cx, |this, cx| {
1003                                    if let Some(sidebar) = this.sidebar.as_mut() {
1004                                        sidebar.set_width(None, cx);
1005                                    }
1006                                    this.serialize(cx);
1007                                })
1008                                .ok();
1009                                cx.stop_propagation();
1010                            } else {
1011                                weak.update(cx, |this, cx| {
1012                                    this.serialize(cx);
1013                                })
1014                                .ok();
1015                            }
1016                        })
1017                        .occlude(),
1018                );
1019
1020                div()
1021                    .id("sidebar-container")
1022                    .relative()
1023                    .h_full()
1024                    .w(sidebar_width)
1025                    .flex_shrink_0()
1026                    .child(sidebar_handle.to_any())
1027                    .child(resize_handle)
1028                    .into_any_element()
1029            })
1030        } else {
1031            None
1032        };
1033
1034        let (left_sidebar, right_sidebar) = if sidebar_on_right {
1035            (None, sidebar)
1036        } else {
1037            (sidebar, None)
1038        };
1039
1040        let ui_font = theme_settings::setup_ui_font(window, cx);
1041        let text_color = cx.theme().colors().text;
1042
1043        let workspace = self.workspace().clone();
1044        let workspace_key_context = workspace.update(cx, |workspace, cx| workspace.key_context(cx));
1045        let root = workspace.update(cx, |workspace, cx| workspace.actions(h_flex(), window, cx));
1046
1047        client_side_decorations(
1048            root.key_context(workspace_key_context)
1049                .relative()
1050                .size_full()
1051                .font(ui_font)
1052                .text_color(text_color)
1053                .on_action(cx.listener(Self::close_window))
1054                .when(self.multi_workspace_enabled(cx), |this| {
1055                    this.on_action(cx.listener(
1056                        |this: &mut Self, _: &ToggleWorkspaceSidebar, window, cx| {
1057                            this.toggle_sidebar(window, cx);
1058                        },
1059                    ))
1060                    .on_action(cx.listener(
1061                        |this: &mut Self, _: &CloseWorkspaceSidebar, window, cx| {
1062                            this.close_sidebar_action(window, cx);
1063                        },
1064                    ))
1065                    .on_action(cx.listener(
1066                        |this: &mut Self, _: &FocusWorkspaceSidebar, window, cx| {
1067                            this.focus_sidebar(window, cx);
1068                        },
1069                    ))
1070                    .on_action(cx.listener(Self::next_workspace))
1071                    .on_action(cx.listener(Self::previous_workspace))
1072                    .on_action(cx.listener(Self::move_active_workspace_to_new_window))
1073                    .on_action(cx.listener(
1074                        |this: &mut Self, action: &ToggleThreadSwitcher, window, cx| {
1075                            if let Some(sidebar) = &this.sidebar {
1076                                sidebar.toggle_thread_switcher(action.select_last, window, cx);
1077                            }
1078                        },
1079                    ))
1080                })
1081                .when(
1082                    self.sidebar_open() && self.multi_workspace_enabled(cx),
1083                    |this| {
1084                        this.on_drag_move(cx.listener(
1085                            move |this: &mut Self,
1086                                  e: &DragMoveEvent<DraggedSidebar>,
1087                                  window,
1088                                  cx| {
1089                                if let Some(sidebar) = &this.sidebar {
1090                                    let new_width = if sidebar_on_right {
1091                                        window.bounds().size.width - e.event.position.x
1092                                    } else {
1093                                        e.event.position.x
1094                                    };
1095                                    sidebar.set_width(Some(new_width), cx);
1096                                }
1097                            },
1098                        ))
1099                    },
1100                )
1101                .children(left_sidebar)
1102                .child(
1103                    div()
1104                        .flex()
1105                        .flex_1()
1106                        .size_full()
1107                        .overflow_hidden()
1108                        .child(self.workspace().clone()),
1109                )
1110                .children(right_sidebar)
1111                .child(self.workspace().read(cx).modal_layer.clone())
1112                .children(self.sidebar_overlay.as_ref().map(|view| {
1113                    deferred(div().absolute().size_full().inset_0().occlude().child(
1114                        v_flex().h(px(0.0)).top_20().items_center().child(
1115                            h_flex().occlude().child(view.clone()).on_mouse_down(
1116                                MouseButton::Left,
1117                                |_, _, cx| {
1118                                    cx.stop_propagation();
1119                                },
1120                            ),
1121                        ),
1122                    ))
1123                    .with_priority(2)
1124                })),
1125            window,
1126            cx,
1127            Tiling {
1128                left: !sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1129                right: sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1130                ..Tiling::default()
1131            },
1132        )
1133    }
1134}