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