multi_workspace.rs

   1use anyhow::Result;
   2use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
   3use gpui::PathPromptOptions;
   4use gpui::{
   5    AnyView, App, Context, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
   6    ManagedView, MouseButton, Pixels, Render, Subscription, Task, Tiling, Window, WindowId,
   7    actions, deferred, px,
   8};
   9#[cfg(any(test, feature = "test-support"))]
  10use project::Project;
  11use project::{DirectoryLister, DisableAiSettings, ProjectGroupKey};
  12use settings::Settings;
  13pub use settings::SidebarSide;
  14use std::future::Future;
  15use std::path::Path;
  16use std::path::PathBuf;
  17use std::sync::Arc;
  18use ui::prelude::*;
  19use util::ResultExt;
  20use util::path_list::PathList;
  21use zed_actions::agents_sidebar::{MoveWorkspaceToNewWindow, 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::AppState;
  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        /// Switches to the next workspace.
  46        NextWorkspace,
  47        /// Switches to the previous workspace.
  48        PreviousWorkspace,
  49    ]
  50);
  51
  52#[derive(Default)]
  53pub struct SidebarRenderState {
  54    pub open: bool,
  55    pub side: SidebarSide,
  56}
  57
  58pub fn sidebar_side_context_menu(
  59    id: impl Into<ElementId>,
  60    cx: &App,
  61) -> ui::RightClickMenu<ContextMenu> {
  62    let current_position = AgentSettings::get_global(cx).sidebar_side;
  63    right_click_menu(id).menu(move |window, cx| {
  64        let fs = <dyn fs::Fs>::global(cx);
  65        ContextMenu::build(window, cx, move |mut menu, _, _cx| {
  66            let positions: [(SidebarDockPosition, &str); 2] = [
  67                (SidebarDockPosition::Left, "Left"),
  68                (SidebarDockPosition::Right, "Right"),
  69            ];
  70            for (position, label) in positions {
  71                let fs = fs.clone();
  72                menu = menu.toggleable_entry(
  73                    label,
  74                    position == current_position,
  75                    IconPosition::Start,
  76                    None,
  77                    move |_window, cx| {
  78                        settings::update_settings_file(fs.clone(), cx, move |settings, _cx| {
  79                            settings
  80                                .agent
  81                                .get_or_insert_default()
  82                                .set_sidebar_side(position);
  83                        });
  84                    },
  85                );
  86            }
  87            menu
  88        })
  89    })
  90}
  91
  92pub enum MultiWorkspaceEvent {
  93    ActiveWorkspaceChanged,
  94    WorkspaceAdded(Entity<Workspace>),
  95    WorkspaceRemoved(EntityId),
  96}
  97
  98pub enum SidebarEvent {
  99    SerializeNeeded,
 100}
 101
 102pub trait Sidebar: Focusable + Render + EventEmitter<SidebarEvent> + Sized {
 103    fn width(&self, cx: &App) -> Pixels;
 104    fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>);
 105    fn has_notifications(&self, cx: &App) -> bool;
 106    fn side(&self, _cx: &App) -> SidebarSide;
 107
 108    fn is_threads_list_view_active(&self) -> bool {
 109        true
 110    }
 111    /// Makes focus reset back to the search editor upon toggling the sidebar from outside
 112    fn prepare_for_focus(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
 113    /// Opens or cycles the thread switcher popup.
 114    fn toggle_thread_switcher(
 115        &mut self,
 116        _select_last: bool,
 117        _window: &mut Window,
 118        _cx: &mut Context<Self>,
 119    ) {
 120    }
 121
 122    /// Return an opaque JSON blob of sidebar-specific state to persist.
 123    fn serialized_state(&self, _cx: &App) -> Option<String> {
 124        None
 125    }
 126
 127    /// Restore sidebar state from a previously-serialized blob.
 128    fn restore_serialized_state(
 129        &mut self,
 130        _state: &str,
 131        _window: &mut Window,
 132        _cx: &mut Context<Self>,
 133    ) {
 134    }
 135}
 136
 137pub trait SidebarHandle: 'static + Send + Sync {
 138    fn width(&self, cx: &App) -> Pixels;
 139    fn set_width(&self, width: Option<Pixels>, cx: &mut App);
 140    fn focus_handle(&self, cx: &App) -> FocusHandle;
 141    fn focus(&self, window: &mut Window, cx: &mut App);
 142    fn prepare_for_focus(&self, window: &mut Window, cx: &mut App);
 143    fn has_notifications(&self, cx: &App) -> bool;
 144    fn to_any(&self) -> AnyView;
 145    fn entity_id(&self) -> EntityId;
 146    fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App);
 147
 148    fn is_threads_list_view_active(&self, cx: &App) -> bool;
 149
 150    fn side(&self, cx: &App) -> SidebarSide;
 151    fn serialized_state(&self, cx: &App) -> Option<String>;
 152    fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App);
 153}
 154
 155#[derive(Clone)]
 156pub struct DraggedSidebar;
 157
 158impl Render for DraggedSidebar {
 159    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 160        gpui::Empty
 161    }
 162}
 163
 164impl<T: Sidebar> SidebarHandle for Entity<T> {
 165    fn width(&self, cx: &App) -> Pixels {
 166        self.read(cx).width(cx)
 167    }
 168
 169    fn set_width(&self, width: Option<Pixels>, cx: &mut App) {
 170        self.update(cx, |this, cx| this.set_width(width, cx))
 171    }
 172
 173    fn focus_handle(&self, cx: &App) -> FocusHandle {
 174        self.read(cx).focus_handle(cx)
 175    }
 176
 177    fn focus(&self, window: &mut Window, cx: &mut App) {
 178        let handle = self.read(cx).focus_handle(cx);
 179        window.focus(&handle, cx);
 180    }
 181
 182    fn prepare_for_focus(&self, window: &mut Window, cx: &mut App) {
 183        self.update(cx, |this, cx| this.prepare_for_focus(window, cx));
 184    }
 185
 186    fn has_notifications(&self, cx: &App) -> bool {
 187        self.read(cx).has_notifications(cx)
 188    }
 189
 190    fn to_any(&self) -> AnyView {
 191        self.clone().into()
 192    }
 193
 194    fn entity_id(&self) -> EntityId {
 195        Entity::entity_id(self)
 196    }
 197
 198    fn toggle_thread_switcher(&self, select_last: bool, window: &mut Window, cx: &mut App) {
 199        let entity = self.clone();
 200        window.defer(cx, move |window, cx| {
 201            entity.update(cx, |this, cx| {
 202                this.toggle_thread_switcher(select_last, window, cx);
 203            });
 204        });
 205    }
 206
 207    fn is_threads_list_view_active(&self, cx: &App) -> bool {
 208        self.read(cx).is_threads_list_view_active()
 209    }
 210
 211    fn side(&self, cx: &App) -> SidebarSide {
 212        self.read(cx).side(cx)
 213    }
 214
 215    fn serialized_state(&self, cx: &App) -> Option<String> {
 216        self.read(cx).serialized_state(cx)
 217    }
 218
 219    fn restore_serialized_state(&self, state: &str, window: &mut Window, cx: &mut App) {
 220        self.update(cx, |this, cx| {
 221            this.restore_serialized_state(state, window, cx)
 222        })
 223    }
 224}
 225
 226pub struct MultiWorkspace {
 227    window_id: WindowId,
 228    workspaces: Vec<Entity<Workspace>>,
 229    active_workspace_index: usize,
 230    project_group_keys: Vec<ProjectGroupKey>,
 231    sidebar: Option<Box<dyn SidebarHandle>>,
 232    sidebar_open: bool,
 233    sidebar_overlay: Option<AnyView>,
 234    pending_removal_tasks: Vec<Task<()>>,
 235    _serialize_task: Option<Task<()>>,
 236    _subscriptions: Vec<Subscription>,
 237}
 238
 239impl EventEmitter<MultiWorkspaceEvent> for MultiWorkspace {}
 240
 241impl MultiWorkspace {
 242    pub fn sidebar_side(&self, cx: &App) -> SidebarSide {
 243        self.sidebar
 244            .as_ref()
 245            .map_or(SidebarSide::Left, |s| s.side(cx))
 246    }
 247
 248    pub fn sidebar_render_state(&self, cx: &App) -> SidebarRenderState {
 249        SidebarRenderState {
 250            open: self.sidebar_open() && self.multi_workspace_enabled(cx),
 251            side: self.sidebar_side(cx),
 252        }
 253    }
 254
 255    pub fn new(workspace: Entity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 256        let release_subscription = cx.on_release(|this: &mut MultiWorkspace, _cx| {
 257            if let Some(task) = this._serialize_task.take() {
 258                task.detach();
 259            }
 260            for task in std::mem::take(&mut this.pending_removal_tasks) {
 261                task.detach();
 262            }
 263        });
 264        let quit_subscription = cx.on_app_quit(Self::app_will_quit);
 265        let settings_subscription =
 266            cx.observe_global_in::<settings::SettingsStore>(window, |this, window, cx| {
 267                if DisableAiSettings::get_global(cx).disable_ai && this.sidebar_open {
 268                    this.close_sidebar(window, cx);
 269                }
 270            });
 271        Self::subscribe_to_workspace(&workspace, window, cx);
 272        let weak_self = cx.weak_entity();
 273        workspace.update(cx, |workspace, cx| {
 274            workspace.set_multi_workspace(weak_self, cx);
 275        });
 276        Self {
 277            window_id: window.window_handle().window_id(),
 278            project_group_keys: vec![workspace.read(cx).project_group_key(cx)],
 279            workspaces: vec![workspace],
 280            active_workspace_index: 0,
 281            sidebar: None,
 282            sidebar_open: false,
 283            sidebar_overlay: None,
 284            pending_removal_tasks: Vec::new(),
 285            _serialize_task: None,
 286            _subscriptions: vec![
 287                release_subscription,
 288                quit_subscription,
 289                settings_subscription,
 290            ],
 291        }
 292    }
 293
 294    pub fn register_sidebar<T: Sidebar>(&mut self, sidebar: Entity<T>, cx: &mut Context<Self>) {
 295        self._subscriptions
 296            .push(cx.observe(&sidebar, |_this, _, cx| {
 297                cx.notify();
 298            }));
 299        self._subscriptions
 300            .push(cx.subscribe(&sidebar, |this, _, event, cx| match event {
 301                SidebarEvent::SerializeNeeded => {
 302                    this.serialize(cx);
 303                }
 304            }));
 305        self.sidebar = Some(Box::new(sidebar));
 306    }
 307
 308    pub fn sidebar(&self) -> Option<&dyn SidebarHandle> {
 309        self.sidebar.as_deref()
 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 restore_project_group_keys(&mut self, keys: Vec<ProjectGroupKey>) {
 478        let mut restored = keys;
 479        for existing_key in &self.project_group_keys {
 480            if !restored.contains(existing_key) {
 481                restored.push(existing_key.clone());
 482            }
 483        }
 484        self.project_group_keys = restored;
 485    }
 486
 487    pub fn project_group_keys(&self) -> impl Iterator<Item = &ProjectGroupKey> {
 488        self.project_group_keys.iter()
 489    }
 490
 491    /// Returns the project groups, ordered by most recently added.
 492    pub fn project_groups(
 493        &self,
 494        cx: &App,
 495    ) -> impl Iterator<Item = (ProjectGroupKey, Vec<Entity<Workspace>>)> {
 496        let mut groups = self
 497            .project_group_keys
 498            .iter()
 499            .rev()
 500            .map(|key| (key.clone(), Vec::new()))
 501            .collect::<Vec<_>>();
 502        for workspace in &self.workspaces {
 503            let key = workspace.read(cx).project_group_key(cx);
 504            if let Some((_, workspaces)) = groups.iter_mut().find(|(k, _)| k == &key) {
 505                workspaces.push(workspace.clone());
 506            }
 507        }
 508        groups.into_iter()
 509    }
 510
 511    pub fn workspaces_for_project_group(
 512        &self,
 513        project_group_key: &ProjectGroupKey,
 514        cx: &App,
 515    ) -> impl Iterator<Item = &Entity<Workspace>> {
 516        self.workspaces
 517            .iter()
 518            .filter(move |ws| ws.read(cx).project_group_key(cx) == *project_group_key)
 519    }
 520
 521    pub fn remove_folder_from_project_group(
 522        &mut self,
 523        project_group_key: &ProjectGroupKey,
 524        path: &Path,
 525        cx: &mut Context<Self>,
 526    ) {
 527        let new_path_list = project_group_key.path_list().without_path(path);
 528        if new_path_list.is_empty() {
 529            return;
 530        }
 531
 532        let new_key = ProjectGroupKey::new(project_group_key.host(), new_path_list);
 533
 534        let workspaces: Vec<_> = self
 535            .workspaces_for_project_group(project_group_key, cx)
 536            .cloned()
 537            .collect();
 538
 539        self.add_project_group_key(new_key);
 540
 541        for workspace in workspaces {
 542            let project = workspace.read(cx).project().clone();
 543            project.update(cx, |project, cx| {
 544                project.remove_worktree_for_main_worktree_path(path, cx);
 545            });
 546        }
 547
 548        self.serialize(cx);
 549        cx.notify();
 550    }
 551
 552    pub fn prompt_to_add_folders_to_project_group(
 553        &mut self,
 554        key: &ProjectGroupKey,
 555        window: &mut Window,
 556        cx: &mut Context<Self>,
 557    ) {
 558        let paths = self.workspace().update(cx, |workspace, cx| {
 559            workspace.prompt_for_open_path(
 560                PathPromptOptions {
 561                    files: false,
 562                    directories: true,
 563                    multiple: true,
 564                    prompt: None,
 565                },
 566                DirectoryLister::Project(workspace.project().clone()),
 567                window,
 568                cx,
 569            )
 570        });
 571
 572        let key = key.clone();
 573        cx.spawn_in(window, async move |this, cx| {
 574            if let Some(new_paths) = paths.await.ok().flatten() {
 575                if !new_paths.is_empty() {
 576                    this.update(cx, |multi_workspace, cx| {
 577                        multi_workspace.add_folders_to_project_group(&key, new_paths, cx);
 578                    })?;
 579                }
 580            }
 581            anyhow::Ok(())
 582        })
 583        .detach_and_log_err(cx);
 584    }
 585
 586    pub fn add_folders_to_project_group(
 587        &mut self,
 588        project_group_key: &ProjectGroupKey,
 589        new_paths: Vec<PathBuf>,
 590        cx: &mut Context<Self>,
 591    ) {
 592        let mut all_paths: Vec<PathBuf> = project_group_key.path_list().paths().to_vec();
 593        all_paths.extend(new_paths.iter().cloned());
 594        let new_path_list = PathList::new(&all_paths);
 595        let new_key = ProjectGroupKey::new(project_group_key.host(), new_path_list);
 596
 597        let workspaces: Vec<_> = self
 598            .workspaces_for_project_group(project_group_key, cx)
 599            .cloned()
 600            .collect();
 601
 602        self.add_project_group_key(new_key);
 603
 604        for workspace in workspaces {
 605            let project = workspace.read(cx).project().clone();
 606            for path in &new_paths {
 607                project
 608                    .update(cx, |project, cx| {
 609                        project.find_or_create_worktree(path, true, cx)
 610                    })
 611                    .detach_and_log_err(cx);
 612            }
 613        }
 614
 615        self.serialize(cx);
 616        cx.notify();
 617    }
 618
 619    pub fn remove_project_group(
 620        &mut self,
 621        key: &ProjectGroupKey,
 622        window: &mut Window,
 623        cx: &mut Context<Self>,
 624    ) {
 625        self.project_group_keys.retain(|k| k != key);
 626
 627        let workspaces: Vec<_> = self
 628            .workspaces_for_project_group(key, cx)
 629            .cloned()
 630            .collect();
 631        for workspace in workspaces {
 632            self.remove(&workspace, window, cx);
 633        }
 634
 635        self.serialize(cx);
 636        cx.notify();
 637    }
 638
 639    /// Finds an existing workspace in this multi-workspace whose paths match,
 640    /// or creates a new one (deserializing its saved state from the database).
 641    /// Never searches other windows or matches workspaces with a superset of
 642    /// the requested paths.
 643    pub fn find_or_create_local_workspace(
 644        &mut self,
 645        path_list: PathList,
 646        window: &mut Window,
 647        cx: &mut Context<Self>,
 648    ) -> Task<Result<Entity<Workspace>>> {
 649        if let Some(workspace) = self
 650            .workspaces
 651            .iter()
 652            .find(|ws| ws.read(cx).project_group_key(cx).path_list() == &path_list)
 653            .cloned()
 654        {
 655            self.activate(workspace.clone(), window, cx);
 656            return Task::ready(Ok(workspace));
 657        }
 658
 659        let paths = path_list.paths().to_vec();
 660        let app_state = self.workspace().read(cx).app_state().clone();
 661        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 662
 663        cx.spawn(async move |_this, cx| {
 664            let result = cx
 665                .update(|cx| {
 666                    Workspace::new_local(
 667                        paths,
 668                        app_state,
 669                        requesting_window,
 670                        None,
 671                        None,
 672                        OpenMode::Activate,
 673                        cx,
 674                    )
 675                })
 676                .await?;
 677            Ok(result.workspace)
 678        })
 679    }
 680
 681    pub fn workspace(&self) -> &Entity<Workspace> {
 682        &self.workspaces[self.active_workspace_index]
 683    }
 684
 685    pub fn workspaces(&self) -> &[Entity<Workspace>] {
 686        &self.workspaces
 687    }
 688
 689    pub fn active_workspace_index(&self) -> usize {
 690        self.active_workspace_index
 691    }
 692
 693    /// Adds a workspace to this window without changing which workspace is
 694    /// active.
 695    pub fn add(&mut self, workspace: Entity<Workspace>, window: &Window, cx: &mut Context<Self>) {
 696        if !self.multi_workspace_enabled(cx) {
 697            self.set_single_workspace(workspace, cx);
 698            return;
 699        }
 700
 701        self.insert_workspace(workspace, window, cx);
 702    }
 703
 704    /// Ensures the workspace is in the multiworkspace and makes it the active one.
 705    pub fn activate(
 706        &mut self,
 707        workspace: Entity<Workspace>,
 708        window: &mut Window,
 709        cx: &mut Context<Self>,
 710    ) {
 711        if !self.multi_workspace_enabled(cx) {
 712            self.set_single_workspace(workspace, cx);
 713            return;
 714        }
 715
 716        let index = self.insert_workspace(workspace, &*window, cx);
 717        let changed = self.active_workspace_index != index;
 718        self.active_workspace_index = index;
 719        if changed {
 720            cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
 721            self.serialize(cx);
 722        }
 723        self.focus_active_workspace(window, cx);
 724        cx.notify();
 725    }
 726
 727    fn set_single_workspace(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) {
 728        self.workspaces[0] = workspace;
 729        self.active_workspace_index = 0;
 730        cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
 731        cx.notify();
 732    }
 733
 734    /// Inserts a workspace into the list if not already present. Returns the
 735    /// index of the workspace (existing or newly inserted). Does not change
 736    /// the active workspace index.
 737    fn insert_workspace(
 738        &mut self,
 739        workspace: Entity<Workspace>,
 740        window: &Window,
 741        cx: &mut Context<Self>,
 742    ) -> usize {
 743        if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
 744            index
 745        } else {
 746            let project_group_key = workspace.read(cx).project().read(cx).project_group_key(cx);
 747
 748            Self::subscribe_to_workspace(&workspace, window, cx);
 749            self.sync_sidebar_to_workspace(&workspace, cx);
 750            let weak_self = cx.weak_entity();
 751            workspace.update(cx, |workspace, cx| {
 752                workspace.set_multi_workspace(weak_self, cx);
 753            });
 754
 755            self.add_project_group_key(project_group_key);
 756            self.workspaces.push(workspace.clone());
 757            cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
 758            cx.notify();
 759            self.workspaces.len() - 1
 760        }
 761    }
 762
 763    /// Clears session state and DB binding for a workspace that is being
 764    /// removed or replaced. The DB row is preserved so the workspace still
 765    /// appears in the recent-projects list.
 766    fn detach_workspace(&mut self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
 767        workspace.update(cx, |workspace, _cx| {
 768            workspace.session_id.take();
 769            workspace._schedule_serialize_workspace.take();
 770            workspace._serialize_workspace_task.take();
 771        });
 772
 773        if let Some(workspace_id) = workspace.read(cx).database_id() {
 774            let db = crate::persistence::WorkspaceDb::global(cx);
 775            self.pending_removal_tasks.retain(|task| !task.is_ready());
 776            self.pending_removal_tasks
 777                .push(cx.background_spawn(async move {
 778                    db.set_session_binding(workspace_id, None, None)
 779                        .await
 780                        .log_err();
 781                }));
 782        }
 783    }
 784
 785    fn sync_sidebar_to_workspace(&self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
 786        if self.sidebar_open {
 787            let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
 788            workspace.update(cx, |workspace, _| {
 789                workspace.set_sidebar_focus_handle(sidebar_focus_handle);
 790            });
 791        }
 792    }
 793
 794    fn cycle_workspace(&mut self, delta: isize, window: &mut Window, cx: &mut Context<Self>) {
 795        let count = self.workspaces.len() as isize;
 796        if count <= 1 {
 797            return;
 798        }
 799        let current = self.active_workspace_index as isize;
 800        let next = ((current + delta).rem_euclid(count)) as usize;
 801        let workspace = self.workspaces[next].clone();
 802        self.activate(workspace, window, cx);
 803    }
 804
 805    fn next_workspace(&mut self, _: &NextWorkspace, window: &mut Window, cx: &mut Context<Self>) {
 806        self.cycle_workspace(1, window, cx);
 807    }
 808
 809    fn previous_workspace(
 810        &mut self,
 811        _: &PreviousWorkspace,
 812        window: &mut Window,
 813        cx: &mut Context<Self>,
 814    ) {
 815        self.cycle_workspace(-1, window, cx);
 816    }
 817
 818    pub(crate) fn serialize(&mut self, cx: &mut Context<Self>) {
 819        self._serialize_task = Some(cx.spawn(async move |this, cx| {
 820            let Some((window_id, state)) = this
 821                .read_with(cx, |this, cx| {
 822                    let state = MultiWorkspaceState {
 823                        active_workspace_id: this.workspace().read(cx).database_id(),
 824                        project_group_keys: this
 825                            .project_group_keys()
 826                            .cloned()
 827                            .map(Into::into)
 828                            .collect::<Vec<_>>(),
 829                        sidebar_open: this.sidebar_open,
 830                        sidebar_state: this.sidebar.as_ref().and_then(|s| s.serialized_state(cx)),
 831                    };
 832                    (this.window_id, state)
 833                })
 834                .ok()
 835            else {
 836                return;
 837            };
 838            let kvp = cx.update(|cx| db::kvp::KeyValueStore::global(cx));
 839            crate::persistence::write_multi_workspace_state(&kvp, window_id, state).await;
 840        }));
 841    }
 842
 843    /// Returns the in-flight serialization task (if any) so the caller can
 844    /// await it. Used by the quit handler to ensure pending DB writes
 845    /// complete before the process exits.
 846    pub fn flush_serialization(&mut self) -> Task<()> {
 847        self._serialize_task.take().unwrap_or(Task::ready(()))
 848    }
 849
 850    fn app_will_quit(&mut self, _cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
 851        let mut tasks: Vec<Task<()>> = Vec::new();
 852        if let Some(task) = self._serialize_task.take() {
 853            tasks.push(task);
 854        }
 855        tasks.extend(std::mem::take(&mut self.pending_removal_tasks));
 856
 857        async move {
 858            futures::future::join_all(tasks).await;
 859        }
 860    }
 861
 862    pub fn focus_active_workspace(&self, window: &mut Window, cx: &mut App) {
 863        // If a dock panel is zoomed, focus it instead of the center pane.
 864        // Otherwise, focusing the center pane triggers dismiss_zoomed_items_to_reveal
 865        // which closes the zoomed dock.
 866        let focus_handle = {
 867            let workspace = self.workspace().read(cx);
 868            let mut target = None;
 869            for dock in workspace.all_docks() {
 870                let dock = dock.read(cx);
 871                if dock.is_open() {
 872                    if let Some(panel) = dock.active_panel() {
 873                        if panel.is_zoomed(window, cx) {
 874                            target = Some(panel.panel_focus_handle(cx));
 875                            break;
 876                        }
 877                    }
 878                }
 879            }
 880            target.unwrap_or_else(|| {
 881                let pane = workspace.active_pane().clone();
 882                pane.read(cx).focus_handle(cx)
 883            })
 884        };
 885        window.focus(&focus_handle, cx);
 886    }
 887
 888    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 889        self.workspace().read(cx).panel::<T>(cx)
 890    }
 891
 892    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 893        self.workspace().read(cx).active_modal::<V>(cx)
 894    }
 895
 896    pub fn add_panel<T: Panel>(
 897        &mut self,
 898        panel: Entity<T>,
 899        window: &mut Window,
 900        cx: &mut Context<Self>,
 901    ) {
 902        self.workspace().update(cx, |workspace, cx| {
 903            workspace.add_panel(panel, window, cx);
 904        });
 905    }
 906
 907    pub fn focus_panel<T: Panel>(
 908        &mut self,
 909        window: &mut Window,
 910        cx: &mut Context<Self>,
 911    ) -> Option<Entity<T>> {
 912        self.workspace()
 913            .update(cx, |workspace, cx| workspace.focus_panel::<T>(window, cx))
 914    }
 915
 916    // used in a test
 917    pub fn toggle_modal<V: ModalView, B>(
 918        &mut self,
 919        window: &mut Window,
 920        cx: &mut Context<Self>,
 921        build: B,
 922    ) where
 923        B: FnOnce(&mut Window, &mut gpui::Context<V>) -> V,
 924    {
 925        self.workspace().update(cx, |workspace, cx| {
 926            workspace.toggle_modal(window, cx, build);
 927        });
 928    }
 929
 930    pub fn toggle_dock(
 931        &mut self,
 932        dock_side: DockPosition,
 933        window: &mut Window,
 934        cx: &mut Context<Self>,
 935    ) {
 936        self.workspace().update(cx, |workspace, cx| {
 937            workspace.toggle_dock(dock_side, window, cx);
 938        });
 939    }
 940
 941    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 942        self.workspace().read(cx).active_item_as::<I>(cx)
 943    }
 944
 945    pub fn items_of_type<'a, T: Item>(
 946        &'a self,
 947        cx: &'a App,
 948    ) -> impl 'a + Iterator<Item = Entity<T>> {
 949        self.workspace().read(cx).items_of_type::<T>(cx)
 950    }
 951
 952    pub fn database_id(&self, cx: &App) -> Option<WorkspaceId> {
 953        self.workspace().read(cx).database_id()
 954    }
 955
 956    pub fn take_pending_removal_tasks(&mut self) -> Vec<Task<()>> {
 957        let tasks: Vec<Task<()>> = std::mem::take(&mut self.pending_removal_tasks)
 958            .into_iter()
 959            .filter(|task| !task.is_ready())
 960            .collect();
 961        tasks
 962    }
 963
 964    #[cfg(any(test, feature = "test-support"))]
 965    pub fn set_random_database_id(&mut self, cx: &mut Context<Self>) {
 966        self.workspace().update(cx, |workspace, _cx| {
 967            workspace.set_random_database_id();
 968        });
 969    }
 970
 971    #[cfg(any(test, feature = "test-support"))]
 972    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 973        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
 974        Self::new(workspace, window, cx)
 975    }
 976
 977    #[cfg(any(test, feature = "test-support"))]
 978    pub fn test_add_workspace(
 979        &mut self,
 980        project: Entity<Project>,
 981        window: &mut Window,
 982        cx: &mut Context<Self>,
 983    ) -> Entity<Workspace> {
 984        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
 985        self.activate(workspace.clone(), window, cx);
 986        workspace
 987    }
 988
 989    #[cfg(any(test, feature = "test-support"))]
 990    pub fn create_test_workspace(
 991        &mut self,
 992        window: &mut Window,
 993        cx: &mut Context<Self>,
 994    ) -> Task<()> {
 995        let app_state = self.workspace().read(cx).app_state().clone();
 996        let project = Project::local(
 997            app_state.client.clone(),
 998            app_state.node_runtime.clone(),
 999            app_state.user_store.clone(),
1000            app_state.languages.clone(),
1001            app_state.fs.clone(),
1002            None,
1003            project::LocalProjectFlags::default(),
1004            cx,
1005        );
1006        let new_workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
1007        self.activate(new_workspace.clone(), window, cx);
1008
1009        let weak_workspace = new_workspace.downgrade();
1010        let db = crate::persistence::WorkspaceDb::global(cx);
1011        cx.spawn_in(window, async move |this, cx| {
1012            let workspace_id = db.next_id().await.unwrap();
1013            let workspace = weak_workspace.upgrade().unwrap();
1014            let task: Task<()> = this
1015                .update_in(cx, |this, window, cx| {
1016                    let session_id = workspace.read(cx).session_id();
1017                    let window_id = window.window_handle().window_id().as_u64();
1018                    workspace.update(cx, |workspace, _cx| {
1019                        workspace.set_database_id(workspace_id);
1020                    });
1021                    this.serialize(cx);
1022                    let db = db.clone();
1023                    cx.background_spawn(async move {
1024                        db.set_session_binding(workspace_id, session_id, Some(window_id))
1025                            .await
1026                            .log_err();
1027                    })
1028                })
1029                .unwrap();
1030            task.await
1031        })
1032    }
1033
1034    pub fn remove(
1035        &mut self,
1036        workspace: &Entity<Workspace>,
1037        window: &mut Window,
1038        cx: &mut Context<Self>,
1039    ) -> bool {
1040        let Some(index) = self.workspaces.iter().position(|w| w == workspace) else {
1041            return false;
1042        };
1043        if self.workspaces.len() <= 1 {
1044            return false;
1045        }
1046
1047        let removed_workspace = self.workspaces.remove(index);
1048
1049        if self.active_workspace_index >= self.workspaces.len() {
1050            self.active_workspace_index = self.workspaces.len() - 1;
1051        } else if self.active_workspace_index > index {
1052            self.active_workspace_index -= 1;
1053        }
1054
1055        self.detach_workspace(&removed_workspace, cx);
1056
1057        self.serialize(cx);
1058        self.focus_active_workspace(window, cx);
1059        cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(
1060            removed_workspace.entity_id(),
1061        ));
1062        cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
1063        cx.notify();
1064
1065        true
1066    }
1067
1068    pub fn move_workspace_to_new_window(
1069        &mut self,
1070        workspace: &Entity<Workspace>,
1071        window: &mut Window,
1072        cx: &mut Context<Self>,
1073    ) {
1074        let workspace = workspace.clone();
1075        if !self.remove(&workspace, window, cx) {
1076            return;
1077        }
1078
1079        let app_state: Arc<AppState> = workspace.read(cx).app_state().clone();
1080
1081        cx.defer(move |cx| {
1082            let options = (app_state.build_window_options)(None, cx);
1083
1084            let Ok(window) = cx.open_window(options, |window, cx| {
1085                cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1086            }) else {
1087                return;
1088            };
1089
1090            let _ = window.update(cx, |_, window, _| {
1091                window.activate_window();
1092            });
1093        });
1094    }
1095
1096    pub fn move_project_group_to_new_window(
1097        &mut self,
1098        key: &ProjectGroupKey,
1099        window: &mut Window,
1100        cx: &mut Context<Self>,
1101    ) {
1102        let workspaces: Vec<_> = self
1103            .workspaces_for_project_group(key, cx)
1104            .cloned()
1105            .collect();
1106        if workspaces.is_empty() {
1107            return;
1108        }
1109
1110        self.project_group_keys.retain(|k| k != key);
1111
1112        let mut removed = Vec::new();
1113        for workspace in &workspaces {
1114            if self.remove(workspace, window, cx) {
1115                removed.push(workspace.clone());
1116            }
1117        }
1118
1119        if removed.is_empty() {
1120            return;
1121        }
1122
1123        let app_state = removed[0].read(cx).app_state().clone();
1124
1125        cx.defer(move |cx| {
1126            let options = (app_state.build_window_options)(None, cx);
1127
1128            let first = removed[0].clone();
1129            let rest = removed[1..].to_vec();
1130
1131            let Ok(new_window) = cx.open_window(options, |window, cx| {
1132                cx.new(|cx| MultiWorkspace::new(first, window, cx))
1133            }) else {
1134                return;
1135            };
1136
1137            new_window
1138                .update(cx, |mw, window, cx| {
1139                    for workspace in rest {
1140                        mw.activate(workspace, window, cx);
1141                    }
1142                    window.activate_window();
1143                })
1144                .log_err();
1145        });
1146    }
1147
1148    fn move_active_workspace_to_new_window(
1149        &mut self,
1150        _: &MoveWorkspaceToNewWindow,
1151        window: &mut Window,
1152        cx: &mut Context<Self>,
1153    ) {
1154        let workspace = self.workspace().clone();
1155        self.move_workspace_to_new_window(&workspace, window, cx);
1156    }
1157
1158    pub fn open_project(
1159        &mut self,
1160        paths: Vec<PathBuf>,
1161        open_mode: OpenMode,
1162        window: &mut Window,
1163        cx: &mut Context<Self>,
1164    ) -> Task<Result<Entity<Workspace>>> {
1165        if self.multi_workspace_enabled(cx) {
1166            self.find_or_create_local_workspace(PathList::new(&paths), window, cx)
1167        } else {
1168            let workspace = self.workspace().clone();
1169            cx.spawn_in(window, async move |_this, cx| {
1170                let should_continue = workspace
1171                    .update_in(cx, |workspace, window, cx| {
1172                        workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx)
1173                    })?
1174                    .await?;
1175                if should_continue {
1176                    workspace
1177                        .update_in(cx, |workspace, window, cx| {
1178                            workspace.open_workspace_for_paths(open_mode, paths, window, cx)
1179                        })?
1180                        .await
1181                } else {
1182                    Ok(workspace)
1183                }
1184            })
1185        }
1186    }
1187}
1188
1189impl Render for MultiWorkspace {
1190    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1191        let multi_workspace_enabled = self.multi_workspace_enabled(cx);
1192        let sidebar_side = self.sidebar_side(cx);
1193        let sidebar_on_right = sidebar_side == SidebarSide::Right;
1194
1195        let sidebar: Option<AnyElement> = if multi_workspace_enabled && self.sidebar_open() {
1196            self.sidebar.as_ref().map(|sidebar_handle| {
1197                let weak = cx.weak_entity();
1198
1199                let sidebar_width = sidebar_handle.width(cx);
1200                let resize_handle = deferred(
1201                    div()
1202                        .id("sidebar-resize-handle")
1203                        .absolute()
1204                        .when(!sidebar_on_right, |el| {
1205                            el.right(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1206                        })
1207                        .when(sidebar_on_right, |el| {
1208                            el.left(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1209                        })
1210                        .top(px(0.))
1211                        .h_full()
1212                        .w(SIDEBAR_RESIZE_HANDLE_SIZE)
1213                        .cursor_col_resize()
1214                        .on_drag(DraggedSidebar, |dragged, _, _, cx| {
1215                            cx.stop_propagation();
1216                            cx.new(|_| dragged.clone())
1217                        })
1218                        .on_mouse_down(MouseButton::Left, |_, _, cx| {
1219                            cx.stop_propagation();
1220                        })
1221                        .on_mouse_up(MouseButton::Left, move |event, _, cx| {
1222                            if event.click_count == 2 {
1223                                weak.update(cx, |this, cx| {
1224                                    if let Some(sidebar) = this.sidebar.as_mut() {
1225                                        sidebar.set_width(None, cx);
1226                                    }
1227                                    this.serialize(cx);
1228                                })
1229                                .ok();
1230                                cx.stop_propagation();
1231                            } else {
1232                                weak.update(cx, |this, cx| {
1233                                    this.serialize(cx);
1234                                })
1235                                .ok();
1236                            }
1237                        })
1238                        .occlude(),
1239                );
1240
1241                div()
1242                    .id("sidebar-container")
1243                    .relative()
1244                    .h_full()
1245                    .w(sidebar_width)
1246                    .flex_shrink_0()
1247                    .child(sidebar_handle.to_any())
1248                    .child(resize_handle)
1249                    .into_any_element()
1250            })
1251        } else {
1252            None
1253        };
1254
1255        let (left_sidebar, right_sidebar) = if sidebar_on_right {
1256            (None, sidebar)
1257        } else {
1258            (sidebar, None)
1259        };
1260
1261        let ui_font = theme_settings::setup_ui_font(window, cx);
1262        let text_color = cx.theme().colors().text;
1263
1264        let workspace = self.workspace().clone();
1265        let workspace_key_context = workspace.update(cx, |workspace, cx| workspace.key_context(cx));
1266        let root = workspace.update(cx, |workspace, cx| workspace.actions(h_flex(), window, cx));
1267
1268        client_side_decorations(
1269            root.key_context(workspace_key_context)
1270                .relative()
1271                .size_full()
1272                .font(ui_font)
1273                .text_color(text_color)
1274                .on_action(cx.listener(Self::close_window))
1275                .when(self.multi_workspace_enabled(cx), |this| {
1276                    this.on_action(cx.listener(
1277                        |this: &mut Self, _: &ToggleWorkspaceSidebar, window, cx| {
1278                            this.toggle_sidebar(window, cx);
1279                        },
1280                    ))
1281                    .on_action(cx.listener(
1282                        |this: &mut Self, _: &CloseWorkspaceSidebar, window, cx| {
1283                            this.close_sidebar_action(window, cx);
1284                        },
1285                    ))
1286                    .on_action(cx.listener(
1287                        |this: &mut Self, _: &FocusWorkspaceSidebar, window, cx| {
1288                            this.focus_sidebar(window, cx);
1289                        },
1290                    ))
1291                    .on_action(cx.listener(Self::next_workspace))
1292                    .on_action(cx.listener(Self::previous_workspace))
1293                    .on_action(cx.listener(Self::move_active_workspace_to_new_window))
1294                    .on_action(cx.listener(
1295                        |this: &mut Self, action: &ToggleThreadSwitcher, window, cx| {
1296                            if let Some(sidebar) = &this.sidebar {
1297                                sidebar.toggle_thread_switcher(action.select_last, window, cx);
1298                            }
1299                        },
1300                    ))
1301                })
1302                .when(
1303                    self.sidebar_open() && self.multi_workspace_enabled(cx),
1304                    |this| {
1305                        this.on_drag_move(cx.listener(
1306                            move |this: &mut Self,
1307                                  e: &DragMoveEvent<DraggedSidebar>,
1308                                  window,
1309                                  cx| {
1310                                if let Some(sidebar) = &this.sidebar {
1311                                    let new_width = if sidebar_on_right {
1312                                        window.bounds().size.width - e.event.position.x
1313                                    } else {
1314                                        e.event.position.x
1315                                    };
1316                                    sidebar.set_width(Some(new_width), cx);
1317                                }
1318                            },
1319                        ))
1320                    },
1321                )
1322                .children(left_sidebar)
1323                .child(
1324                    div()
1325                        .flex()
1326                        .flex_1()
1327                        .size_full()
1328                        .overflow_hidden()
1329                        .child(self.workspace().clone()),
1330                )
1331                .children(right_sidebar)
1332                .child(self.workspace().read(cx).modal_layer.clone())
1333                .children(self.sidebar_overlay.as_ref().map(|view| {
1334                    deferred(div().absolute().size_full().inset_0().occlude().child(
1335                        v_flex().h(px(0.0)).top_20().items_center().child(
1336                            h_flex().occlude().child(view.clone()).on_mouse_down(
1337                                MouseButton::Left,
1338                                |_, _, cx| {
1339                                    cx.stop_propagation();
1340                                },
1341                            ),
1342                        ),
1343                    ))
1344                    .with_priority(2)
1345                })),
1346            window,
1347            cx,
1348            Tiling {
1349                left: !sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1350                right: sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1351                ..Tiling::default()
1352            },
1353        )
1354    }
1355}