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 window_id(&self) -> WindowId {
 313        self.window_id
 314    }
 315
 316    pub fn set_sidebar_overlay(&mut self, overlay: Option<AnyView>, cx: &mut Context<Self>) {
 317        self.sidebar_overlay = overlay;
 318        cx.notify();
 319    }
 320
 321    pub fn sidebar_open(&self) -> bool {
 322        self.sidebar_open
 323    }
 324
 325    pub fn sidebar_has_notifications(&self, cx: &App) -> bool {
 326        self.sidebar
 327            .as_ref()
 328            .map_or(false, |s| s.has_notifications(cx))
 329    }
 330
 331    pub fn is_threads_list_view_active(&self, cx: &App) -> bool {
 332        self.sidebar
 333            .as_ref()
 334            .map_or(false, |s| s.is_threads_list_view_active(cx))
 335    }
 336
 337    pub fn multi_workspace_enabled(&self, cx: &App) -> bool {
 338        cx.has_flag::<AgentV2FeatureFlag>() && !DisableAiSettings::get_global(cx).disable_ai
 339    }
 340
 341    pub fn toggle_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 342        if !self.multi_workspace_enabled(cx) {
 343            return;
 344        }
 345
 346        if self.sidebar_open {
 347            self.close_sidebar(window, cx);
 348        } else {
 349            self.open_sidebar(cx);
 350            if let Some(sidebar) = &self.sidebar {
 351                sidebar.prepare_for_focus(window, cx);
 352                sidebar.focus(window, cx);
 353            }
 354        }
 355    }
 356
 357    pub fn close_sidebar_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 358        if !self.multi_workspace_enabled(cx) {
 359            return;
 360        }
 361
 362        if self.sidebar_open {
 363            self.close_sidebar(window, cx);
 364        }
 365    }
 366
 367    pub fn focus_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 368        if !self.multi_workspace_enabled(cx) {
 369            return;
 370        }
 371
 372        if self.sidebar_open {
 373            let sidebar_is_focused = self
 374                .sidebar
 375                .as_ref()
 376                .is_some_and(|s| s.focus_handle(cx).contains_focused(window, cx));
 377
 378            if sidebar_is_focused {
 379                let pane = self.workspace().read(cx).active_pane().clone();
 380                let pane_focus = pane.read(cx).focus_handle(cx);
 381                window.focus(&pane_focus, cx);
 382            } else if let Some(sidebar) = &self.sidebar {
 383                sidebar.prepare_for_focus(window, cx);
 384                sidebar.focus(window, cx);
 385            }
 386        } else {
 387            self.open_sidebar(cx);
 388            if let Some(sidebar) = &self.sidebar {
 389                sidebar.prepare_for_focus(window, cx);
 390                sidebar.focus(window, cx);
 391            }
 392        }
 393    }
 394
 395    pub fn open_sidebar(&mut self, cx: &mut Context<Self>) {
 396        self.sidebar_open = true;
 397        let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
 398        for workspace in &self.workspaces {
 399            workspace.update(cx, |workspace, _cx| {
 400                workspace.set_sidebar_focus_handle(sidebar_focus_handle.clone());
 401            });
 402        }
 403        self.serialize(cx);
 404        cx.notify();
 405    }
 406
 407    pub fn close_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 408        self.sidebar_open = false;
 409        for workspace in &self.workspaces {
 410            workspace.update(cx, |workspace, _cx| {
 411                workspace.set_sidebar_focus_handle(None);
 412            });
 413        }
 414        let pane = self.workspace().read(cx).active_pane().clone();
 415        let pane_focus = pane.read(cx).focus_handle(cx);
 416        window.focus(&pane_focus, cx);
 417        self.serialize(cx);
 418        cx.notify();
 419    }
 420
 421    pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
 422        cx.spawn_in(window, async move |this, cx| {
 423            let workspaces = this.update(cx, |multi_workspace, _cx| {
 424                multi_workspace.workspaces().to_vec()
 425            })?;
 426
 427            for workspace in workspaces {
 428                let should_continue = workspace
 429                    .update_in(cx, |workspace, window, cx| {
 430                        workspace.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 431                    })?
 432                    .await?;
 433                if !should_continue {
 434                    return anyhow::Ok(());
 435                }
 436            }
 437
 438            cx.update(|window, _cx| {
 439                window.remove_window();
 440            })?;
 441
 442            anyhow::Ok(())
 443        })
 444        .detach_and_log_err(cx);
 445    }
 446
 447    fn subscribe_to_workspace(
 448        workspace: &Entity<Workspace>,
 449        window: &Window,
 450        cx: &mut Context<Self>,
 451    ) {
 452        let project = workspace.read(cx).project().clone();
 453        cx.subscribe_in(&project, window, {
 454            let workspace = workspace.downgrade();
 455            move |this, _project, event, _window, cx| match event {
 456                project::Event::WorktreeAdded(_) | project::Event::WorktreeRemoved(_) => {
 457                    if let Some(workspace) = workspace.upgrade() {
 458                        this.add_project_group_key(workspace.read(cx).project_group_key(cx));
 459                    }
 460                }
 461                _ => {}
 462            }
 463        })
 464        .detach();
 465
 466        cx.subscribe_in(workspace, window, |this, workspace, event, window, cx| {
 467            if let WorkspaceEvent::Activate = event {
 468                this.activate(workspace.clone(), window, cx);
 469            }
 470        })
 471        .detach();
 472    }
 473
 474    pub fn add_project_group_key(&mut self, project_group_key: ProjectGroupKey) {
 475        if self.project_group_keys.contains(&project_group_key) {
 476            return;
 477        }
 478        self.project_group_keys.push(project_group_key);
 479    }
 480
 481    pub fn project_group_keys(&self) -> impl Iterator<Item = &ProjectGroupKey> {
 482        self.project_group_keys.iter()
 483    }
 484
 485    /// Returns the project groups, ordered by most recently added.
 486    pub fn project_groups(
 487        &self,
 488        cx: &App,
 489    ) -> impl Iterator<Item = (ProjectGroupKey, Vec<Entity<Workspace>>)> {
 490        let mut groups = self
 491            .project_group_keys
 492            .iter()
 493            .rev()
 494            .map(|key| (key.clone(), Vec::new()))
 495            .collect::<Vec<_>>();
 496        for workspace in &self.workspaces {
 497            let key = workspace.read(cx).project_group_key(cx);
 498            if let Some((_, workspaces)) = groups.iter_mut().find(|(k, _)| k == &key) {
 499                workspaces.push(workspace.clone());
 500            }
 501        }
 502        groups.into_iter()
 503    }
 504
 505    pub fn workspaces_for_project_group(
 506        &self,
 507        project_group_key: &ProjectGroupKey,
 508        cx: &App,
 509    ) -> impl Iterator<Item = &Entity<Workspace>> {
 510        self.workspaces
 511            .iter()
 512            .filter(move |ws| ws.read(cx).project_group_key(cx) == *project_group_key)
 513    }
 514
 515    pub fn remove_folder_from_project_group(
 516        &mut self,
 517        project_group_key: &ProjectGroupKey,
 518        path: &Path,
 519        cx: &mut Context<Self>,
 520    ) {
 521        let new_path_list = project_group_key.path_list().without_path(path);
 522        if new_path_list.is_empty() {
 523            return;
 524        }
 525
 526        let new_key = ProjectGroupKey::new(project_group_key.host(), new_path_list);
 527
 528        let workspaces: Vec<_> = self
 529            .workspaces_for_project_group(project_group_key, cx)
 530            .cloned()
 531            .collect();
 532
 533        self.add_project_group_key(new_key);
 534
 535        for workspace in workspaces {
 536            let project = workspace.read(cx).project().clone();
 537            project.update(cx, |project, cx| {
 538                project.remove_worktree_for_main_worktree_path(path, cx);
 539            });
 540        }
 541
 542        self.serialize(cx);
 543        cx.notify();
 544    }
 545
 546    pub fn prompt_to_add_folders_to_project_group(
 547        &mut self,
 548        key: &ProjectGroupKey,
 549        window: &mut Window,
 550        cx: &mut Context<Self>,
 551    ) {
 552        let paths = self.workspace().update(cx, |workspace, cx| {
 553            workspace.prompt_for_open_path(
 554                PathPromptOptions {
 555                    files: false,
 556                    directories: true,
 557                    multiple: true,
 558                    prompt: None,
 559                },
 560                DirectoryLister::Project(workspace.project().clone()),
 561                window,
 562                cx,
 563            )
 564        });
 565
 566        let key = key.clone();
 567        cx.spawn_in(window, async move |this, cx| {
 568            if let Some(new_paths) = paths.await.ok().flatten() {
 569                if !new_paths.is_empty() {
 570                    this.update(cx, |multi_workspace, cx| {
 571                        multi_workspace.add_folders_to_project_group(&key, new_paths, cx);
 572                    })?;
 573                }
 574            }
 575            anyhow::Ok(())
 576        })
 577        .detach_and_log_err(cx);
 578    }
 579
 580    pub fn add_folders_to_project_group(
 581        &mut self,
 582        project_group_key: &ProjectGroupKey,
 583        new_paths: Vec<PathBuf>,
 584        cx: &mut Context<Self>,
 585    ) {
 586        let mut all_paths: Vec<PathBuf> = project_group_key.path_list().paths().to_vec();
 587        all_paths.extend(new_paths.iter().cloned());
 588        let new_path_list = PathList::new(&all_paths);
 589        let new_key = ProjectGroupKey::new(project_group_key.host(), new_path_list);
 590
 591        let workspaces: Vec<_> = self
 592            .workspaces_for_project_group(project_group_key, cx)
 593            .cloned()
 594            .collect();
 595
 596        self.add_project_group_key(new_key);
 597
 598        for workspace in workspaces {
 599            let project = workspace.read(cx).project().clone();
 600            for path in &new_paths {
 601                project
 602                    .update(cx, |project, cx| {
 603                        project.find_or_create_worktree(path, true, cx)
 604                    })
 605                    .detach_and_log_err(cx);
 606            }
 607        }
 608
 609        self.serialize(cx);
 610        cx.notify();
 611    }
 612
 613    pub fn remove_project_group(
 614        &mut self,
 615        key: &ProjectGroupKey,
 616        window: &mut Window,
 617        cx: &mut Context<Self>,
 618    ) {
 619        self.project_group_keys.retain(|k| k != key);
 620
 621        let workspaces: Vec<_> = self
 622            .workspaces_for_project_group(key, cx)
 623            .cloned()
 624            .collect();
 625        for workspace in workspaces {
 626            self.remove(&workspace, window, cx);
 627        }
 628
 629        self.serialize(cx);
 630        cx.notify();
 631    }
 632
 633    /// Finds an existing workspace in this multi-workspace whose paths match,
 634    /// or creates a new one (deserializing its saved state from the database).
 635    /// Never searches other windows or matches workspaces with a superset of
 636    /// the requested paths.
 637    pub fn find_or_create_local_workspace(
 638        &mut self,
 639        path_list: PathList,
 640        window: &mut Window,
 641        cx: &mut Context<Self>,
 642    ) -> Task<Result<Entity<Workspace>>> {
 643        if let Some(workspace) = self
 644            .workspaces
 645            .iter()
 646            .find(|ws| ws.read(cx).project_group_key(cx).path_list() == &path_list)
 647            .cloned()
 648        {
 649            self.activate(workspace.clone(), window, cx);
 650            return Task::ready(Ok(workspace));
 651        }
 652
 653        let paths = path_list.paths().to_vec();
 654        let app_state = self.workspace().read(cx).app_state().clone();
 655        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 656
 657        cx.spawn(async move |_this, cx| {
 658            let result = cx
 659                .update(|cx| {
 660                    Workspace::new_local(
 661                        paths,
 662                        app_state,
 663                        requesting_window,
 664                        None,
 665                        None,
 666                        OpenMode::Activate,
 667                        cx,
 668                    )
 669                })
 670                .await?;
 671            Ok(result.workspace)
 672        })
 673    }
 674
 675    pub fn workspace(&self) -> &Entity<Workspace> {
 676        &self.workspaces[self.active_workspace_index]
 677    }
 678
 679    pub fn workspaces(&self) -> &[Entity<Workspace>] {
 680        &self.workspaces
 681    }
 682
 683    pub fn active_workspace_index(&self) -> usize {
 684        self.active_workspace_index
 685    }
 686
 687    /// Adds a workspace to this window without changing which workspace is
 688    /// active.
 689    pub fn add(&mut self, workspace: Entity<Workspace>, window: &Window, cx: &mut Context<Self>) {
 690        if !self.multi_workspace_enabled(cx) {
 691            self.set_single_workspace(workspace, cx);
 692            return;
 693        }
 694
 695        self.insert_workspace(workspace, window, cx);
 696    }
 697
 698    /// Ensures the workspace is in the multiworkspace and makes it the active one.
 699    pub fn activate(
 700        &mut self,
 701        workspace: Entity<Workspace>,
 702        window: &mut Window,
 703        cx: &mut Context<Self>,
 704    ) {
 705        if !self.multi_workspace_enabled(cx) {
 706            self.set_single_workspace(workspace, cx);
 707            return;
 708        }
 709
 710        let index = self.insert_workspace(workspace, &*window, cx);
 711        let changed = self.active_workspace_index != index;
 712        self.active_workspace_index = index;
 713        if changed {
 714            cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
 715            self.serialize(cx);
 716        }
 717        self.focus_active_workspace(window, cx);
 718        cx.notify();
 719    }
 720
 721    fn set_single_workspace(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) {
 722        self.workspaces[0] = workspace;
 723        self.active_workspace_index = 0;
 724        cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
 725        cx.notify();
 726    }
 727
 728    /// Inserts a workspace into the list if not already present. Returns the
 729    /// index of the workspace (existing or newly inserted). Does not change
 730    /// the active workspace index.
 731    fn insert_workspace(
 732        &mut self,
 733        workspace: Entity<Workspace>,
 734        window: &Window,
 735        cx: &mut Context<Self>,
 736    ) -> usize {
 737        if let Some(index) = self.workspaces.iter().position(|w| *w == workspace) {
 738            index
 739        } else {
 740            let project_group_key = workspace.read(cx).project().read(cx).project_group_key(cx);
 741
 742            Self::subscribe_to_workspace(&workspace, window, cx);
 743            self.sync_sidebar_to_workspace(&workspace, cx);
 744            let weak_self = cx.weak_entity();
 745            workspace.update(cx, |workspace, cx| {
 746                workspace.set_multi_workspace(weak_self, cx);
 747            });
 748
 749            self.add_project_group_key(project_group_key);
 750            self.workspaces.push(workspace.clone());
 751            cx.emit(MultiWorkspaceEvent::WorkspaceAdded(workspace));
 752            cx.notify();
 753            self.workspaces.len() - 1
 754        }
 755    }
 756
 757    /// Clears session state and DB binding for a workspace that is being
 758    /// removed or replaced. The DB row is preserved so the workspace still
 759    /// appears in the recent-projects list.
 760    fn detach_workspace(&mut self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
 761        workspace.update(cx, |workspace, _cx| {
 762            workspace.session_id.take();
 763            workspace._schedule_serialize_workspace.take();
 764            workspace._serialize_workspace_task.take();
 765        });
 766
 767        if let Some(workspace_id) = workspace.read(cx).database_id() {
 768            let db = crate::persistence::WorkspaceDb::global(cx);
 769            self.pending_removal_tasks.retain(|task| !task.is_ready());
 770            self.pending_removal_tasks
 771                .push(cx.background_spawn(async move {
 772                    db.set_session_binding(workspace_id, None, None)
 773                        .await
 774                        .log_err();
 775                }));
 776        }
 777    }
 778
 779    fn sync_sidebar_to_workspace(&self, workspace: &Entity<Workspace>, cx: &mut Context<Self>) {
 780        if self.sidebar_open {
 781            let sidebar_focus_handle = self.sidebar.as_ref().map(|s| s.focus_handle(cx));
 782            workspace.update(cx, |workspace, _| {
 783                workspace.set_sidebar_focus_handle(sidebar_focus_handle);
 784            });
 785        }
 786    }
 787
 788    fn cycle_workspace(&mut self, delta: isize, window: &mut Window, cx: &mut Context<Self>) {
 789        let count = self.workspaces.len() as isize;
 790        if count <= 1 {
 791            return;
 792        }
 793        let current = self.active_workspace_index as isize;
 794        let next = ((current + delta).rem_euclid(count)) as usize;
 795        let workspace = self.workspaces[next].clone();
 796        self.activate(workspace, window, cx);
 797    }
 798
 799    fn next_workspace(&mut self, _: &NextWorkspace, window: &mut Window, cx: &mut Context<Self>) {
 800        self.cycle_workspace(1, window, cx);
 801    }
 802
 803    fn previous_workspace(
 804        &mut self,
 805        _: &PreviousWorkspace,
 806        window: &mut Window,
 807        cx: &mut Context<Self>,
 808    ) {
 809        self.cycle_workspace(-1, window, cx);
 810    }
 811
 812    pub(crate) fn serialize(&mut self, cx: &mut Context<Self>) {
 813        self._serialize_task = Some(cx.spawn(async move |this, cx| {
 814            let Some((window_id, state)) = this
 815                .read_with(cx, |this, cx| {
 816                    let state = MultiWorkspaceState {
 817                        active_workspace_id: this.workspace().read(cx).database_id(),
 818                        project_group_keys: this
 819                            .project_group_keys()
 820                            .cloned()
 821                            .map(Into::into)
 822                            .collect::<Vec<_>>(),
 823                        sidebar_open: this.sidebar_open,
 824                        sidebar_state: this.sidebar.as_ref().and_then(|s| s.serialized_state(cx)),
 825                    };
 826                    (this.window_id, state)
 827                })
 828                .ok()
 829            else {
 830                return;
 831            };
 832            let kvp = cx.update(|cx| db::kvp::KeyValueStore::global(cx));
 833            crate::persistence::write_multi_workspace_state(&kvp, window_id, state).await;
 834        }));
 835    }
 836
 837    /// Returns the in-flight serialization task (if any) so the caller can
 838    /// await it. Used by the quit handler to ensure pending DB writes
 839    /// complete before the process exits.
 840    pub fn flush_serialization(&mut self) -> Task<()> {
 841        self._serialize_task.take().unwrap_or(Task::ready(()))
 842    }
 843
 844    fn app_will_quit(&mut self, _cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
 845        let mut tasks: Vec<Task<()>> = Vec::new();
 846        if let Some(task) = self._serialize_task.take() {
 847            tasks.push(task);
 848        }
 849        tasks.extend(std::mem::take(&mut self.pending_removal_tasks));
 850
 851        async move {
 852            futures::future::join_all(tasks).await;
 853        }
 854    }
 855
 856    pub fn focus_active_workspace(&self, window: &mut Window, cx: &mut App) {
 857        // If a dock panel is zoomed, focus it instead of the center pane.
 858        // Otherwise, focusing the center pane triggers dismiss_zoomed_items_to_reveal
 859        // which closes the zoomed dock.
 860        let focus_handle = {
 861            let workspace = self.workspace().read(cx);
 862            let mut target = None;
 863            for dock in workspace.all_docks() {
 864                let dock = dock.read(cx);
 865                if dock.is_open() {
 866                    if let Some(panel) = dock.active_panel() {
 867                        if panel.is_zoomed(window, cx) {
 868                            target = Some(panel.panel_focus_handle(cx));
 869                            break;
 870                        }
 871                    }
 872                }
 873            }
 874            target.unwrap_or_else(|| {
 875                let pane = workspace.active_pane().clone();
 876                pane.read(cx).focus_handle(cx)
 877            })
 878        };
 879        window.focus(&focus_handle, cx);
 880    }
 881
 882    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 883        self.workspace().read(cx).panel::<T>(cx)
 884    }
 885
 886    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 887        self.workspace().read(cx).active_modal::<V>(cx)
 888    }
 889
 890    pub fn add_panel<T: Panel>(
 891        &mut self,
 892        panel: Entity<T>,
 893        window: &mut Window,
 894        cx: &mut Context<Self>,
 895    ) {
 896        self.workspace().update(cx, |workspace, cx| {
 897            workspace.add_panel(panel, window, cx);
 898        });
 899    }
 900
 901    pub fn focus_panel<T: Panel>(
 902        &mut self,
 903        window: &mut Window,
 904        cx: &mut Context<Self>,
 905    ) -> Option<Entity<T>> {
 906        self.workspace()
 907            .update(cx, |workspace, cx| workspace.focus_panel::<T>(window, cx))
 908    }
 909
 910    // used in a test
 911    pub fn toggle_modal<V: ModalView, B>(
 912        &mut self,
 913        window: &mut Window,
 914        cx: &mut Context<Self>,
 915        build: B,
 916    ) where
 917        B: FnOnce(&mut Window, &mut gpui::Context<V>) -> V,
 918    {
 919        self.workspace().update(cx, |workspace, cx| {
 920            workspace.toggle_modal(window, cx, build);
 921        });
 922    }
 923
 924    pub fn toggle_dock(
 925        &mut self,
 926        dock_side: DockPosition,
 927        window: &mut Window,
 928        cx: &mut Context<Self>,
 929    ) {
 930        self.workspace().update(cx, |workspace, cx| {
 931            workspace.toggle_dock(dock_side, window, cx);
 932        });
 933    }
 934
 935    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 936        self.workspace().read(cx).active_item_as::<I>(cx)
 937    }
 938
 939    pub fn items_of_type<'a, T: Item>(
 940        &'a self,
 941        cx: &'a App,
 942    ) -> impl 'a + Iterator<Item = Entity<T>> {
 943        self.workspace().read(cx).items_of_type::<T>(cx)
 944    }
 945
 946    pub fn database_id(&self, cx: &App) -> Option<WorkspaceId> {
 947        self.workspace().read(cx).database_id()
 948    }
 949
 950    pub fn take_pending_removal_tasks(&mut self) -> Vec<Task<()>> {
 951        let tasks: Vec<Task<()>> = std::mem::take(&mut self.pending_removal_tasks)
 952            .into_iter()
 953            .filter(|task| !task.is_ready())
 954            .collect();
 955        tasks
 956    }
 957
 958    #[cfg(any(test, feature = "test-support"))]
 959    pub fn set_random_database_id(&mut self, cx: &mut Context<Self>) {
 960        self.workspace().update(cx, |workspace, _cx| {
 961            workspace.set_random_database_id();
 962        });
 963    }
 964
 965    #[cfg(any(test, feature = "test-support"))]
 966    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 967        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
 968        Self::new(workspace, window, cx)
 969    }
 970
 971    #[cfg(any(test, feature = "test-support"))]
 972    pub fn test_add_workspace(
 973        &mut self,
 974        project: Entity<Project>,
 975        window: &mut Window,
 976        cx: &mut Context<Self>,
 977    ) -> Entity<Workspace> {
 978        let workspace = cx.new(|cx| Workspace::test_new(project, window, cx));
 979        self.activate(workspace.clone(), window, cx);
 980        workspace
 981    }
 982
 983    #[cfg(any(test, feature = "test-support"))]
 984    pub fn create_test_workspace(
 985        &mut self,
 986        window: &mut Window,
 987        cx: &mut Context<Self>,
 988    ) -> Task<()> {
 989        let app_state = self.workspace().read(cx).app_state().clone();
 990        let project = Project::local(
 991            app_state.client.clone(),
 992            app_state.node_runtime.clone(),
 993            app_state.user_store.clone(),
 994            app_state.languages.clone(),
 995            app_state.fs.clone(),
 996            None,
 997            project::LocalProjectFlags::default(),
 998            cx,
 999        );
1000        let new_workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
1001        self.activate(new_workspace.clone(), window, cx);
1002
1003        let weak_workspace = new_workspace.downgrade();
1004        let db = crate::persistence::WorkspaceDb::global(cx);
1005        cx.spawn_in(window, async move |this, cx| {
1006            let workspace_id = db.next_id().await.unwrap();
1007            let workspace = weak_workspace.upgrade().unwrap();
1008            let task: Task<()> = this
1009                .update_in(cx, |this, window, cx| {
1010                    let session_id = workspace.read(cx).session_id();
1011                    let window_id = window.window_handle().window_id().as_u64();
1012                    workspace.update(cx, |workspace, _cx| {
1013                        workspace.set_database_id(workspace_id);
1014                    });
1015                    this.serialize(cx);
1016                    let db = db.clone();
1017                    cx.background_spawn(async move {
1018                        db.set_session_binding(workspace_id, session_id, Some(window_id))
1019                            .await
1020                            .log_err();
1021                    })
1022                })
1023                .unwrap();
1024            task.await
1025        })
1026    }
1027
1028    pub fn remove(
1029        &mut self,
1030        workspace: &Entity<Workspace>,
1031        window: &mut Window,
1032        cx: &mut Context<Self>,
1033    ) -> bool {
1034        let Some(index) = self.workspaces.iter().position(|w| w == workspace) else {
1035            return false;
1036        };
1037        if self.workspaces.len() <= 1 {
1038            return false;
1039        }
1040
1041        let removed_workspace = self.workspaces.remove(index);
1042
1043        if self.active_workspace_index >= self.workspaces.len() {
1044            self.active_workspace_index = self.workspaces.len() - 1;
1045        } else if self.active_workspace_index > index {
1046            self.active_workspace_index -= 1;
1047        }
1048
1049        self.detach_workspace(&removed_workspace, cx);
1050
1051        self.serialize(cx);
1052        self.focus_active_workspace(window, cx);
1053        cx.emit(MultiWorkspaceEvent::WorkspaceRemoved(
1054            removed_workspace.entity_id(),
1055        ));
1056        cx.emit(MultiWorkspaceEvent::ActiveWorkspaceChanged);
1057        cx.notify();
1058
1059        true
1060    }
1061
1062    pub fn move_workspace_to_new_window(
1063        &mut self,
1064        workspace: &Entity<Workspace>,
1065        window: &mut Window,
1066        cx: &mut Context<Self>,
1067    ) {
1068        let workspace = workspace.clone();
1069        if !self.remove(&workspace, window, cx) {
1070            return;
1071        }
1072
1073        let app_state: Arc<AppState> = workspace.read(cx).app_state().clone();
1074
1075        cx.defer(move |cx| {
1076            let options = (app_state.build_window_options)(None, cx);
1077
1078            let Ok(window) = cx.open_window(options, |window, cx| {
1079                cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1080            }) else {
1081                return;
1082            };
1083
1084            let _ = window.update(cx, |_, window, _| {
1085                window.activate_window();
1086            });
1087        });
1088    }
1089
1090    pub fn move_project_group_to_new_window(
1091        &mut self,
1092        key: &ProjectGroupKey,
1093        window: &mut Window,
1094        cx: &mut Context<Self>,
1095    ) {
1096        let workspaces: Vec<_> = self
1097            .workspaces_for_project_group(key, cx)
1098            .cloned()
1099            .collect();
1100        if workspaces.is_empty() {
1101            return;
1102        }
1103
1104        self.project_group_keys.retain(|k| k != key);
1105
1106        let mut removed = Vec::new();
1107        for workspace in &workspaces {
1108            if self.remove(workspace, window, cx) {
1109                removed.push(workspace.clone());
1110            }
1111        }
1112
1113        if removed.is_empty() {
1114            return;
1115        }
1116
1117        let app_state = removed[0].read(cx).app_state().clone();
1118
1119        cx.defer(move |cx| {
1120            let options = (app_state.build_window_options)(None, cx);
1121
1122            let first = removed[0].clone();
1123            let rest = removed[1..].to_vec();
1124
1125            let Ok(new_window) = cx.open_window(options, |window, cx| {
1126                cx.new(|cx| MultiWorkspace::new(first, window, cx))
1127            }) else {
1128                return;
1129            };
1130
1131            new_window
1132                .update(cx, |mw, window, cx| {
1133                    for workspace in rest {
1134                        mw.activate(workspace, window, cx);
1135                    }
1136                    window.activate_window();
1137                })
1138                .log_err();
1139        });
1140    }
1141
1142    fn move_active_workspace_to_new_window(
1143        &mut self,
1144        _: &MoveWorkspaceToNewWindow,
1145        window: &mut Window,
1146        cx: &mut Context<Self>,
1147    ) {
1148        let workspace = self.workspace().clone();
1149        self.move_workspace_to_new_window(&workspace, window, cx);
1150    }
1151
1152    pub fn open_project(
1153        &mut self,
1154        paths: Vec<PathBuf>,
1155        open_mode: OpenMode,
1156        window: &mut Window,
1157        cx: &mut Context<Self>,
1158    ) -> Task<Result<Entity<Workspace>>> {
1159        if self.multi_workspace_enabled(cx) {
1160            self.find_or_create_local_workspace(PathList::new(&paths), window, cx)
1161        } else {
1162            let workspace = self.workspace().clone();
1163            cx.spawn_in(window, async move |_this, cx| {
1164                let should_continue = workspace
1165                    .update_in(cx, |workspace, window, cx| {
1166                        workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx)
1167                    })?
1168                    .await?;
1169                if should_continue {
1170                    workspace
1171                        .update_in(cx, |workspace, window, cx| {
1172                            workspace.open_workspace_for_paths(open_mode, paths, window, cx)
1173                        })?
1174                        .await
1175                } else {
1176                    Ok(workspace)
1177                }
1178            })
1179        }
1180    }
1181}
1182
1183impl Render for MultiWorkspace {
1184    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1185        let multi_workspace_enabled = self.multi_workspace_enabled(cx);
1186        let sidebar_side = self.sidebar_side(cx);
1187        let sidebar_on_right = sidebar_side == SidebarSide::Right;
1188
1189        let sidebar: Option<AnyElement> = if multi_workspace_enabled && self.sidebar_open() {
1190            self.sidebar.as_ref().map(|sidebar_handle| {
1191                let weak = cx.weak_entity();
1192
1193                let sidebar_width = sidebar_handle.width(cx);
1194                let resize_handle = deferred(
1195                    div()
1196                        .id("sidebar-resize-handle")
1197                        .absolute()
1198                        .when(!sidebar_on_right, |el| {
1199                            el.right(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1200                        })
1201                        .when(sidebar_on_right, |el| {
1202                            el.left(-SIDEBAR_RESIZE_HANDLE_SIZE / 2.)
1203                        })
1204                        .top(px(0.))
1205                        .h_full()
1206                        .w(SIDEBAR_RESIZE_HANDLE_SIZE)
1207                        .cursor_col_resize()
1208                        .on_drag(DraggedSidebar, |dragged, _, _, cx| {
1209                            cx.stop_propagation();
1210                            cx.new(|_| dragged.clone())
1211                        })
1212                        .on_mouse_down(MouseButton::Left, |_, _, cx| {
1213                            cx.stop_propagation();
1214                        })
1215                        .on_mouse_up(MouseButton::Left, move |event, _, cx| {
1216                            if event.click_count == 2 {
1217                                weak.update(cx, |this, cx| {
1218                                    if let Some(sidebar) = this.sidebar.as_mut() {
1219                                        sidebar.set_width(None, cx);
1220                                    }
1221                                    this.serialize(cx);
1222                                })
1223                                .ok();
1224                                cx.stop_propagation();
1225                            } else {
1226                                weak.update(cx, |this, cx| {
1227                                    this.serialize(cx);
1228                                })
1229                                .ok();
1230                            }
1231                        })
1232                        .occlude(),
1233                );
1234
1235                div()
1236                    .id("sidebar-container")
1237                    .relative()
1238                    .h_full()
1239                    .w(sidebar_width)
1240                    .flex_shrink_0()
1241                    .child(sidebar_handle.to_any())
1242                    .child(resize_handle)
1243                    .into_any_element()
1244            })
1245        } else {
1246            None
1247        };
1248
1249        let (left_sidebar, right_sidebar) = if sidebar_on_right {
1250            (None, sidebar)
1251        } else {
1252            (sidebar, None)
1253        };
1254
1255        let ui_font = theme_settings::setup_ui_font(window, cx);
1256        let text_color = cx.theme().colors().text;
1257
1258        let workspace = self.workspace().clone();
1259        let workspace_key_context = workspace.update(cx, |workspace, cx| workspace.key_context(cx));
1260        let root = workspace.update(cx, |workspace, cx| workspace.actions(h_flex(), window, cx));
1261
1262        client_side_decorations(
1263            root.key_context(workspace_key_context)
1264                .relative()
1265                .size_full()
1266                .font(ui_font)
1267                .text_color(text_color)
1268                .on_action(cx.listener(Self::close_window))
1269                .when(self.multi_workspace_enabled(cx), |this| {
1270                    this.on_action(cx.listener(
1271                        |this: &mut Self, _: &ToggleWorkspaceSidebar, window, cx| {
1272                            this.toggle_sidebar(window, cx);
1273                        },
1274                    ))
1275                    .on_action(cx.listener(
1276                        |this: &mut Self, _: &CloseWorkspaceSidebar, window, cx| {
1277                            this.close_sidebar_action(window, cx);
1278                        },
1279                    ))
1280                    .on_action(cx.listener(
1281                        |this: &mut Self, _: &FocusWorkspaceSidebar, window, cx| {
1282                            this.focus_sidebar(window, cx);
1283                        },
1284                    ))
1285                    .on_action(cx.listener(Self::next_workspace))
1286                    .on_action(cx.listener(Self::previous_workspace))
1287                    .on_action(cx.listener(Self::move_active_workspace_to_new_window))
1288                    .on_action(cx.listener(
1289                        |this: &mut Self, action: &ToggleThreadSwitcher, window, cx| {
1290                            if let Some(sidebar) = &this.sidebar {
1291                                sidebar.toggle_thread_switcher(action.select_last, window, cx);
1292                            }
1293                        },
1294                    ))
1295                })
1296                .when(
1297                    self.sidebar_open() && self.multi_workspace_enabled(cx),
1298                    |this| {
1299                        this.on_drag_move(cx.listener(
1300                            move |this: &mut Self,
1301                                  e: &DragMoveEvent<DraggedSidebar>,
1302                                  window,
1303                                  cx| {
1304                                if let Some(sidebar) = &this.sidebar {
1305                                    let new_width = if sidebar_on_right {
1306                                        window.bounds().size.width - e.event.position.x
1307                                    } else {
1308                                        e.event.position.x
1309                                    };
1310                                    sidebar.set_width(Some(new_width), cx);
1311                                }
1312                            },
1313                        ))
1314                    },
1315                )
1316                .children(left_sidebar)
1317                .child(
1318                    div()
1319                        .flex()
1320                        .flex_1()
1321                        .size_full()
1322                        .overflow_hidden()
1323                        .child(self.workspace().clone()),
1324                )
1325                .children(right_sidebar)
1326                .child(self.workspace().read(cx).modal_layer.clone())
1327                .children(self.sidebar_overlay.as_ref().map(|view| {
1328                    deferred(div().absolute().size_full().inset_0().occlude().child(
1329                        v_flex().h(px(0.0)).top_20().items_center().child(
1330                            h_flex().occlude().child(view.clone()).on_mouse_down(
1331                                MouseButton::Left,
1332                                |_, _, cx| {
1333                                    cx.stop_propagation();
1334                                },
1335                            ),
1336                        ),
1337                    ))
1338                    .with_priority(2)
1339                })),
1340            window,
1341            cx,
1342            Tiling {
1343                left: !sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1344                right: sidebar_on_right && multi_workspace_enabled && self.sidebar_open(),
1345                ..Tiling::default()
1346            },
1347        )
1348    }
1349}