workspace.rs

    1pub mod dock;
    2pub mod history_manager;
    3pub mod invalid_item_view;
    4pub mod item;
    5mod modal_layer;
    6mod multi_workspace;
    7pub mod notifications;
    8pub mod pane;
    9pub mod pane_group;
   10pub mod path_list {
   11    pub use util::path_list::{PathList, SerializedPathList};
   12}
   13mod persistence;
   14pub mod searchable;
   15mod security_modal;
   16pub mod shared_screen;
   17pub use shared_screen::SharedScreen;
   18mod status_bar;
   19pub mod tasks;
   20mod theme_preview;
   21mod toast_layer;
   22mod toolbar;
   23pub mod welcome;
   24mod workspace_settings;
   25
   26pub use crate::notifications::NotificationFrame;
   27pub use dock::Panel;
   28pub use multi_workspace::{
   29    DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, NewWorkspaceInWindow,
   30    NextWorkspaceInWindow, PreviousWorkspaceInWindow, Sidebar, SidebarEvent, SidebarHandle,
   31    ToggleWorkspaceSidebar,
   32};
   33pub use path_list::{PathList, SerializedPathList};
   34pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   35
   36use anyhow::{Context as _, Result, anyhow};
   37use client::{
   38    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   39    proto::{self, ErrorCode, PanelId, PeerId},
   40};
   41use collections::{HashMap, HashSet, hash_map};
   42use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   43use fs::Fs;
   44use futures::{
   45    Future, FutureExt, StreamExt,
   46    channel::{
   47        mpsc::{self, UnboundedReceiver, UnboundedSender},
   48        oneshot,
   49    },
   50    future::{Shared, try_join_all},
   51};
   52use gpui::{
   53    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
   54    CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   55    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   56    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   57    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   58    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   59};
   60pub use history_manager::*;
   61pub use item::{
   62    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   63    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   64};
   65use itertools::Itertools;
   66use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   67pub use modal_layer::*;
   68use node_runtime::NodeRuntime;
   69use notifications::{
   70    DetachAndPromptErr, Notifications, dismiss_app_notification,
   71    simple_message_notification::MessageNotification,
   72};
   73pub use pane::*;
   74pub use pane_group::{
   75    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   76    SplitDirection,
   77};
   78use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
   79pub use persistence::{
   80    DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
   81    model::{ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation, SessionWorkspace},
   82    read_serialized_multi_workspaces,
   83};
   84use postage::stream::Stream;
   85use project::{
   86    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   87    WorktreeSettings,
   88    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   89    project_settings::ProjectSettings,
   90    toolchain_store::ToolchainStoreEvent,
   91    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   92};
   93use remote::{
   94    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
   95    remote_client::ConnectionIdentifier,
   96};
   97use schemars::JsonSchema;
   98use serde::Deserialize;
   99use session::AppSession;
  100use settings::{
  101    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  102};
  103
  104use sqlez::{
  105    bindable::{Bind, Column, StaticColumnCount},
  106    statement::Statement,
  107};
  108use status_bar::StatusBar;
  109pub use status_bar::StatusItemView;
  110use std::{
  111    any::TypeId,
  112    borrow::Cow,
  113    cell::RefCell,
  114    cmp,
  115    collections::VecDeque,
  116    env,
  117    hash::Hash,
  118    path::{Path, PathBuf},
  119    process::ExitStatus,
  120    rc::Rc,
  121    sync::{
  122        Arc, LazyLock, Weak,
  123        atomic::{AtomicBool, AtomicUsize},
  124    },
  125    time::Duration,
  126};
  127use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  128use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
  129pub use toolbar::{
  130    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  131};
  132pub use ui;
  133use ui::{Window, prelude::*};
  134use util::{
  135    ResultExt, TryFutureExt,
  136    paths::{PathStyle, SanitizedPath},
  137    rel_path::RelPath,
  138    serde::default_true,
  139};
  140use uuid::Uuid;
  141pub use workspace_settings::{
  142    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  143    WorkspaceSettings,
  144};
  145use zed_actions::{Spawn, feedback::FileBugReport};
  146
  147use crate::{item::ItemBufferKind, notifications::NotificationId};
  148use crate::{
  149    persistence::{
  150        SerializedAxis,
  151        model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
  152    },
  153    security_modal::SecurityModal,
  154};
  155
  156pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  157
  158static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  159    env::var("ZED_WINDOW_SIZE")
  160        .ok()
  161        .as_deref()
  162        .and_then(parse_pixel_size_env_var)
  163});
  164
  165static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  166    env::var("ZED_WINDOW_POSITION")
  167        .ok()
  168        .as_deref()
  169        .and_then(parse_pixel_position_env_var)
  170});
  171
  172pub trait TerminalProvider {
  173    fn spawn(
  174        &self,
  175        task: SpawnInTerminal,
  176        window: &mut Window,
  177        cx: &mut App,
  178    ) -> Task<Option<Result<ExitStatus>>>;
  179}
  180
  181pub trait DebuggerProvider {
  182    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  183    fn start_session(
  184        &self,
  185        definition: DebugScenario,
  186        task_context: SharedTaskContext,
  187        active_buffer: Option<Entity<Buffer>>,
  188        worktree_id: Option<WorktreeId>,
  189        window: &mut Window,
  190        cx: &mut App,
  191    );
  192
  193    fn spawn_task_or_modal(
  194        &self,
  195        workspace: &mut Workspace,
  196        action: &Spawn,
  197        window: &mut Window,
  198        cx: &mut Context<Workspace>,
  199    );
  200
  201    fn task_scheduled(&self, cx: &mut App);
  202    fn debug_scenario_scheduled(&self, cx: &mut App);
  203    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  204
  205    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  206}
  207
  208actions!(
  209    workspace,
  210    [
  211        /// Activates the next pane in the workspace.
  212        ActivateNextPane,
  213        /// Activates the previous pane in the workspace.
  214        ActivatePreviousPane,
  215        /// Activates the last pane in the workspace.
  216        ActivateLastPane,
  217        /// Switches to the next window.
  218        ActivateNextWindow,
  219        /// Switches to the previous window.
  220        ActivatePreviousWindow,
  221        /// Adds a folder to the current project.
  222        AddFolderToProject,
  223        /// Clears all notifications.
  224        ClearAllNotifications,
  225        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  226        ClearNavigationHistory,
  227        /// Closes the active dock.
  228        CloseActiveDock,
  229        /// Closes all docks.
  230        CloseAllDocks,
  231        /// Toggles all docks.
  232        ToggleAllDocks,
  233        /// Closes the current window.
  234        CloseWindow,
  235        /// Closes the current project.
  236        CloseProject,
  237        /// Opens the feedback dialog.
  238        Feedback,
  239        /// Follows the next collaborator in the session.
  240        FollowNextCollaborator,
  241        /// Moves the focused panel to the next position.
  242        MoveFocusedPanelToNextPosition,
  243        /// Creates a new file.
  244        NewFile,
  245        /// Creates a new file in a vertical split.
  246        NewFileSplitVertical,
  247        /// Creates a new file in a horizontal split.
  248        NewFileSplitHorizontal,
  249        /// Opens a new search.
  250        NewSearch,
  251        /// Opens a new window.
  252        NewWindow,
  253        /// Opens a file or directory.
  254        Open,
  255        /// Opens multiple files.
  256        OpenFiles,
  257        /// Opens the current location in terminal.
  258        OpenInTerminal,
  259        /// Opens the component preview.
  260        OpenComponentPreview,
  261        /// Reloads the active item.
  262        ReloadActiveItem,
  263        /// Resets the active dock to its default size.
  264        ResetActiveDockSize,
  265        /// Resets all open docks to their default sizes.
  266        ResetOpenDocksSize,
  267        /// Reloads the application
  268        Reload,
  269        /// Saves the current file with a new name.
  270        SaveAs,
  271        /// Saves without formatting.
  272        SaveWithoutFormat,
  273        /// Shuts down all debug adapters.
  274        ShutdownDebugAdapters,
  275        /// Suppresses the current notification.
  276        SuppressNotification,
  277        /// Toggles the bottom dock.
  278        ToggleBottomDock,
  279        /// Toggles centered layout mode.
  280        ToggleCenteredLayout,
  281        /// Toggles edit prediction feature globally for all files.
  282        ToggleEditPrediction,
  283        /// Toggles the left dock.
  284        ToggleLeftDock,
  285        /// Toggles the right dock.
  286        ToggleRightDock,
  287        /// Toggles zoom on the active pane.
  288        ToggleZoom,
  289        /// Toggles read-only mode for the active item (if supported by that item).
  290        ToggleReadOnlyFile,
  291        /// Zooms in on the active pane.
  292        ZoomIn,
  293        /// Zooms out of the active pane.
  294        ZoomOut,
  295        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  296        /// If the modal is shown already, closes it without trusting any worktree.
  297        ToggleWorktreeSecurity,
  298        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  299        /// Requires restart to take effect on already opened projects.
  300        ClearTrustedWorktrees,
  301        /// Stops following a collaborator.
  302        Unfollow,
  303        /// Restores the banner.
  304        RestoreBanner,
  305        /// Toggles expansion of the selected item.
  306        ToggleExpandItem,
  307    ]
  308);
  309
  310/// Activates a specific pane by its index.
  311#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  312#[action(namespace = workspace)]
  313pub struct ActivatePane(pub usize);
  314
  315/// Moves an item to a specific pane by index.
  316#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  317#[action(namespace = workspace)]
  318#[serde(deny_unknown_fields)]
  319pub struct MoveItemToPane {
  320    #[serde(default = "default_1")]
  321    pub destination: usize,
  322    #[serde(default = "default_true")]
  323    pub focus: bool,
  324    #[serde(default)]
  325    pub clone: bool,
  326}
  327
  328fn default_1() -> usize {
  329    1
  330}
  331
  332/// Moves an item to a pane in the specified direction.
  333#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  334#[action(namespace = workspace)]
  335#[serde(deny_unknown_fields)]
  336pub struct MoveItemToPaneInDirection {
  337    #[serde(default = "default_right")]
  338    pub direction: SplitDirection,
  339    #[serde(default = "default_true")]
  340    pub focus: bool,
  341    #[serde(default)]
  342    pub clone: bool,
  343}
  344
  345/// Creates a new file in a split of the desired direction.
  346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  347#[action(namespace = workspace)]
  348#[serde(deny_unknown_fields)]
  349pub struct NewFileSplit(pub SplitDirection);
  350
  351fn default_right() -> SplitDirection {
  352    SplitDirection::Right
  353}
  354
  355/// Saves all open files in the workspace.
  356#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  357#[action(namespace = workspace)]
  358#[serde(deny_unknown_fields)]
  359pub struct SaveAll {
  360    #[serde(default)]
  361    pub save_intent: Option<SaveIntent>,
  362}
  363
  364/// Saves the current file with the specified options.
  365#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  366#[action(namespace = workspace)]
  367#[serde(deny_unknown_fields)]
  368pub struct Save {
  369    #[serde(default)]
  370    pub save_intent: Option<SaveIntent>,
  371}
  372
  373/// Closes all items and panes in the workspace.
  374#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  375#[action(namespace = workspace)]
  376#[serde(deny_unknown_fields)]
  377pub struct CloseAllItemsAndPanes {
  378    #[serde(default)]
  379    pub save_intent: Option<SaveIntent>,
  380}
  381
  382/// Closes all inactive tabs and panes in the workspace.
  383#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  384#[action(namespace = workspace)]
  385#[serde(deny_unknown_fields)]
  386pub struct CloseInactiveTabsAndPanes {
  387    #[serde(default)]
  388    pub save_intent: Option<SaveIntent>,
  389}
  390
  391/// Closes the active item across all panes.
  392#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  393#[action(namespace = workspace)]
  394#[serde(deny_unknown_fields)]
  395pub struct CloseItemInAllPanes {
  396    #[serde(default)]
  397    pub save_intent: Option<SaveIntent>,
  398    #[serde(default)]
  399    pub close_pinned: bool,
  400}
  401
  402/// Sends a sequence of keystrokes to the active element.
  403#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  404#[action(namespace = workspace)]
  405pub struct SendKeystrokes(pub String);
  406
  407actions!(
  408    project_symbols,
  409    [
  410        /// Toggles the project symbols search.
  411        #[action(name = "Toggle")]
  412        ToggleProjectSymbols
  413    ]
  414);
  415
  416/// Toggles the file finder interface.
  417#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  418#[action(namespace = file_finder, name = "Toggle")]
  419#[serde(deny_unknown_fields)]
  420pub struct ToggleFileFinder {
  421    #[serde(default)]
  422    pub separate_history: bool,
  423}
  424
  425/// Opens a new terminal in the center.
  426#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  427#[action(namespace = workspace)]
  428#[serde(deny_unknown_fields)]
  429pub struct NewCenterTerminal {
  430    /// If true, creates a local terminal even in remote projects.
  431    #[serde(default)]
  432    pub local: bool,
  433}
  434
  435/// Opens a new terminal.
  436#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  437#[action(namespace = workspace)]
  438#[serde(deny_unknown_fields)]
  439pub struct NewTerminal {
  440    /// If true, creates a local terminal even in remote projects.
  441    #[serde(default)]
  442    pub local: bool,
  443}
  444
  445/// Increases size of a currently focused dock by a given amount of pixels.
  446#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  447#[action(namespace = workspace)]
  448#[serde(deny_unknown_fields)]
  449pub struct IncreaseActiveDockSize {
  450    /// For 0px parameter, uses UI font size value.
  451    #[serde(default)]
  452    pub px: u32,
  453}
  454
  455/// Decreases size of a currently focused dock by a given amount of pixels.
  456#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  457#[action(namespace = workspace)]
  458#[serde(deny_unknown_fields)]
  459pub struct DecreaseActiveDockSize {
  460    /// For 0px parameter, uses UI font size value.
  461    #[serde(default)]
  462    pub px: u32,
  463}
  464
  465/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  466#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  467#[action(namespace = workspace)]
  468#[serde(deny_unknown_fields)]
  469pub struct IncreaseOpenDocksSize {
  470    /// For 0px parameter, uses UI font size value.
  471    #[serde(default)]
  472    pub px: u32,
  473}
  474
  475/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  476#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  477#[action(namespace = workspace)]
  478#[serde(deny_unknown_fields)]
  479pub struct DecreaseOpenDocksSize {
  480    /// For 0px parameter, uses UI font size value.
  481    #[serde(default)]
  482    pub px: u32,
  483}
  484
  485actions!(
  486    workspace,
  487    [
  488        /// Activates the pane to the left.
  489        ActivatePaneLeft,
  490        /// Activates the pane to the right.
  491        ActivatePaneRight,
  492        /// Activates the pane above.
  493        ActivatePaneUp,
  494        /// Activates the pane below.
  495        ActivatePaneDown,
  496        /// Swaps the current pane with the one to the left.
  497        SwapPaneLeft,
  498        /// Swaps the current pane with the one to the right.
  499        SwapPaneRight,
  500        /// Swaps the current pane with the one above.
  501        SwapPaneUp,
  502        /// Swaps the current pane with the one below.
  503        SwapPaneDown,
  504        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  505        SwapPaneAdjacent,
  506        /// Move the current pane to be at the far left.
  507        MovePaneLeft,
  508        /// Move the current pane to be at the far right.
  509        MovePaneRight,
  510        /// Move the current pane to be at the very top.
  511        MovePaneUp,
  512        /// Move the current pane to be at the very bottom.
  513        MovePaneDown,
  514    ]
  515);
  516
  517#[derive(PartialEq, Eq, Debug)]
  518pub enum CloseIntent {
  519    /// Quit the program entirely.
  520    Quit,
  521    /// Close a window.
  522    CloseWindow,
  523    /// Replace the workspace in an existing window.
  524    ReplaceWindow,
  525}
  526
  527#[derive(Clone)]
  528pub struct Toast {
  529    id: NotificationId,
  530    msg: Cow<'static, str>,
  531    autohide: bool,
  532    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  533}
  534
  535impl Toast {
  536    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  537        Toast {
  538            id,
  539            msg: msg.into(),
  540            on_click: None,
  541            autohide: false,
  542        }
  543    }
  544
  545    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  546    where
  547        M: Into<Cow<'static, str>>,
  548        F: Fn(&mut Window, &mut App) + 'static,
  549    {
  550        self.on_click = Some((message.into(), Arc::new(on_click)));
  551        self
  552    }
  553
  554    pub fn autohide(mut self) -> Self {
  555        self.autohide = true;
  556        self
  557    }
  558}
  559
  560impl PartialEq for Toast {
  561    fn eq(&self, other: &Self) -> bool {
  562        self.id == other.id
  563            && self.msg == other.msg
  564            && self.on_click.is_some() == other.on_click.is_some()
  565    }
  566}
  567
  568/// Opens a new terminal with the specified working directory.
  569#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  570#[action(namespace = workspace)]
  571#[serde(deny_unknown_fields)]
  572pub struct OpenTerminal {
  573    pub working_directory: PathBuf,
  574    /// If true, creates a local terminal even in remote projects.
  575    #[serde(default)]
  576    pub local: bool,
  577}
  578
  579#[derive(
  580    Clone,
  581    Copy,
  582    Debug,
  583    Default,
  584    Hash,
  585    PartialEq,
  586    Eq,
  587    PartialOrd,
  588    Ord,
  589    serde::Serialize,
  590    serde::Deserialize,
  591)]
  592pub struct WorkspaceId(i64);
  593
  594impl WorkspaceId {
  595    pub fn from_i64(value: i64) -> Self {
  596        Self(value)
  597    }
  598}
  599
  600impl StaticColumnCount for WorkspaceId {}
  601impl Bind for WorkspaceId {
  602    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  603        self.0.bind(statement, start_index)
  604    }
  605}
  606impl Column for WorkspaceId {
  607    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  608        i64::column(statement, start_index)
  609            .map(|(i, next_index)| (Self(i), next_index))
  610            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  611    }
  612}
  613impl From<WorkspaceId> for i64 {
  614    fn from(val: WorkspaceId) -> Self {
  615        val.0
  616    }
  617}
  618
  619fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  620    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  621        workspace_window
  622            .update(cx, |multi_workspace, window, cx| {
  623                let workspace = multi_workspace.workspace().clone();
  624                workspace.update(cx, |workspace, cx| {
  625                    prompt_for_open_path_and_open(workspace, app_state, options, window, cx);
  626                });
  627            })
  628            .ok();
  629    } else {
  630        let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, cx);
  631        cx.spawn(async move |cx| {
  632            let (window, _) = task.await?;
  633            window.update(cx, |multi_workspace, window, cx| {
  634                window.activate_window();
  635                let workspace = multi_workspace.workspace().clone();
  636                workspace.update(cx, |workspace, cx| {
  637                    prompt_for_open_path_and_open(workspace, app_state, options, window, cx);
  638                });
  639            })?;
  640            anyhow::Ok(())
  641        })
  642        .detach_and_log_err(cx);
  643    }
  644}
  645
  646pub fn prompt_for_open_path_and_open(
  647    workspace: &mut Workspace,
  648    app_state: Arc<AppState>,
  649    options: PathPromptOptions,
  650    window: &mut Window,
  651    cx: &mut Context<Workspace>,
  652) {
  653    let paths = workspace.prompt_for_open_path(
  654        options,
  655        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  656        window,
  657        cx,
  658    );
  659    cx.spawn_in(window, async move |this, cx| {
  660        let Some(paths) = paths.await.log_err().flatten() else {
  661            return;
  662        };
  663        if let Some(task) = this
  664            .update_in(cx, |this, window, cx| {
  665                this.open_workspace_for_paths(false, paths, window, cx)
  666            })
  667            .log_err()
  668        {
  669            task.await.log_err();
  670        }
  671    })
  672    .detach();
  673}
  674
  675pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  676    component::init();
  677    theme_preview::init(cx);
  678    toast_layer::init(cx);
  679    history_manager::init(app_state.fs.clone(), cx);
  680
  681    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  682        .on_action(|_: &Reload, cx| reload(cx))
  683        .on_action({
  684            let app_state = Arc::downgrade(&app_state);
  685            move |_: &Open, cx: &mut App| {
  686                if let Some(app_state) = app_state.upgrade() {
  687                    prompt_and_open_paths(
  688                        app_state,
  689                        PathPromptOptions {
  690                            files: true,
  691                            directories: true,
  692                            multiple: true,
  693                            prompt: None,
  694                        },
  695                        cx,
  696                    );
  697                }
  698            }
  699        })
  700        .on_action({
  701            let app_state = Arc::downgrade(&app_state);
  702            move |_: &OpenFiles, cx: &mut App| {
  703                let directories = cx.can_select_mixed_files_and_dirs();
  704                if let Some(app_state) = app_state.upgrade() {
  705                    prompt_and_open_paths(
  706                        app_state,
  707                        PathPromptOptions {
  708                            files: true,
  709                            directories,
  710                            multiple: true,
  711                            prompt: None,
  712                        },
  713                        cx,
  714                    );
  715                }
  716            }
  717        });
  718}
  719
  720type BuildProjectItemFn =
  721    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  722
  723type BuildProjectItemForPathFn =
  724    fn(
  725        &Entity<Project>,
  726        &ProjectPath,
  727        &mut Window,
  728        &mut App,
  729    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  730
  731#[derive(Clone, Default)]
  732struct ProjectItemRegistry {
  733    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  734    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  735}
  736
  737impl ProjectItemRegistry {
  738    fn register<T: ProjectItem>(&mut self) {
  739        self.build_project_item_fns_by_type.insert(
  740            TypeId::of::<T::Item>(),
  741            |item, project, pane, window, cx| {
  742                let item = item.downcast().unwrap();
  743                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  744                    as Box<dyn ItemHandle>
  745            },
  746        );
  747        self.build_project_item_for_path_fns
  748            .push(|project, project_path, window, cx| {
  749                let project_path = project_path.clone();
  750                let is_file = project
  751                    .read(cx)
  752                    .entry_for_path(&project_path, cx)
  753                    .is_some_and(|entry| entry.is_file());
  754                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  755                let is_local = project.read(cx).is_local();
  756                let project_item =
  757                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  758                let project = project.clone();
  759                Some(window.spawn(cx, async move |cx| {
  760                    match project_item.await.with_context(|| {
  761                        format!(
  762                            "opening project path {:?}",
  763                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  764                        )
  765                    }) {
  766                        Ok(project_item) => {
  767                            let project_item = project_item;
  768                            let project_entry_id: Option<ProjectEntryId> =
  769                                project_item.read_with(cx, project::ProjectItem::entry_id);
  770                            let build_workspace_item = Box::new(
  771                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  772                                    Box::new(cx.new(|cx| {
  773                                        T::for_project_item(
  774                                            project,
  775                                            Some(pane),
  776                                            project_item,
  777                                            window,
  778                                            cx,
  779                                        )
  780                                    })) as Box<dyn ItemHandle>
  781                                },
  782                            ) as Box<_>;
  783                            Ok((project_entry_id, build_workspace_item))
  784                        }
  785                        Err(e) => {
  786                            log::warn!("Failed to open a project item: {e:#}");
  787                            if e.error_code() == ErrorCode::Internal {
  788                                if let Some(abs_path) =
  789                                    entry_abs_path.as_deref().filter(|_| is_file)
  790                                {
  791                                    if let Some(broken_project_item_view) =
  792                                        cx.update(|window, cx| {
  793                                            T::for_broken_project_item(
  794                                                abs_path, is_local, &e, window, cx,
  795                                            )
  796                                        })?
  797                                    {
  798                                        let build_workspace_item = Box::new(
  799                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  800                                                cx.new(|_| broken_project_item_view).boxed_clone()
  801                                            },
  802                                        )
  803                                        as Box<_>;
  804                                        return Ok((None, build_workspace_item));
  805                                    }
  806                                }
  807                            }
  808                            Err(e)
  809                        }
  810                    }
  811                }))
  812            });
  813    }
  814
  815    fn open_path(
  816        &self,
  817        project: &Entity<Project>,
  818        path: &ProjectPath,
  819        window: &mut Window,
  820        cx: &mut App,
  821    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  822        let Some(open_project_item) = self
  823            .build_project_item_for_path_fns
  824            .iter()
  825            .rev()
  826            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  827        else {
  828            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  829        };
  830        open_project_item
  831    }
  832
  833    fn build_item<T: project::ProjectItem>(
  834        &self,
  835        item: Entity<T>,
  836        project: Entity<Project>,
  837        pane: Option<&Pane>,
  838        window: &mut Window,
  839        cx: &mut App,
  840    ) -> Option<Box<dyn ItemHandle>> {
  841        let build = self
  842            .build_project_item_fns_by_type
  843            .get(&TypeId::of::<T>())?;
  844        Some(build(item.into_any(), project, pane, window, cx))
  845    }
  846}
  847
  848type WorkspaceItemBuilder =
  849    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  850
  851impl Global for ProjectItemRegistry {}
  852
  853/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  854/// items will get a chance to open the file, starting from the project item that
  855/// was added last.
  856pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  857    cx.default_global::<ProjectItemRegistry>().register::<I>();
  858}
  859
  860#[derive(Default)]
  861pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  862
  863struct FollowableViewDescriptor {
  864    from_state_proto: fn(
  865        Entity<Workspace>,
  866        ViewId,
  867        &mut Option<proto::view::Variant>,
  868        &mut Window,
  869        &mut App,
  870    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  871    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  872}
  873
  874impl Global for FollowableViewRegistry {}
  875
  876impl FollowableViewRegistry {
  877    pub fn register<I: FollowableItem>(cx: &mut App) {
  878        cx.default_global::<Self>().0.insert(
  879            TypeId::of::<I>(),
  880            FollowableViewDescriptor {
  881                from_state_proto: |workspace, id, state, window, cx| {
  882                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  883                        cx.foreground_executor()
  884                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  885                    })
  886                },
  887                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  888            },
  889        );
  890    }
  891
  892    pub fn from_state_proto(
  893        workspace: Entity<Workspace>,
  894        view_id: ViewId,
  895        mut state: Option<proto::view::Variant>,
  896        window: &mut Window,
  897        cx: &mut App,
  898    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  899        cx.update_default_global(|this: &mut Self, cx| {
  900            this.0.values().find_map(|descriptor| {
  901                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  902            })
  903        })
  904    }
  905
  906    pub fn to_followable_view(
  907        view: impl Into<AnyView>,
  908        cx: &App,
  909    ) -> Option<Box<dyn FollowableItemHandle>> {
  910        let this = cx.try_global::<Self>()?;
  911        let view = view.into();
  912        let descriptor = this.0.get(&view.entity_type())?;
  913        Some((descriptor.to_followable_view)(&view))
  914    }
  915}
  916
  917#[derive(Copy, Clone)]
  918struct SerializableItemDescriptor {
  919    deserialize: fn(
  920        Entity<Project>,
  921        WeakEntity<Workspace>,
  922        WorkspaceId,
  923        ItemId,
  924        &mut Window,
  925        &mut Context<Pane>,
  926    ) -> Task<Result<Box<dyn ItemHandle>>>,
  927    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  928    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  929}
  930
  931#[derive(Default)]
  932struct SerializableItemRegistry {
  933    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  934    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  935}
  936
  937impl Global for SerializableItemRegistry {}
  938
  939impl SerializableItemRegistry {
  940    fn deserialize(
  941        item_kind: &str,
  942        project: Entity<Project>,
  943        workspace: WeakEntity<Workspace>,
  944        workspace_id: WorkspaceId,
  945        item_item: ItemId,
  946        window: &mut Window,
  947        cx: &mut Context<Pane>,
  948    ) -> Task<Result<Box<dyn ItemHandle>>> {
  949        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  950            return Task::ready(Err(anyhow!(
  951                "cannot deserialize {}, descriptor not found",
  952                item_kind
  953            )));
  954        };
  955
  956        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
  957    }
  958
  959    fn cleanup(
  960        item_kind: &str,
  961        workspace_id: WorkspaceId,
  962        loaded_items: Vec<ItemId>,
  963        window: &mut Window,
  964        cx: &mut App,
  965    ) -> Task<Result<()>> {
  966        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  967            return Task::ready(Err(anyhow!(
  968                "cannot cleanup {}, descriptor not found",
  969                item_kind
  970            )));
  971        };
  972
  973        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
  974    }
  975
  976    fn view_to_serializable_item_handle(
  977        view: AnyView,
  978        cx: &App,
  979    ) -> Option<Box<dyn SerializableItemHandle>> {
  980        let this = cx.try_global::<Self>()?;
  981        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
  982        Some((descriptor.view_to_serializable_item)(view))
  983    }
  984
  985    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
  986        let this = cx.try_global::<Self>()?;
  987        this.descriptors_by_kind.get(item_kind).copied()
  988    }
  989}
  990
  991pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
  992    let serialized_item_kind = I::serialized_item_kind();
  993
  994    let registry = cx.default_global::<SerializableItemRegistry>();
  995    let descriptor = SerializableItemDescriptor {
  996        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
  997            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
  998            cx.foreground_executor()
  999                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1000        },
 1001        cleanup: |workspace_id, loaded_items, window, cx| {
 1002            I::cleanup(workspace_id, loaded_items, window, cx)
 1003        },
 1004        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1005    };
 1006    registry
 1007        .descriptors_by_kind
 1008        .insert(Arc::from(serialized_item_kind), descriptor);
 1009    registry
 1010        .descriptors_by_type
 1011        .insert(TypeId::of::<I>(), descriptor);
 1012}
 1013
 1014pub struct AppState {
 1015    pub languages: Arc<LanguageRegistry>,
 1016    pub client: Arc<Client>,
 1017    pub user_store: Entity<UserStore>,
 1018    pub workspace_store: Entity<WorkspaceStore>,
 1019    pub fs: Arc<dyn fs::Fs>,
 1020    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1021    pub node_runtime: NodeRuntime,
 1022    pub session: Entity<AppSession>,
 1023}
 1024
 1025struct GlobalAppState(Weak<AppState>);
 1026
 1027impl Global for GlobalAppState {}
 1028
 1029pub struct WorkspaceStore {
 1030    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1031    client: Arc<Client>,
 1032    _subscriptions: Vec<client::Subscription>,
 1033}
 1034
 1035#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1036pub enum CollaboratorId {
 1037    PeerId(PeerId),
 1038    Agent,
 1039}
 1040
 1041impl From<PeerId> for CollaboratorId {
 1042    fn from(peer_id: PeerId) -> Self {
 1043        CollaboratorId::PeerId(peer_id)
 1044    }
 1045}
 1046
 1047impl From<&PeerId> for CollaboratorId {
 1048    fn from(peer_id: &PeerId) -> Self {
 1049        CollaboratorId::PeerId(*peer_id)
 1050    }
 1051}
 1052
 1053#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1054struct Follower {
 1055    project_id: Option<u64>,
 1056    peer_id: PeerId,
 1057}
 1058
 1059impl AppState {
 1060    #[track_caller]
 1061    pub fn global(cx: &App) -> Weak<Self> {
 1062        cx.global::<GlobalAppState>().0.clone()
 1063    }
 1064    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
 1065        cx.try_global::<GlobalAppState>()
 1066            .map(|state| state.0.clone())
 1067    }
 1068    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
 1069        cx.set_global(GlobalAppState(state));
 1070    }
 1071
 1072    #[cfg(any(test, feature = "test-support"))]
 1073    pub fn test(cx: &mut App) -> Arc<Self> {
 1074        use fs::Fs;
 1075        use node_runtime::NodeRuntime;
 1076        use session::Session;
 1077        use settings::SettingsStore;
 1078
 1079        if !cx.has_global::<SettingsStore>() {
 1080            let settings_store = SettingsStore::test(cx);
 1081            cx.set_global(settings_store);
 1082        }
 1083
 1084        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1085        <dyn Fs>::set_global(fs.clone(), cx);
 1086        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1087        let clock = Arc::new(clock::FakeSystemClock::new());
 1088        let http_client = http_client::FakeHttpClient::with_404_response();
 1089        let client = Client::new(clock, http_client, cx);
 1090        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1091        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1092        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1093
 1094        theme::init(theme::LoadThemes::JustBase, cx);
 1095        client::init(&client, cx);
 1096
 1097        Arc::new(Self {
 1098            client,
 1099            fs,
 1100            languages,
 1101            user_store,
 1102            workspace_store,
 1103            node_runtime: NodeRuntime::unavailable(),
 1104            build_window_options: |_, _| Default::default(),
 1105            session,
 1106        })
 1107    }
 1108}
 1109
 1110struct DelayedDebouncedEditAction {
 1111    task: Option<Task<()>>,
 1112    cancel_channel: Option<oneshot::Sender<()>>,
 1113}
 1114
 1115impl DelayedDebouncedEditAction {
 1116    fn new() -> DelayedDebouncedEditAction {
 1117        DelayedDebouncedEditAction {
 1118            task: None,
 1119            cancel_channel: None,
 1120        }
 1121    }
 1122
 1123    fn fire_new<F>(
 1124        &mut self,
 1125        delay: Duration,
 1126        window: &mut Window,
 1127        cx: &mut Context<Workspace>,
 1128        func: F,
 1129    ) where
 1130        F: 'static
 1131            + Send
 1132            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1133    {
 1134        if let Some(channel) = self.cancel_channel.take() {
 1135            _ = channel.send(());
 1136        }
 1137
 1138        let (sender, mut receiver) = oneshot::channel::<()>();
 1139        self.cancel_channel = Some(sender);
 1140
 1141        let previous_task = self.task.take();
 1142        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1143            let mut timer = cx.background_executor().timer(delay).fuse();
 1144            if let Some(previous_task) = previous_task {
 1145                previous_task.await;
 1146            }
 1147
 1148            futures::select_biased! {
 1149                _ = receiver => return,
 1150                    _ = timer => {}
 1151            }
 1152
 1153            if let Some(result) = workspace
 1154                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1155                .log_err()
 1156            {
 1157                result.await.log_err();
 1158            }
 1159        }));
 1160    }
 1161}
 1162
 1163pub enum Event {
 1164    PaneAdded(Entity<Pane>),
 1165    PaneRemoved,
 1166    ItemAdded {
 1167        item: Box<dyn ItemHandle>,
 1168    },
 1169    ActiveItemChanged,
 1170    ItemRemoved {
 1171        item_id: EntityId,
 1172    },
 1173    UserSavedItem {
 1174        pane: WeakEntity<Pane>,
 1175        item: Box<dyn WeakItemHandle>,
 1176        save_intent: SaveIntent,
 1177    },
 1178    ContactRequestedJoin(u64),
 1179    WorkspaceCreated(WeakEntity<Workspace>),
 1180    OpenBundledFile {
 1181        text: Cow<'static, str>,
 1182        title: &'static str,
 1183        language: &'static str,
 1184    },
 1185    ZoomChanged,
 1186    ModalOpened,
 1187    Activate,
 1188}
 1189
 1190#[derive(Debug, Clone)]
 1191pub enum OpenVisible {
 1192    All,
 1193    None,
 1194    OnlyFiles,
 1195    OnlyDirectories,
 1196}
 1197
 1198enum WorkspaceLocation {
 1199    // Valid local paths or SSH project to serialize
 1200    Location(SerializedWorkspaceLocation, PathList),
 1201    // No valid location found hence clear session id
 1202    DetachFromSession,
 1203    // No valid location found to serialize
 1204    None,
 1205}
 1206
 1207type PromptForNewPath = Box<
 1208    dyn Fn(
 1209        &mut Workspace,
 1210        DirectoryLister,
 1211        Option<String>,
 1212        &mut Window,
 1213        &mut Context<Workspace>,
 1214    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1215>;
 1216
 1217type PromptForOpenPath = Box<
 1218    dyn Fn(
 1219        &mut Workspace,
 1220        DirectoryLister,
 1221        &mut Window,
 1222        &mut Context<Workspace>,
 1223    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1224>;
 1225
 1226#[derive(Default)]
 1227struct DispatchingKeystrokes {
 1228    dispatched: HashSet<Vec<Keystroke>>,
 1229    queue: VecDeque<Keystroke>,
 1230    task: Option<Shared<Task<()>>>,
 1231}
 1232
 1233/// Collects everything project-related for a certain window opened.
 1234/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1235///
 1236/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1237/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1238/// that can be used to register a global action to be triggered from any place in the window.
 1239pub struct Workspace {
 1240    weak_self: WeakEntity<Self>,
 1241    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1242    zoomed: Option<AnyWeakView>,
 1243    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1244    zoomed_position: Option<DockPosition>,
 1245    center: PaneGroup,
 1246    left_dock: Entity<Dock>,
 1247    bottom_dock: Entity<Dock>,
 1248    right_dock: Entity<Dock>,
 1249    panes: Vec<Entity<Pane>>,
 1250    active_worktree_override: Option<WorktreeId>,
 1251    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1252    active_pane: Entity<Pane>,
 1253    last_active_center_pane: Option<WeakEntity<Pane>>,
 1254    last_active_view_id: Option<proto::ViewId>,
 1255    status_bar: Entity<StatusBar>,
 1256    pub(crate) modal_layer: Entity<ModalLayer>,
 1257    toast_layer: Entity<ToastLayer>,
 1258    titlebar_item: Option<AnyView>,
 1259    notifications: Notifications,
 1260    suppressed_notifications: HashSet<NotificationId>,
 1261    project: Entity<Project>,
 1262    follower_states: HashMap<CollaboratorId, FollowerState>,
 1263    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1264    window_edited: bool,
 1265    last_window_title: Option<String>,
 1266    dirty_items: HashMap<EntityId, Subscription>,
 1267    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1268    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1269    database_id: Option<WorkspaceId>,
 1270    app_state: Arc<AppState>,
 1271    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1272    _subscriptions: Vec<Subscription>,
 1273    _apply_leader_updates: Task<Result<()>>,
 1274    _observe_current_user: Task<Result<()>>,
 1275    _schedule_serialize_workspace: Option<Task<()>>,
 1276    _serialize_workspace_task: Option<Task<()>>,
 1277    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1278    pane_history_timestamp: Arc<AtomicUsize>,
 1279    bounds: Bounds<Pixels>,
 1280    pub centered_layout: bool,
 1281    bounds_save_task_queued: Option<Task<()>>,
 1282    on_prompt_for_new_path: Option<PromptForNewPath>,
 1283    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1284    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1285    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1286    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1287    _items_serializer: Task<Result<()>>,
 1288    session_id: Option<String>,
 1289    scheduled_tasks: Vec<Task<()>>,
 1290    last_open_dock_positions: Vec<DockPosition>,
 1291    removing: bool,
 1292}
 1293
 1294impl EventEmitter<Event> for Workspace {}
 1295
 1296#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1297pub struct ViewId {
 1298    pub creator: CollaboratorId,
 1299    pub id: u64,
 1300}
 1301
 1302pub struct FollowerState {
 1303    center_pane: Entity<Pane>,
 1304    dock_pane: Option<Entity<Pane>>,
 1305    active_view_id: Option<ViewId>,
 1306    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1307}
 1308
 1309struct FollowerView {
 1310    view: Box<dyn FollowableItemHandle>,
 1311    location: Option<proto::PanelId>,
 1312}
 1313
 1314impl Workspace {
 1315    pub fn new(
 1316        workspace_id: Option<WorkspaceId>,
 1317        project: Entity<Project>,
 1318        app_state: Arc<AppState>,
 1319        window: &mut Window,
 1320        cx: &mut Context<Self>,
 1321    ) -> Self {
 1322        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1323            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1324                if let TrustedWorktreesEvent::Trusted(..) = e {
 1325                    // Do not persist auto trusted worktrees
 1326                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1327                        worktrees_store.update(cx, |worktrees_store, cx| {
 1328                            worktrees_store.schedule_serialization(
 1329                                cx,
 1330                                |new_trusted_worktrees, cx| {
 1331                                    let timeout =
 1332                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1333                                    cx.background_spawn(async move {
 1334                                        timeout.await;
 1335                                        persistence::DB
 1336                                            .save_trusted_worktrees(new_trusted_worktrees)
 1337                                            .await
 1338                                            .log_err();
 1339                                    })
 1340                                },
 1341                            )
 1342                        });
 1343                    }
 1344                }
 1345            })
 1346            .detach();
 1347
 1348            cx.observe_global::<SettingsStore>(|_, cx| {
 1349                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1350                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1351                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1352                            trusted_worktrees.auto_trust_all(cx);
 1353                        })
 1354                    }
 1355                }
 1356            })
 1357            .detach();
 1358        }
 1359
 1360        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1361            match event {
 1362                project::Event::RemoteIdChanged(_) => {
 1363                    this.update_window_title(window, cx);
 1364                }
 1365
 1366                project::Event::CollaboratorLeft(peer_id) => {
 1367                    this.collaborator_left(*peer_id, window, cx);
 1368                }
 1369
 1370                &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
 1371                    this.update_window_title(window, cx);
 1372                    if this
 1373                        .project()
 1374                        .read(cx)
 1375                        .worktree_for_id(id, cx)
 1376                        .is_some_and(|wt| wt.read(cx).is_visible())
 1377                    {
 1378                        this.serialize_workspace(window, cx);
 1379                        this.update_history(cx);
 1380                    }
 1381                }
 1382                project::Event::WorktreeUpdatedEntries(..) => {
 1383                    this.update_window_title(window, cx);
 1384                    this.serialize_workspace(window, cx);
 1385                }
 1386
 1387                project::Event::DisconnectedFromHost => {
 1388                    this.update_window_edited(window, cx);
 1389                    let leaders_to_unfollow =
 1390                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1391                    for leader_id in leaders_to_unfollow {
 1392                        this.unfollow(leader_id, window, cx);
 1393                    }
 1394                }
 1395
 1396                project::Event::DisconnectedFromRemote {
 1397                    server_not_running: _,
 1398                } => {
 1399                    this.update_window_edited(window, cx);
 1400                }
 1401
 1402                project::Event::Closed => {
 1403                    window.remove_window();
 1404                }
 1405
 1406                project::Event::DeletedEntry(_, entry_id) => {
 1407                    for pane in this.panes.iter() {
 1408                        pane.update(cx, |pane, cx| {
 1409                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1410                        });
 1411                    }
 1412                }
 1413
 1414                project::Event::Toast {
 1415                    notification_id,
 1416                    message,
 1417                    link,
 1418                } => this.show_notification(
 1419                    NotificationId::named(notification_id.clone()),
 1420                    cx,
 1421                    |cx| {
 1422                        let mut notification = MessageNotification::new(message.clone(), cx);
 1423                        if let Some(link) = link {
 1424                            notification = notification
 1425                                .more_info_message(link.label)
 1426                                .more_info_url(link.url);
 1427                        }
 1428
 1429                        cx.new(|_| notification)
 1430                    },
 1431                ),
 1432
 1433                project::Event::HideToast { notification_id } => {
 1434                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1435                }
 1436
 1437                project::Event::LanguageServerPrompt(request) => {
 1438                    struct LanguageServerPrompt;
 1439
 1440                    this.show_notification(
 1441                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1442                        cx,
 1443                        |cx| {
 1444                            cx.new(|cx| {
 1445                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1446                            })
 1447                        },
 1448                    );
 1449                }
 1450
 1451                project::Event::AgentLocationChanged => {
 1452                    this.handle_agent_location_changed(window, cx)
 1453                }
 1454
 1455                _ => {}
 1456            }
 1457            cx.notify()
 1458        })
 1459        .detach();
 1460
 1461        cx.subscribe_in(
 1462            &project.read(cx).breakpoint_store(),
 1463            window,
 1464            |workspace, _, event, window, cx| match event {
 1465                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1466                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1467                    workspace.serialize_workspace(window, cx);
 1468                }
 1469                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1470            },
 1471        )
 1472        .detach();
 1473        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1474            cx.subscribe_in(
 1475                &toolchain_store,
 1476                window,
 1477                |workspace, _, event, window, cx| match event {
 1478                    ToolchainStoreEvent::CustomToolchainsModified => {
 1479                        workspace.serialize_workspace(window, cx);
 1480                    }
 1481                    _ => {}
 1482                },
 1483            )
 1484            .detach();
 1485        }
 1486
 1487        cx.on_focus_lost(window, |this, window, cx| {
 1488            let focus_handle = this.focus_handle(cx);
 1489            window.focus(&focus_handle, cx);
 1490        })
 1491        .detach();
 1492
 1493        let weak_handle = cx.entity().downgrade();
 1494        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1495
 1496        let center_pane = cx.new(|cx| {
 1497            let mut center_pane = Pane::new(
 1498                weak_handle.clone(),
 1499                project.clone(),
 1500                pane_history_timestamp.clone(),
 1501                None,
 1502                NewFile.boxed_clone(),
 1503                true,
 1504                window,
 1505                cx,
 1506            );
 1507            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1508            center_pane.set_should_display_welcome_page(true);
 1509            center_pane
 1510        });
 1511        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1512            .detach();
 1513
 1514        window.focus(&center_pane.focus_handle(cx), cx);
 1515
 1516        cx.emit(Event::PaneAdded(center_pane.clone()));
 1517
 1518        let any_window_handle = window.window_handle();
 1519        app_state.workspace_store.update(cx, |store, _| {
 1520            store
 1521                .workspaces
 1522                .insert((any_window_handle, weak_handle.clone()));
 1523        });
 1524
 1525        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1526        let mut connection_status = app_state.client.status();
 1527        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1528            current_user.next().await;
 1529            connection_status.next().await;
 1530            let mut stream =
 1531                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1532
 1533            while stream.recv().await.is_some() {
 1534                this.update(cx, |_, cx| cx.notify())?;
 1535            }
 1536            anyhow::Ok(())
 1537        });
 1538
 1539        // All leader updates are enqueued and then processed in a single task, so
 1540        // that each asynchronous operation can be run in order.
 1541        let (leader_updates_tx, mut leader_updates_rx) =
 1542            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1543        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1544            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1545                Self::process_leader_update(&this, leader_id, update, cx)
 1546                    .await
 1547                    .log_err();
 1548            }
 1549
 1550            Ok(())
 1551        });
 1552
 1553        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1554        let modal_layer = cx.new(|_| ModalLayer::new());
 1555        let toast_layer = cx.new(|_| ToastLayer::new());
 1556        cx.subscribe(
 1557            &modal_layer,
 1558            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1559                cx.emit(Event::ModalOpened);
 1560            },
 1561        )
 1562        .detach();
 1563
 1564        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1565        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1566        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1567        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1568        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1569        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1570        let status_bar = cx.new(|cx| {
 1571            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1572            status_bar.add_left_item(left_dock_buttons, window, cx);
 1573            status_bar.add_right_item(right_dock_buttons, window, cx);
 1574            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1575            status_bar
 1576        });
 1577
 1578        let session_id = app_state.session.read(cx).id().to_owned();
 1579
 1580        let mut active_call = None;
 1581        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1582            let subscriptions =
 1583                vec![
 1584                    call.0
 1585                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1586                ];
 1587            active_call = Some((call, subscriptions));
 1588        }
 1589
 1590        let (serializable_items_tx, serializable_items_rx) =
 1591            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1592        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1593            Self::serialize_items(&this, serializable_items_rx, cx).await
 1594        });
 1595
 1596        let subscriptions = vec![
 1597            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1598            cx.observe_window_bounds(window, move |this, window, cx| {
 1599                if this.bounds_save_task_queued.is_some() {
 1600                    return;
 1601                }
 1602                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1603                    cx.background_executor()
 1604                        .timer(Duration::from_millis(100))
 1605                        .await;
 1606                    this.update_in(cx, |this, window, cx| {
 1607                        this.save_window_bounds(window, cx).detach();
 1608                        this.bounds_save_task_queued.take();
 1609                    })
 1610                    .ok();
 1611                }));
 1612                cx.notify();
 1613            }),
 1614            cx.observe_window_appearance(window, |_, window, cx| {
 1615                let window_appearance = window.appearance();
 1616
 1617                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1618
 1619                GlobalTheme::reload_theme(cx);
 1620                GlobalTheme::reload_icon_theme(cx);
 1621            }),
 1622            cx.on_release({
 1623                let weak_handle = weak_handle.clone();
 1624                move |this, cx| {
 1625                    this.app_state.workspace_store.update(cx, move |store, _| {
 1626                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1627                    })
 1628                }
 1629            }),
 1630        ];
 1631
 1632        cx.defer_in(window, move |this, window, cx| {
 1633            this.update_window_title(window, cx);
 1634            this.show_initial_notifications(cx);
 1635        });
 1636
 1637        let mut center = PaneGroup::new(center_pane.clone());
 1638        center.set_is_center(true);
 1639        center.mark_positions(cx);
 1640
 1641        Workspace {
 1642            weak_self: weak_handle.clone(),
 1643            zoomed: None,
 1644            zoomed_position: None,
 1645            previous_dock_drag_coordinates: None,
 1646            center,
 1647            panes: vec![center_pane.clone()],
 1648            panes_by_item: Default::default(),
 1649            active_pane: center_pane.clone(),
 1650            last_active_center_pane: Some(center_pane.downgrade()),
 1651            last_active_view_id: None,
 1652            status_bar,
 1653            modal_layer,
 1654            toast_layer,
 1655            titlebar_item: None,
 1656            active_worktree_override: None,
 1657            notifications: Notifications::default(),
 1658            suppressed_notifications: HashSet::default(),
 1659            left_dock,
 1660            bottom_dock,
 1661            right_dock,
 1662            project: project.clone(),
 1663            follower_states: Default::default(),
 1664            last_leaders_by_pane: Default::default(),
 1665            dispatching_keystrokes: Default::default(),
 1666            window_edited: false,
 1667            last_window_title: None,
 1668            dirty_items: Default::default(),
 1669            active_call,
 1670            database_id: workspace_id,
 1671            app_state,
 1672            _observe_current_user,
 1673            _apply_leader_updates,
 1674            _schedule_serialize_workspace: None,
 1675            _serialize_workspace_task: None,
 1676            _schedule_serialize_ssh_paths: None,
 1677            leader_updates_tx,
 1678            _subscriptions: subscriptions,
 1679            pane_history_timestamp,
 1680            workspace_actions: Default::default(),
 1681            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1682            bounds: Default::default(),
 1683            centered_layout: false,
 1684            bounds_save_task_queued: None,
 1685            on_prompt_for_new_path: None,
 1686            on_prompt_for_open_path: None,
 1687            terminal_provider: None,
 1688            debugger_provider: None,
 1689            serializable_items_tx,
 1690            _items_serializer,
 1691            session_id: Some(session_id),
 1692
 1693            scheduled_tasks: Vec::new(),
 1694            last_open_dock_positions: Vec::new(),
 1695            removing: false,
 1696        }
 1697    }
 1698
 1699    pub fn new_local(
 1700        abs_paths: Vec<PathBuf>,
 1701        app_state: Arc<AppState>,
 1702        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1703        env: Option<HashMap<String, String>>,
 1704        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1705        cx: &mut App,
 1706    ) -> Task<
 1707        anyhow::Result<(
 1708            WindowHandle<MultiWorkspace>,
 1709            Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 1710        )>,
 1711    > {
 1712        let project_handle = Project::local(
 1713            app_state.client.clone(),
 1714            app_state.node_runtime.clone(),
 1715            app_state.user_store.clone(),
 1716            app_state.languages.clone(),
 1717            app_state.fs.clone(),
 1718            env,
 1719            Default::default(),
 1720            cx,
 1721        );
 1722
 1723        cx.spawn(async move |cx| {
 1724            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1725            for path in abs_paths.into_iter() {
 1726                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1727                    paths_to_open.push(canonical)
 1728                } else {
 1729                    paths_to_open.push(path)
 1730                }
 1731            }
 1732
 1733            let serialized_workspace =
 1734                persistence::DB.workspace_for_roots(paths_to_open.as_slice());
 1735
 1736            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1737                paths_to_open = paths.ordered_paths().cloned().collect();
 1738                if !paths.is_lexicographically_ordered() {
 1739                    project_handle.update(cx, |project, cx| {
 1740                        project.set_worktrees_reordered(true, cx);
 1741                    });
 1742                }
 1743            }
 1744
 1745            // Get project paths for all of the abs_paths
 1746            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1747                Vec::with_capacity(paths_to_open.len());
 1748
 1749            for path in paths_to_open.into_iter() {
 1750                if let Some((_, project_entry)) = cx
 1751                    .update(|cx| {
 1752                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1753                    })
 1754                    .await
 1755                    .log_err()
 1756                {
 1757                    project_paths.push((path, Some(project_entry)));
 1758                } else {
 1759                    project_paths.push((path, None));
 1760                }
 1761            }
 1762
 1763            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1764                serialized_workspace.id
 1765            } else {
 1766                DB.next_id().await.unwrap_or_else(|_| Default::default())
 1767            };
 1768
 1769            let toolchains = DB.toolchains(workspace_id).await?;
 1770
 1771            for (toolchain, worktree_path, path) in toolchains {
 1772                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1773                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1774                    this.find_worktree(&worktree_path, cx)
 1775                        .and_then(|(worktree, rel_path)| {
 1776                            if rel_path.is_empty() {
 1777                                Some(worktree.read(cx).id())
 1778                            } else {
 1779                                None
 1780                            }
 1781                        })
 1782                }) else {
 1783                    // We did not find a worktree with a given path, but that's whatever.
 1784                    continue;
 1785                };
 1786                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1787                    continue;
 1788                }
 1789
 1790                project_handle
 1791                    .update(cx, |this, cx| {
 1792                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1793                    })
 1794                    .await;
 1795            }
 1796            if let Some(workspace) = serialized_workspace.as_ref() {
 1797                project_handle.update(cx, |this, cx| {
 1798                    for (scope, toolchains) in &workspace.user_toolchains {
 1799                        for toolchain in toolchains {
 1800                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1801                        }
 1802                    }
 1803                });
 1804            }
 1805
 1806            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1807                if let Some(window) = requesting_window {
 1808                    let centered_layout = serialized_workspace
 1809                        .as_ref()
 1810                        .map(|w| w.centered_layout)
 1811                        .unwrap_or(false);
 1812
 1813                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1814                        let workspace = cx.new(|cx| {
 1815                            let mut workspace = Workspace::new(
 1816                                Some(workspace_id),
 1817                                project_handle.clone(),
 1818                                app_state.clone(),
 1819                                window,
 1820                                cx,
 1821                            );
 1822
 1823                            workspace.centered_layout = centered_layout;
 1824
 1825                            // Call init callback to add items before window renders
 1826                            if let Some(init) = init {
 1827                                init(&mut workspace, window, cx);
 1828                            }
 1829
 1830                            workspace
 1831                        });
 1832                        multi_workspace.activate(workspace.clone(), cx);
 1833                        workspace
 1834                    })?;
 1835                    (window, workspace)
 1836                } else {
 1837                    let window_bounds_override = window_bounds_env_override();
 1838
 1839                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1840                        (Some(WindowBounds::Windowed(bounds)), None)
 1841                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1842                        && let Some(display) = workspace.display
 1843                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1844                    {
 1845                        // Reopening an existing workspace - restore its saved bounds
 1846                        (Some(bounds.0), Some(display))
 1847                    } else if let Some((display, bounds)) =
 1848                        persistence::read_default_window_bounds()
 1849                    {
 1850                        // New or empty workspace - use the last known window bounds
 1851                        (Some(bounds), Some(display))
 1852                    } else {
 1853                        // New window - let GPUI's default_bounds() handle cascading
 1854                        (None, None)
 1855                    };
 1856
 1857                    // Use the serialized workspace to construct the new window
 1858                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1859                    options.window_bounds = window_bounds;
 1860                    let centered_layout = serialized_workspace
 1861                        .as_ref()
 1862                        .map(|w| w.centered_layout)
 1863                        .unwrap_or(false);
 1864                    let window = cx.open_window(options, {
 1865                        let app_state = app_state.clone();
 1866                        let project_handle = project_handle.clone();
 1867                        move |window, cx| {
 1868                            let workspace = cx.new(|cx| {
 1869                                let mut workspace = Workspace::new(
 1870                                    Some(workspace_id),
 1871                                    project_handle,
 1872                                    app_state,
 1873                                    window,
 1874                                    cx,
 1875                                );
 1876                                workspace.centered_layout = centered_layout;
 1877
 1878                                // Call init callback to add items before window renders
 1879                                if let Some(init) = init {
 1880                                    init(&mut workspace, window, cx);
 1881                                }
 1882
 1883                                workspace
 1884                            });
 1885                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1886                        }
 1887                    })?;
 1888                    let workspace =
 1889                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1890                            multi_workspace.workspace().clone()
 1891                        })?;
 1892                    (window, workspace)
 1893                };
 1894
 1895            notify_if_database_failed(window, cx);
 1896            // Check if this is an empty workspace (no paths to open)
 1897            // An empty workspace is one where project_paths is empty
 1898            let is_empty_workspace = project_paths.is_empty();
 1899            // Check if serialized workspace has paths before it's moved
 1900            let serialized_workspace_has_paths = serialized_workspace
 1901                .as_ref()
 1902                .map(|ws| !ws.paths.is_empty())
 1903                .unwrap_or(false);
 1904
 1905            let opened_items = window
 1906                .update(cx, |_, window, cx| {
 1907                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 1908                        open_items(serialized_workspace, project_paths, window, cx)
 1909                    })
 1910                })?
 1911                .await
 1912                .unwrap_or_default();
 1913
 1914            // Restore default dock state for empty workspaces
 1915            // Only restore if:
 1916            // 1. This is an empty workspace (no paths), AND
 1917            // 2. The serialized workspace either doesn't exist or has no paths
 1918            if is_empty_workspace && !serialized_workspace_has_paths {
 1919                if let Some(default_docks) = persistence::read_default_dock_state() {
 1920                    window
 1921                        .update(cx, |_, window, cx| {
 1922                            workspace.update(cx, |workspace, cx| {
 1923                                for (dock, serialized_dock) in [
 1924                                    (&workspace.right_dock, &default_docks.right),
 1925                                    (&workspace.left_dock, &default_docks.left),
 1926                                    (&workspace.bottom_dock, &default_docks.bottom),
 1927                                ] {
 1928                                    dock.update(cx, |dock, cx| {
 1929                                        dock.serialized_dock = Some(serialized_dock.clone());
 1930                                        dock.restore_state(window, cx);
 1931                                    });
 1932                                }
 1933                                cx.notify();
 1934                            });
 1935                        })
 1936                        .log_err();
 1937                }
 1938            }
 1939
 1940            window
 1941                .update(cx, |_, _window, cx| {
 1942                    workspace.update(cx, |this: &mut Workspace, cx| {
 1943                        this.update_history(cx);
 1944                    });
 1945                })
 1946                .log_err();
 1947            Ok((window, opened_items))
 1948        })
 1949    }
 1950
 1951    pub fn weak_handle(&self) -> WeakEntity<Self> {
 1952        self.weak_self.clone()
 1953    }
 1954
 1955    pub fn left_dock(&self) -> &Entity<Dock> {
 1956        &self.left_dock
 1957    }
 1958
 1959    pub fn bottom_dock(&self) -> &Entity<Dock> {
 1960        &self.bottom_dock
 1961    }
 1962
 1963    pub fn set_bottom_dock_layout(
 1964        &mut self,
 1965        layout: BottomDockLayout,
 1966        window: &mut Window,
 1967        cx: &mut Context<Self>,
 1968    ) {
 1969        let fs = self.project().read(cx).fs();
 1970        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 1971            content.workspace.bottom_dock_layout = Some(layout);
 1972        });
 1973
 1974        cx.notify();
 1975        self.serialize_workspace(window, cx);
 1976    }
 1977
 1978    pub fn right_dock(&self) -> &Entity<Dock> {
 1979        &self.right_dock
 1980    }
 1981
 1982    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 1983        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 1984    }
 1985
 1986    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 1987        match position {
 1988            DockPosition::Left => &self.left_dock,
 1989            DockPosition::Bottom => &self.bottom_dock,
 1990            DockPosition::Right => &self.right_dock,
 1991        }
 1992    }
 1993
 1994    pub fn is_edited(&self) -> bool {
 1995        self.window_edited
 1996    }
 1997
 1998    pub fn add_panel<T: Panel>(
 1999        &mut self,
 2000        panel: Entity<T>,
 2001        window: &mut Window,
 2002        cx: &mut Context<Self>,
 2003    ) {
 2004        let focus_handle = panel.panel_focus_handle(cx);
 2005        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2006            .detach();
 2007
 2008        let dock_position = panel.position(window, cx);
 2009        let dock = self.dock_at_position(dock_position);
 2010
 2011        dock.update(cx, |dock, cx| {
 2012            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 2013        });
 2014    }
 2015
 2016    pub fn remove_panel<T: Panel>(
 2017        &mut self,
 2018        panel: &Entity<T>,
 2019        window: &mut Window,
 2020        cx: &mut Context<Self>,
 2021    ) {
 2022        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2023            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2024        }
 2025    }
 2026
 2027    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2028        &self.status_bar
 2029    }
 2030
 2031    pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
 2032        self.status_bar.update(cx, |status_bar, cx| {
 2033            status_bar.set_workspace_sidebar_open(open, cx);
 2034        });
 2035    }
 2036
 2037    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2038        StatusBarSettings::get_global(cx).show
 2039    }
 2040
 2041    pub fn app_state(&self) -> &Arc<AppState> {
 2042        &self.app_state
 2043    }
 2044
 2045    pub fn user_store(&self) -> &Entity<UserStore> {
 2046        &self.app_state.user_store
 2047    }
 2048
 2049    pub fn project(&self) -> &Entity<Project> {
 2050        &self.project
 2051    }
 2052
 2053    pub fn path_style(&self, cx: &App) -> PathStyle {
 2054        self.project.read(cx).path_style(cx)
 2055    }
 2056
 2057    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2058        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2059
 2060        for pane_handle in &self.panes {
 2061            let pane = pane_handle.read(cx);
 2062
 2063            for entry in pane.activation_history() {
 2064                history.insert(
 2065                    entry.entity_id,
 2066                    history
 2067                        .get(&entry.entity_id)
 2068                        .cloned()
 2069                        .unwrap_or(0)
 2070                        .max(entry.timestamp),
 2071                );
 2072            }
 2073        }
 2074
 2075        history
 2076    }
 2077
 2078    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2079        let mut recent_item: Option<Entity<T>> = None;
 2080        let mut recent_timestamp = 0;
 2081        for pane_handle in &self.panes {
 2082            let pane = pane_handle.read(cx);
 2083            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2084                pane.items().map(|item| (item.item_id(), item)).collect();
 2085            for entry in pane.activation_history() {
 2086                if entry.timestamp > recent_timestamp
 2087                    && let Some(&item) = item_map.get(&entry.entity_id)
 2088                    && let Some(typed_item) = item.act_as::<T>(cx)
 2089                {
 2090                    recent_timestamp = entry.timestamp;
 2091                    recent_item = Some(typed_item);
 2092                }
 2093            }
 2094        }
 2095        recent_item
 2096    }
 2097
 2098    pub fn recent_navigation_history_iter(
 2099        &self,
 2100        cx: &App,
 2101    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2102        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2103        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2104
 2105        for pane in &self.panes {
 2106            let pane = pane.read(cx);
 2107
 2108            pane.nav_history()
 2109                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2110                    if let Some(fs_path) = &fs_path {
 2111                        abs_paths_opened
 2112                            .entry(fs_path.clone())
 2113                            .or_default()
 2114                            .insert(project_path.clone());
 2115                    }
 2116                    let timestamp = entry.timestamp;
 2117                    match history.entry(project_path) {
 2118                        hash_map::Entry::Occupied(mut entry) => {
 2119                            let (_, old_timestamp) = entry.get();
 2120                            if &timestamp > old_timestamp {
 2121                                entry.insert((fs_path, timestamp));
 2122                            }
 2123                        }
 2124                        hash_map::Entry::Vacant(entry) => {
 2125                            entry.insert((fs_path, timestamp));
 2126                        }
 2127                    }
 2128                });
 2129
 2130            if let Some(item) = pane.active_item()
 2131                && let Some(project_path) = item.project_path(cx)
 2132            {
 2133                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2134
 2135                if let Some(fs_path) = &fs_path {
 2136                    abs_paths_opened
 2137                        .entry(fs_path.clone())
 2138                        .or_default()
 2139                        .insert(project_path.clone());
 2140                }
 2141
 2142                history.insert(project_path, (fs_path, std::usize::MAX));
 2143            }
 2144        }
 2145
 2146        history
 2147            .into_iter()
 2148            .sorted_by_key(|(_, (_, order))| *order)
 2149            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2150            .rev()
 2151            .filter(move |(history_path, abs_path)| {
 2152                let latest_project_path_opened = abs_path
 2153                    .as_ref()
 2154                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2155                    .and_then(|project_paths| {
 2156                        project_paths
 2157                            .iter()
 2158                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2159                    });
 2160
 2161                latest_project_path_opened.is_none_or(|path| path == history_path)
 2162            })
 2163    }
 2164
 2165    pub fn recent_navigation_history(
 2166        &self,
 2167        limit: Option<usize>,
 2168        cx: &App,
 2169    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2170        self.recent_navigation_history_iter(cx)
 2171            .take(limit.unwrap_or(usize::MAX))
 2172            .collect()
 2173    }
 2174
 2175    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2176        for pane in &self.panes {
 2177            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2178        }
 2179    }
 2180
 2181    fn navigate_history(
 2182        &mut self,
 2183        pane: WeakEntity<Pane>,
 2184        mode: NavigationMode,
 2185        window: &mut Window,
 2186        cx: &mut Context<Workspace>,
 2187    ) -> Task<Result<()>> {
 2188        self.navigate_history_impl(
 2189            pane,
 2190            mode,
 2191            window,
 2192            &mut |history, cx| history.pop(mode, cx),
 2193            cx,
 2194        )
 2195    }
 2196
 2197    fn navigate_tag_history(
 2198        &mut self,
 2199        pane: WeakEntity<Pane>,
 2200        mode: TagNavigationMode,
 2201        window: &mut Window,
 2202        cx: &mut Context<Workspace>,
 2203    ) -> Task<Result<()>> {
 2204        self.navigate_history_impl(
 2205            pane,
 2206            NavigationMode::Normal,
 2207            window,
 2208            &mut |history, _cx| history.pop_tag(mode),
 2209            cx,
 2210        )
 2211    }
 2212
 2213    fn navigate_history_impl(
 2214        &mut self,
 2215        pane: WeakEntity<Pane>,
 2216        mode: NavigationMode,
 2217        window: &mut Window,
 2218        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2219        cx: &mut Context<Workspace>,
 2220    ) -> Task<Result<()>> {
 2221        let to_load = if let Some(pane) = pane.upgrade() {
 2222            pane.update(cx, |pane, cx| {
 2223                window.focus(&pane.focus_handle(cx), cx);
 2224                loop {
 2225                    // Retrieve the weak item handle from the history.
 2226                    let entry = cb(pane.nav_history_mut(), cx)?;
 2227
 2228                    // If the item is still present in this pane, then activate it.
 2229                    if let Some(index) = entry
 2230                        .item
 2231                        .upgrade()
 2232                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2233                    {
 2234                        let prev_active_item_index = pane.active_item_index();
 2235                        pane.nav_history_mut().set_mode(mode);
 2236                        pane.activate_item(index, true, true, window, cx);
 2237                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2238
 2239                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2240                        if let Some(data) = entry.data {
 2241                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2242                        }
 2243
 2244                        if navigated {
 2245                            break None;
 2246                        }
 2247                    } else {
 2248                        // If the item is no longer present in this pane, then retrieve its
 2249                        // path info in order to reopen it.
 2250                        break pane
 2251                            .nav_history()
 2252                            .path_for_item(entry.item.id())
 2253                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2254                    }
 2255                }
 2256            })
 2257        } else {
 2258            None
 2259        };
 2260
 2261        if let Some((project_path, abs_path, entry)) = to_load {
 2262            // If the item was no longer present, then load it again from its previous path, first try the local path
 2263            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2264
 2265            cx.spawn_in(window, async move  |workspace, cx| {
 2266                let open_by_project_path = open_by_project_path.await;
 2267                let mut navigated = false;
 2268                match open_by_project_path
 2269                    .with_context(|| format!("Navigating to {project_path:?}"))
 2270                {
 2271                    Ok((project_entry_id, build_item)) => {
 2272                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2273                            pane.nav_history_mut().set_mode(mode);
 2274                            pane.active_item().map(|p| p.item_id())
 2275                        })?;
 2276
 2277                        pane.update_in(cx, |pane, window, cx| {
 2278                            let item = pane.open_item(
 2279                                project_entry_id,
 2280                                project_path,
 2281                                true,
 2282                                entry.is_preview,
 2283                                true,
 2284                                None,
 2285                                window, cx,
 2286                                build_item,
 2287                            );
 2288                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2289                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2290                            if let Some(data) = entry.data {
 2291                                navigated |= item.navigate(data, window, cx);
 2292                            }
 2293                        })?;
 2294                    }
 2295                    Err(open_by_project_path_e) => {
 2296                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2297                        // and its worktree is now dropped
 2298                        if let Some(abs_path) = abs_path {
 2299                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2300                                pane.nav_history_mut().set_mode(mode);
 2301                                pane.active_item().map(|p| p.item_id())
 2302                            })?;
 2303                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2304                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2305                            })?;
 2306                            match open_by_abs_path
 2307                                .await
 2308                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2309                            {
 2310                                Ok(item) => {
 2311                                    pane.update_in(cx, |pane, window, cx| {
 2312                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2313                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2314                                        if let Some(data) = entry.data {
 2315                                            navigated |= item.navigate(data, window, cx);
 2316                                        }
 2317                                    })?;
 2318                                }
 2319                                Err(open_by_abs_path_e) => {
 2320                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2321                                }
 2322                            }
 2323                        }
 2324                    }
 2325                }
 2326
 2327                if !navigated {
 2328                    workspace
 2329                        .update_in(cx, |workspace, window, cx| {
 2330                            Self::navigate_history(workspace, pane, mode, window, cx)
 2331                        })?
 2332                        .await?;
 2333                }
 2334
 2335                Ok(())
 2336            })
 2337        } else {
 2338            Task::ready(Ok(()))
 2339        }
 2340    }
 2341
 2342    pub fn go_back(
 2343        &mut self,
 2344        pane: WeakEntity<Pane>,
 2345        window: &mut Window,
 2346        cx: &mut Context<Workspace>,
 2347    ) -> Task<Result<()>> {
 2348        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2349    }
 2350
 2351    pub fn go_forward(
 2352        &mut self,
 2353        pane: WeakEntity<Pane>,
 2354        window: &mut Window,
 2355        cx: &mut Context<Workspace>,
 2356    ) -> Task<Result<()>> {
 2357        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2358    }
 2359
 2360    pub fn reopen_closed_item(
 2361        &mut self,
 2362        window: &mut Window,
 2363        cx: &mut Context<Workspace>,
 2364    ) -> Task<Result<()>> {
 2365        self.navigate_history(
 2366            self.active_pane().downgrade(),
 2367            NavigationMode::ReopeningClosedItem,
 2368            window,
 2369            cx,
 2370        )
 2371    }
 2372
 2373    pub fn client(&self) -> &Arc<Client> {
 2374        &self.app_state.client
 2375    }
 2376
 2377    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2378        self.titlebar_item = Some(item);
 2379        cx.notify();
 2380    }
 2381
 2382    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2383        self.on_prompt_for_new_path = Some(prompt)
 2384    }
 2385
 2386    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2387        self.on_prompt_for_open_path = Some(prompt)
 2388    }
 2389
 2390    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2391        self.terminal_provider = Some(Box::new(provider));
 2392    }
 2393
 2394    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2395        self.debugger_provider = Some(Arc::new(provider));
 2396    }
 2397
 2398    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2399        self.debugger_provider.clone()
 2400    }
 2401
 2402    pub fn prompt_for_open_path(
 2403        &mut self,
 2404        path_prompt_options: PathPromptOptions,
 2405        lister: DirectoryLister,
 2406        window: &mut Window,
 2407        cx: &mut Context<Self>,
 2408    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2409        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2410            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2411            let rx = prompt(self, lister, window, cx);
 2412            self.on_prompt_for_open_path = Some(prompt);
 2413            rx
 2414        } else {
 2415            let (tx, rx) = oneshot::channel();
 2416            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2417
 2418            cx.spawn_in(window, async move |workspace, cx| {
 2419                let Ok(result) = abs_path.await else {
 2420                    return Ok(());
 2421                };
 2422
 2423                match result {
 2424                    Ok(result) => {
 2425                        tx.send(result).ok();
 2426                    }
 2427                    Err(err) => {
 2428                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2429                            workspace.show_portal_error(err.to_string(), cx);
 2430                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2431                            let rx = prompt(workspace, lister, window, cx);
 2432                            workspace.on_prompt_for_open_path = Some(prompt);
 2433                            rx
 2434                        })?;
 2435                        if let Ok(path) = rx.await {
 2436                            tx.send(path).ok();
 2437                        }
 2438                    }
 2439                };
 2440                anyhow::Ok(())
 2441            })
 2442            .detach();
 2443
 2444            rx
 2445        }
 2446    }
 2447
 2448    pub fn prompt_for_new_path(
 2449        &mut self,
 2450        lister: DirectoryLister,
 2451        suggested_name: Option<String>,
 2452        window: &mut Window,
 2453        cx: &mut Context<Self>,
 2454    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2455        if self.project.read(cx).is_via_collab()
 2456            || self.project.read(cx).is_via_remote_server()
 2457            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2458        {
 2459            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2460            let rx = prompt(self, lister, suggested_name, window, cx);
 2461            self.on_prompt_for_new_path = Some(prompt);
 2462            return rx;
 2463        }
 2464
 2465        let (tx, rx) = oneshot::channel();
 2466        cx.spawn_in(window, async move |workspace, cx| {
 2467            let abs_path = workspace.update(cx, |workspace, cx| {
 2468                let relative_to = workspace
 2469                    .most_recent_active_path(cx)
 2470                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2471                    .or_else(|| {
 2472                        let project = workspace.project.read(cx);
 2473                        project.visible_worktrees(cx).find_map(|worktree| {
 2474                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2475                        })
 2476                    })
 2477                    .or_else(std::env::home_dir)
 2478                    .unwrap_or_else(|| PathBuf::from(""));
 2479                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2480            })?;
 2481            let abs_path = match abs_path.await? {
 2482                Ok(path) => path,
 2483                Err(err) => {
 2484                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2485                        workspace.show_portal_error(err.to_string(), cx);
 2486
 2487                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2488                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2489                        workspace.on_prompt_for_new_path = Some(prompt);
 2490                        rx
 2491                    })?;
 2492                    if let Ok(path) = rx.await {
 2493                        tx.send(path).ok();
 2494                    }
 2495                    return anyhow::Ok(());
 2496                }
 2497            };
 2498
 2499            tx.send(abs_path.map(|path| vec![path])).ok();
 2500            anyhow::Ok(())
 2501        })
 2502        .detach();
 2503
 2504        rx
 2505    }
 2506
 2507    pub fn titlebar_item(&self) -> Option<AnyView> {
 2508        self.titlebar_item.clone()
 2509    }
 2510
 2511    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2512    /// When set, git-related operations should use this worktree instead of deriving
 2513    /// the active worktree from the focused file.
 2514    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2515        self.active_worktree_override
 2516    }
 2517
 2518    pub fn set_active_worktree_override(
 2519        &mut self,
 2520        worktree_id: Option<WorktreeId>,
 2521        cx: &mut Context<Self>,
 2522    ) {
 2523        self.active_worktree_override = worktree_id;
 2524        cx.notify();
 2525    }
 2526
 2527    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2528        self.active_worktree_override = None;
 2529        cx.notify();
 2530    }
 2531
 2532    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2533    ///
 2534    /// If the given workspace has a local project, then it will be passed
 2535    /// to the callback. Otherwise, a new empty window will be created.
 2536    pub fn with_local_workspace<T, F>(
 2537        &mut self,
 2538        window: &mut Window,
 2539        cx: &mut Context<Self>,
 2540        callback: F,
 2541    ) -> Task<Result<T>>
 2542    where
 2543        T: 'static,
 2544        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2545    {
 2546        if self.project.read(cx).is_local() {
 2547            Task::ready(Ok(callback(self, window, cx)))
 2548        } else {
 2549            let env = self.project.read(cx).cli_environment(cx);
 2550            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
 2551            cx.spawn_in(window, async move |_vh, cx| {
 2552                let (multi_workspace_window, _) = task.await?;
 2553                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2554                    let workspace = multi_workspace.workspace().clone();
 2555                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2556                })
 2557            })
 2558        }
 2559    }
 2560
 2561    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2562    ///
 2563    /// If the given workspace has a local project, then it will be passed
 2564    /// to the callback. Otherwise, a new empty window will be created.
 2565    pub fn with_local_or_wsl_workspace<T, F>(
 2566        &mut self,
 2567        window: &mut Window,
 2568        cx: &mut Context<Self>,
 2569        callback: F,
 2570    ) -> Task<Result<T>>
 2571    where
 2572        T: 'static,
 2573        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2574    {
 2575        let project = self.project.read(cx);
 2576        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2577            Task::ready(Ok(callback(self, window, cx)))
 2578        } else {
 2579            let env = self.project.read(cx).cli_environment(cx);
 2580            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
 2581            cx.spawn_in(window, async move |_vh, cx| {
 2582                let (multi_workspace_window, _) = task.await?;
 2583                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2584                    let workspace = multi_workspace.workspace().clone();
 2585                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2586                })
 2587            })
 2588        }
 2589    }
 2590
 2591    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2592        self.project.read(cx).worktrees(cx)
 2593    }
 2594
 2595    pub fn visible_worktrees<'a>(
 2596        &self,
 2597        cx: &'a App,
 2598    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2599        self.project.read(cx).visible_worktrees(cx)
 2600    }
 2601
 2602    #[cfg(any(test, feature = "test-support"))]
 2603    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2604        let futures = self
 2605            .worktrees(cx)
 2606            .filter_map(|worktree| worktree.read(cx).as_local())
 2607            .map(|worktree| worktree.scan_complete())
 2608            .collect::<Vec<_>>();
 2609        async move {
 2610            for future in futures {
 2611                future.await;
 2612            }
 2613        }
 2614    }
 2615
 2616    pub fn close_global(cx: &mut App) {
 2617        cx.defer(|cx| {
 2618            cx.windows().iter().find(|window| {
 2619                window
 2620                    .update(cx, |_, window, _| {
 2621                        if window.is_window_active() {
 2622                            //This can only get called when the window's project connection has been lost
 2623                            //so we don't need to prompt the user for anything and instead just close the window
 2624                            window.remove_window();
 2625                            true
 2626                        } else {
 2627                            false
 2628                        }
 2629                    })
 2630                    .unwrap_or(false)
 2631            });
 2632        });
 2633    }
 2634
 2635    pub fn move_focused_panel_to_next_position(
 2636        &mut self,
 2637        _: &MoveFocusedPanelToNextPosition,
 2638        window: &mut Window,
 2639        cx: &mut Context<Self>,
 2640    ) {
 2641        let docks = self.all_docks();
 2642        let active_dock = docks
 2643            .into_iter()
 2644            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2645
 2646        if let Some(dock) = active_dock {
 2647            dock.update(cx, |dock, cx| {
 2648                let active_panel = dock
 2649                    .active_panel()
 2650                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2651
 2652                if let Some(panel) = active_panel {
 2653                    panel.move_to_next_position(window, cx);
 2654                }
 2655            })
 2656        }
 2657    }
 2658
 2659    pub fn prepare_to_close(
 2660        &mut self,
 2661        close_intent: CloseIntent,
 2662        window: &mut Window,
 2663        cx: &mut Context<Self>,
 2664    ) -> Task<Result<bool>> {
 2665        let active_call = self.active_global_call();
 2666
 2667        cx.spawn_in(window, async move |this, cx| {
 2668            this.update(cx, |this, _| {
 2669                if close_intent == CloseIntent::CloseWindow {
 2670                    this.removing = true;
 2671                }
 2672            })?;
 2673
 2674            let workspace_count = cx.update(|_window, cx| {
 2675                cx.windows()
 2676                    .iter()
 2677                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 2678                    .count()
 2679            })?;
 2680
 2681            #[cfg(target_os = "macos")]
 2682            let save_last_workspace = false;
 2683
 2684            // On Linux and Windows, closing the last window should restore the last workspace.
 2685            #[cfg(not(target_os = "macos"))]
 2686            let save_last_workspace = {
 2687                let remaining_workspaces = cx.update(|_window, cx| {
 2688                    cx.windows()
 2689                        .iter()
 2690                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 2691                        .filter_map(|multi_workspace| {
 2692                            multi_workspace
 2693                                .update(cx, |multi_workspace, _, cx| {
 2694                                    multi_workspace.workspace().read(cx).removing
 2695                                })
 2696                                .ok()
 2697                        })
 2698                        .filter(|removing| !removing)
 2699                        .count()
 2700                })?;
 2701
 2702                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 2703            };
 2704
 2705            if let Some(active_call) = active_call
 2706                && workspace_count == 1
 2707                && cx
 2708                    .update(|_window, cx| active_call.0.is_in_room(cx))
 2709                    .unwrap_or(false)
 2710            {
 2711                if close_intent == CloseIntent::CloseWindow {
 2712                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 2713                    let answer = cx.update(|window, cx| {
 2714                        window.prompt(
 2715                            PromptLevel::Warning,
 2716                            "Do you want to leave the current call?",
 2717                            None,
 2718                            &["Close window and hang up", "Cancel"],
 2719                            cx,
 2720                        )
 2721                    })?;
 2722
 2723                    if answer.await.log_err() == Some(1) {
 2724                        return anyhow::Ok(false);
 2725                    } else {
 2726                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 2727                            task.await.log_err();
 2728                        }
 2729                    }
 2730                }
 2731                if close_intent == CloseIntent::ReplaceWindow {
 2732                    _ = cx.update(|_window, cx| {
 2733                        let multi_workspace = cx
 2734                            .windows()
 2735                            .iter()
 2736                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 2737                            .next()
 2738                            .unwrap();
 2739                        let project = multi_workspace
 2740                            .read(cx)?
 2741                            .workspace()
 2742                            .read(cx)
 2743                            .project
 2744                            .clone();
 2745                        if project.read(cx).is_shared() {
 2746                            active_call.0.unshare_project(project, cx)?;
 2747                        }
 2748                        Ok::<_, anyhow::Error>(())
 2749                    });
 2750                }
 2751            }
 2752
 2753            let save_result = this
 2754                .update_in(cx, |this, window, cx| {
 2755                    this.save_all_internal(SaveIntent::Close, window, cx)
 2756                })?
 2757                .await;
 2758
 2759            // If we're not quitting, but closing, we remove the workspace from
 2760            // the current session.
 2761            if close_intent != CloseIntent::Quit
 2762                && !save_last_workspace
 2763                && save_result.as_ref().is_ok_and(|&res| res)
 2764            {
 2765                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2766                    .await;
 2767            }
 2768
 2769            save_result
 2770        })
 2771    }
 2772
 2773    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2774        self.save_all_internal(
 2775            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2776            window,
 2777            cx,
 2778        )
 2779        .detach_and_log_err(cx);
 2780    }
 2781
 2782    fn send_keystrokes(
 2783        &mut self,
 2784        action: &SendKeystrokes,
 2785        window: &mut Window,
 2786        cx: &mut Context<Self>,
 2787    ) {
 2788        let keystrokes: Vec<Keystroke> = action
 2789            .0
 2790            .split(' ')
 2791            .flat_map(|k| Keystroke::parse(k).log_err())
 2792            .map(|k| {
 2793                cx.keyboard_mapper()
 2794                    .map_key_equivalent(k, false)
 2795                    .inner()
 2796                    .clone()
 2797            })
 2798            .collect();
 2799        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2800    }
 2801
 2802    pub fn send_keystrokes_impl(
 2803        &mut self,
 2804        keystrokes: Vec<Keystroke>,
 2805        window: &mut Window,
 2806        cx: &mut Context<Self>,
 2807    ) -> Shared<Task<()>> {
 2808        let mut state = self.dispatching_keystrokes.borrow_mut();
 2809        if !state.dispatched.insert(keystrokes.clone()) {
 2810            cx.propagate();
 2811            return state.task.clone().unwrap();
 2812        }
 2813
 2814        state.queue.extend(keystrokes);
 2815
 2816        let keystrokes = self.dispatching_keystrokes.clone();
 2817        if state.task.is_none() {
 2818            state.task = Some(
 2819                window
 2820                    .spawn(cx, async move |cx| {
 2821                        // limit to 100 keystrokes to avoid infinite recursion.
 2822                        for _ in 0..100 {
 2823                            let mut state = keystrokes.borrow_mut();
 2824                            let Some(keystroke) = state.queue.pop_front() else {
 2825                                state.dispatched.clear();
 2826                                state.task.take();
 2827                                return;
 2828                            };
 2829                            drop(state);
 2830                            cx.update(|window, cx| {
 2831                                let focused = window.focused(cx);
 2832                                window.dispatch_keystroke(keystroke.clone(), cx);
 2833                                if window.focused(cx) != focused {
 2834                                    // dispatch_keystroke may cause the focus to change.
 2835                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 2836                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 2837                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 2838                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 2839                                    // )
 2840                                    window.draw(cx).clear();
 2841                                }
 2842                            })
 2843                            .ok();
 2844                        }
 2845
 2846                        *keystrokes.borrow_mut() = Default::default();
 2847                        log::error!("over 100 keystrokes passed to send_keystrokes");
 2848                    })
 2849                    .shared(),
 2850            );
 2851        }
 2852        state.task.clone().unwrap()
 2853    }
 2854
 2855    fn save_all_internal(
 2856        &mut self,
 2857        mut save_intent: SaveIntent,
 2858        window: &mut Window,
 2859        cx: &mut Context<Self>,
 2860    ) -> Task<Result<bool>> {
 2861        if self.project.read(cx).is_disconnected(cx) {
 2862            return Task::ready(Ok(true));
 2863        }
 2864        let dirty_items = self
 2865            .panes
 2866            .iter()
 2867            .flat_map(|pane| {
 2868                pane.read(cx).items().filter_map(|item| {
 2869                    if item.is_dirty(cx) {
 2870                        item.tab_content_text(0, cx);
 2871                        Some((pane.downgrade(), item.boxed_clone()))
 2872                    } else {
 2873                        None
 2874                    }
 2875                })
 2876            })
 2877            .collect::<Vec<_>>();
 2878
 2879        let project = self.project.clone();
 2880        cx.spawn_in(window, async move |workspace, cx| {
 2881            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 2882                let (serialize_tasks, remaining_dirty_items) =
 2883                    workspace.update_in(cx, |workspace, window, cx| {
 2884                        let mut remaining_dirty_items = Vec::new();
 2885                        let mut serialize_tasks = Vec::new();
 2886                        for (pane, item) in dirty_items {
 2887                            if let Some(task) = item
 2888                                .to_serializable_item_handle(cx)
 2889                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 2890                            {
 2891                                serialize_tasks.push(task);
 2892                            } else {
 2893                                remaining_dirty_items.push((pane, item));
 2894                            }
 2895                        }
 2896                        (serialize_tasks, remaining_dirty_items)
 2897                    })?;
 2898
 2899                futures::future::try_join_all(serialize_tasks).await?;
 2900
 2901                if !remaining_dirty_items.is_empty() {
 2902                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 2903                }
 2904
 2905                if remaining_dirty_items.len() > 1 {
 2906                    let answer = workspace.update_in(cx, |_, window, cx| {
 2907                        let detail = Pane::file_names_for_prompt(
 2908                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 2909                            cx,
 2910                        );
 2911                        window.prompt(
 2912                            PromptLevel::Warning,
 2913                            "Do you want to save all changes in the following files?",
 2914                            Some(&detail),
 2915                            &["Save all", "Discard all", "Cancel"],
 2916                            cx,
 2917                        )
 2918                    })?;
 2919                    match answer.await.log_err() {
 2920                        Some(0) => save_intent = SaveIntent::SaveAll,
 2921                        Some(1) => save_intent = SaveIntent::Skip,
 2922                        Some(2) => return Ok(false),
 2923                        _ => {}
 2924                    }
 2925                }
 2926
 2927                remaining_dirty_items
 2928            } else {
 2929                dirty_items
 2930            };
 2931
 2932            for (pane, item) in dirty_items {
 2933                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 2934                    (
 2935                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 2936                        item.project_entry_ids(cx),
 2937                    )
 2938                })?;
 2939                if (singleton || !project_entry_ids.is_empty())
 2940                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 2941                {
 2942                    return Ok(false);
 2943                }
 2944            }
 2945            Ok(true)
 2946        })
 2947    }
 2948
 2949    pub fn open_workspace_for_paths(
 2950        &mut self,
 2951        replace_current_window: bool,
 2952        paths: Vec<PathBuf>,
 2953        window: &mut Window,
 2954        cx: &mut Context<Self>,
 2955    ) -> Task<Result<()>> {
 2956        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 2957        let is_remote = self.project.read(cx).is_via_collab();
 2958        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 2959        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 2960
 2961        let window_to_replace = if replace_current_window {
 2962            window_handle
 2963        } else if is_remote || has_worktree || has_dirty_items {
 2964            None
 2965        } else {
 2966            window_handle
 2967        };
 2968        let app_state = self.app_state.clone();
 2969
 2970        cx.spawn(async move |_, cx| {
 2971            cx.update(|cx| {
 2972                open_paths(
 2973                    &paths,
 2974                    app_state,
 2975                    OpenOptions {
 2976                        replace_window: window_to_replace,
 2977                        ..Default::default()
 2978                    },
 2979                    cx,
 2980                )
 2981            })
 2982            .await?;
 2983            Ok(())
 2984        })
 2985    }
 2986
 2987    #[allow(clippy::type_complexity)]
 2988    pub fn open_paths(
 2989        &mut self,
 2990        mut abs_paths: Vec<PathBuf>,
 2991        options: OpenOptions,
 2992        pane: Option<WeakEntity<Pane>>,
 2993        window: &mut Window,
 2994        cx: &mut Context<Self>,
 2995    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 2996        let fs = self.app_state.fs.clone();
 2997
 2998        let caller_ordered_abs_paths = abs_paths.clone();
 2999
 3000        // Sort the paths to ensure we add worktrees for parents before their children.
 3001        abs_paths.sort_unstable();
 3002        cx.spawn_in(window, async move |this, cx| {
 3003            let mut tasks = Vec::with_capacity(abs_paths.len());
 3004
 3005            for abs_path in &abs_paths {
 3006                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3007                    OpenVisible::All => Some(true),
 3008                    OpenVisible::None => Some(false),
 3009                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3010                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3011                        Some(None) => Some(true),
 3012                        None => None,
 3013                    },
 3014                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3015                        Some(Some(metadata)) => Some(metadata.is_dir),
 3016                        Some(None) => Some(false),
 3017                        None => None,
 3018                    },
 3019                };
 3020                let project_path = match visible {
 3021                    Some(visible) => match this
 3022                        .update(cx, |this, cx| {
 3023                            Workspace::project_path_for_path(
 3024                                this.project.clone(),
 3025                                abs_path,
 3026                                visible,
 3027                                cx,
 3028                            )
 3029                        })
 3030                        .log_err()
 3031                    {
 3032                        Some(project_path) => project_path.await.log_err(),
 3033                        None => None,
 3034                    },
 3035                    None => None,
 3036                };
 3037
 3038                let this = this.clone();
 3039                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3040                let fs = fs.clone();
 3041                let pane = pane.clone();
 3042                let task = cx.spawn(async move |cx| {
 3043                    let (_worktree, project_path) = project_path?;
 3044                    if fs.is_dir(&abs_path).await {
 3045                        // Opening a directory should not race to update the active entry.
 3046                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3047                        None
 3048                    } else {
 3049                        Some(
 3050                            this.update_in(cx, |this, window, cx| {
 3051                                this.open_path(
 3052                                    project_path,
 3053                                    pane,
 3054                                    options.focus.unwrap_or(true),
 3055                                    window,
 3056                                    cx,
 3057                                )
 3058                            })
 3059                            .ok()?
 3060                            .await,
 3061                        )
 3062                    }
 3063                });
 3064                tasks.push(task);
 3065            }
 3066
 3067            let results = futures::future::join_all(tasks).await;
 3068
 3069            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3070            let mut winner: Option<(PathBuf, bool)> = None;
 3071            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3072                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3073                    if !metadata.is_dir {
 3074                        winner = Some((abs_path, false));
 3075                        break;
 3076                    }
 3077                    if winner.is_none() {
 3078                        winner = Some((abs_path, true));
 3079                    }
 3080                } else if winner.is_none() {
 3081                    winner = Some((abs_path, false));
 3082                }
 3083            }
 3084
 3085            // Compute the winner entry id on the foreground thread and emit once, after all
 3086            // paths finish opening. This avoids races between concurrently-opening paths
 3087            // (directories in particular) and makes the resulting project panel selection
 3088            // deterministic.
 3089            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3090                'emit_winner: {
 3091                    let winner_abs_path: Arc<Path> =
 3092                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3093
 3094                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3095                        OpenVisible::All => true,
 3096                        OpenVisible::None => false,
 3097                        OpenVisible::OnlyFiles => !winner_is_dir,
 3098                        OpenVisible::OnlyDirectories => winner_is_dir,
 3099                    };
 3100
 3101                    let Some(worktree_task) = this
 3102                        .update(cx, |workspace, cx| {
 3103                            workspace.project.update(cx, |project, cx| {
 3104                                project.find_or_create_worktree(
 3105                                    winner_abs_path.as_ref(),
 3106                                    visible,
 3107                                    cx,
 3108                                )
 3109                            })
 3110                        })
 3111                        .ok()
 3112                    else {
 3113                        break 'emit_winner;
 3114                    };
 3115
 3116                    let Ok((worktree, _)) = worktree_task.await else {
 3117                        break 'emit_winner;
 3118                    };
 3119
 3120                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3121                        let worktree = worktree.read(cx);
 3122                        let worktree_abs_path = worktree.abs_path();
 3123                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3124                            worktree.root_entry()
 3125                        } else {
 3126                            winner_abs_path
 3127                                .strip_prefix(worktree_abs_path.as_ref())
 3128                                .ok()
 3129                                .and_then(|relative_path| {
 3130                                    let relative_path =
 3131                                        RelPath::new(relative_path, PathStyle::local())
 3132                                            .log_err()?;
 3133                                    worktree.entry_for_path(&relative_path)
 3134                                })
 3135                        }?;
 3136                        Some(entry.id)
 3137                    }) else {
 3138                        break 'emit_winner;
 3139                    };
 3140
 3141                    this.update(cx, |workspace, cx| {
 3142                        workspace.project.update(cx, |_, cx| {
 3143                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3144                        });
 3145                    })
 3146                    .ok();
 3147                }
 3148            }
 3149
 3150            results
 3151        })
 3152    }
 3153
 3154    pub fn open_resolved_path(
 3155        &mut self,
 3156        path: ResolvedPath,
 3157        window: &mut Window,
 3158        cx: &mut Context<Self>,
 3159    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3160        match path {
 3161            ResolvedPath::ProjectPath { project_path, .. } => {
 3162                self.open_path(project_path, None, true, window, cx)
 3163            }
 3164            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3165                PathBuf::from(path),
 3166                OpenOptions {
 3167                    visible: Some(OpenVisible::None),
 3168                    ..Default::default()
 3169                },
 3170                window,
 3171                cx,
 3172            ),
 3173        }
 3174    }
 3175
 3176    pub fn absolute_path_of_worktree(
 3177        &self,
 3178        worktree_id: WorktreeId,
 3179        cx: &mut Context<Self>,
 3180    ) -> Option<PathBuf> {
 3181        self.project
 3182            .read(cx)
 3183            .worktree_for_id(worktree_id, cx)
 3184            // TODO: use `abs_path` or `root_dir`
 3185            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3186    }
 3187
 3188    fn add_folder_to_project(
 3189        &mut self,
 3190        _: &AddFolderToProject,
 3191        window: &mut Window,
 3192        cx: &mut Context<Self>,
 3193    ) {
 3194        let project = self.project.read(cx);
 3195        if project.is_via_collab() {
 3196            self.show_error(
 3197                &anyhow!("You cannot add folders to someone else's project"),
 3198                cx,
 3199            );
 3200            return;
 3201        }
 3202        let paths = self.prompt_for_open_path(
 3203            PathPromptOptions {
 3204                files: false,
 3205                directories: true,
 3206                multiple: true,
 3207                prompt: None,
 3208            },
 3209            DirectoryLister::Project(self.project.clone()),
 3210            window,
 3211            cx,
 3212        );
 3213        cx.spawn_in(window, async move |this, cx| {
 3214            if let Some(paths) = paths.await.log_err().flatten() {
 3215                let results = this
 3216                    .update_in(cx, |this, window, cx| {
 3217                        this.open_paths(
 3218                            paths,
 3219                            OpenOptions {
 3220                                visible: Some(OpenVisible::All),
 3221                                ..Default::default()
 3222                            },
 3223                            None,
 3224                            window,
 3225                            cx,
 3226                        )
 3227                    })?
 3228                    .await;
 3229                for result in results.into_iter().flatten() {
 3230                    result.log_err();
 3231                }
 3232            }
 3233            anyhow::Ok(())
 3234        })
 3235        .detach_and_log_err(cx);
 3236    }
 3237
 3238    pub fn project_path_for_path(
 3239        project: Entity<Project>,
 3240        abs_path: &Path,
 3241        visible: bool,
 3242        cx: &mut App,
 3243    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3244        let entry = project.update(cx, |project, cx| {
 3245            project.find_or_create_worktree(abs_path, visible, cx)
 3246        });
 3247        cx.spawn(async move |cx| {
 3248            let (worktree, path) = entry.await?;
 3249            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3250            Ok((worktree, ProjectPath { worktree_id, path }))
 3251        })
 3252    }
 3253
 3254    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3255        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3256    }
 3257
 3258    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3259        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3260    }
 3261
 3262    pub fn items_of_type<'a, T: Item>(
 3263        &'a self,
 3264        cx: &'a App,
 3265    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3266        self.panes
 3267            .iter()
 3268            .flat_map(|pane| pane.read(cx).items_of_type())
 3269    }
 3270
 3271    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3272        self.active_pane().read(cx).active_item()
 3273    }
 3274
 3275    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3276        let item = self.active_item(cx)?;
 3277        item.to_any_view().downcast::<I>().ok()
 3278    }
 3279
 3280    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3281        self.active_item(cx).and_then(|item| item.project_path(cx))
 3282    }
 3283
 3284    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3285        self.recent_navigation_history_iter(cx)
 3286            .filter_map(|(path, abs_path)| {
 3287                let worktree = self
 3288                    .project
 3289                    .read(cx)
 3290                    .worktree_for_id(path.worktree_id, cx)?;
 3291                if worktree.read(cx).is_visible() {
 3292                    abs_path
 3293                } else {
 3294                    None
 3295                }
 3296            })
 3297            .next()
 3298    }
 3299
 3300    pub fn save_active_item(
 3301        &mut self,
 3302        save_intent: SaveIntent,
 3303        window: &mut Window,
 3304        cx: &mut App,
 3305    ) -> Task<Result<()>> {
 3306        let project = self.project.clone();
 3307        let pane = self.active_pane();
 3308        let item = pane.read(cx).active_item();
 3309        let pane = pane.downgrade();
 3310
 3311        window.spawn(cx, async move |cx| {
 3312            if let Some(item) = item {
 3313                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3314                    .await
 3315                    .map(|_| ())
 3316            } else {
 3317                Ok(())
 3318            }
 3319        })
 3320    }
 3321
 3322    pub fn close_inactive_items_and_panes(
 3323        &mut self,
 3324        action: &CloseInactiveTabsAndPanes,
 3325        window: &mut Window,
 3326        cx: &mut Context<Self>,
 3327    ) {
 3328        if let Some(task) = self.close_all_internal(
 3329            true,
 3330            action.save_intent.unwrap_or(SaveIntent::Close),
 3331            window,
 3332            cx,
 3333        ) {
 3334            task.detach_and_log_err(cx)
 3335        }
 3336    }
 3337
 3338    pub fn close_all_items_and_panes(
 3339        &mut self,
 3340        action: &CloseAllItemsAndPanes,
 3341        window: &mut Window,
 3342        cx: &mut Context<Self>,
 3343    ) {
 3344        if let Some(task) = self.close_all_internal(
 3345            false,
 3346            action.save_intent.unwrap_or(SaveIntent::Close),
 3347            window,
 3348            cx,
 3349        ) {
 3350            task.detach_and_log_err(cx)
 3351        }
 3352    }
 3353
 3354    /// Closes the active item across all panes.
 3355    pub fn close_item_in_all_panes(
 3356        &mut self,
 3357        action: &CloseItemInAllPanes,
 3358        window: &mut Window,
 3359        cx: &mut Context<Self>,
 3360    ) {
 3361        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3362            return;
 3363        };
 3364
 3365        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3366        let close_pinned = action.close_pinned;
 3367
 3368        if let Some(project_path) = active_item.project_path(cx) {
 3369            self.close_items_with_project_path(
 3370                &project_path,
 3371                save_intent,
 3372                close_pinned,
 3373                window,
 3374                cx,
 3375            );
 3376        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3377            let item_id = active_item.item_id();
 3378            self.active_pane().update(cx, |pane, cx| {
 3379                pane.close_item_by_id(item_id, save_intent, window, cx)
 3380                    .detach_and_log_err(cx);
 3381            });
 3382        }
 3383    }
 3384
 3385    /// Closes all items with the given project path across all panes.
 3386    pub fn close_items_with_project_path(
 3387        &mut self,
 3388        project_path: &ProjectPath,
 3389        save_intent: SaveIntent,
 3390        close_pinned: bool,
 3391        window: &mut Window,
 3392        cx: &mut Context<Self>,
 3393    ) {
 3394        let panes = self.panes().to_vec();
 3395        for pane in panes {
 3396            pane.update(cx, |pane, cx| {
 3397                pane.close_items_for_project_path(
 3398                    project_path,
 3399                    save_intent,
 3400                    close_pinned,
 3401                    window,
 3402                    cx,
 3403                )
 3404                .detach_and_log_err(cx);
 3405            });
 3406        }
 3407    }
 3408
 3409    fn close_all_internal(
 3410        &mut self,
 3411        retain_active_pane: bool,
 3412        save_intent: SaveIntent,
 3413        window: &mut Window,
 3414        cx: &mut Context<Self>,
 3415    ) -> Option<Task<Result<()>>> {
 3416        let current_pane = self.active_pane();
 3417
 3418        let mut tasks = Vec::new();
 3419
 3420        if retain_active_pane {
 3421            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3422                pane.close_other_items(
 3423                    &CloseOtherItems {
 3424                        save_intent: None,
 3425                        close_pinned: false,
 3426                    },
 3427                    None,
 3428                    window,
 3429                    cx,
 3430                )
 3431            });
 3432
 3433            tasks.push(current_pane_close);
 3434        }
 3435
 3436        for pane in self.panes() {
 3437            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3438                continue;
 3439            }
 3440
 3441            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3442                pane.close_all_items(
 3443                    &CloseAllItems {
 3444                        save_intent: Some(save_intent),
 3445                        close_pinned: false,
 3446                    },
 3447                    window,
 3448                    cx,
 3449                )
 3450            });
 3451
 3452            tasks.push(close_pane_items)
 3453        }
 3454
 3455        if tasks.is_empty() {
 3456            None
 3457        } else {
 3458            Some(cx.spawn_in(window, async move |_, _| {
 3459                for task in tasks {
 3460                    task.await?
 3461                }
 3462                Ok(())
 3463            }))
 3464        }
 3465    }
 3466
 3467    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3468        self.dock_at_position(position).read(cx).is_open()
 3469    }
 3470
 3471    pub fn toggle_dock(
 3472        &mut self,
 3473        dock_side: DockPosition,
 3474        window: &mut Window,
 3475        cx: &mut Context<Self>,
 3476    ) {
 3477        let mut focus_center = false;
 3478        let mut reveal_dock = false;
 3479
 3480        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3481        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3482
 3483        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3484            telemetry::event!(
 3485                "Panel Button Clicked",
 3486                name = panel.persistent_name(),
 3487                toggle_state = !was_visible
 3488            );
 3489        }
 3490        if was_visible {
 3491            self.save_open_dock_positions(cx);
 3492        }
 3493
 3494        let dock = self.dock_at_position(dock_side);
 3495        dock.update(cx, |dock, cx| {
 3496            dock.set_open(!was_visible, window, cx);
 3497
 3498            if dock.active_panel().is_none() {
 3499                let Some(panel_ix) = dock
 3500                    .first_enabled_panel_idx(cx)
 3501                    .log_with_level(log::Level::Info)
 3502                else {
 3503                    return;
 3504                };
 3505                dock.activate_panel(panel_ix, window, cx);
 3506            }
 3507
 3508            if let Some(active_panel) = dock.active_panel() {
 3509                if was_visible {
 3510                    if active_panel
 3511                        .panel_focus_handle(cx)
 3512                        .contains_focused(window, cx)
 3513                    {
 3514                        focus_center = true;
 3515                    }
 3516                } else {
 3517                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3518                    window.focus(focus_handle, cx);
 3519                    reveal_dock = true;
 3520                }
 3521            }
 3522        });
 3523
 3524        if reveal_dock {
 3525            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3526        }
 3527
 3528        if focus_center {
 3529            self.active_pane
 3530                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3531        }
 3532
 3533        cx.notify();
 3534        self.serialize_workspace(window, cx);
 3535    }
 3536
 3537    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3538        self.all_docks().into_iter().find(|&dock| {
 3539            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3540        })
 3541    }
 3542
 3543    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3544        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3545            self.save_open_dock_positions(cx);
 3546            dock.update(cx, |dock, cx| {
 3547                dock.set_open(false, window, cx);
 3548            });
 3549            return true;
 3550        }
 3551        false
 3552    }
 3553
 3554    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3555        self.save_open_dock_positions(cx);
 3556        for dock in self.all_docks() {
 3557            dock.update(cx, |dock, cx| {
 3558                dock.set_open(false, window, cx);
 3559            });
 3560        }
 3561
 3562        cx.focus_self(window);
 3563        cx.notify();
 3564        self.serialize_workspace(window, cx);
 3565    }
 3566
 3567    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3568        self.all_docks()
 3569            .into_iter()
 3570            .filter_map(|dock| {
 3571                let dock_ref = dock.read(cx);
 3572                if dock_ref.is_open() {
 3573                    Some(dock_ref.position())
 3574                } else {
 3575                    None
 3576                }
 3577            })
 3578            .collect()
 3579    }
 3580
 3581    /// Saves the positions of currently open docks.
 3582    ///
 3583    /// Updates `last_open_dock_positions` with positions of all currently open
 3584    /// docks, to later be restored by the 'Toggle All Docks' action.
 3585    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3586        let open_dock_positions = self.get_open_dock_positions(cx);
 3587        if !open_dock_positions.is_empty() {
 3588            self.last_open_dock_positions = open_dock_positions;
 3589        }
 3590    }
 3591
 3592    /// Toggles all docks between open and closed states.
 3593    ///
 3594    /// If any docks are open, closes all and remembers their positions. If all
 3595    /// docks are closed, restores the last remembered dock configuration.
 3596    fn toggle_all_docks(
 3597        &mut self,
 3598        _: &ToggleAllDocks,
 3599        window: &mut Window,
 3600        cx: &mut Context<Self>,
 3601    ) {
 3602        let open_dock_positions = self.get_open_dock_positions(cx);
 3603
 3604        if !open_dock_positions.is_empty() {
 3605            self.close_all_docks(window, cx);
 3606        } else if !self.last_open_dock_positions.is_empty() {
 3607            self.restore_last_open_docks(window, cx);
 3608        }
 3609    }
 3610
 3611    /// Reopens docks from the most recently remembered configuration.
 3612    ///
 3613    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3614    /// and clears the stored positions.
 3615    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3616        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3617
 3618        for position in positions_to_open {
 3619            let dock = self.dock_at_position(position);
 3620            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3621        }
 3622
 3623        cx.focus_self(window);
 3624        cx.notify();
 3625        self.serialize_workspace(window, cx);
 3626    }
 3627
 3628    /// Transfer focus to the panel of the given type.
 3629    pub fn focus_panel<T: Panel>(
 3630        &mut self,
 3631        window: &mut Window,
 3632        cx: &mut Context<Self>,
 3633    ) -> Option<Entity<T>> {
 3634        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 3635        panel.to_any().downcast().ok()
 3636    }
 3637
 3638    /// Focus the panel of the given type if it isn't already focused. If it is
 3639    /// already focused, then transfer focus back to the workspace center.
 3640    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 3641    /// panel when transferring focus back to the center.
 3642    pub fn toggle_panel_focus<T: Panel>(
 3643        &mut self,
 3644        window: &mut Window,
 3645        cx: &mut Context<Self>,
 3646    ) -> bool {
 3647        let mut did_focus_panel = false;
 3648        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 3649            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3650            did_focus_panel
 3651        });
 3652
 3653        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 3654            self.close_panel::<T>(window, cx);
 3655        }
 3656
 3657        telemetry::event!(
 3658            "Panel Button Clicked",
 3659            name = T::persistent_name(),
 3660            toggle_state = did_focus_panel
 3661        );
 3662
 3663        did_focus_panel
 3664    }
 3665
 3666    pub fn activate_panel_for_proto_id(
 3667        &mut self,
 3668        panel_id: PanelId,
 3669        window: &mut Window,
 3670        cx: &mut Context<Self>,
 3671    ) -> Option<Arc<dyn PanelHandle>> {
 3672        let mut panel = None;
 3673        for dock in self.all_docks() {
 3674            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3675                panel = dock.update(cx, |dock, cx| {
 3676                    dock.activate_panel(panel_index, window, cx);
 3677                    dock.set_open(true, window, cx);
 3678                    dock.active_panel().cloned()
 3679                });
 3680                break;
 3681            }
 3682        }
 3683
 3684        if panel.is_some() {
 3685            cx.notify();
 3686            self.serialize_workspace(window, cx);
 3687        }
 3688
 3689        panel
 3690    }
 3691
 3692    /// Focus or unfocus the given panel type, depending on the given callback.
 3693    fn focus_or_unfocus_panel<T: Panel>(
 3694        &mut self,
 3695        window: &mut Window,
 3696        cx: &mut Context<Self>,
 3697        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3698    ) -> Option<Arc<dyn PanelHandle>> {
 3699        let mut result_panel = None;
 3700        let mut serialize = false;
 3701        for dock in self.all_docks() {
 3702            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3703                let mut focus_center = false;
 3704                let panel = dock.update(cx, |dock, cx| {
 3705                    dock.activate_panel(panel_index, window, cx);
 3706
 3707                    let panel = dock.active_panel().cloned();
 3708                    if let Some(panel) = panel.as_ref() {
 3709                        if should_focus(&**panel, window, cx) {
 3710                            dock.set_open(true, window, cx);
 3711                            panel.panel_focus_handle(cx).focus(window, cx);
 3712                        } else {
 3713                            focus_center = true;
 3714                        }
 3715                    }
 3716                    panel
 3717                });
 3718
 3719                if focus_center {
 3720                    self.active_pane
 3721                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3722                }
 3723
 3724                result_panel = panel;
 3725                serialize = true;
 3726                break;
 3727            }
 3728        }
 3729
 3730        if serialize {
 3731            self.serialize_workspace(window, cx);
 3732        }
 3733
 3734        cx.notify();
 3735        result_panel
 3736    }
 3737
 3738    /// Open the panel of the given type
 3739    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3740        for dock in self.all_docks() {
 3741            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3742                dock.update(cx, |dock, cx| {
 3743                    dock.activate_panel(panel_index, window, cx);
 3744                    dock.set_open(true, window, cx);
 3745                });
 3746            }
 3747        }
 3748    }
 3749
 3750    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3751        for dock in self.all_docks().iter() {
 3752            dock.update(cx, |dock, cx| {
 3753                if dock.panel::<T>().is_some() {
 3754                    dock.set_open(false, window, cx)
 3755                }
 3756            })
 3757        }
 3758    }
 3759
 3760    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3761        self.all_docks()
 3762            .iter()
 3763            .find_map(|dock| dock.read(cx).panel::<T>())
 3764    }
 3765
 3766    fn dismiss_zoomed_items_to_reveal(
 3767        &mut self,
 3768        dock_to_reveal: Option<DockPosition>,
 3769        window: &mut Window,
 3770        cx: &mut Context<Self>,
 3771    ) {
 3772        // If a center pane is zoomed, unzoom it.
 3773        for pane in &self.panes {
 3774            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3775                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3776            }
 3777        }
 3778
 3779        // If another dock is zoomed, hide it.
 3780        let mut focus_center = false;
 3781        for dock in self.all_docks() {
 3782            dock.update(cx, |dock, cx| {
 3783                if Some(dock.position()) != dock_to_reveal
 3784                    && let Some(panel) = dock.active_panel()
 3785                    && panel.is_zoomed(window, cx)
 3786                {
 3787                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3788                    dock.set_open(false, window, cx);
 3789                }
 3790            });
 3791        }
 3792
 3793        if focus_center {
 3794            self.active_pane
 3795                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3796        }
 3797
 3798        if self.zoomed_position != dock_to_reveal {
 3799            self.zoomed = None;
 3800            self.zoomed_position = None;
 3801            cx.emit(Event::ZoomChanged);
 3802        }
 3803
 3804        cx.notify();
 3805    }
 3806
 3807    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3808        let pane = cx.new(|cx| {
 3809            let mut pane = Pane::new(
 3810                self.weak_handle(),
 3811                self.project.clone(),
 3812                self.pane_history_timestamp.clone(),
 3813                None,
 3814                NewFile.boxed_clone(),
 3815                true,
 3816                window,
 3817                cx,
 3818            );
 3819            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 3820            pane
 3821        });
 3822        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 3823            .detach();
 3824        self.panes.push(pane.clone());
 3825
 3826        window.focus(&pane.focus_handle(cx), cx);
 3827
 3828        cx.emit(Event::PaneAdded(pane.clone()));
 3829        pane
 3830    }
 3831
 3832    pub fn add_item_to_center(
 3833        &mut self,
 3834        item: Box<dyn ItemHandle>,
 3835        window: &mut Window,
 3836        cx: &mut Context<Self>,
 3837    ) -> bool {
 3838        if let Some(center_pane) = self.last_active_center_pane.clone() {
 3839            if let Some(center_pane) = center_pane.upgrade() {
 3840                center_pane.update(cx, |pane, cx| {
 3841                    pane.add_item(item, true, true, None, window, cx)
 3842                });
 3843                true
 3844            } else {
 3845                false
 3846            }
 3847        } else {
 3848            false
 3849        }
 3850    }
 3851
 3852    pub fn add_item_to_active_pane(
 3853        &mut self,
 3854        item: Box<dyn ItemHandle>,
 3855        destination_index: Option<usize>,
 3856        focus_item: bool,
 3857        window: &mut Window,
 3858        cx: &mut App,
 3859    ) {
 3860        self.add_item(
 3861            self.active_pane.clone(),
 3862            item,
 3863            destination_index,
 3864            false,
 3865            focus_item,
 3866            window,
 3867            cx,
 3868        )
 3869    }
 3870
 3871    pub fn add_item(
 3872        &mut self,
 3873        pane: Entity<Pane>,
 3874        item: Box<dyn ItemHandle>,
 3875        destination_index: Option<usize>,
 3876        activate_pane: bool,
 3877        focus_item: bool,
 3878        window: &mut Window,
 3879        cx: &mut App,
 3880    ) {
 3881        pane.update(cx, |pane, cx| {
 3882            pane.add_item(
 3883                item,
 3884                activate_pane,
 3885                focus_item,
 3886                destination_index,
 3887                window,
 3888                cx,
 3889            )
 3890        });
 3891    }
 3892
 3893    pub fn split_item(
 3894        &mut self,
 3895        split_direction: SplitDirection,
 3896        item: Box<dyn ItemHandle>,
 3897        window: &mut Window,
 3898        cx: &mut Context<Self>,
 3899    ) {
 3900        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 3901        self.add_item(new_pane, item, None, true, true, window, cx);
 3902    }
 3903
 3904    pub fn open_abs_path(
 3905        &mut self,
 3906        abs_path: PathBuf,
 3907        options: OpenOptions,
 3908        window: &mut Window,
 3909        cx: &mut Context<Self>,
 3910    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3911        cx.spawn_in(window, async move |workspace, cx| {
 3912            let open_paths_task_result = workspace
 3913                .update_in(cx, |workspace, window, cx| {
 3914                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 3915                })
 3916                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 3917                .await;
 3918            anyhow::ensure!(
 3919                open_paths_task_result.len() == 1,
 3920                "open abs path {abs_path:?} task returned incorrect number of results"
 3921            );
 3922            match open_paths_task_result
 3923                .into_iter()
 3924                .next()
 3925                .expect("ensured single task result")
 3926            {
 3927                Some(open_result) => {
 3928                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 3929                }
 3930                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 3931            }
 3932        })
 3933    }
 3934
 3935    pub fn split_abs_path(
 3936        &mut self,
 3937        abs_path: PathBuf,
 3938        visible: bool,
 3939        window: &mut Window,
 3940        cx: &mut Context<Self>,
 3941    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3942        let project_path_task =
 3943            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 3944        cx.spawn_in(window, async move |this, cx| {
 3945            let (_, path) = project_path_task.await?;
 3946            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 3947                .await
 3948        })
 3949    }
 3950
 3951    pub fn open_path(
 3952        &mut self,
 3953        path: impl Into<ProjectPath>,
 3954        pane: Option<WeakEntity<Pane>>,
 3955        focus_item: bool,
 3956        window: &mut Window,
 3957        cx: &mut App,
 3958    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3959        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 3960    }
 3961
 3962    pub fn open_path_preview(
 3963        &mut self,
 3964        path: impl Into<ProjectPath>,
 3965        pane: Option<WeakEntity<Pane>>,
 3966        focus_item: bool,
 3967        allow_preview: bool,
 3968        activate: bool,
 3969        window: &mut Window,
 3970        cx: &mut App,
 3971    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3972        let pane = pane.unwrap_or_else(|| {
 3973            self.last_active_center_pane.clone().unwrap_or_else(|| {
 3974                self.panes
 3975                    .first()
 3976                    .expect("There must be an active pane")
 3977                    .downgrade()
 3978            })
 3979        });
 3980
 3981        let project_path = path.into();
 3982        let task = self.load_path(project_path.clone(), window, cx);
 3983        window.spawn(cx, async move |cx| {
 3984            let (project_entry_id, build_item) = task.await?;
 3985
 3986            pane.update_in(cx, |pane, window, cx| {
 3987                pane.open_item(
 3988                    project_entry_id,
 3989                    project_path,
 3990                    focus_item,
 3991                    allow_preview,
 3992                    activate,
 3993                    None,
 3994                    window,
 3995                    cx,
 3996                    build_item,
 3997                )
 3998            })
 3999        })
 4000    }
 4001
 4002    pub fn split_path(
 4003        &mut self,
 4004        path: impl Into<ProjectPath>,
 4005        window: &mut Window,
 4006        cx: &mut Context<Self>,
 4007    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4008        self.split_path_preview(path, false, None, window, cx)
 4009    }
 4010
 4011    pub fn split_path_preview(
 4012        &mut self,
 4013        path: impl Into<ProjectPath>,
 4014        allow_preview: bool,
 4015        split_direction: Option<SplitDirection>,
 4016        window: &mut Window,
 4017        cx: &mut Context<Self>,
 4018    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4019        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4020            self.panes
 4021                .first()
 4022                .expect("There must be an active pane")
 4023                .downgrade()
 4024        });
 4025
 4026        if let Member::Pane(center_pane) = &self.center.root
 4027            && center_pane.read(cx).items_len() == 0
 4028        {
 4029            return self.open_path(path, Some(pane), true, window, cx);
 4030        }
 4031
 4032        let project_path = path.into();
 4033        let task = self.load_path(project_path.clone(), window, cx);
 4034        cx.spawn_in(window, async move |this, cx| {
 4035            let (project_entry_id, build_item) = task.await?;
 4036            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4037                let pane = pane.upgrade()?;
 4038                let new_pane = this.split_pane(
 4039                    pane,
 4040                    split_direction.unwrap_or(SplitDirection::Right),
 4041                    window,
 4042                    cx,
 4043                );
 4044                new_pane.update(cx, |new_pane, cx| {
 4045                    Some(new_pane.open_item(
 4046                        project_entry_id,
 4047                        project_path,
 4048                        true,
 4049                        allow_preview,
 4050                        true,
 4051                        None,
 4052                        window,
 4053                        cx,
 4054                        build_item,
 4055                    ))
 4056                })
 4057            })
 4058            .map(|option| option.context("pane was dropped"))?
 4059        })
 4060    }
 4061
 4062    fn load_path(
 4063        &mut self,
 4064        path: ProjectPath,
 4065        window: &mut Window,
 4066        cx: &mut App,
 4067    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4068        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4069        registry.open_path(self.project(), &path, window, cx)
 4070    }
 4071
 4072    pub fn find_project_item<T>(
 4073        &self,
 4074        pane: &Entity<Pane>,
 4075        project_item: &Entity<T::Item>,
 4076        cx: &App,
 4077    ) -> Option<Entity<T>>
 4078    where
 4079        T: ProjectItem,
 4080    {
 4081        use project::ProjectItem as _;
 4082        let project_item = project_item.read(cx);
 4083        let entry_id = project_item.entry_id(cx);
 4084        let project_path = project_item.project_path(cx);
 4085
 4086        let mut item = None;
 4087        if let Some(entry_id) = entry_id {
 4088            item = pane.read(cx).item_for_entry(entry_id, cx);
 4089        }
 4090        if item.is_none()
 4091            && let Some(project_path) = project_path
 4092        {
 4093            item = pane.read(cx).item_for_path(project_path, cx);
 4094        }
 4095
 4096        item.and_then(|item| item.downcast::<T>())
 4097    }
 4098
 4099    pub fn is_project_item_open<T>(
 4100        &self,
 4101        pane: &Entity<Pane>,
 4102        project_item: &Entity<T::Item>,
 4103        cx: &App,
 4104    ) -> bool
 4105    where
 4106        T: ProjectItem,
 4107    {
 4108        self.find_project_item::<T>(pane, project_item, cx)
 4109            .is_some()
 4110    }
 4111
 4112    pub fn open_project_item<T>(
 4113        &mut self,
 4114        pane: Entity<Pane>,
 4115        project_item: Entity<T::Item>,
 4116        activate_pane: bool,
 4117        focus_item: bool,
 4118        keep_old_preview: bool,
 4119        allow_new_preview: bool,
 4120        window: &mut Window,
 4121        cx: &mut Context<Self>,
 4122    ) -> Entity<T>
 4123    where
 4124        T: ProjectItem,
 4125    {
 4126        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4127
 4128        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4129            if !keep_old_preview
 4130                && let Some(old_id) = old_item_id
 4131                && old_id != item.item_id()
 4132            {
 4133                // switching to a different item, so unpreview old active item
 4134                pane.update(cx, |pane, _| {
 4135                    pane.unpreview_item_if_preview(old_id);
 4136                });
 4137            }
 4138
 4139            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4140            if !allow_new_preview {
 4141                pane.update(cx, |pane, _| {
 4142                    pane.unpreview_item_if_preview(item.item_id());
 4143                });
 4144            }
 4145            return item;
 4146        }
 4147
 4148        let item = pane.update(cx, |pane, cx| {
 4149            cx.new(|cx| {
 4150                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4151            })
 4152        });
 4153        let mut destination_index = None;
 4154        pane.update(cx, |pane, cx| {
 4155            if !keep_old_preview && let Some(old_id) = old_item_id {
 4156                pane.unpreview_item_if_preview(old_id);
 4157            }
 4158            if allow_new_preview {
 4159                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4160            }
 4161        });
 4162
 4163        self.add_item(
 4164            pane,
 4165            Box::new(item.clone()),
 4166            destination_index,
 4167            activate_pane,
 4168            focus_item,
 4169            window,
 4170            cx,
 4171        );
 4172        item
 4173    }
 4174
 4175    pub fn open_shared_screen(
 4176        &mut self,
 4177        peer_id: PeerId,
 4178        window: &mut Window,
 4179        cx: &mut Context<Self>,
 4180    ) {
 4181        if let Some(shared_screen) =
 4182            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4183        {
 4184            self.active_pane.update(cx, |pane, cx| {
 4185                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4186            });
 4187        }
 4188    }
 4189
 4190    pub fn activate_item(
 4191        &mut self,
 4192        item: &dyn ItemHandle,
 4193        activate_pane: bool,
 4194        focus_item: bool,
 4195        window: &mut Window,
 4196        cx: &mut App,
 4197    ) -> bool {
 4198        let result = self.panes.iter().find_map(|pane| {
 4199            pane.read(cx)
 4200                .index_for_item(item)
 4201                .map(|ix| (pane.clone(), ix))
 4202        });
 4203        if let Some((pane, ix)) = result {
 4204            pane.update(cx, |pane, cx| {
 4205                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4206            });
 4207            true
 4208        } else {
 4209            false
 4210        }
 4211    }
 4212
 4213    fn activate_pane_at_index(
 4214        &mut self,
 4215        action: &ActivatePane,
 4216        window: &mut Window,
 4217        cx: &mut Context<Self>,
 4218    ) {
 4219        let panes = self.center.panes();
 4220        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4221            window.focus(&pane.focus_handle(cx), cx);
 4222        } else {
 4223            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4224                .detach();
 4225        }
 4226    }
 4227
 4228    fn move_item_to_pane_at_index(
 4229        &mut self,
 4230        action: &MoveItemToPane,
 4231        window: &mut Window,
 4232        cx: &mut Context<Self>,
 4233    ) {
 4234        let panes = self.center.panes();
 4235        let destination = match panes.get(action.destination) {
 4236            Some(&destination) => destination.clone(),
 4237            None => {
 4238                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4239                    return;
 4240                }
 4241                let direction = SplitDirection::Right;
 4242                let split_off_pane = self
 4243                    .find_pane_in_direction(direction, cx)
 4244                    .unwrap_or_else(|| self.active_pane.clone());
 4245                let new_pane = self.add_pane(window, cx);
 4246                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4247                new_pane
 4248            }
 4249        };
 4250
 4251        if action.clone {
 4252            if self
 4253                .active_pane
 4254                .read(cx)
 4255                .active_item()
 4256                .is_some_and(|item| item.can_split(cx))
 4257            {
 4258                clone_active_item(
 4259                    self.database_id(),
 4260                    &self.active_pane,
 4261                    &destination,
 4262                    action.focus,
 4263                    window,
 4264                    cx,
 4265                );
 4266                return;
 4267            }
 4268        }
 4269        move_active_item(
 4270            &self.active_pane,
 4271            &destination,
 4272            action.focus,
 4273            true,
 4274            window,
 4275            cx,
 4276        )
 4277    }
 4278
 4279    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4280        let panes = self.center.panes();
 4281        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4282            let next_ix = (ix + 1) % panes.len();
 4283            let next_pane = panes[next_ix].clone();
 4284            window.focus(&next_pane.focus_handle(cx), cx);
 4285        }
 4286    }
 4287
 4288    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4289        let panes = self.center.panes();
 4290        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4291            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4292            let prev_pane = panes[prev_ix].clone();
 4293            window.focus(&prev_pane.focus_handle(cx), cx);
 4294        }
 4295    }
 4296
 4297    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4298        let last_pane = self.center.last_pane();
 4299        window.focus(&last_pane.focus_handle(cx), cx);
 4300    }
 4301
 4302    pub fn activate_pane_in_direction(
 4303        &mut self,
 4304        direction: SplitDirection,
 4305        window: &mut Window,
 4306        cx: &mut App,
 4307    ) {
 4308        use ActivateInDirectionTarget as Target;
 4309        enum Origin {
 4310            LeftDock,
 4311            RightDock,
 4312            BottomDock,
 4313            Center,
 4314        }
 4315
 4316        let origin: Origin = [
 4317            (&self.left_dock, Origin::LeftDock),
 4318            (&self.right_dock, Origin::RightDock),
 4319            (&self.bottom_dock, Origin::BottomDock),
 4320        ]
 4321        .into_iter()
 4322        .find_map(|(dock, origin)| {
 4323            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4324                Some(origin)
 4325            } else {
 4326                None
 4327            }
 4328        })
 4329        .unwrap_or(Origin::Center);
 4330
 4331        let get_last_active_pane = || {
 4332            let pane = self
 4333                .last_active_center_pane
 4334                .clone()
 4335                .unwrap_or_else(|| {
 4336                    self.panes
 4337                        .first()
 4338                        .expect("There must be an active pane")
 4339                        .downgrade()
 4340                })
 4341                .upgrade()?;
 4342            (pane.read(cx).items_len() != 0).then_some(pane)
 4343        };
 4344
 4345        let try_dock =
 4346            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4347
 4348        let target = match (origin, direction) {
 4349            // We're in the center, so we first try to go to a different pane,
 4350            // otherwise try to go to a dock.
 4351            (Origin::Center, direction) => {
 4352                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4353                    Some(Target::Pane(pane))
 4354                } else {
 4355                    match direction {
 4356                        SplitDirection::Up => None,
 4357                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4358                        SplitDirection::Left => try_dock(&self.left_dock),
 4359                        SplitDirection::Right => try_dock(&self.right_dock),
 4360                    }
 4361                }
 4362            }
 4363
 4364            (Origin::LeftDock, SplitDirection::Right) => {
 4365                if let Some(last_active_pane) = get_last_active_pane() {
 4366                    Some(Target::Pane(last_active_pane))
 4367                } else {
 4368                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4369                }
 4370            }
 4371
 4372            (Origin::LeftDock, SplitDirection::Down)
 4373            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4374
 4375            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4376            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 4377            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4378
 4379            (Origin::RightDock, SplitDirection::Left) => {
 4380                if let Some(last_active_pane) = get_last_active_pane() {
 4381                    Some(Target::Pane(last_active_pane))
 4382                } else {
 4383                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4384                }
 4385            }
 4386
 4387            _ => None,
 4388        };
 4389
 4390        match target {
 4391            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4392                let pane = pane.read(cx);
 4393                if let Some(item) = pane.active_item() {
 4394                    item.item_focus_handle(cx).focus(window, cx);
 4395                } else {
 4396                    log::error!(
 4397                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4398                    );
 4399                }
 4400            }
 4401            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4402                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4403                window.defer(cx, move |window, cx| {
 4404                    let dock = dock.read(cx);
 4405                    if let Some(panel) = dock.active_panel() {
 4406                        panel.panel_focus_handle(cx).focus(window, cx);
 4407                    } else {
 4408                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4409                    }
 4410                })
 4411            }
 4412            None => {}
 4413        }
 4414    }
 4415
 4416    pub fn move_item_to_pane_in_direction(
 4417        &mut self,
 4418        action: &MoveItemToPaneInDirection,
 4419        window: &mut Window,
 4420        cx: &mut Context<Self>,
 4421    ) {
 4422        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4423            Some(destination) => destination,
 4424            None => {
 4425                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4426                    return;
 4427                }
 4428                let new_pane = self.add_pane(window, cx);
 4429                self.center
 4430                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4431                new_pane
 4432            }
 4433        };
 4434
 4435        if action.clone {
 4436            if self
 4437                .active_pane
 4438                .read(cx)
 4439                .active_item()
 4440                .is_some_and(|item| item.can_split(cx))
 4441            {
 4442                clone_active_item(
 4443                    self.database_id(),
 4444                    &self.active_pane,
 4445                    &destination,
 4446                    action.focus,
 4447                    window,
 4448                    cx,
 4449                );
 4450                return;
 4451            }
 4452        }
 4453        move_active_item(
 4454            &self.active_pane,
 4455            &destination,
 4456            action.focus,
 4457            true,
 4458            window,
 4459            cx,
 4460        );
 4461    }
 4462
 4463    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4464        self.center.bounding_box_for_pane(pane)
 4465    }
 4466
 4467    pub fn find_pane_in_direction(
 4468        &mut self,
 4469        direction: SplitDirection,
 4470        cx: &App,
 4471    ) -> Option<Entity<Pane>> {
 4472        self.center
 4473            .find_pane_in_direction(&self.active_pane, direction, cx)
 4474            .cloned()
 4475    }
 4476
 4477    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4478        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4479            self.center.swap(&self.active_pane, &to, cx);
 4480            cx.notify();
 4481        }
 4482    }
 4483
 4484    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4485        if self
 4486            .center
 4487            .move_to_border(&self.active_pane, direction, cx)
 4488            .unwrap()
 4489        {
 4490            cx.notify();
 4491        }
 4492    }
 4493
 4494    pub fn resize_pane(
 4495        &mut self,
 4496        axis: gpui::Axis,
 4497        amount: Pixels,
 4498        window: &mut Window,
 4499        cx: &mut Context<Self>,
 4500    ) {
 4501        let docks = self.all_docks();
 4502        let active_dock = docks
 4503            .into_iter()
 4504            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4505
 4506        if let Some(dock) = active_dock {
 4507            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4508                return;
 4509            };
 4510            match dock.read(cx).position() {
 4511                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4512                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4513                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4514            }
 4515        } else {
 4516            self.center
 4517                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4518        }
 4519        cx.notify();
 4520    }
 4521
 4522    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4523        self.center.reset_pane_sizes(cx);
 4524        cx.notify();
 4525    }
 4526
 4527    fn handle_pane_focused(
 4528        &mut self,
 4529        pane: Entity<Pane>,
 4530        window: &mut Window,
 4531        cx: &mut Context<Self>,
 4532    ) {
 4533        // This is explicitly hoisted out of the following check for pane identity as
 4534        // terminal panel panes are not registered as a center panes.
 4535        self.status_bar.update(cx, |status_bar, cx| {
 4536            status_bar.set_active_pane(&pane, window, cx);
 4537        });
 4538        if self.active_pane != pane {
 4539            self.set_active_pane(&pane, window, cx);
 4540        }
 4541
 4542        if self.last_active_center_pane.is_none() {
 4543            self.last_active_center_pane = Some(pane.downgrade());
 4544        }
 4545
 4546        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4547        // This prevents the dock from closing when focus events fire during window activation.
 4548        // We also preserve any dock whose active panel itself has focus — this covers
 4549        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4550        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4551            let dock_read = dock.read(cx);
 4552            if let Some(panel) = dock_read.active_panel() {
 4553                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4554                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4555                {
 4556                    return Some(dock_read.position());
 4557                }
 4558            }
 4559            None
 4560        });
 4561
 4562        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4563        if pane.read(cx).is_zoomed() {
 4564            self.zoomed = Some(pane.downgrade().into());
 4565        } else {
 4566            self.zoomed = None;
 4567        }
 4568        self.zoomed_position = None;
 4569        cx.emit(Event::ZoomChanged);
 4570        self.update_active_view_for_followers(window, cx);
 4571        pane.update(cx, |pane, _| {
 4572            pane.track_alternate_file_items();
 4573        });
 4574
 4575        cx.notify();
 4576    }
 4577
 4578    fn set_active_pane(
 4579        &mut self,
 4580        pane: &Entity<Pane>,
 4581        window: &mut Window,
 4582        cx: &mut Context<Self>,
 4583    ) {
 4584        self.active_pane = pane.clone();
 4585        self.active_item_path_changed(true, window, cx);
 4586        self.last_active_center_pane = Some(pane.downgrade());
 4587    }
 4588
 4589    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4590        self.update_active_view_for_followers(window, cx);
 4591    }
 4592
 4593    fn handle_pane_event(
 4594        &mut self,
 4595        pane: &Entity<Pane>,
 4596        event: &pane::Event,
 4597        window: &mut Window,
 4598        cx: &mut Context<Self>,
 4599    ) {
 4600        let mut serialize_workspace = true;
 4601        match event {
 4602            pane::Event::AddItem { item } => {
 4603                item.added_to_pane(self, pane.clone(), window, cx);
 4604                cx.emit(Event::ItemAdded {
 4605                    item: item.boxed_clone(),
 4606                });
 4607            }
 4608            pane::Event::Split { direction, mode } => {
 4609                match mode {
 4610                    SplitMode::ClonePane => {
 4611                        self.split_and_clone(pane.clone(), *direction, window, cx)
 4612                            .detach();
 4613                    }
 4614                    SplitMode::EmptyPane => {
 4615                        self.split_pane(pane.clone(), *direction, window, cx);
 4616                    }
 4617                    SplitMode::MovePane => {
 4618                        self.split_and_move(pane.clone(), *direction, window, cx);
 4619                    }
 4620                };
 4621            }
 4622            pane::Event::JoinIntoNext => {
 4623                self.join_pane_into_next(pane.clone(), window, cx);
 4624            }
 4625            pane::Event::JoinAll => {
 4626                self.join_all_panes(window, cx);
 4627            }
 4628            pane::Event::Remove { focus_on_pane } => {
 4629                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4630            }
 4631            pane::Event::ActivateItem {
 4632                local,
 4633                focus_changed,
 4634            } => {
 4635                window.invalidate_character_coordinates();
 4636
 4637                pane.update(cx, |pane, _| {
 4638                    pane.track_alternate_file_items();
 4639                });
 4640                if *local {
 4641                    self.unfollow_in_pane(pane, window, cx);
 4642                }
 4643                serialize_workspace = *focus_changed || pane != self.active_pane();
 4644                if pane == self.active_pane() {
 4645                    self.active_item_path_changed(*focus_changed, window, cx);
 4646                    self.update_active_view_for_followers(window, cx);
 4647                } else if *local {
 4648                    self.set_active_pane(pane, window, cx);
 4649                }
 4650            }
 4651            pane::Event::UserSavedItem { item, save_intent } => {
 4652                cx.emit(Event::UserSavedItem {
 4653                    pane: pane.downgrade(),
 4654                    item: item.boxed_clone(),
 4655                    save_intent: *save_intent,
 4656                });
 4657                serialize_workspace = false;
 4658            }
 4659            pane::Event::ChangeItemTitle => {
 4660                if *pane == self.active_pane {
 4661                    self.active_item_path_changed(false, window, cx);
 4662                }
 4663                serialize_workspace = false;
 4664            }
 4665            pane::Event::RemovedItem { item } => {
 4666                cx.emit(Event::ActiveItemChanged);
 4667                self.update_window_edited(window, cx);
 4668                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4669                    && entry.get().entity_id() == pane.entity_id()
 4670                {
 4671                    entry.remove();
 4672                }
 4673                cx.emit(Event::ItemRemoved {
 4674                    item_id: item.item_id(),
 4675                });
 4676            }
 4677            pane::Event::Focus => {
 4678                window.invalidate_character_coordinates();
 4679                self.handle_pane_focused(pane.clone(), window, cx);
 4680            }
 4681            pane::Event::ZoomIn => {
 4682                if *pane == self.active_pane {
 4683                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4684                    if pane.read(cx).has_focus(window, cx) {
 4685                        self.zoomed = Some(pane.downgrade().into());
 4686                        self.zoomed_position = None;
 4687                        cx.emit(Event::ZoomChanged);
 4688                    }
 4689                    cx.notify();
 4690                }
 4691            }
 4692            pane::Event::ZoomOut => {
 4693                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4694                if self.zoomed_position.is_none() {
 4695                    self.zoomed = None;
 4696                    cx.emit(Event::ZoomChanged);
 4697                }
 4698                cx.notify();
 4699            }
 4700            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4701        }
 4702
 4703        if serialize_workspace {
 4704            self.serialize_workspace(window, cx);
 4705        }
 4706    }
 4707
 4708    pub fn unfollow_in_pane(
 4709        &mut self,
 4710        pane: &Entity<Pane>,
 4711        window: &mut Window,
 4712        cx: &mut Context<Workspace>,
 4713    ) -> Option<CollaboratorId> {
 4714        let leader_id = self.leader_for_pane(pane)?;
 4715        self.unfollow(leader_id, window, cx);
 4716        Some(leader_id)
 4717    }
 4718
 4719    pub fn split_pane(
 4720        &mut self,
 4721        pane_to_split: Entity<Pane>,
 4722        split_direction: SplitDirection,
 4723        window: &mut Window,
 4724        cx: &mut Context<Self>,
 4725    ) -> Entity<Pane> {
 4726        let new_pane = self.add_pane(window, cx);
 4727        self.center
 4728            .split(&pane_to_split, &new_pane, split_direction, cx);
 4729        cx.notify();
 4730        new_pane
 4731    }
 4732
 4733    pub fn split_and_move(
 4734        &mut self,
 4735        pane: Entity<Pane>,
 4736        direction: SplitDirection,
 4737        window: &mut Window,
 4738        cx: &mut Context<Self>,
 4739    ) {
 4740        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4741            return;
 4742        };
 4743        let new_pane = self.add_pane(window, cx);
 4744        new_pane.update(cx, |pane, cx| {
 4745            pane.add_item(item, true, true, None, window, cx)
 4746        });
 4747        self.center.split(&pane, &new_pane, direction, cx);
 4748        cx.notify();
 4749    }
 4750
 4751    pub fn split_and_clone(
 4752        &mut self,
 4753        pane: Entity<Pane>,
 4754        direction: SplitDirection,
 4755        window: &mut Window,
 4756        cx: &mut Context<Self>,
 4757    ) -> Task<Option<Entity<Pane>>> {
 4758        let Some(item) = pane.read(cx).active_item() else {
 4759            return Task::ready(None);
 4760        };
 4761        if !item.can_split(cx) {
 4762            return Task::ready(None);
 4763        }
 4764        let task = item.clone_on_split(self.database_id(), window, cx);
 4765        cx.spawn_in(window, async move |this, cx| {
 4766            if let Some(clone) = task.await {
 4767                this.update_in(cx, |this, window, cx| {
 4768                    let new_pane = this.add_pane(window, cx);
 4769                    let nav_history = pane.read(cx).fork_nav_history();
 4770                    new_pane.update(cx, |pane, cx| {
 4771                        pane.set_nav_history(nav_history, cx);
 4772                        pane.add_item(clone, true, true, None, window, cx)
 4773                    });
 4774                    this.center.split(&pane, &new_pane, direction, cx);
 4775                    cx.notify();
 4776                    new_pane
 4777                })
 4778                .ok()
 4779            } else {
 4780                None
 4781            }
 4782        })
 4783    }
 4784
 4785    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4786        let active_item = self.active_pane.read(cx).active_item();
 4787        for pane in &self.panes {
 4788            join_pane_into_active(&self.active_pane, pane, window, cx);
 4789        }
 4790        if let Some(active_item) = active_item {
 4791            self.activate_item(active_item.as_ref(), true, true, window, cx);
 4792        }
 4793        cx.notify();
 4794    }
 4795
 4796    pub fn join_pane_into_next(
 4797        &mut self,
 4798        pane: Entity<Pane>,
 4799        window: &mut Window,
 4800        cx: &mut Context<Self>,
 4801    ) {
 4802        let next_pane = self
 4803            .find_pane_in_direction(SplitDirection::Right, cx)
 4804            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 4805            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4806            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 4807        let Some(next_pane) = next_pane else {
 4808            return;
 4809        };
 4810        move_all_items(&pane, &next_pane, window, cx);
 4811        cx.notify();
 4812    }
 4813
 4814    fn remove_pane(
 4815        &mut self,
 4816        pane: Entity<Pane>,
 4817        focus_on: Option<Entity<Pane>>,
 4818        window: &mut Window,
 4819        cx: &mut Context<Self>,
 4820    ) {
 4821        if self.center.remove(&pane, cx).unwrap() {
 4822            self.force_remove_pane(&pane, &focus_on, window, cx);
 4823            self.unfollow_in_pane(&pane, window, cx);
 4824            self.last_leaders_by_pane.remove(&pane.downgrade());
 4825            for removed_item in pane.read(cx).items() {
 4826                self.panes_by_item.remove(&removed_item.item_id());
 4827            }
 4828
 4829            cx.notify();
 4830        } else {
 4831            self.active_item_path_changed(true, window, cx);
 4832        }
 4833        cx.emit(Event::PaneRemoved);
 4834    }
 4835
 4836    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 4837        &mut self.panes
 4838    }
 4839
 4840    pub fn panes(&self) -> &[Entity<Pane>] {
 4841        &self.panes
 4842    }
 4843
 4844    pub fn active_pane(&self) -> &Entity<Pane> {
 4845        &self.active_pane
 4846    }
 4847
 4848    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 4849        for dock in self.all_docks() {
 4850            if dock.focus_handle(cx).contains_focused(window, cx)
 4851                && let Some(pane) = dock
 4852                    .read(cx)
 4853                    .active_panel()
 4854                    .and_then(|panel| panel.pane(cx))
 4855            {
 4856                return pane;
 4857            }
 4858        }
 4859        self.active_pane().clone()
 4860    }
 4861
 4862    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4863        self.find_pane_in_direction(SplitDirection::Right, cx)
 4864            .unwrap_or_else(|| {
 4865                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4866            })
 4867    }
 4868
 4869    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 4870        self.pane_for_item_id(handle.item_id())
 4871    }
 4872
 4873    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 4874        let weak_pane = self.panes_by_item.get(&item_id)?;
 4875        weak_pane.upgrade()
 4876    }
 4877
 4878    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 4879        self.panes
 4880            .iter()
 4881            .find(|pane| pane.entity_id() == entity_id)
 4882            .cloned()
 4883    }
 4884
 4885    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 4886        self.follower_states.retain(|leader_id, state| {
 4887            if *leader_id == CollaboratorId::PeerId(peer_id) {
 4888                for item in state.items_by_leader_view_id.values() {
 4889                    item.view.set_leader_id(None, window, cx);
 4890                }
 4891                false
 4892            } else {
 4893                true
 4894            }
 4895        });
 4896        cx.notify();
 4897    }
 4898
 4899    pub fn start_following(
 4900        &mut self,
 4901        leader_id: impl Into<CollaboratorId>,
 4902        window: &mut Window,
 4903        cx: &mut Context<Self>,
 4904    ) -> Option<Task<Result<()>>> {
 4905        let leader_id = leader_id.into();
 4906        let pane = self.active_pane().clone();
 4907
 4908        self.last_leaders_by_pane
 4909            .insert(pane.downgrade(), leader_id);
 4910        self.unfollow(leader_id, window, cx);
 4911        self.unfollow_in_pane(&pane, window, cx);
 4912        self.follower_states.insert(
 4913            leader_id,
 4914            FollowerState {
 4915                center_pane: pane.clone(),
 4916                dock_pane: None,
 4917                active_view_id: None,
 4918                items_by_leader_view_id: Default::default(),
 4919            },
 4920        );
 4921        cx.notify();
 4922
 4923        match leader_id {
 4924            CollaboratorId::PeerId(leader_peer_id) => {
 4925                let room_id = self.active_call()?.room_id(cx)?;
 4926                let project_id = self.project.read(cx).remote_id();
 4927                let request = self.app_state.client.request(proto::Follow {
 4928                    room_id,
 4929                    project_id,
 4930                    leader_id: Some(leader_peer_id),
 4931                });
 4932
 4933                Some(cx.spawn_in(window, async move |this, cx| {
 4934                    let response = request.await?;
 4935                    this.update(cx, |this, _| {
 4936                        let state = this
 4937                            .follower_states
 4938                            .get_mut(&leader_id)
 4939                            .context("following interrupted")?;
 4940                        state.active_view_id = response
 4941                            .active_view
 4942                            .as_ref()
 4943                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4944                        anyhow::Ok(())
 4945                    })??;
 4946                    if let Some(view) = response.active_view {
 4947                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 4948                    }
 4949                    this.update_in(cx, |this, window, cx| {
 4950                        this.leader_updated(leader_id, window, cx)
 4951                    })?;
 4952                    Ok(())
 4953                }))
 4954            }
 4955            CollaboratorId::Agent => {
 4956                self.leader_updated(leader_id, window, cx)?;
 4957                Some(Task::ready(Ok(())))
 4958            }
 4959        }
 4960    }
 4961
 4962    pub fn follow_next_collaborator(
 4963        &mut self,
 4964        _: &FollowNextCollaborator,
 4965        window: &mut Window,
 4966        cx: &mut Context<Self>,
 4967    ) {
 4968        let collaborators = self.project.read(cx).collaborators();
 4969        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 4970            let mut collaborators = collaborators.keys().copied();
 4971            for peer_id in collaborators.by_ref() {
 4972                if CollaboratorId::PeerId(peer_id) == leader_id {
 4973                    break;
 4974                }
 4975            }
 4976            collaborators.next().map(CollaboratorId::PeerId)
 4977        } else if let Some(last_leader_id) =
 4978            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 4979        {
 4980            match last_leader_id {
 4981                CollaboratorId::PeerId(peer_id) => {
 4982                    if collaborators.contains_key(peer_id) {
 4983                        Some(*last_leader_id)
 4984                    } else {
 4985                        None
 4986                    }
 4987                }
 4988                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 4989            }
 4990        } else {
 4991            None
 4992        };
 4993
 4994        let pane = self.active_pane.clone();
 4995        let Some(leader_id) = next_leader_id.or_else(|| {
 4996            Some(CollaboratorId::PeerId(
 4997                collaborators.keys().copied().next()?,
 4998            ))
 4999        }) else {
 5000            return;
 5001        };
 5002        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5003            return;
 5004        }
 5005        if let Some(task) = self.start_following(leader_id, window, cx) {
 5006            task.detach_and_log_err(cx)
 5007        }
 5008    }
 5009
 5010    pub fn follow(
 5011        &mut self,
 5012        leader_id: impl Into<CollaboratorId>,
 5013        window: &mut Window,
 5014        cx: &mut Context<Self>,
 5015    ) {
 5016        let leader_id = leader_id.into();
 5017
 5018        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5019            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5020                return;
 5021            };
 5022            let Some(remote_participant) =
 5023                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5024            else {
 5025                return;
 5026            };
 5027
 5028            let project = self.project.read(cx);
 5029
 5030            let other_project_id = match remote_participant.location {
 5031                ParticipantLocation::External => None,
 5032                ParticipantLocation::UnsharedProject => None,
 5033                ParticipantLocation::SharedProject { project_id } => {
 5034                    if Some(project_id) == project.remote_id() {
 5035                        None
 5036                    } else {
 5037                        Some(project_id)
 5038                    }
 5039                }
 5040            };
 5041
 5042            // if they are active in another project, follow there.
 5043            if let Some(project_id) = other_project_id {
 5044                let app_state = self.app_state.clone();
 5045                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5046                    .detach_and_log_err(cx);
 5047            }
 5048        }
 5049
 5050        // if you're already following, find the right pane and focus it.
 5051        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5052            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5053
 5054            return;
 5055        }
 5056
 5057        // Otherwise, follow.
 5058        if let Some(task) = self.start_following(leader_id, window, cx) {
 5059            task.detach_and_log_err(cx)
 5060        }
 5061    }
 5062
 5063    pub fn unfollow(
 5064        &mut self,
 5065        leader_id: impl Into<CollaboratorId>,
 5066        window: &mut Window,
 5067        cx: &mut Context<Self>,
 5068    ) -> Option<()> {
 5069        cx.notify();
 5070
 5071        let leader_id = leader_id.into();
 5072        let state = self.follower_states.remove(&leader_id)?;
 5073        for (_, item) in state.items_by_leader_view_id {
 5074            item.view.set_leader_id(None, window, cx);
 5075        }
 5076
 5077        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5078            let project_id = self.project.read(cx).remote_id();
 5079            let room_id = self.active_call()?.room_id(cx)?;
 5080            self.app_state
 5081                .client
 5082                .send(proto::Unfollow {
 5083                    room_id,
 5084                    project_id,
 5085                    leader_id: Some(leader_peer_id),
 5086                })
 5087                .log_err();
 5088        }
 5089
 5090        Some(())
 5091    }
 5092
 5093    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5094        self.follower_states.contains_key(&id.into())
 5095    }
 5096
 5097    fn active_item_path_changed(
 5098        &mut self,
 5099        focus_changed: bool,
 5100        window: &mut Window,
 5101        cx: &mut Context<Self>,
 5102    ) {
 5103        cx.emit(Event::ActiveItemChanged);
 5104        let active_entry = self.active_project_path(cx);
 5105        self.project.update(cx, |project, cx| {
 5106            project.set_active_path(active_entry.clone(), cx)
 5107        });
 5108
 5109        if focus_changed && let Some(project_path) = &active_entry {
 5110            let git_store_entity = self.project.read(cx).git_store().clone();
 5111            git_store_entity.update(cx, |git_store, cx| {
 5112                git_store.set_active_repo_for_path(project_path, cx);
 5113            });
 5114        }
 5115
 5116        self.update_window_title(window, cx);
 5117    }
 5118
 5119    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5120        let project = self.project().read(cx);
 5121        let mut title = String::new();
 5122
 5123        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5124            let name = {
 5125                let settings_location = SettingsLocation {
 5126                    worktree_id: worktree.read(cx).id(),
 5127                    path: RelPath::empty(),
 5128                };
 5129
 5130                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5131                match &settings.project_name {
 5132                    Some(name) => name.as_str(),
 5133                    None => worktree.read(cx).root_name_str(),
 5134                }
 5135            };
 5136            if i > 0 {
 5137                title.push_str(", ");
 5138            }
 5139            title.push_str(name);
 5140        }
 5141
 5142        if title.is_empty() {
 5143            title = "empty project".to_string();
 5144        }
 5145
 5146        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5147            let filename = path.path.file_name().or_else(|| {
 5148                Some(
 5149                    project
 5150                        .worktree_for_id(path.worktree_id, cx)?
 5151                        .read(cx)
 5152                        .root_name_str(),
 5153                )
 5154            });
 5155
 5156            if let Some(filename) = filename {
 5157                title.push_str("");
 5158                title.push_str(filename.as_ref());
 5159            }
 5160        }
 5161
 5162        if project.is_via_collab() {
 5163            title.push_str("");
 5164        } else if project.is_shared() {
 5165            title.push_str("");
 5166        }
 5167
 5168        if let Some(last_title) = self.last_window_title.as_ref()
 5169            && &title == last_title
 5170        {
 5171            return;
 5172        }
 5173        window.set_window_title(&title);
 5174        SystemWindowTabController::update_tab_title(
 5175            cx,
 5176            window.window_handle().window_id(),
 5177            SharedString::from(&title),
 5178        );
 5179        self.last_window_title = Some(title);
 5180    }
 5181
 5182    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5183        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5184        if is_edited != self.window_edited {
 5185            self.window_edited = is_edited;
 5186            window.set_window_edited(self.window_edited)
 5187        }
 5188    }
 5189
 5190    fn update_item_dirty_state(
 5191        &mut self,
 5192        item: &dyn ItemHandle,
 5193        window: &mut Window,
 5194        cx: &mut App,
 5195    ) {
 5196        let is_dirty = item.is_dirty(cx);
 5197        let item_id = item.item_id();
 5198        let was_dirty = self.dirty_items.contains_key(&item_id);
 5199        if is_dirty == was_dirty {
 5200            return;
 5201        }
 5202        if was_dirty {
 5203            self.dirty_items.remove(&item_id);
 5204            self.update_window_edited(window, cx);
 5205            return;
 5206        }
 5207
 5208        let workspace = self.weak_handle();
 5209        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5210            return;
 5211        };
 5212        let on_release_callback = Box::new(move |cx: &mut App| {
 5213            window_handle
 5214                .update(cx, |_, window, cx| {
 5215                    workspace
 5216                        .update(cx, |workspace, cx| {
 5217                            workspace.dirty_items.remove(&item_id);
 5218                            workspace.update_window_edited(window, cx)
 5219                        })
 5220                        .ok();
 5221                })
 5222                .ok();
 5223        });
 5224
 5225        let s = item.on_release(cx, on_release_callback);
 5226        self.dirty_items.insert(item_id, s);
 5227        self.update_window_edited(window, cx);
 5228    }
 5229
 5230    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5231        if self.notifications.is_empty() {
 5232            None
 5233        } else {
 5234            Some(
 5235                div()
 5236                    .absolute()
 5237                    .right_3()
 5238                    .bottom_3()
 5239                    .w_112()
 5240                    .h_full()
 5241                    .flex()
 5242                    .flex_col()
 5243                    .justify_end()
 5244                    .gap_2()
 5245                    .children(
 5246                        self.notifications
 5247                            .iter()
 5248                            .map(|(_, notification)| notification.clone().into_any()),
 5249                    ),
 5250            )
 5251        }
 5252    }
 5253
 5254    // RPC handlers
 5255
 5256    fn active_view_for_follower(
 5257        &self,
 5258        follower_project_id: Option<u64>,
 5259        window: &mut Window,
 5260        cx: &mut Context<Self>,
 5261    ) -> Option<proto::View> {
 5262        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5263        let item = item?;
 5264        let leader_id = self
 5265            .pane_for(&*item)
 5266            .and_then(|pane| self.leader_for_pane(&pane));
 5267        let leader_peer_id = match leader_id {
 5268            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5269            Some(CollaboratorId::Agent) | None => None,
 5270        };
 5271
 5272        let item_handle = item.to_followable_item_handle(cx)?;
 5273        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5274        let variant = item_handle.to_state_proto(window, cx)?;
 5275
 5276        if item_handle.is_project_item(window, cx)
 5277            && (follower_project_id.is_none()
 5278                || follower_project_id != self.project.read(cx).remote_id())
 5279        {
 5280            return None;
 5281        }
 5282
 5283        Some(proto::View {
 5284            id: id.to_proto(),
 5285            leader_id: leader_peer_id,
 5286            variant: Some(variant),
 5287            panel_id: panel_id.map(|id| id as i32),
 5288        })
 5289    }
 5290
 5291    fn handle_follow(
 5292        &mut self,
 5293        follower_project_id: Option<u64>,
 5294        window: &mut Window,
 5295        cx: &mut Context<Self>,
 5296    ) -> proto::FollowResponse {
 5297        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5298
 5299        cx.notify();
 5300        proto::FollowResponse {
 5301            views: active_view.iter().cloned().collect(),
 5302            active_view,
 5303        }
 5304    }
 5305
 5306    fn handle_update_followers(
 5307        &mut self,
 5308        leader_id: PeerId,
 5309        message: proto::UpdateFollowers,
 5310        _window: &mut Window,
 5311        _cx: &mut Context<Self>,
 5312    ) {
 5313        self.leader_updates_tx
 5314            .unbounded_send((leader_id, message))
 5315            .ok();
 5316    }
 5317
 5318    async fn process_leader_update(
 5319        this: &WeakEntity<Self>,
 5320        leader_id: PeerId,
 5321        update: proto::UpdateFollowers,
 5322        cx: &mut AsyncWindowContext,
 5323    ) -> Result<()> {
 5324        match update.variant.context("invalid update")? {
 5325            proto::update_followers::Variant::CreateView(view) => {
 5326                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5327                let should_add_view = this.update(cx, |this, _| {
 5328                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5329                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5330                    } else {
 5331                        anyhow::Ok(false)
 5332                    }
 5333                })??;
 5334
 5335                if should_add_view {
 5336                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5337                }
 5338            }
 5339            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5340                let should_add_view = this.update(cx, |this, _| {
 5341                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5342                        state.active_view_id = update_active_view
 5343                            .view
 5344                            .as_ref()
 5345                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5346
 5347                        if state.active_view_id.is_some_and(|view_id| {
 5348                            !state.items_by_leader_view_id.contains_key(&view_id)
 5349                        }) {
 5350                            anyhow::Ok(true)
 5351                        } else {
 5352                            anyhow::Ok(false)
 5353                        }
 5354                    } else {
 5355                        anyhow::Ok(false)
 5356                    }
 5357                })??;
 5358
 5359                if should_add_view && let Some(view) = update_active_view.view {
 5360                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5361                }
 5362            }
 5363            proto::update_followers::Variant::UpdateView(update_view) => {
 5364                let variant = update_view.variant.context("missing update view variant")?;
 5365                let id = update_view.id.context("missing update view id")?;
 5366                let mut tasks = Vec::new();
 5367                this.update_in(cx, |this, window, cx| {
 5368                    let project = this.project.clone();
 5369                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5370                        let view_id = ViewId::from_proto(id.clone())?;
 5371                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5372                            tasks.push(item.view.apply_update_proto(
 5373                                &project,
 5374                                variant.clone(),
 5375                                window,
 5376                                cx,
 5377                            ));
 5378                        }
 5379                    }
 5380                    anyhow::Ok(())
 5381                })??;
 5382                try_join_all(tasks).await.log_err();
 5383            }
 5384        }
 5385        this.update_in(cx, |this, window, cx| {
 5386            this.leader_updated(leader_id, window, cx)
 5387        })?;
 5388        Ok(())
 5389    }
 5390
 5391    async fn add_view_from_leader(
 5392        this: WeakEntity<Self>,
 5393        leader_id: PeerId,
 5394        view: &proto::View,
 5395        cx: &mut AsyncWindowContext,
 5396    ) -> Result<()> {
 5397        let this = this.upgrade().context("workspace dropped")?;
 5398
 5399        let Some(id) = view.id.clone() else {
 5400            anyhow::bail!("no id for view");
 5401        };
 5402        let id = ViewId::from_proto(id)?;
 5403        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5404
 5405        let pane = this.update(cx, |this, _cx| {
 5406            let state = this
 5407                .follower_states
 5408                .get(&leader_id.into())
 5409                .context("stopped following")?;
 5410            anyhow::Ok(state.pane().clone())
 5411        })?;
 5412        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5413            let client = this.read(cx).client().clone();
 5414            pane.items().find_map(|item| {
 5415                let item = item.to_followable_item_handle(cx)?;
 5416                if item.remote_id(&client, window, cx) == Some(id) {
 5417                    Some(item)
 5418                } else {
 5419                    None
 5420                }
 5421            })
 5422        })?;
 5423        let item = if let Some(existing_item) = existing_item {
 5424            existing_item
 5425        } else {
 5426            let variant = view.variant.clone();
 5427            anyhow::ensure!(variant.is_some(), "missing view variant");
 5428
 5429            let task = cx.update(|window, cx| {
 5430                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5431            })?;
 5432
 5433            let Some(task) = task else {
 5434                anyhow::bail!(
 5435                    "failed to construct view from leader (maybe from a different version of zed?)"
 5436                );
 5437            };
 5438
 5439            let mut new_item = task.await?;
 5440            pane.update_in(cx, |pane, window, cx| {
 5441                let mut item_to_remove = None;
 5442                for (ix, item) in pane.items().enumerate() {
 5443                    if let Some(item) = item.to_followable_item_handle(cx) {
 5444                        match new_item.dedup(item.as_ref(), window, cx) {
 5445                            Some(item::Dedup::KeepExisting) => {
 5446                                new_item =
 5447                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5448                                break;
 5449                            }
 5450                            Some(item::Dedup::ReplaceExisting) => {
 5451                                item_to_remove = Some((ix, item.item_id()));
 5452                                break;
 5453                            }
 5454                            None => {}
 5455                        }
 5456                    }
 5457                }
 5458
 5459                if let Some((ix, id)) = item_to_remove {
 5460                    pane.remove_item(id, false, false, window, cx);
 5461                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5462                }
 5463            })?;
 5464
 5465            new_item
 5466        };
 5467
 5468        this.update_in(cx, |this, window, cx| {
 5469            let state = this.follower_states.get_mut(&leader_id.into())?;
 5470            item.set_leader_id(Some(leader_id.into()), window, cx);
 5471            state.items_by_leader_view_id.insert(
 5472                id,
 5473                FollowerView {
 5474                    view: item,
 5475                    location: panel_id,
 5476                },
 5477            );
 5478
 5479            Some(())
 5480        })
 5481        .context("no follower state")?;
 5482
 5483        Ok(())
 5484    }
 5485
 5486    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5487        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5488            return;
 5489        };
 5490
 5491        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5492            let buffer_entity_id = agent_location.buffer.entity_id();
 5493            let view_id = ViewId {
 5494                creator: CollaboratorId::Agent,
 5495                id: buffer_entity_id.as_u64(),
 5496            };
 5497            follower_state.active_view_id = Some(view_id);
 5498
 5499            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5500                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5501                hash_map::Entry::Vacant(entry) => {
 5502                    let existing_view =
 5503                        follower_state
 5504                            .center_pane
 5505                            .read(cx)
 5506                            .items()
 5507                            .find_map(|item| {
 5508                                let item = item.to_followable_item_handle(cx)?;
 5509                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5510                                    && item.project_item_model_ids(cx).as_slice()
 5511                                        == [buffer_entity_id]
 5512                                {
 5513                                    Some(item)
 5514                                } else {
 5515                                    None
 5516                                }
 5517                            });
 5518                    let view = existing_view.or_else(|| {
 5519                        agent_location.buffer.upgrade().and_then(|buffer| {
 5520                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5521                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5522                            })?
 5523                            .to_followable_item_handle(cx)
 5524                        })
 5525                    });
 5526
 5527                    view.map(|view| {
 5528                        entry.insert(FollowerView {
 5529                            view,
 5530                            location: None,
 5531                        })
 5532                    })
 5533                }
 5534            };
 5535
 5536            if let Some(item) = item {
 5537                item.view
 5538                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5539                item.view
 5540                    .update_agent_location(agent_location.position, window, cx);
 5541            }
 5542        } else {
 5543            follower_state.active_view_id = None;
 5544        }
 5545
 5546        self.leader_updated(CollaboratorId::Agent, window, cx);
 5547    }
 5548
 5549    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5550        let mut is_project_item = true;
 5551        let mut update = proto::UpdateActiveView::default();
 5552        if window.is_window_active() {
 5553            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5554
 5555            if let Some(item) = active_item
 5556                && item.item_focus_handle(cx).contains_focused(window, cx)
 5557            {
 5558                let leader_id = self
 5559                    .pane_for(&*item)
 5560                    .and_then(|pane| self.leader_for_pane(&pane));
 5561                let leader_peer_id = match leader_id {
 5562                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5563                    Some(CollaboratorId::Agent) | None => None,
 5564                };
 5565
 5566                if let Some(item) = item.to_followable_item_handle(cx) {
 5567                    let id = item
 5568                        .remote_id(&self.app_state.client, window, cx)
 5569                        .map(|id| id.to_proto());
 5570
 5571                    if let Some(id) = id
 5572                        && let Some(variant) = item.to_state_proto(window, cx)
 5573                    {
 5574                        let view = Some(proto::View {
 5575                            id,
 5576                            leader_id: leader_peer_id,
 5577                            variant: Some(variant),
 5578                            panel_id: panel_id.map(|id| id as i32),
 5579                        });
 5580
 5581                        is_project_item = item.is_project_item(window, cx);
 5582                        update = proto::UpdateActiveView { view };
 5583                    };
 5584                }
 5585            }
 5586        }
 5587
 5588        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5589        if active_view_id != self.last_active_view_id.as_ref() {
 5590            self.last_active_view_id = active_view_id.cloned();
 5591            self.update_followers(
 5592                is_project_item,
 5593                proto::update_followers::Variant::UpdateActiveView(update),
 5594                window,
 5595                cx,
 5596            );
 5597        }
 5598    }
 5599
 5600    fn active_item_for_followers(
 5601        &self,
 5602        window: &mut Window,
 5603        cx: &mut App,
 5604    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5605        let mut active_item = None;
 5606        let mut panel_id = None;
 5607        for dock in self.all_docks() {
 5608            if dock.focus_handle(cx).contains_focused(window, cx)
 5609                && let Some(panel) = dock.read(cx).active_panel()
 5610                && let Some(pane) = panel.pane(cx)
 5611                && let Some(item) = pane.read(cx).active_item()
 5612            {
 5613                active_item = Some(item);
 5614                panel_id = panel.remote_id();
 5615                break;
 5616            }
 5617        }
 5618
 5619        if active_item.is_none() {
 5620            active_item = self.active_pane().read(cx).active_item();
 5621        }
 5622        (active_item, panel_id)
 5623    }
 5624
 5625    fn update_followers(
 5626        &self,
 5627        project_only: bool,
 5628        update: proto::update_followers::Variant,
 5629        _: &mut Window,
 5630        cx: &mut App,
 5631    ) -> Option<()> {
 5632        // If this update only applies to for followers in the current project,
 5633        // then skip it unless this project is shared. If it applies to all
 5634        // followers, regardless of project, then set `project_id` to none,
 5635        // indicating that it goes to all followers.
 5636        let project_id = if project_only {
 5637            Some(self.project.read(cx).remote_id()?)
 5638        } else {
 5639            None
 5640        };
 5641        self.app_state().workspace_store.update(cx, |store, cx| {
 5642            store.update_followers(project_id, update, cx)
 5643        })
 5644    }
 5645
 5646    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5647        self.follower_states.iter().find_map(|(leader_id, state)| {
 5648            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5649                Some(*leader_id)
 5650            } else {
 5651                None
 5652            }
 5653        })
 5654    }
 5655
 5656    fn leader_updated(
 5657        &mut self,
 5658        leader_id: impl Into<CollaboratorId>,
 5659        window: &mut Window,
 5660        cx: &mut Context<Self>,
 5661    ) -> Option<Box<dyn ItemHandle>> {
 5662        cx.notify();
 5663
 5664        let leader_id = leader_id.into();
 5665        let (panel_id, item) = match leader_id {
 5666            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5667            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5668        };
 5669
 5670        let state = self.follower_states.get(&leader_id)?;
 5671        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5672        let pane;
 5673        if let Some(panel_id) = panel_id {
 5674            pane = self
 5675                .activate_panel_for_proto_id(panel_id, window, cx)?
 5676                .pane(cx)?;
 5677            let state = self.follower_states.get_mut(&leader_id)?;
 5678            state.dock_pane = Some(pane.clone());
 5679        } else {
 5680            pane = state.center_pane.clone();
 5681            let state = self.follower_states.get_mut(&leader_id)?;
 5682            if let Some(dock_pane) = state.dock_pane.take() {
 5683                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5684            }
 5685        }
 5686
 5687        pane.update(cx, |pane, cx| {
 5688            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5689            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5690                pane.activate_item(index, false, false, window, cx);
 5691            } else {
 5692                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5693            }
 5694
 5695            if focus_active_item {
 5696                pane.focus_active_item(window, cx)
 5697            }
 5698        });
 5699
 5700        Some(item)
 5701    }
 5702
 5703    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5704        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5705        let active_view_id = state.active_view_id?;
 5706        Some(
 5707            state
 5708                .items_by_leader_view_id
 5709                .get(&active_view_id)?
 5710                .view
 5711                .boxed_clone(),
 5712        )
 5713    }
 5714
 5715    fn active_item_for_peer(
 5716        &self,
 5717        peer_id: PeerId,
 5718        window: &mut Window,
 5719        cx: &mut Context<Self>,
 5720    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5721        let call = self.active_call()?;
 5722        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 5723        let leader_in_this_app;
 5724        let leader_in_this_project;
 5725        match participant.location {
 5726            ParticipantLocation::SharedProject { project_id } => {
 5727                leader_in_this_app = true;
 5728                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5729            }
 5730            ParticipantLocation::UnsharedProject => {
 5731                leader_in_this_app = true;
 5732                leader_in_this_project = false;
 5733            }
 5734            ParticipantLocation::External => {
 5735                leader_in_this_app = false;
 5736                leader_in_this_project = false;
 5737            }
 5738        };
 5739        let state = self.follower_states.get(&peer_id.into())?;
 5740        let mut item_to_activate = None;
 5741        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5742            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5743                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5744            {
 5745                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5746            }
 5747        } else if let Some(shared_screen) =
 5748            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5749        {
 5750            item_to_activate = Some((None, Box::new(shared_screen)));
 5751        }
 5752        item_to_activate
 5753    }
 5754
 5755    fn shared_screen_for_peer(
 5756        &self,
 5757        peer_id: PeerId,
 5758        pane: &Entity<Pane>,
 5759        window: &mut Window,
 5760        cx: &mut App,
 5761    ) -> Option<Entity<SharedScreen>> {
 5762        self.active_call()?
 5763            .create_shared_screen(peer_id, pane, window, cx)
 5764    }
 5765
 5766    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5767        if window.is_window_active() {
 5768            self.update_active_view_for_followers(window, cx);
 5769
 5770            if let Some(database_id) = self.database_id {
 5771                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 5772                    .detach();
 5773            }
 5774        } else {
 5775            for pane in &self.panes {
 5776                pane.update(cx, |pane, cx| {
 5777                    if let Some(item) = pane.active_item() {
 5778                        item.workspace_deactivated(window, cx);
 5779                    }
 5780                    for item in pane.items() {
 5781                        if matches!(
 5782                            item.workspace_settings(cx).autosave,
 5783                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 5784                        ) {
 5785                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 5786                                .detach_and_log_err(cx);
 5787                        }
 5788                    }
 5789                });
 5790            }
 5791        }
 5792    }
 5793
 5794    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 5795        self.active_call.as_ref().map(|(call, _)| &*call.0)
 5796    }
 5797
 5798    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 5799        self.active_call.as_ref().map(|(call, _)| call.clone())
 5800    }
 5801
 5802    fn on_active_call_event(
 5803        &mut self,
 5804        event: &ActiveCallEvent,
 5805        window: &mut Window,
 5806        cx: &mut Context<Self>,
 5807    ) {
 5808        match event {
 5809            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 5810            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 5811                self.leader_updated(participant_id, window, cx);
 5812            }
 5813        }
 5814    }
 5815
 5816    pub fn database_id(&self) -> Option<WorkspaceId> {
 5817        self.database_id
 5818    }
 5819
 5820    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 5821        self.database_id = Some(id);
 5822    }
 5823
 5824    pub fn session_id(&self) -> Option<String> {
 5825        self.session_id.clone()
 5826    }
 5827
 5828    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5829        let Some(display) = window.display(cx) else {
 5830            return Task::ready(());
 5831        };
 5832        let Ok(display_uuid) = display.uuid() else {
 5833            return Task::ready(());
 5834        };
 5835
 5836        let window_bounds = window.inner_window_bounds();
 5837        let database_id = self.database_id;
 5838        let has_paths = !self.root_paths(cx).is_empty();
 5839
 5840        cx.background_executor().spawn(async move {
 5841            if !has_paths {
 5842                persistence::write_default_window_bounds(window_bounds, display_uuid)
 5843                    .await
 5844                    .log_err();
 5845            }
 5846            if let Some(database_id) = database_id {
 5847                DB.set_window_open_status(
 5848                    database_id,
 5849                    SerializedWindowBounds(window_bounds),
 5850                    display_uuid,
 5851                )
 5852                .await
 5853                .log_err();
 5854            } else {
 5855                persistence::write_default_window_bounds(window_bounds, display_uuid)
 5856                    .await
 5857                    .log_err();
 5858            }
 5859        })
 5860    }
 5861
 5862    /// Bypass the 200ms serialization throttle and write workspace state to
 5863    /// the DB immediately. Returns a task the caller can await to ensure the
 5864    /// write completes. Used by the quit handler so the most recent state
 5865    /// isn't lost to a pending throttle timer when the process exits.
 5866    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5867        self._schedule_serialize_workspace.take();
 5868        self._serialize_workspace_task.take();
 5869        self.bounds_save_task_queued.take();
 5870
 5871        let bounds_task = self.save_window_bounds(window, cx);
 5872        let serialize_task = self.serialize_workspace_internal(window, cx);
 5873        cx.spawn(async move |_| {
 5874            bounds_task.await;
 5875            serialize_task.await;
 5876        })
 5877    }
 5878
 5879    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 5880        let project = self.project().read(cx);
 5881        project
 5882            .visible_worktrees(cx)
 5883            .map(|worktree| worktree.read(cx).abs_path())
 5884            .collect::<Vec<_>>()
 5885    }
 5886
 5887    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 5888        match member {
 5889            Member::Axis(PaneAxis { members, .. }) => {
 5890                for child in members.iter() {
 5891                    self.remove_panes(child.clone(), window, cx)
 5892                }
 5893            }
 5894            Member::Pane(pane) => {
 5895                self.force_remove_pane(&pane, &None, window, cx);
 5896            }
 5897        }
 5898    }
 5899
 5900    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5901        self.session_id.take();
 5902        self.serialize_workspace_internal(window, cx)
 5903    }
 5904
 5905    fn force_remove_pane(
 5906        &mut self,
 5907        pane: &Entity<Pane>,
 5908        focus_on: &Option<Entity<Pane>>,
 5909        window: &mut Window,
 5910        cx: &mut Context<Workspace>,
 5911    ) {
 5912        self.panes.retain(|p| p != pane);
 5913        if let Some(focus_on) = focus_on {
 5914            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 5915        } else if self.active_pane() == pane {
 5916            self.panes
 5917                .last()
 5918                .unwrap()
 5919                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 5920        }
 5921        if self.last_active_center_pane == Some(pane.downgrade()) {
 5922            self.last_active_center_pane = None;
 5923        }
 5924        cx.notify();
 5925    }
 5926
 5927    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5928        if self._schedule_serialize_workspace.is_none() {
 5929            self._schedule_serialize_workspace =
 5930                Some(cx.spawn_in(window, async move |this, cx| {
 5931                    cx.background_executor()
 5932                        .timer(SERIALIZATION_THROTTLE_TIME)
 5933                        .await;
 5934                    this.update_in(cx, |this, window, cx| {
 5935                        this._serialize_workspace_task =
 5936                            Some(this.serialize_workspace_internal(window, cx));
 5937                        this._schedule_serialize_workspace.take();
 5938                    })
 5939                    .log_err();
 5940                }));
 5941        }
 5942    }
 5943
 5944    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5945        let Some(database_id) = self.database_id() else {
 5946            return Task::ready(());
 5947        };
 5948
 5949        fn serialize_pane_handle(
 5950            pane_handle: &Entity<Pane>,
 5951            window: &mut Window,
 5952            cx: &mut App,
 5953        ) -> SerializedPane {
 5954            let (items, active, pinned_count) = {
 5955                let pane = pane_handle.read(cx);
 5956                let active_item_id = pane.active_item().map(|item| item.item_id());
 5957                (
 5958                    pane.items()
 5959                        .filter_map(|handle| {
 5960                            let handle = handle.to_serializable_item_handle(cx)?;
 5961
 5962                            Some(SerializedItem {
 5963                                kind: Arc::from(handle.serialized_item_kind()),
 5964                                item_id: handle.item_id().as_u64(),
 5965                                active: Some(handle.item_id()) == active_item_id,
 5966                                preview: pane.is_active_preview_item(handle.item_id()),
 5967                            })
 5968                        })
 5969                        .collect::<Vec<_>>(),
 5970                    pane.has_focus(window, cx),
 5971                    pane.pinned_count(),
 5972                )
 5973            };
 5974
 5975            SerializedPane::new(items, active, pinned_count)
 5976        }
 5977
 5978        fn build_serialized_pane_group(
 5979            pane_group: &Member,
 5980            window: &mut Window,
 5981            cx: &mut App,
 5982        ) -> SerializedPaneGroup {
 5983            match pane_group {
 5984                Member::Axis(PaneAxis {
 5985                    axis,
 5986                    members,
 5987                    flexes,
 5988                    bounding_boxes: _,
 5989                }) => SerializedPaneGroup::Group {
 5990                    axis: SerializedAxis(*axis),
 5991                    children: members
 5992                        .iter()
 5993                        .map(|member| build_serialized_pane_group(member, window, cx))
 5994                        .collect::<Vec<_>>(),
 5995                    flexes: Some(flexes.lock().clone()),
 5996                },
 5997                Member::Pane(pane_handle) => {
 5998                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 5999                }
 6000            }
 6001        }
 6002
 6003        fn build_serialized_docks(
 6004            this: &Workspace,
 6005            window: &mut Window,
 6006            cx: &mut App,
 6007        ) -> DockStructure {
 6008            let left_dock = this.left_dock.read(cx);
 6009            let left_visible = left_dock.is_open();
 6010            let left_active_panel = left_dock
 6011                .active_panel()
 6012                .map(|panel| panel.persistent_name().to_string());
 6013            let left_dock_zoom = left_dock
 6014                .active_panel()
 6015                .map(|panel| panel.is_zoomed(window, cx))
 6016                .unwrap_or(false);
 6017
 6018            let right_dock = this.right_dock.read(cx);
 6019            let right_visible = right_dock.is_open();
 6020            let right_active_panel = right_dock
 6021                .active_panel()
 6022                .map(|panel| panel.persistent_name().to_string());
 6023            let right_dock_zoom = right_dock
 6024                .active_panel()
 6025                .map(|panel| panel.is_zoomed(window, cx))
 6026                .unwrap_or(false);
 6027
 6028            let bottom_dock = this.bottom_dock.read(cx);
 6029            let bottom_visible = bottom_dock.is_open();
 6030            let bottom_active_panel = bottom_dock
 6031                .active_panel()
 6032                .map(|panel| panel.persistent_name().to_string());
 6033            let bottom_dock_zoom = bottom_dock
 6034                .active_panel()
 6035                .map(|panel| panel.is_zoomed(window, cx))
 6036                .unwrap_or(false);
 6037
 6038            DockStructure {
 6039                left: DockData {
 6040                    visible: left_visible,
 6041                    active_panel: left_active_panel,
 6042                    zoom: left_dock_zoom,
 6043                },
 6044                right: DockData {
 6045                    visible: right_visible,
 6046                    active_panel: right_active_panel,
 6047                    zoom: right_dock_zoom,
 6048                },
 6049                bottom: DockData {
 6050                    visible: bottom_visible,
 6051                    active_panel: bottom_active_panel,
 6052                    zoom: bottom_dock_zoom,
 6053                },
 6054            }
 6055        }
 6056
 6057        match self.workspace_location(cx) {
 6058            WorkspaceLocation::Location(location, paths) => {
 6059                let breakpoints = self.project.update(cx, |project, cx| {
 6060                    project
 6061                        .breakpoint_store()
 6062                        .read(cx)
 6063                        .all_source_breakpoints(cx)
 6064                });
 6065                let user_toolchains = self
 6066                    .project
 6067                    .read(cx)
 6068                    .user_toolchains(cx)
 6069                    .unwrap_or_default();
 6070
 6071                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6072                let docks = build_serialized_docks(self, window, cx);
 6073                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6074
 6075                let serialized_workspace = SerializedWorkspace {
 6076                    id: database_id,
 6077                    location,
 6078                    paths,
 6079                    center_group,
 6080                    window_bounds,
 6081                    display: Default::default(),
 6082                    docks,
 6083                    centered_layout: self.centered_layout,
 6084                    session_id: self.session_id.clone(),
 6085                    breakpoints,
 6086                    window_id: Some(window.window_handle().window_id().as_u64()),
 6087                    user_toolchains,
 6088                };
 6089
 6090                window.spawn(cx, async move |_| {
 6091                    persistence::DB.save_workspace(serialized_workspace).await;
 6092                })
 6093            }
 6094            WorkspaceLocation::DetachFromSession => {
 6095                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6096                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6097                // Save dock state for empty local workspaces
 6098                let docks = build_serialized_docks(self, window, cx);
 6099                window.spawn(cx, async move |_| {
 6100                    persistence::DB
 6101                        .set_window_open_status(
 6102                            database_id,
 6103                            window_bounds,
 6104                            display.unwrap_or_default(),
 6105                        )
 6106                        .await
 6107                        .log_err();
 6108                    persistence::DB
 6109                        .set_session_id(database_id, None)
 6110                        .await
 6111                        .log_err();
 6112                    persistence::write_default_dock_state(docks).await.log_err();
 6113                })
 6114            }
 6115            WorkspaceLocation::None => {
 6116                // Save dock state for empty non-local workspaces
 6117                let docks = build_serialized_docks(self, window, cx);
 6118                window.spawn(cx, async move |_| {
 6119                    persistence::write_default_dock_state(docks).await.log_err();
 6120                })
 6121            }
 6122        }
 6123    }
 6124
 6125    fn has_any_items_open(&self, cx: &App) -> bool {
 6126        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6127    }
 6128
 6129    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6130        let paths = PathList::new(&self.root_paths(cx));
 6131        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6132            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6133        } else if self.project.read(cx).is_local() {
 6134            if !paths.is_empty() || self.has_any_items_open(cx) {
 6135                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6136            } else {
 6137                WorkspaceLocation::DetachFromSession
 6138            }
 6139        } else {
 6140            WorkspaceLocation::None
 6141        }
 6142    }
 6143
 6144    fn update_history(&self, cx: &mut App) {
 6145        let Some(id) = self.database_id() else {
 6146            return;
 6147        };
 6148        if !self.project.read(cx).is_local() {
 6149            return;
 6150        }
 6151        if let Some(manager) = HistoryManager::global(cx) {
 6152            let paths = PathList::new(&self.root_paths(cx));
 6153            manager.update(cx, |this, cx| {
 6154                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6155            });
 6156        }
 6157    }
 6158
 6159    async fn serialize_items(
 6160        this: &WeakEntity<Self>,
 6161        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6162        cx: &mut AsyncWindowContext,
 6163    ) -> Result<()> {
 6164        const CHUNK_SIZE: usize = 200;
 6165
 6166        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6167
 6168        while let Some(items_received) = serializable_items.next().await {
 6169            let unique_items =
 6170                items_received
 6171                    .into_iter()
 6172                    .fold(HashMap::default(), |mut acc, item| {
 6173                        acc.entry(item.item_id()).or_insert(item);
 6174                        acc
 6175                    });
 6176
 6177            // We use into_iter() here so that the references to the items are moved into
 6178            // the tasks and not kept alive while we're sleeping.
 6179            for (_, item) in unique_items.into_iter() {
 6180                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6181                    item.serialize(workspace, false, window, cx)
 6182                }) {
 6183                    cx.background_spawn(async move { task.await.log_err() })
 6184                        .detach();
 6185                }
 6186            }
 6187
 6188            cx.background_executor()
 6189                .timer(SERIALIZATION_THROTTLE_TIME)
 6190                .await;
 6191        }
 6192
 6193        Ok(())
 6194    }
 6195
 6196    pub(crate) fn enqueue_item_serialization(
 6197        &mut self,
 6198        item: Box<dyn SerializableItemHandle>,
 6199    ) -> Result<()> {
 6200        self.serializable_items_tx
 6201            .unbounded_send(item)
 6202            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6203    }
 6204
 6205    pub(crate) fn load_workspace(
 6206        serialized_workspace: SerializedWorkspace,
 6207        paths_to_open: Vec<Option<ProjectPath>>,
 6208        window: &mut Window,
 6209        cx: &mut Context<Workspace>,
 6210    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6211        cx.spawn_in(window, async move |workspace, cx| {
 6212            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6213
 6214            let mut center_group = None;
 6215            let mut center_items = None;
 6216
 6217            // Traverse the splits tree and add to things
 6218            if let Some((group, active_pane, items)) = serialized_workspace
 6219                .center_group
 6220                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6221                .await
 6222            {
 6223                center_items = Some(items);
 6224                center_group = Some((group, active_pane))
 6225            }
 6226
 6227            let mut items_by_project_path = HashMap::default();
 6228            let mut item_ids_by_kind = HashMap::default();
 6229            let mut all_deserialized_items = Vec::default();
 6230            cx.update(|_, cx| {
 6231                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6232                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6233                        item_ids_by_kind
 6234                            .entry(serializable_item_handle.serialized_item_kind())
 6235                            .or_insert(Vec::new())
 6236                            .push(item.item_id().as_u64() as ItemId);
 6237                    }
 6238
 6239                    if let Some(project_path) = item.project_path(cx) {
 6240                        items_by_project_path.insert(project_path, item.clone());
 6241                    }
 6242                    all_deserialized_items.push(item);
 6243                }
 6244            })?;
 6245
 6246            let opened_items = paths_to_open
 6247                .into_iter()
 6248                .map(|path_to_open| {
 6249                    path_to_open
 6250                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6251                })
 6252                .collect::<Vec<_>>();
 6253
 6254            // Remove old panes from workspace panes list
 6255            workspace.update_in(cx, |workspace, window, cx| {
 6256                if let Some((center_group, active_pane)) = center_group {
 6257                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6258
 6259                    // Swap workspace center group
 6260                    workspace.center = PaneGroup::with_root(center_group);
 6261                    workspace.center.set_is_center(true);
 6262                    workspace.center.mark_positions(cx);
 6263
 6264                    if let Some(active_pane) = active_pane {
 6265                        workspace.set_active_pane(&active_pane, window, cx);
 6266                        cx.focus_self(window);
 6267                    } else {
 6268                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6269                    }
 6270                }
 6271
 6272                let docks = serialized_workspace.docks;
 6273
 6274                for (dock, serialized_dock) in [
 6275                    (&mut workspace.right_dock, docks.right),
 6276                    (&mut workspace.left_dock, docks.left),
 6277                    (&mut workspace.bottom_dock, docks.bottom),
 6278                ]
 6279                .iter_mut()
 6280                {
 6281                    dock.update(cx, |dock, cx| {
 6282                        dock.serialized_dock = Some(serialized_dock.clone());
 6283                        dock.restore_state(window, cx);
 6284                    });
 6285                }
 6286
 6287                cx.notify();
 6288            })?;
 6289
 6290            let _ = project
 6291                .update(cx, |project, cx| {
 6292                    project
 6293                        .breakpoint_store()
 6294                        .update(cx, |breakpoint_store, cx| {
 6295                            breakpoint_store
 6296                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6297                        })
 6298                })
 6299                .await;
 6300
 6301            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6302            // after loading the items, we might have different items and in order to avoid
 6303            // the database filling up, we delete items that haven't been loaded now.
 6304            //
 6305            // The items that have been loaded, have been saved after they've been added to the workspace.
 6306            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6307                item_ids_by_kind
 6308                    .into_iter()
 6309                    .map(|(item_kind, loaded_items)| {
 6310                        SerializableItemRegistry::cleanup(
 6311                            item_kind,
 6312                            serialized_workspace.id,
 6313                            loaded_items,
 6314                            window,
 6315                            cx,
 6316                        )
 6317                        .log_err()
 6318                    })
 6319                    .collect::<Vec<_>>()
 6320            })?;
 6321
 6322            futures::future::join_all(clean_up_tasks).await;
 6323
 6324            workspace
 6325                .update_in(cx, |workspace, window, cx| {
 6326                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6327                    workspace.serialize_workspace_internal(window, cx).detach();
 6328
 6329                    // Ensure that we mark the window as edited if we did load dirty items
 6330                    workspace.update_window_edited(window, cx);
 6331                })
 6332                .ok();
 6333
 6334            Ok(opened_items)
 6335        })
 6336    }
 6337
 6338    pub fn key_context(&self, cx: &App) -> KeyContext {
 6339        let mut context = KeyContext::new_with_defaults();
 6340        context.add("Workspace");
 6341        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6342        if let Some(status) = self
 6343            .debugger_provider
 6344            .as_ref()
 6345            .and_then(|provider| provider.active_thread_state(cx))
 6346        {
 6347            match status {
 6348                ThreadStatus::Running | ThreadStatus::Stepping => {
 6349                    context.add("debugger_running");
 6350                }
 6351                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6352                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6353            }
 6354        }
 6355
 6356        if self.left_dock.read(cx).is_open() {
 6357            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6358                context.set("left_dock", active_panel.panel_key());
 6359            }
 6360        }
 6361
 6362        if self.right_dock.read(cx).is_open() {
 6363            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6364                context.set("right_dock", active_panel.panel_key());
 6365            }
 6366        }
 6367
 6368        if self.bottom_dock.read(cx).is_open() {
 6369            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6370                context.set("bottom_dock", active_panel.panel_key());
 6371            }
 6372        }
 6373
 6374        context
 6375    }
 6376
 6377    /// Multiworkspace uses this to add workspace action handling to itself
 6378    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6379        self.add_workspace_actions_listeners(div, window, cx)
 6380            .on_action(cx.listener(
 6381                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6382                    for action in &action_sequence.0 {
 6383                        window.dispatch_action(action.boxed_clone(), cx);
 6384                    }
 6385                },
 6386            ))
 6387            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6388            .on_action(cx.listener(Self::close_all_items_and_panes))
 6389            .on_action(cx.listener(Self::close_item_in_all_panes))
 6390            .on_action(cx.listener(Self::save_all))
 6391            .on_action(cx.listener(Self::send_keystrokes))
 6392            .on_action(cx.listener(Self::add_folder_to_project))
 6393            .on_action(cx.listener(Self::follow_next_collaborator))
 6394            .on_action(cx.listener(Self::activate_pane_at_index))
 6395            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6396            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6397            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6398            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6399                let pane = workspace.active_pane().clone();
 6400                workspace.unfollow_in_pane(&pane, window, cx);
 6401            }))
 6402            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6403                workspace
 6404                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6405                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6406            }))
 6407            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6408                workspace
 6409                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6410                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6411            }))
 6412            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6413                workspace
 6414                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6415                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6416            }))
 6417            .on_action(
 6418                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6419                    workspace.activate_previous_pane(window, cx)
 6420                }),
 6421            )
 6422            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6423                workspace.activate_next_pane(window, cx)
 6424            }))
 6425            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6426                workspace.activate_last_pane(window, cx)
 6427            }))
 6428            .on_action(
 6429                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6430                    workspace.activate_next_window(cx)
 6431                }),
 6432            )
 6433            .on_action(
 6434                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6435                    workspace.activate_previous_window(cx)
 6436                }),
 6437            )
 6438            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6439                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6440            }))
 6441            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6442                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6443            }))
 6444            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6445                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6446            }))
 6447            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6448                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6449            }))
 6450            .on_action(cx.listener(
 6451                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6452                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6453                },
 6454            ))
 6455            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6456                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6457            }))
 6458            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6459                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6460            }))
 6461            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6462                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6463            }))
 6464            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6465                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6466            }))
 6467            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6468                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6469                    SplitDirection::Down,
 6470                    SplitDirection::Up,
 6471                    SplitDirection::Right,
 6472                    SplitDirection::Left,
 6473                ];
 6474                for dir in DIRECTION_PRIORITY {
 6475                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6476                        workspace.swap_pane_in_direction(dir, cx);
 6477                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6478                        break;
 6479                    }
 6480                }
 6481            }))
 6482            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6483                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6484            }))
 6485            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6486                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6487            }))
 6488            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6489                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6490            }))
 6491            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6492                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6493            }))
 6494            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6495                this.toggle_dock(DockPosition::Left, window, cx);
 6496            }))
 6497            .on_action(cx.listener(
 6498                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6499                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6500                },
 6501            ))
 6502            .on_action(cx.listener(
 6503                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6504                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6505                },
 6506            ))
 6507            .on_action(cx.listener(
 6508                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6509                    if !workspace.close_active_dock(window, cx) {
 6510                        cx.propagate();
 6511                    }
 6512                },
 6513            ))
 6514            .on_action(
 6515                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6516                    workspace.close_all_docks(window, cx);
 6517                }),
 6518            )
 6519            .on_action(cx.listener(Self::toggle_all_docks))
 6520            .on_action(cx.listener(
 6521                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6522                    workspace.clear_all_notifications(cx);
 6523                },
 6524            ))
 6525            .on_action(cx.listener(
 6526                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6527                    workspace.clear_navigation_history(window, cx);
 6528                },
 6529            ))
 6530            .on_action(cx.listener(
 6531                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6532                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6533                        workspace.suppress_notification(&notification_id, cx);
 6534                    }
 6535                },
 6536            ))
 6537            .on_action(cx.listener(
 6538                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6539                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6540                },
 6541            ))
 6542            .on_action(
 6543                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6544                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6545                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6546                            trusted_worktrees.clear_trusted_paths()
 6547                        });
 6548                        let clear_task = persistence::DB.clear_trusted_worktrees();
 6549                        cx.spawn(async move |_, cx| {
 6550                            if clear_task.await.log_err().is_some() {
 6551                                cx.update(|cx| reload(cx));
 6552                            }
 6553                        })
 6554                        .detach();
 6555                    }
 6556                }),
 6557            )
 6558            .on_action(cx.listener(
 6559                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6560                    workspace.reopen_closed_item(window, cx).detach();
 6561                },
 6562            ))
 6563            .on_action(cx.listener(
 6564                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6565                    for dock in workspace.all_docks() {
 6566                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6567                            let Some(panel) = dock.read(cx).active_panel() else {
 6568                                return;
 6569                            };
 6570
 6571                            // Set to `None`, then the size will fall back to the default.
 6572                            panel.clone().set_size(None, window, cx);
 6573
 6574                            return;
 6575                        }
 6576                    }
 6577                },
 6578            ))
 6579            .on_action(cx.listener(
 6580                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6581                    for dock in workspace.all_docks() {
 6582                        if let Some(panel) = dock.read(cx).visible_panel() {
 6583                            // Set to `None`, then the size will fall back to the default.
 6584                            panel.clone().set_size(None, window, cx);
 6585                        }
 6586                    }
 6587                },
 6588            ))
 6589            .on_action(cx.listener(
 6590                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6591                    adjust_active_dock_size_by_px(
 6592                        px_with_ui_font_fallback(act.px, cx),
 6593                        workspace,
 6594                        window,
 6595                        cx,
 6596                    );
 6597                },
 6598            ))
 6599            .on_action(cx.listener(
 6600                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6601                    adjust_active_dock_size_by_px(
 6602                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6603                        workspace,
 6604                        window,
 6605                        cx,
 6606                    );
 6607                },
 6608            ))
 6609            .on_action(cx.listener(
 6610                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6611                    adjust_open_docks_size_by_px(
 6612                        px_with_ui_font_fallback(act.px, cx),
 6613                        workspace,
 6614                        window,
 6615                        cx,
 6616                    );
 6617                },
 6618            ))
 6619            .on_action(cx.listener(
 6620                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6621                    adjust_open_docks_size_by_px(
 6622                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6623                        workspace,
 6624                        window,
 6625                        cx,
 6626                    );
 6627                },
 6628            ))
 6629            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6630            .on_action(cx.listener(
 6631                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6632                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6633                        let dock = active_dock.read(cx);
 6634                        if let Some(active_panel) = dock.active_panel() {
 6635                            if active_panel.pane(cx).is_none() {
 6636                                let mut recent_pane: Option<Entity<Pane>> = None;
 6637                                let mut recent_timestamp = 0;
 6638                                for pane_handle in workspace.panes() {
 6639                                    let pane = pane_handle.read(cx);
 6640                                    for entry in pane.activation_history() {
 6641                                        if entry.timestamp > recent_timestamp {
 6642                                            recent_timestamp = entry.timestamp;
 6643                                            recent_pane = Some(pane_handle.clone());
 6644                                        }
 6645                                    }
 6646                                }
 6647
 6648                                if let Some(pane) = recent_pane {
 6649                                    pane.update(cx, |pane, cx| {
 6650                                        let current_index = pane.active_item_index();
 6651                                        let items_len = pane.items_len();
 6652                                        if items_len > 0 {
 6653                                            let next_index = if current_index + 1 < items_len {
 6654                                                current_index + 1
 6655                                            } else {
 6656                                                0
 6657                                            };
 6658                                            pane.activate_item(
 6659                                                next_index, false, false, window, cx,
 6660                                            );
 6661                                        }
 6662                                    });
 6663                                    return;
 6664                                }
 6665                            }
 6666                        }
 6667                    }
 6668                    cx.propagate();
 6669                },
 6670            ))
 6671            .on_action(cx.listener(
 6672                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6673                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6674                        let dock = active_dock.read(cx);
 6675                        if let Some(active_panel) = dock.active_panel() {
 6676                            if active_panel.pane(cx).is_none() {
 6677                                let mut recent_pane: Option<Entity<Pane>> = None;
 6678                                let mut recent_timestamp = 0;
 6679                                for pane_handle in workspace.panes() {
 6680                                    let pane = pane_handle.read(cx);
 6681                                    for entry in pane.activation_history() {
 6682                                        if entry.timestamp > recent_timestamp {
 6683                                            recent_timestamp = entry.timestamp;
 6684                                            recent_pane = Some(pane_handle.clone());
 6685                                        }
 6686                                    }
 6687                                }
 6688
 6689                                if let Some(pane) = recent_pane {
 6690                                    pane.update(cx, |pane, cx| {
 6691                                        let current_index = pane.active_item_index();
 6692                                        let items_len = pane.items_len();
 6693                                        if items_len > 0 {
 6694                                            let prev_index = if current_index > 0 {
 6695                                                current_index - 1
 6696                                            } else {
 6697                                                items_len.saturating_sub(1)
 6698                                            };
 6699                                            pane.activate_item(
 6700                                                prev_index, false, false, window, cx,
 6701                                            );
 6702                                        }
 6703                                    });
 6704                                    return;
 6705                                }
 6706                            }
 6707                        }
 6708                    }
 6709                    cx.propagate();
 6710                },
 6711            ))
 6712            .on_action(cx.listener(
 6713                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 6714                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6715                        let dock = active_dock.read(cx);
 6716                        if let Some(active_panel) = dock.active_panel() {
 6717                            if active_panel.pane(cx).is_none() {
 6718                                let active_pane = workspace.active_pane().clone();
 6719                                active_pane.update(cx, |pane, cx| {
 6720                                    pane.close_active_item(action, window, cx)
 6721                                        .detach_and_log_err(cx);
 6722                                });
 6723                                return;
 6724                            }
 6725                        }
 6726                    }
 6727                    cx.propagate();
 6728                },
 6729            ))
 6730            .on_action(
 6731                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6732                    let pane = workspace.active_pane().clone();
 6733                    if let Some(item) = pane.read(cx).active_item() {
 6734                        item.toggle_read_only(window, cx);
 6735                    }
 6736                }),
 6737            )
 6738            .on_action(cx.listener(Workspace::cancel))
 6739    }
 6740
 6741    #[cfg(any(test, feature = "test-support"))]
 6742    pub fn set_random_database_id(&mut self) {
 6743        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6744    }
 6745
 6746    #[cfg(any(test, feature = "test-support"))]
 6747    pub(crate) fn test_new(
 6748        project: Entity<Project>,
 6749        window: &mut Window,
 6750        cx: &mut Context<Self>,
 6751    ) -> Self {
 6752        use node_runtime::NodeRuntime;
 6753        use session::Session;
 6754
 6755        let client = project.read(cx).client();
 6756        let user_store = project.read(cx).user_store();
 6757        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6758        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6759        window.activate_window();
 6760        let app_state = Arc::new(AppState {
 6761            languages: project.read(cx).languages().clone(),
 6762            workspace_store,
 6763            client,
 6764            user_store,
 6765            fs: project.read(cx).fs().clone(),
 6766            build_window_options: |_, _| Default::default(),
 6767            node_runtime: NodeRuntime::unavailable(),
 6768            session,
 6769        });
 6770        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6771        workspace
 6772            .active_pane
 6773            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6774        workspace
 6775    }
 6776
 6777    pub fn register_action<A: Action>(
 6778        &mut self,
 6779        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6780    ) -> &mut Self {
 6781        let callback = Arc::new(callback);
 6782
 6783        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6784            let callback = callback.clone();
 6785            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6786                (callback)(workspace, event, window, cx)
 6787            }))
 6788        }));
 6789        self
 6790    }
 6791    pub fn register_action_renderer(
 6792        &mut self,
 6793        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6794    ) -> &mut Self {
 6795        self.workspace_actions.push(Box::new(callback));
 6796        self
 6797    }
 6798
 6799    fn add_workspace_actions_listeners(
 6800        &self,
 6801        mut div: Div,
 6802        window: &mut Window,
 6803        cx: &mut Context<Self>,
 6804    ) -> Div {
 6805        for action in self.workspace_actions.iter() {
 6806            div = (action)(div, self, window, cx)
 6807        }
 6808        div
 6809    }
 6810
 6811    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 6812        self.modal_layer.read(cx).has_active_modal()
 6813    }
 6814
 6815    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 6816        self.modal_layer.read(cx).active_modal()
 6817    }
 6818
 6819    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 6820    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 6821    /// If no modal is active, the new modal will be shown.
 6822    ///
 6823    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 6824    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 6825    /// will not be shown.
 6826    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 6827    where
 6828        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 6829    {
 6830        self.modal_layer.update(cx, |modal_layer, cx| {
 6831            modal_layer.toggle_modal(window, cx, build)
 6832        })
 6833    }
 6834
 6835    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 6836        self.modal_layer
 6837            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 6838    }
 6839
 6840    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 6841        self.toast_layer
 6842            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 6843    }
 6844
 6845    pub fn toggle_centered_layout(
 6846        &mut self,
 6847        _: &ToggleCenteredLayout,
 6848        _: &mut Window,
 6849        cx: &mut Context<Self>,
 6850    ) {
 6851        self.centered_layout = !self.centered_layout;
 6852        if let Some(database_id) = self.database_id() {
 6853            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 6854                .detach_and_log_err(cx);
 6855        }
 6856        cx.notify();
 6857    }
 6858
 6859    fn adjust_padding(padding: Option<f32>) -> f32 {
 6860        padding
 6861            .unwrap_or(CenteredPaddingSettings::default().0)
 6862            .clamp(
 6863                CenteredPaddingSettings::MIN_PADDING,
 6864                CenteredPaddingSettings::MAX_PADDING,
 6865            )
 6866    }
 6867
 6868    fn render_dock(
 6869        &self,
 6870        position: DockPosition,
 6871        dock: &Entity<Dock>,
 6872        window: &mut Window,
 6873        cx: &mut App,
 6874    ) -> Option<Div> {
 6875        if self.zoomed_position == Some(position) {
 6876            return None;
 6877        }
 6878
 6879        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 6880            let pane = panel.pane(cx)?;
 6881            let follower_states = &self.follower_states;
 6882            leader_border_for_pane(follower_states, &pane, window, cx)
 6883        });
 6884
 6885        Some(
 6886            div()
 6887                .flex()
 6888                .flex_none()
 6889                .overflow_hidden()
 6890                .child(dock.clone())
 6891                .children(leader_border),
 6892        )
 6893    }
 6894
 6895    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 6896        window
 6897            .root::<MultiWorkspace>()
 6898            .flatten()
 6899            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 6900    }
 6901
 6902    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 6903        self.zoomed.as_ref()
 6904    }
 6905
 6906    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 6907        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6908            return;
 6909        };
 6910        let windows = cx.windows();
 6911        let next_window =
 6912            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 6913                || {
 6914                    windows
 6915                        .iter()
 6916                        .cycle()
 6917                        .skip_while(|window| window.window_id() != current_window_id)
 6918                        .nth(1)
 6919                },
 6920            );
 6921
 6922        if let Some(window) = next_window {
 6923            window
 6924                .update(cx, |_, window, _| window.activate_window())
 6925                .ok();
 6926        }
 6927    }
 6928
 6929    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 6930        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6931            return;
 6932        };
 6933        let windows = cx.windows();
 6934        let prev_window =
 6935            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 6936                || {
 6937                    windows
 6938                        .iter()
 6939                        .rev()
 6940                        .cycle()
 6941                        .skip_while(|window| window.window_id() != current_window_id)
 6942                        .nth(1)
 6943                },
 6944            );
 6945
 6946        if let Some(window) = prev_window {
 6947            window
 6948                .update(cx, |_, window, _| window.activate_window())
 6949                .ok();
 6950        }
 6951    }
 6952
 6953    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 6954        if cx.stop_active_drag(window) {
 6955        } else if let Some((notification_id, _)) = self.notifications.pop() {
 6956            dismiss_app_notification(&notification_id, cx);
 6957        } else {
 6958            cx.propagate();
 6959        }
 6960    }
 6961
 6962    fn adjust_dock_size_by_px(
 6963        &mut self,
 6964        panel_size: Pixels,
 6965        dock_pos: DockPosition,
 6966        px: Pixels,
 6967        window: &mut Window,
 6968        cx: &mut Context<Self>,
 6969    ) {
 6970        match dock_pos {
 6971            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 6972            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 6973            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 6974        }
 6975    }
 6976
 6977    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6978        let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
 6979
 6980        self.left_dock.update(cx, |left_dock, cx| {
 6981            if WorkspaceSettings::get_global(cx)
 6982                .resize_all_panels_in_dock
 6983                .contains(&DockPosition::Left)
 6984            {
 6985                left_dock.resize_all_panels(Some(size), window, cx);
 6986            } else {
 6987                left_dock.resize_active_panel(Some(size), window, cx);
 6988            }
 6989        });
 6990    }
 6991
 6992    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6993        let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
 6994        self.left_dock.read_with(cx, |left_dock, cx| {
 6995            let left_dock_size = left_dock
 6996                .active_panel_size(window, cx)
 6997                .unwrap_or(Pixels::ZERO);
 6998            if left_dock_size + size > self.bounds.right() {
 6999                size = self.bounds.right() - left_dock_size
 7000            }
 7001        });
 7002        self.right_dock.update(cx, |right_dock, cx| {
 7003            if WorkspaceSettings::get_global(cx)
 7004                .resize_all_panels_in_dock
 7005                .contains(&DockPosition::Right)
 7006            {
 7007                right_dock.resize_all_panels(Some(size), window, cx);
 7008            } else {
 7009                right_dock.resize_active_panel(Some(size), window, cx);
 7010            }
 7011        });
 7012    }
 7013
 7014    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7015        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7016        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7017            if WorkspaceSettings::get_global(cx)
 7018                .resize_all_panels_in_dock
 7019                .contains(&DockPosition::Bottom)
 7020            {
 7021                bottom_dock.resize_all_panels(Some(size), window, cx);
 7022            } else {
 7023                bottom_dock.resize_active_panel(Some(size), window, cx);
 7024            }
 7025        });
 7026    }
 7027
 7028    fn toggle_edit_predictions_all_files(
 7029        &mut self,
 7030        _: &ToggleEditPrediction,
 7031        _window: &mut Window,
 7032        cx: &mut Context<Self>,
 7033    ) {
 7034        let fs = self.project().read(cx).fs().clone();
 7035        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7036        update_settings_file(fs, cx, move |file, _| {
 7037            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7038        });
 7039    }
 7040
 7041    pub fn show_worktree_trust_security_modal(
 7042        &mut self,
 7043        toggle: bool,
 7044        window: &mut Window,
 7045        cx: &mut Context<Self>,
 7046    ) {
 7047        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7048            if toggle {
 7049                security_modal.update(cx, |security_modal, cx| {
 7050                    security_modal.dismiss(cx);
 7051                })
 7052            } else {
 7053                security_modal.update(cx, |security_modal, cx| {
 7054                    security_modal.refresh_restricted_paths(cx);
 7055                });
 7056            }
 7057        } else {
 7058            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7059                .map(|trusted_worktrees| {
 7060                    trusted_worktrees
 7061                        .read(cx)
 7062                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7063                })
 7064                .unwrap_or(false);
 7065            if has_restricted_worktrees {
 7066                let project = self.project().read(cx);
 7067                let remote_host = project
 7068                    .remote_connection_options(cx)
 7069                    .map(RemoteHostLocation::from);
 7070                let worktree_store = project.worktree_store().downgrade();
 7071                self.toggle_modal(window, cx, |_, cx| {
 7072                    SecurityModal::new(worktree_store, remote_host, cx)
 7073                });
 7074            }
 7075        }
 7076    }
 7077}
 7078
 7079pub trait AnyActiveCall {
 7080    fn entity(&self) -> AnyEntity;
 7081    fn is_in_room(&self, _: &App) -> bool;
 7082    fn room_id(&self, _: &App) -> Option<u64>;
 7083    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7084    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7085    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7086    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7087    fn is_sharing_project(&self, _: &App) -> bool;
 7088    fn has_remote_participants(&self, _: &App) -> bool;
 7089    fn local_participant_is_guest(&self, _: &App) -> bool;
 7090    fn client(&self, _: &App) -> Arc<Client>;
 7091    fn share_on_join(&self, _: &App) -> bool;
 7092    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7093    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7094    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7095    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7096    fn join_project(
 7097        &self,
 7098        _: u64,
 7099        _: Arc<LanguageRegistry>,
 7100        _: Arc<dyn Fs>,
 7101        _: &mut App,
 7102    ) -> Task<Result<Entity<Project>>>;
 7103    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7104    fn subscribe(
 7105        &self,
 7106        _: &mut Window,
 7107        _: &mut Context<Workspace>,
 7108        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7109    ) -> Subscription;
 7110    fn create_shared_screen(
 7111        &self,
 7112        _: PeerId,
 7113        _: &Entity<Pane>,
 7114        _: &mut Window,
 7115        _: &mut App,
 7116    ) -> Option<Entity<SharedScreen>>;
 7117}
 7118
 7119#[derive(Clone)]
 7120pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7121impl Global for GlobalAnyActiveCall {}
 7122
 7123impl GlobalAnyActiveCall {
 7124    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7125        cx.try_global()
 7126    }
 7127
 7128    pub(crate) fn global(cx: &App) -> &Self {
 7129        cx.global()
 7130    }
 7131}
 7132/// Workspace-local view of a remote participant's location.
 7133#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7134pub enum ParticipantLocation {
 7135    SharedProject { project_id: u64 },
 7136    UnsharedProject,
 7137    External,
 7138}
 7139
 7140impl ParticipantLocation {
 7141    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7142        match location
 7143            .and_then(|l| l.variant)
 7144            .context("participant location was not provided")?
 7145        {
 7146            proto::participant_location::Variant::SharedProject(project) => {
 7147                Ok(Self::SharedProject {
 7148                    project_id: project.id,
 7149                })
 7150            }
 7151            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7152            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7153        }
 7154    }
 7155}
 7156/// Workspace-local view of a remote collaborator's state.
 7157/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7158#[derive(Clone)]
 7159pub struct RemoteCollaborator {
 7160    pub user: Arc<User>,
 7161    pub peer_id: PeerId,
 7162    pub location: ParticipantLocation,
 7163    pub participant_index: ParticipantIndex,
 7164}
 7165
 7166pub enum ActiveCallEvent {
 7167    ParticipantLocationChanged { participant_id: PeerId },
 7168    RemoteVideoTracksChanged { participant_id: PeerId },
 7169}
 7170
 7171fn leader_border_for_pane(
 7172    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7173    pane: &Entity<Pane>,
 7174    _: &Window,
 7175    cx: &App,
 7176) -> Option<Div> {
 7177    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7178        if state.pane() == pane {
 7179            Some((*leader_id, state))
 7180        } else {
 7181            None
 7182        }
 7183    })?;
 7184
 7185    let mut leader_color = match leader_id {
 7186        CollaboratorId::PeerId(leader_peer_id) => {
 7187            let leader = GlobalAnyActiveCall::try_global(cx)?
 7188                .0
 7189                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7190
 7191            cx.theme()
 7192                .players()
 7193                .color_for_participant(leader.participant_index.0)
 7194                .cursor
 7195        }
 7196        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7197    };
 7198    leader_color.fade_out(0.3);
 7199    Some(
 7200        div()
 7201            .absolute()
 7202            .size_full()
 7203            .left_0()
 7204            .top_0()
 7205            .border_2()
 7206            .border_color(leader_color),
 7207    )
 7208}
 7209
 7210fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7211    ZED_WINDOW_POSITION
 7212        .zip(*ZED_WINDOW_SIZE)
 7213        .map(|(position, size)| Bounds {
 7214            origin: position,
 7215            size,
 7216        })
 7217}
 7218
 7219fn open_items(
 7220    serialized_workspace: Option<SerializedWorkspace>,
 7221    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7222    window: &mut Window,
 7223    cx: &mut Context<Workspace>,
 7224) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7225    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7226        Workspace::load_workspace(
 7227            serialized_workspace,
 7228            project_paths_to_open
 7229                .iter()
 7230                .map(|(_, project_path)| project_path)
 7231                .cloned()
 7232                .collect(),
 7233            window,
 7234            cx,
 7235        )
 7236    });
 7237
 7238    cx.spawn_in(window, async move |workspace, cx| {
 7239        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7240
 7241        if let Some(restored_items) = restored_items {
 7242            let restored_items = restored_items.await?;
 7243
 7244            let restored_project_paths = restored_items
 7245                .iter()
 7246                .filter_map(|item| {
 7247                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7248                        .ok()
 7249                        .flatten()
 7250                })
 7251                .collect::<HashSet<_>>();
 7252
 7253            for restored_item in restored_items {
 7254                opened_items.push(restored_item.map(Ok));
 7255            }
 7256
 7257            project_paths_to_open
 7258                .iter_mut()
 7259                .for_each(|(_, project_path)| {
 7260                    if let Some(project_path_to_open) = project_path
 7261                        && restored_project_paths.contains(project_path_to_open)
 7262                    {
 7263                        *project_path = None;
 7264                    }
 7265                });
 7266        } else {
 7267            for _ in 0..project_paths_to_open.len() {
 7268                opened_items.push(None);
 7269            }
 7270        }
 7271        assert!(opened_items.len() == project_paths_to_open.len());
 7272
 7273        let tasks =
 7274            project_paths_to_open
 7275                .into_iter()
 7276                .enumerate()
 7277                .map(|(ix, (abs_path, project_path))| {
 7278                    let workspace = workspace.clone();
 7279                    cx.spawn(async move |cx| {
 7280                        let file_project_path = project_path?;
 7281                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7282                            workspace.project().update(cx, |project, cx| {
 7283                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7284                            })
 7285                        });
 7286
 7287                        // We only want to open file paths here. If one of the items
 7288                        // here is a directory, it was already opened further above
 7289                        // with a `find_or_create_worktree`.
 7290                        if let Ok(task) = abs_path_task
 7291                            && task.await.is_none_or(|p| p.is_file())
 7292                        {
 7293                            return Some((
 7294                                ix,
 7295                                workspace
 7296                                    .update_in(cx, |workspace, window, cx| {
 7297                                        workspace.open_path(
 7298                                            file_project_path,
 7299                                            None,
 7300                                            true,
 7301                                            window,
 7302                                            cx,
 7303                                        )
 7304                                    })
 7305                                    .log_err()?
 7306                                    .await,
 7307                            ));
 7308                        }
 7309                        None
 7310                    })
 7311                });
 7312
 7313        let tasks = tasks.collect::<Vec<_>>();
 7314
 7315        let tasks = futures::future::join_all(tasks);
 7316        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7317            opened_items[ix] = Some(path_open_result);
 7318        }
 7319
 7320        Ok(opened_items)
 7321    })
 7322}
 7323
 7324enum ActivateInDirectionTarget {
 7325    Pane(Entity<Pane>),
 7326    Dock(Entity<Dock>),
 7327}
 7328
 7329fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7330    window
 7331        .update(cx, |multi_workspace, _, cx| {
 7332            let workspace = multi_workspace.workspace().clone();
 7333            workspace.update(cx, |workspace, cx| {
 7334                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7335                    struct DatabaseFailedNotification;
 7336
 7337                    workspace.show_notification(
 7338                        NotificationId::unique::<DatabaseFailedNotification>(),
 7339                        cx,
 7340                        |cx| {
 7341                            cx.new(|cx| {
 7342                                MessageNotification::new("Failed to load the database file.", cx)
 7343                                    .primary_message("File an Issue")
 7344                                    .primary_icon(IconName::Plus)
 7345                                    .primary_on_click(|window, cx| {
 7346                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7347                                    })
 7348                            })
 7349                        },
 7350                    );
 7351                }
 7352            });
 7353        })
 7354        .log_err();
 7355}
 7356
 7357fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7358    if val == 0 {
 7359        ThemeSettings::get_global(cx).ui_font_size(cx)
 7360    } else {
 7361        px(val as f32)
 7362    }
 7363}
 7364
 7365fn adjust_active_dock_size_by_px(
 7366    px: Pixels,
 7367    workspace: &mut Workspace,
 7368    window: &mut Window,
 7369    cx: &mut Context<Workspace>,
 7370) {
 7371    let Some(active_dock) = workspace
 7372        .all_docks()
 7373        .into_iter()
 7374        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7375    else {
 7376        return;
 7377    };
 7378    let dock = active_dock.read(cx);
 7379    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 7380        return;
 7381    };
 7382    let dock_pos = dock.position();
 7383    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 7384}
 7385
 7386fn adjust_open_docks_size_by_px(
 7387    px: Pixels,
 7388    workspace: &mut Workspace,
 7389    window: &mut Window,
 7390    cx: &mut Context<Workspace>,
 7391) {
 7392    let docks = workspace
 7393        .all_docks()
 7394        .into_iter()
 7395        .filter_map(|dock| {
 7396            if dock.read(cx).is_open() {
 7397                let dock = dock.read(cx);
 7398                let panel_size = dock.active_panel_size(window, cx)?;
 7399                let dock_pos = dock.position();
 7400                Some((panel_size, dock_pos, px))
 7401            } else {
 7402                None
 7403            }
 7404        })
 7405        .collect::<Vec<_>>();
 7406
 7407    docks
 7408        .into_iter()
 7409        .for_each(|(panel_size, dock_pos, offset)| {
 7410            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 7411        });
 7412}
 7413
 7414impl Focusable for Workspace {
 7415    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7416        self.active_pane.focus_handle(cx)
 7417    }
 7418}
 7419
 7420#[derive(Clone)]
 7421struct DraggedDock(DockPosition);
 7422
 7423impl Render for DraggedDock {
 7424    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7425        gpui::Empty
 7426    }
 7427}
 7428
 7429impl Render for Workspace {
 7430    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7431        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7432        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7433            log::info!("Rendered first frame");
 7434        }
 7435
 7436        let centered_layout = self.centered_layout
 7437            && self.center.panes().len() == 1
 7438            && self.active_item(cx).is_some();
 7439        let render_padding = |size| {
 7440            (size > 0.0).then(|| {
 7441                div()
 7442                    .h_full()
 7443                    .w(relative(size))
 7444                    .bg(cx.theme().colors().editor_background)
 7445                    .border_color(cx.theme().colors().pane_group_border)
 7446            })
 7447        };
 7448        let paddings = if centered_layout {
 7449            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7450            (
 7451                render_padding(Self::adjust_padding(
 7452                    settings.left_padding.map(|padding| padding.0),
 7453                )),
 7454                render_padding(Self::adjust_padding(
 7455                    settings.right_padding.map(|padding| padding.0),
 7456                )),
 7457            )
 7458        } else {
 7459            (None, None)
 7460        };
 7461        let ui_font = theme::setup_ui_font(window, cx);
 7462
 7463        let theme = cx.theme().clone();
 7464        let colors = theme.colors();
 7465        let notification_entities = self
 7466            .notifications
 7467            .iter()
 7468            .map(|(_, notification)| notification.entity_id())
 7469            .collect::<Vec<_>>();
 7470        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7471
 7472        div()
 7473            .relative()
 7474            .size_full()
 7475            .flex()
 7476            .flex_col()
 7477            .font(ui_font)
 7478            .gap_0()
 7479                .justify_start()
 7480                .items_start()
 7481                .text_color(colors.text)
 7482                .overflow_hidden()
 7483                .children(self.titlebar_item.clone())
 7484                .on_modifiers_changed(move |_, _, cx| {
 7485                    for &id in &notification_entities {
 7486                        cx.notify(id);
 7487                    }
 7488                })
 7489                .child(
 7490                    div()
 7491                        .size_full()
 7492                        .relative()
 7493                        .flex_1()
 7494                        .flex()
 7495                        .flex_col()
 7496                        .child(
 7497                            div()
 7498                                .id("workspace")
 7499                                .bg(colors.background)
 7500                                .relative()
 7501                                .flex_1()
 7502                                .w_full()
 7503                                .flex()
 7504                                .flex_col()
 7505                                .overflow_hidden()
 7506                                .border_t_1()
 7507                                .border_b_1()
 7508                                .border_color(colors.border)
 7509                                .child({
 7510                                    let this = cx.entity();
 7511                                    canvas(
 7512                                        move |bounds, window, cx| {
 7513                                            this.update(cx, |this, cx| {
 7514                                                let bounds_changed = this.bounds != bounds;
 7515                                                this.bounds = bounds;
 7516
 7517                                                if bounds_changed {
 7518                                                    this.left_dock.update(cx, |dock, cx| {
 7519                                                        dock.clamp_panel_size(
 7520                                                            bounds.size.width,
 7521                                                            window,
 7522                                                            cx,
 7523                                                        )
 7524                                                    });
 7525
 7526                                                    this.right_dock.update(cx, |dock, cx| {
 7527                                                        dock.clamp_panel_size(
 7528                                                            bounds.size.width,
 7529                                                            window,
 7530                                                            cx,
 7531                                                        )
 7532                                                    });
 7533
 7534                                                    this.bottom_dock.update(cx, |dock, cx| {
 7535                                                        dock.clamp_panel_size(
 7536                                                            bounds.size.height,
 7537                                                            window,
 7538                                                            cx,
 7539                                                        )
 7540                                                    });
 7541                                                }
 7542                                            })
 7543                                        },
 7544                                        |_, _, _, _| {},
 7545                                    )
 7546                                    .absolute()
 7547                                    .size_full()
 7548                                })
 7549                                .when(self.zoomed.is_none(), |this| {
 7550                                    this.on_drag_move(cx.listener(
 7551                                        move |workspace,
 7552                                              e: &DragMoveEvent<DraggedDock>,
 7553                                              window,
 7554                                              cx| {
 7555                                            if workspace.previous_dock_drag_coordinates
 7556                                                != Some(e.event.position)
 7557                                            {
 7558                                                workspace.previous_dock_drag_coordinates =
 7559                                                    Some(e.event.position);
 7560                                                match e.drag(cx).0 {
 7561                                                    DockPosition::Left => {
 7562                                                        workspace.resize_left_dock(
 7563                                                            e.event.position.x
 7564                                                                - workspace.bounds.left(),
 7565                                                            window,
 7566                                                            cx,
 7567                                                        );
 7568                                                    }
 7569                                                    DockPosition::Right => {
 7570                                                        workspace.resize_right_dock(
 7571                                                            workspace.bounds.right()
 7572                                                                - e.event.position.x,
 7573                                                            window,
 7574                                                            cx,
 7575                                                        );
 7576                                                    }
 7577                                                    DockPosition::Bottom => {
 7578                                                        workspace.resize_bottom_dock(
 7579                                                            workspace.bounds.bottom()
 7580                                                                - e.event.position.y,
 7581                                                            window,
 7582                                                            cx,
 7583                                                        );
 7584                                                    }
 7585                                                };
 7586                                                workspace.serialize_workspace(window, cx);
 7587                                            }
 7588                                        },
 7589                                    ))
 7590
 7591                                })
 7592                                .child({
 7593                                    match bottom_dock_layout {
 7594                                        BottomDockLayout::Full => div()
 7595                                            .flex()
 7596                                            .flex_col()
 7597                                            .h_full()
 7598                                            .child(
 7599                                                div()
 7600                                                    .flex()
 7601                                                    .flex_row()
 7602                                                    .flex_1()
 7603                                                    .overflow_hidden()
 7604                                                    .children(self.render_dock(
 7605                                                        DockPosition::Left,
 7606                                                        &self.left_dock,
 7607                                                        window,
 7608                                                        cx,
 7609                                                    ))
 7610
 7611                                                    .child(
 7612                                                        div()
 7613                                                            .flex()
 7614                                                            .flex_col()
 7615                                                            .flex_1()
 7616                                                            .overflow_hidden()
 7617                                                            .child(
 7618                                                                h_flex()
 7619                                                                    .flex_1()
 7620                                                                    .when_some(
 7621                                                                        paddings.0,
 7622                                                                        |this, p| {
 7623                                                                            this.child(
 7624                                                                                p.border_r_1(),
 7625                                                                            )
 7626                                                                        },
 7627                                                                    )
 7628                                                                    .child(self.center.render(
 7629                                                                        self.zoomed.as_ref(),
 7630                                                                        &PaneRenderContext {
 7631                                                                            follower_states:
 7632                                                                                &self.follower_states,
 7633                                                                            active_call: self.active_call(),
 7634                                                                            active_pane: &self.active_pane,
 7635                                                                            app_state: &self.app_state,
 7636                                                                            project: &self.project,
 7637                                                                            workspace: &self.weak_self,
 7638                                                                        },
 7639                                                                        window,
 7640                                                                        cx,
 7641                                                                    ))
 7642                                                                    .when_some(
 7643                                                                        paddings.1,
 7644                                                                        |this, p| {
 7645                                                                            this.child(
 7646                                                                                p.border_l_1(),
 7647                                                                            )
 7648                                                                        },
 7649                                                                    ),
 7650                                                            ),
 7651                                                    )
 7652
 7653                                                    .children(self.render_dock(
 7654                                                        DockPosition::Right,
 7655                                                        &self.right_dock,
 7656                                                        window,
 7657                                                        cx,
 7658                                                    )),
 7659                                            )
 7660                                            .child(div().w_full().children(self.render_dock(
 7661                                                DockPosition::Bottom,
 7662                                                &self.bottom_dock,
 7663                                                window,
 7664                                                cx
 7665                                            ))),
 7666
 7667                                        BottomDockLayout::LeftAligned => div()
 7668                                            .flex()
 7669                                            .flex_row()
 7670                                            .h_full()
 7671                                            .child(
 7672                                                div()
 7673                                                    .flex()
 7674                                                    .flex_col()
 7675                                                    .flex_1()
 7676                                                    .h_full()
 7677                                                    .child(
 7678                                                        div()
 7679                                                            .flex()
 7680                                                            .flex_row()
 7681                                                            .flex_1()
 7682                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 7683
 7684                                                            .child(
 7685                                                                div()
 7686                                                                    .flex()
 7687                                                                    .flex_col()
 7688                                                                    .flex_1()
 7689                                                                    .overflow_hidden()
 7690                                                                    .child(
 7691                                                                        h_flex()
 7692                                                                            .flex_1()
 7693                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7694                                                                            .child(self.center.render(
 7695                                                                                self.zoomed.as_ref(),
 7696                                                                                &PaneRenderContext {
 7697                                                                                    follower_states:
 7698                                                                                        &self.follower_states,
 7699                                                                                    active_call: self.active_call(),
 7700                                                                                    active_pane: &self.active_pane,
 7701                                                                                    app_state: &self.app_state,
 7702                                                                                    project: &self.project,
 7703                                                                                    workspace: &self.weak_self,
 7704                                                                                },
 7705                                                                                window,
 7706                                                                                cx,
 7707                                                                            ))
 7708                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7709                                                                    )
 7710                                                            )
 7711
 7712                                                    )
 7713                                                    .child(
 7714                                                        div()
 7715                                                            .w_full()
 7716                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7717                                                    ),
 7718                                            )
 7719                                            .children(self.render_dock(
 7720                                                DockPosition::Right,
 7721                                                &self.right_dock,
 7722                                                window,
 7723                                                cx,
 7724                                            )),
 7725
 7726                                        BottomDockLayout::RightAligned => div()
 7727                                            .flex()
 7728                                            .flex_row()
 7729                                            .h_full()
 7730                                            .children(self.render_dock(
 7731                                                DockPosition::Left,
 7732                                                &self.left_dock,
 7733                                                window,
 7734                                                cx,
 7735                                            ))
 7736
 7737                                            .child(
 7738                                                div()
 7739                                                    .flex()
 7740                                                    .flex_col()
 7741                                                    .flex_1()
 7742                                                    .h_full()
 7743                                                    .child(
 7744                                                        div()
 7745                                                            .flex()
 7746                                                            .flex_row()
 7747                                                            .flex_1()
 7748                                                            .child(
 7749                                                                div()
 7750                                                                    .flex()
 7751                                                                    .flex_col()
 7752                                                                    .flex_1()
 7753                                                                    .overflow_hidden()
 7754                                                                    .child(
 7755                                                                        h_flex()
 7756                                                                            .flex_1()
 7757                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7758                                                                            .child(self.center.render(
 7759                                                                                self.zoomed.as_ref(),
 7760                                                                                &PaneRenderContext {
 7761                                                                                    follower_states:
 7762                                                                                        &self.follower_states,
 7763                                                                                    active_call: self.active_call(),
 7764                                                                                    active_pane: &self.active_pane,
 7765                                                                                    app_state: &self.app_state,
 7766                                                                                    project: &self.project,
 7767                                                                                    workspace: &self.weak_self,
 7768                                                                                },
 7769                                                                                window,
 7770                                                                                cx,
 7771                                                                            ))
 7772                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7773                                                                    )
 7774                                                            )
 7775
 7776                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 7777                                                    )
 7778                                                    .child(
 7779                                                        div()
 7780                                                            .w_full()
 7781                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7782                                                    ),
 7783                                            ),
 7784
 7785                                        BottomDockLayout::Contained => div()
 7786                                            .flex()
 7787                                            .flex_row()
 7788                                            .h_full()
 7789                                            .children(self.render_dock(
 7790                                                DockPosition::Left,
 7791                                                &self.left_dock,
 7792                                                window,
 7793                                                cx,
 7794                                            ))
 7795
 7796                                            .child(
 7797                                                div()
 7798                                                    .flex()
 7799                                                    .flex_col()
 7800                                                    .flex_1()
 7801                                                    .overflow_hidden()
 7802                                                    .child(
 7803                                                        h_flex()
 7804                                                            .flex_1()
 7805                                                            .when_some(paddings.0, |this, p| {
 7806                                                                this.child(p.border_r_1())
 7807                                                            })
 7808                                                            .child(self.center.render(
 7809                                                                self.zoomed.as_ref(),
 7810                                                                &PaneRenderContext {
 7811                                                                    follower_states:
 7812                                                                        &self.follower_states,
 7813                                                                    active_call: self.active_call(),
 7814                                                                    active_pane: &self.active_pane,
 7815                                                                    app_state: &self.app_state,
 7816                                                                    project: &self.project,
 7817                                                                    workspace: &self.weak_self,
 7818                                                                },
 7819                                                                window,
 7820                                                                cx,
 7821                                                            ))
 7822                                                            .when_some(paddings.1, |this, p| {
 7823                                                                this.child(p.border_l_1())
 7824                                                            }),
 7825                                                    )
 7826                                                    .children(self.render_dock(
 7827                                                        DockPosition::Bottom,
 7828                                                        &self.bottom_dock,
 7829                                                        window,
 7830                                                        cx,
 7831                                                    )),
 7832                                            )
 7833
 7834                                            .children(self.render_dock(
 7835                                                DockPosition::Right,
 7836                                                &self.right_dock,
 7837                                                window,
 7838                                                cx,
 7839                                            )),
 7840                                    }
 7841                                })
 7842                                .children(self.zoomed.as_ref().and_then(|view| {
 7843                                    let zoomed_view = view.upgrade()?;
 7844                                    let div = div()
 7845                                        .occlude()
 7846                                        .absolute()
 7847                                        .overflow_hidden()
 7848                                        .border_color(colors.border)
 7849                                        .bg(colors.background)
 7850                                        .child(zoomed_view)
 7851                                        .inset_0()
 7852                                        .shadow_lg();
 7853
 7854                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 7855                                       return Some(div);
 7856                                    }
 7857
 7858                                    Some(match self.zoomed_position {
 7859                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 7860                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 7861                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 7862                                        None => {
 7863                                            div.top_2().bottom_2().left_2().right_2().border_1()
 7864                                        }
 7865                                    })
 7866                                }))
 7867                                .children(self.render_notifications(window, cx)),
 7868                        )
 7869                        .when(self.status_bar_visible(cx), |parent| {
 7870                            parent.child(self.status_bar.clone())
 7871                        })
 7872                        .child(self.toast_layer.clone()),
 7873                )
 7874    }
 7875}
 7876
 7877impl WorkspaceStore {
 7878    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 7879        Self {
 7880            workspaces: Default::default(),
 7881            _subscriptions: vec![
 7882                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 7883                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 7884            ],
 7885            client,
 7886        }
 7887    }
 7888
 7889    pub fn update_followers(
 7890        &self,
 7891        project_id: Option<u64>,
 7892        update: proto::update_followers::Variant,
 7893        cx: &App,
 7894    ) -> Option<()> {
 7895        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 7896        let room_id = active_call.0.room_id(cx)?;
 7897        self.client
 7898            .send(proto::UpdateFollowers {
 7899                room_id,
 7900                project_id,
 7901                variant: Some(update),
 7902            })
 7903            .log_err()
 7904    }
 7905
 7906    pub async fn handle_follow(
 7907        this: Entity<Self>,
 7908        envelope: TypedEnvelope<proto::Follow>,
 7909        mut cx: AsyncApp,
 7910    ) -> Result<proto::FollowResponse> {
 7911        this.update(&mut cx, |this, cx| {
 7912            let follower = Follower {
 7913                project_id: envelope.payload.project_id,
 7914                peer_id: envelope.original_sender_id()?,
 7915            };
 7916
 7917            let mut response = proto::FollowResponse::default();
 7918
 7919            this.workspaces.retain(|(window_handle, weak_workspace)| {
 7920                let Some(workspace) = weak_workspace.upgrade() else {
 7921                    return false;
 7922                };
 7923                window_handle
 7924                    .update(cx, |_, window, cx| {
 7925                        workspace.update(cx, |workspace, cx| {
 7926                            let handler_response =
 7927                                workspace.handle_follow(follower.project_id, window, cx);
 7928                            if let Some(active_view) = handler_response.active_view
 7929                                && workspace.project.read(cx).remote_id() == follower.project_id
 7930                            {
 7931                                response.active_view = Some(active_view)
 7932                            }
 7933                        });
 7934                    })
 7935                    .is_ok()
 7936            });
 7937
 7938            Ok(response)
 7939        })
 7940    }
 7941
 7942    async fn handle_update_followers(
 7943        this: Entity<Self>,
 7944        envelope: TypedEnvelope<proto::UpdateFollowers>,
 7945        mut cx: AsyncApp,
 7946    ) -> Result<()> {
 7947        let leader_id = envelope.original_sender_id()?;
 7948        let update = envelope.payload;
 7949
 7950        this.update(&mut cx, |this, cx| {
 7951            this.workspaces.retain(|(window_handle, weak_workspace)| {
 7952                let Some(workspace) = weak_workspace.upgrade() else {
 7953                    return false;
 7954                };
 7955                window_handle
 7956                    .update(cx, |_, window, cx| {
 7957                        workspace.update(cx, |workspace, cx| {
 7958                            let project_id = workspace.project.read(cx).remote_id();
 7959                            if update.project_id != project_id && update.project_id.is_some() {
 7960                                return;
 7961                            }
 7962                            workspace.handle_update_followers(
 7963                                leader_id,
 7964                                update.clone(),
 7965                                window,
 7966                                cx,
 7967                            );
 7968                        });
 7969                    })
 7970                    .is_ok()
 7971            });
 7972            Ok(())
 7973        })
 7974    }
 7975
 7976    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 7977        self.workspaces.iter().map(|(_, weak)| weak)
 7978    }
 7979
 7980    pub fn workspaces_with_windows(
 7981        &self,
 7982    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 7983        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 7984    }
 7985}
 7986
 7987impl ViewId {
 7988    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 7989        Ok(Self {
 7990            creator: message
 7991                .creator
 7992                .map(CollaboratorId::PeerId)
 7993                .context("creator is missing")?,
 7994            id: message.id,
 7995        })
 7996    }
 7997
 7998    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 7999        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8000            Some(proto::ViewId {
 8001                creator: Some(peer_id),
 8002                id: self.id,
 8003            })
 8004        } else {
 8005            None
 8006        }
 8007    }
 8008}
 8009
 8010impl FollowerState {
 8011    fn pane(&self) -> &Entity<Pane> {
 8012        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8013    }
 8014}
 8015
 8016pub trait WorkspaceHandle {
 8017    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8018}
 8019
 8020impl WorkspaceHandle for Entity<Workspace> {
 8021    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8022        self.read(cx)
 8023            .worktrees(cx)
 8024            .flat_map(|worktree| {
 8025                let worktree_id = worktree.read(cx).id();
 8026                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8027                    worktree_id,
 8028                    path: f.path.clone(),
 8029                })
 8030            })
 8031            .collect::<Vec<_>>()
 8032    }
 8033}
 8034
 8035pub async fn last_opened_workspace_location(
 8036    fs: &dyn fs::Fs,
 8037) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8038    DB.last_workspace(fs)
 8039        .await
 8040        .log_err()
 8041        .flatten()
 8042        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8043}
 8044
 8045pub async fn last_session_workspace_locations(
 8046    last_session_id: &str,
 8047    last_session_window_stack: Option<Vec<WindowId>>,
 8048    fs: &dyn fs::Fs,
 8049) -> Option<Vec<SessionWorkspace>> {
 8050    DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8051        .await
 8052        .log_err()
 8053}
 8054
 8055pub struct MultiWorkspaceRestoreResult {
 8056    pub window_handle: WindowHandle<MultiWorkspace>,
 8057    pub errors: Vec<anyhow::Error>,
 8058}
 8059
 8060pub async fn restore_multiworkspace(
 8061    multi_workspace: SerializedMultiWorkspace,
 8062    app_state: Arc<AppState>,
 8063    cx: &mut AsyncApp,
 8064) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8065    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8066    let mut group_iter = workspaces.into_iter();
 8067    let first = group_iter
 8068        .next()
 8069        .context("window group must not be empty")?;
 8070
 8071    let window_handle = if first.paths.is_empty() {
 8072        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8073            .await?
 8074    } else {
 8075        let (window, _items) = cx
 8076            .update(|cx| {
 8077                Workspace::new_local(
 8078                    first.paths.paths().to_vec(),
 8079                    app_state.clone(),
 8080                    None,
 8081                    None,
 8082                    None,
 8083                    cx,
 8084                )
 8085            })
 8086            .await?;
 8087        window
 8088    };
 8089
 8090    let mut errors = Vec::new();
 8091
 8092    for session_workspace in group_iter {
 8093        let error = if session_workspace.paths.is_empty() {
 8094            cx.update(|cx| {
 8095                open_workspace_by_id(
 8096                    session_workspace.workspace_id,
 8097                    app_state.clone(),
 8098                    Some(window_handle),
 8099                    cx,
 8100                )
 8101            })
 8102            .await
 8103            .err()
 8104        } else {
 8105            cx.update(|cx| {
 8106                Workspace::new_local(
 8107                    session_workspace.paths.paths().to_vec(),
 8108                    app_state.clone(),
 8109                    Some(window_handle),
 8110                    None,
 8111                    None,
 8112                    cx,
 8113                )
 8114            })
 8115            .await
 8116            .err()
 8117        };
 8118
 8119        if let Some(error) = error {
 8120            errors.push(error);
 8121        }
 8122    }
 8123
 8124    if let Some(target_id) = state.active_workspace_id {
 8125        window_handle
 8126            .update(cx, |multi_workspace, window, cx| {
 8127                let target_index = multi_workspace
 8128                    .workspaces()
 8129                    .iter()
 8130                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8131                if let Some(index) = target_index {
 8132                    multi_workspace.activate_index(index, window, cx);
 8133                } else if !multi_workspace.workspaces().is_empty() {
 8134                    multi_workspace.activate_index(0, window, cx);
 8135                }
 8136            })
 8137            .ok();
 8138    } else {
 8139        window_handle
 8140            .update(cx, |multi_workspace, window, cx| {
 8141                if !multi_workspace.workspaces().is_empty() {
 8142                    multi_workspace.activate_index(0, window, cx);
 8143                }
 8144            })
 8145            .ok();
 8146    }
 8147
 8148    if state.sidebar_open {
 8149        window_handle
 8150            .update(cx, |multi_workspace, _, cx| {
 8151                multi_workspace.open_sidebar(cx);
 8152            })
 8153            .ok();
 8154    }
 8155
 8156    window_handle
 8157        .update(cx, |_, window, _cx| {
 8158            window.activate_window();
 8159        })
 8160        .ok();
 8161
 8162    Ok(MultiWorkspaceRestoreResult {
 8163        window_handle,
 8164        errors,
 8165    })
 8166}
 8167
 8168actions!(
 8169    collab,
 8170    [
 8171        /// Opens the channel notes for the current call.
 8172        ///
 8173        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8174        /// channel in the collab panel.
 8175        ///
 8176        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8177        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8178        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8179        OpenChannelNotes,
 8180        /// Mutes your microphone.
 8181        Mute,
 8182        /// Deafens yourself (mute both microphone and speakers).
 8183        Deafen,
 8184        /// Leaves the current call.
 8185        LeaveCall,
 8186        /// Shares the current project with collaborators.
 8187        ShareProject,
 8188        /// Shares your screen with collaborators.
 8189        ScreenShare,
 8190        /// Copies the current room name and session id for debugging purposes.
 8191        CopyRoomId,
 8192    ]
 8193);
 8194actions!(
 8195    zed,
 8196    [
 8197        /// Opens the Zed log file.
 8198        OpenLog,
 8199        /// Reveals the Zed log file in the system file manager.
 8200        RevealLogInFileManager
 8201    ]
 8202);
 8203
 8204async fn join_channel_internal(
 8205    channel_id: ChannelId,
 8206    app_state: &Arc<AppState>,
 8207    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8208    requesting_workspace: Option<WeakEntity<Workspace>>,
 8209    active_call: &dyn AnyActiveCall,
 8210    cx: &mut AsyncApp,
 8211) -> Result<bool> {
 8212    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8213        if !active_call.is_in_room(cx) {
 8214            return (false, false);
 8215        }
 8216
 8217        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8218        let should_prompt = active_call.is_sharing_project(cx)
 8219            && active_call.has_remote_participants(cx)
 8220            && !already_in_channel;
 8221        (should_prompt, already_in_channel)
 8222    });
 8223
 8224    if already_in_channel {
 8225        let task = cx.update(|cx| {
 8226            if let Some((project, host)) = active_call.most_active_project(cx) {
 8227                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8228            } else {
 8229                None
 8230            }
 8231        });
 8232        if let Some(task) = task {
 8233            task.await?;
 8234        }
 8235        return anyhow::Ok(true);
 8236    }
 8237
 8238    if should_prompt {
 8239        if let Some(multi_workspace) = requesting_window {
 8240            let answer = multi_workspace
 8241                .update(cx, |_, window, cx| {
 8242                    window.prompt(
 8243                        PromptLevel::Warning,
 8244                        "Do you want to switch channels?",
 8245                        Some("Leaving this call will unshare your current project."),
 8246                        &["Yes, Join Channel", "Cancel"],
 8247                        cx,
 8248                    )
 8249                })?
 8250                .await;
 8251
 8252            if answer == Ok(1) {
 8253                return Ok(false);
 8254            }
 8255        } else {
 8256            return Ok(false);
 8257        }
 8258    }
 8259
 8260    let client = cx.update(|cx| active_call.client(cx));
 8261
 8262    let mut client_status = client.status();
 8263
 8264    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8265    'outer: loop {
 8266        let Some(status) = client_status.recv().await else {
 8267            anyhow::bail!("error connecting");
 8268        };
 8269
 8270        match status {
 8271            Status::Connecting
 8272            | Status::Authenticating
 8273            | Status::Authenticated
 8274            | Status::Reconnecting
 8275            | Status::Reauthenticating
 8276            | Status::Reauthenticated => continue,
 8277            Status::Connected { .. } => break 'outer,
 8278            Status::SignedOut | Status::AuthenticationError => {
 8279                return Err(ErrorCode::SignedOut.into());
 8280            }
 8281            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8282            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8283                return Err(ErrorCode::Disconnected.into());
 8284            }
 8285        }
 8286    }
 8287
 8288    let joined = cx
 8289        .update(|cx| active_call.join_channel(channel_id, cx))
 8290        .await?;
 8291
 8292    if !joined {
 8293        return anyhow::Ok(true);
 8294    }
 8295
 8296    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8297
 8298    let task = cx.update(|cx| {
 8299        if let Some((project, host)) = active_call.most_active_project(cx) {
 8300            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8301        }
 8302
 8303        // If you are the first to join a channel, see if you should share your project.
 8304        if !active_call.has_remote_participants(cx)
 8305            && !active_call.local_participant_is_guest(cx)
 8306            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8307        {
 8308            let project = workspace.update(cx, |workspace, cx| {
 8309                let project = workspace.project.read(cx);
 8310
 8311                if !active_call.share_on_join(cx) {
 8312                    return None;
 8313                }
 8314
 8315                if (project.is_local() || project.is_via_remote_server())
 8316                    && project.visible_worktrees(cx).any(|tree| {
 8317                        tree.read(cx)
 8318                            .root_entry()
 8319                            .is_some_and(|entry| entry.is_dir())
 8320                    })
 8321                {
 8322                    Some(workspace.project.clone())
 8323                } else {
 8324                    None
 8325                }
 8326            });
 8327            if let Some(project) = project {
 8328                let share_task = active_call.share_project(project, cx);
 8329                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8330                    share_task.await?;
 8331                    Ok(())
 8332                }));
 8333            }
 8334        }
 8335
 8336        None
 8337    });
 8338    if let Some(task) = task {
 8339        task.await?;
 8340        return anyhow::Ok(true);
 8341    }
 8342    anyhow::Ok(false)
 8343}
 8344
 8345pub fn join_channel(
 8346    channel_id: ChannelId,
 8347    app_state: Arc<AppState>,
 8348    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8349    requesting_workspace: Option<WeakEntity<Workspace>>,
 8350    cx: &mut App,
 8351) -> Task<Result<()>> {
 8352    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8353    cx.spawn(async move |cx| {
 8354        let result = join_channel_internal(
 8355            channel_id,
 8356            &app_state,
 8357            requesting_window,
 8358            requesting_workspace,
 8359            &*active_call.0,
 8360            cx,
 8361        )
 8362        .await;
 8363
 8364        // join channel succeeded, and opened a window
 8365        if matches!(result, Ok(true)) {
 8366            return anyhow::Ok(());
 8367        }
 8368
 8369        // find an existing workspace to focus and show call controls
 8370        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8371        if active_window.is_none() {
 8372            // no open workspaces, make one to show the error in (blergh)
 8373            let (window_handle, _) = cx
 8374                .update(|cx| {
 8375                    Workspace::new_local(
 8376                        vec![],
 8377                        app_state.clone(),
 8378                        requesting_window,
 8379                        None,
 8380                        None,
 8381                        cx,
 8382                    )
 8383                })
 8384                .await?;
 8385
 8386            window_handle
 8387                .update(cx, |_, window, _cx| {
 8388                    window.activate_window();
 8389                })
 8390                .ok();
 8391
 8392            if result.is_ok() {
 8393                cx.update(|cx| {
 8394                    cx.dispatch_action(&OpenChannelNotes);
 8395                });
 8396            }
 8397
 8398            active_window = Some(window_handle);
 8399        }
 8400
 8401        if let Err(err) = result {
 8402            log::error!("failed to join channel: {}", err);
 8403            if let Some(active_window) = active_window {
 8404                active_window
 8405                    .update(cx, |_, window, cx| {
 8406                        let detail: SharedString = match err.error_code() {
 8407                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8408                            ErrorCode::UpgradeRequired => concat!(
 8409                                "Your are running an unsupported version of Zed. ",
 8410                                "Please update to continue."
 8411                            )
 8412                            .into(),
 8413                            ErrorCode::NoSuchChannel => concat!(
 8414                                "No matching channel was found. ",
 8415                                "Please check the link and try again."
 8416                            )
 8417                            .into(),
 8418                            ErrorCode::Forbidden => concat!(
 8419                                "This channel is private, and you do not have access. ",
 8420                                "Please ask someone to add you and try again."
 8421                            )
 8422                            .into(),
 8423                            ErrorCode::Disconnected => {
 8424                                "Please check your internet connection and try again.".into()
 8425                            }
 8426                            _ => format!("{}\n\nPlease try again.", err).into(),
 8427                        };
 8428                        window.prompt(
 8429                            PromptLevel::Critical,
 8430                            "Failed to join channel",
 8431                            Some(&detail),
 8432                            &["Ok"],
 8433                            cx,
 8434                        )
 8435                    })?
 8436                    .await
 8437                    .ok();
 8438            }
 8439        }
 8440
 8441        // return ok, we showed the error to the user.
 8442        anyhow::Ok(())
 8443    })
 8444}
 8445
 8446pub async fn get_any_active_multi_workspace(
 8447    app_state: Arc<AppState>,
 8448    mut cx: AsyncApp,
 8449) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8450    // find an existing workspace to focus and show call controls
 8451    let active_window = activate_any_workspace_window(&mut cx);
 8452    if active_window.is_none() {
 8453        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, cx))
 8454            .await?;
 8455    }
 8456    activate_any_workspace_window(&mut cx).context("could not open zed")
 8457}
 8458
 8459fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8460    cx.update(|cx| {
 8461        if let Some(workspace_window) = cx
 8462            .active_window()
 8463            .and_then(|window| window.downcast::<MultiWorkspace>())
 8464        {
 8465            return Some(workspace_window);
 8466        }
 8467
 8468        for window in cx.windows() {
 8469            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8470                workspace_window
 8471                    .update(cx, |_, window, _| window.activate_window())
 8472                    .ok();
 8473                return Some(workspace_window);
 8474            }
 8475        }
 8476        None
 8477    })
 8478}
 8479
 8480pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8481    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8482}
 8483
 8484pub fn workspace_windows_for_location(
 8485    serialized_location: &SerializedWorkspaceLocation,
 8486    cx: &App,
 8487) -> Vec<WindowHandle<MultiWorkspace>> {
 8488    cx.windows()
 8489        .into_iter()
 8490        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8491        .filter(|multi_workspace| {
 8492            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 8493                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 8494                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 8495                }
 8496                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 8497                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 8498                    a.distro_name == b.distro_name
 8499                }
 8500                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 8501                    a.container_id == b.container_id
 8502                }
 8503                #[cfg(any(test, feature = "test-support"))]
 8504                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 8505                    a.id == b.id
 8506                }
 8507                _ => false,
 8508            };
 8509
 8510            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 8511                multi_workspace.workspaces().iter().any(|workspace| {
 8512                    match workspace.read(cx).workspace_location(cx) {
 8513                        WorkspaceLocation::Location(location, _) => {
 8514                            match (&location, serialized_location) {
 8515                                (
 8516                                    SerializedWorkspaceLocation::Local,
 8517                                    SerializedWorkspaceLocation::Local,
 8518                                ) => true,
 8519                                (
 8520                                    SerializedWorkspaceLocation::Remote(a),
 8521                                    SerializedWorkspaceLocation::Remote(b),
 8522                                ) => same_host(a, b),
 8523                                _ => false,
 8524                            }
 8525                        }
 8526                        _ => false,
 8527                    }
 8528                })
 8529            })
 8530        })
 8531        .collect()
 8532}
 8533
 8534pub async fn find_existing_workspace(
 8535    abs_paths: &[PathBuf],
 8536    open_options: &OpenOptions,
 8537    location: &SerializedWorkspaceLocation,
 8538    cx: &mut AsyncApp,
 8539) -> (
 8540    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 8541    OpenVisible,
 8542) {
 8543    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 8544    let mut open_visible = OpenVisible::All;
 8545    let mut best_match = None;
 8546
 8547    if open_options.open_new_workspace != Some(true) {
 8548        cx.update(|cx| {
 8549            for window in workspace_windows_for_location(location, cx) {
 8550                if let Ok(multi_workspace) = window.read(cx) {
 8551                    for workspace in multi_workspace.workspaces() {
 8552                        let project = workspace.read(cx).project.read(cx);
 8553                        let m = project.visibility_for_paths(
 8554                            abs_paths,
 8555                            open_options.open_new_workspace == None,
 8556                            cx,
 8557                        );
 8558                        if m > best_match {
 8559                            existing = Some((window, workspace.clone()));
 8560                            best_match = m;
 8561                        } else if best_match.is_none()
 8562                            && open_options.open_new_workspace == Some(false)
 8563                        {
 8564                            existing = Some((window, workspace.clone()))
 8565                        }
 8566                    }
 8567                }
 8568            }
 8569        });
 8570
 8571        let all_paths_are_files = existing
 8572            .as_ref()
 8573            .and_then(|(_, target_workspace)| {
 8574                cx.update(|cx| {
 8575                    let workspace = target_workspace.read(cx);
 8576                    let project = workspace.project.read(cx);
 8577                    let path_style = workspace.path_style(cx);
 8578                    Some(!abs_paths.iter().any(|path| {
 8579                        let path = util::paths::SanitizedPath::new(path);
 8580                        project.worktrees(cx).any(|worktree| {
 8581                            let worktree = worktree.read(cx);
 8582                            let abs_path = worktree.abs_path();
 8583                            path_style
 8584                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 8585                                .and_then(|rel| worktree.entry_for_path(&rel))
 8586                                .is_some_and(|e| e.is_dir())
 8587                        })
 8588                    }))
 8589                })
 8590            })
 8591            .unwrap_or(false);
 8592
 8593        if open_options.open_new_workspace.is_none()
 8594            && existing.is_some()
 8595            && open_options.wait
 8596            && all_paths_are_files
 8597        {
 8598            cx.update(|cx| {
 8599                let windows = workspace_windows_for_location(location, cx);
 8600                let window = cx
 8601                    .active_window()
 8602                    .and_then(|window| window.downcast::<MultiWorkspace>())
 8603                    .filter(|window| windows.contains(window))
 8604                    .or_else(|| windows.into_iter().next());
 8605                if let Some(window) = window {
 8606                    if let Ok(multi_workspace) = window.read(cx) {
 8607                        let active_workspace = multi_workspace.workspace().clone();
 8608                        existing = Some((window, active_workspace));
 8609                        open_visible = OpenVisible::None;
 8610                    }
 8611                }
 8612            });
 8613        }
 8614    }
 8615    (existing, open_visible)
 8616}
 8617
 8618#[derive(Default, Clone)]
 8619pub struct OpenOptions {
 8620    pub visible: Option<OpenVisible>,
 8621    pub focus: Option<bool>,
 8622    pub open_new_workspace: Option<bool>,
 8623    pub wait: bool,
 8624    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 8625    pub env: Option<HashMap<String, String>>,
 8626}
 8627
 8628/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 8629pub fn open_workspace_by_id(
 8630    workspace_id: WorkspaceId,
 8631    app_state: Arc<AppState>,
 8632    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8633    cx: &mut App,
 8634) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 8635    let project_handle = Project::local(
 8636        app_state.client.clone(),
 8637        app_state.node_runtime.clone(),
 8638        app_state.user_store.clone(),
 8639        app_state.languages.clone(),
 8640        app_state.fs.clone(),
 8641        None,
 8642        project::LocalProjectFlags {
 8643            init_worktree_trust: true,
 8644            ..project::LocalProjectFlags::default()
 8645        },
 8646        cx,
 8647    );
 8648
 8649    cx.spawn(async move |cx| {
 8650        let serialized_workspace = persistence::DB
 8651            .workspace_for_id(workspace_id)
 8652            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 8653
 8654        let centered_layout = serialized_workspace.centered_layout;
 8655
 8656        let (window, workspace) = if let Some(window) = requesting_window {
 8657            let workspace = window.update(cx, |multi_workspace, window, cx| {
 8658                let workspace = cx.new(|cx| {
 8659                    let mut workspace = Workspace::new(
 8660                        Some(workspace_id),
 8661                        project_handle.clone(),
 8662                        app_state.clone(),
 8663                        window,
 8664                        cx,
 8665                    );
 8666                    workspace.centered_layout = centered_layout;
 8667                    workspace
 8668                });
 8669                multi_workspace.add_workspace(workspace.clone(), cx);
 8670                workspace
 8671            })?;
 8672            (window, workspace)
 8673        } else {
 8674            let window_bounds_override = window_bounds_env_override();
 8675
 8676            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 8677                (Some(WindowBounds::Windowed(bounds)), None)
 8678            } else if let Some(display) = serialized_workspace.display
 8679                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 8680            {
 8681                (Some(bounds.0), Some(display))
 8682            } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
 8683                (Some(bounds), Some(display))
 8684            } else {
 8685                (None, None)
 8686            };
 8687
 8688            let options = cx.update(|cx| {
 8689                let mut options = (app_state.build_window_options)(display, cx);
 8690                options.window_bounds = window_bounds;
 8691                options
 8692            });
 8693
 8694            let window = cx.open_window(options, {
 8695                let app_state = app_state.clone();
 8696                let project_handle = project_handle.clone();
 8697                move |window, cx| {
 8698                    let workspace = cx.new(|cx| {
 8699                        let mut workspace = Workspace::new(
 8700                            Some(workspace_id),
 8701                            project_handle,
 8702                            app_state,
 8703                            window,
 8704                            cx,
 8705                        );
 8706                        workspace.centered_layout = centered_layout;
 8707                        workspace
 8708                    });
 8709                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 8710                }
 8711            })?;
 8712
 8713            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 8714                multi_workspace.workspace().clone()
 8715            })?;
 8716
 8717            (window, workspace)
 8718        };
 8719
 8720        notify_if_database_failed(window, cx);
 8721
 8722        // Restore items from the serialized workspace
 8723        window
 8724            .update(cx, |_, window, cx| {
 8725                workspace.update(cx, |_workspace, cx| {
 8726                    open_items(Some(serialized_workspace), vec![], window, cx)
 8727                })
 8728            })?
 8729            .await?;
 8730
 8731        window.update(cx, |_, window, cx| {
 8732            workspace.update(cx, |workspace, cx| {
 8733                workspace.serialize_workspace(window, cx);
 8734            });
 8735        })?;
 8736
 8737        Ok(window)
 8738    })
 8739}
 8740
 8741#[allow(clippy::type_complexity)]
 8742pub fn open_paths(
 8743    abs_paths: &[PathBuf],
 8744    app_state: Arc<AppState>,
 8745    open_options: OpenOptions,
 8746    cx: &mut App,
 8747) -> Task<
 8748    anyhow::Result<(
 8749        WindowHandle<MultiWorkspace>,
 8750        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 8751    )>,
 8752> {
 8753    let abs_paths = abs_paths.to_vec();
 8754    #[cfg(target_os = "windows")]
 8755    let wsl_path = abs_paths
 8756        .iter()
 8757        .find_map(|p| util::paths::WslPath::from_path(p));
 8758
 8759    cx.spawn(async move |cx| {
 8760        let (mut existing, mut open_visible) = find_existing_workspace(
 8761            &abs_paths,
 8762            &open_options,
 8763            &SerializedWorkspaceLocation::Local,
 8764            cx,
 8765        )
 8766        .await;
 8767
 8768        // Fallback: if no workspace contains the paths and all paths are files,
 8769        // prefer an existing local workspace window (active window first).
 8770        if open_options.open_new_workspace.is_none() && existing.is_none() {
 8771            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 8772            let all_metadatas = futures::future::join_all(all_paths)
 8773                .await
 8774                .into_iter()
 8775                .filter_map(|result| result.ok().flatten())
 8776                .collect::<Vec<_>>();
 8777
 8778            if all_metadatas.iter().all(|file| !file.is_dir) {
 8779                cx.update(|cx| {
 8780                    let windows = workspace_windows_for_location(
 8781                        &SerializedWorkspaceLocation::Local,
 8782                        cx,
 8783                    );
 8784                    let window = cx
 8785                        .active_window()
 8786                        .and_then(|window| window.downcast::<MultiWorkspace>())
 8787                        .filter(|window| windows.contains(window))
 8788                        .or_else(|| windows.into_iter().next());
 8789                    if let Some(window) = window {
 8790                        if let Ok(multi_workspace) = window.read(cx) {
 8791                            let active_workspace = multi_workspace.workspace().clone();
 8792                            existing = Some((window, active_workspace));
 8793                            open_visible = OpenVisible::None;
 8794                        }
 8795                    }
 8796                });
 8797            }
 8798        }
 8799
 8800        let result = if let Some((existing, target_workspace)) = existing {
 8801            let open_task = existing
 8802                .update(cx, |multi_workspace, window, cx| {
 8803                    window.activate_window();
 8804                    multi_workspace.activate(target_workspace.clone(), cx);
 8805                    target_workspace.update(cx, |workspace, cx| {
 8806                        workspace.open_paths(
 8807                            abs_paths,
 8808                            OpenOptions {
 8809                                visible: Some(open_visible),
 8810                                ..Default::default()
 8811                            },
 8812                            None,
 8813                            window,
 8814                            cx,
 8815                        )
 8816                    })
 8817                })?
 8818                .await;
 8819
 8820            _ = existing.update(cx, |multi_workspace, _, cx| {
 8821                let workspace = multi_workspace.workspace().clone();
 8822                workspace.update(cx, |workspace, cx| {
 8823                    for item in open_task.iter().flatten() {
 8824                        if let Err(e) = item {
 8825                            workspace.show_error(&e, cx);
 8826                        }
 8827                    }
 8828                });
 8829            });
 8830
 8831            Ok((existing, open_task))
 8832        } else {
 8833            let result = cx
 8834                .update(move |cx| {
 8835                    Workspace::new_local(
 8836                        abs_paths,
 8837                        app_state.clone(),
 8838                        open_options.replace_window,
 8839                        open_options.env,
 8840                        None,
 8841                        cx,
 8842                    )
 8843                })
 8844                .await;
 8845
 8846            if let Ok((ref window_handle, _)) = result {
 8847                window_handle
 8848                    .update(cx, |_, window, _cx| {
 8849                        window.activate_window();
 8850                    })
 8851                    .log_err();
 8852            }
 8853
 8854            result
 8855        };
 8856
 8857        #[cfg(target_os = "windows")]
 8858        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 8859            && let Ok((multi_workspace_window, _)) = &result
 8860        {
 8861            multi_workspace_window
 8862                .update(cx, move |multi_workspace, _window, cx| {
 8863                    struct OpenInWsl;
 8864                    let workspace = multi_workspace.workspace().clone();
 8865                    workspace.update(cx, |workspace, cx| {
 8866                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 8867                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 8868                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 8869                            cx.new(move |cx| {
 8870                                MessageNotification::new(msg, cx)
 8871                                    .primary_message("Open in WSL")
 8872                                    .primary_icon(IconName::FolderOpen)
 8873                                    .primary_on_click(move |window, cx| {
 8874                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 8875                                                distro: remote::WslConnectionOptions {
 8876                                                        distro_name: distro.clone(),
 8877                                                    user: None,
 8878                                                },
 8879                                                paths: vec![path.clone().into()],
 8880                                            }), cx)
 8881                                    })
 8882                            })
 8883                        });
 8884                    });
 8885                })
 8886                .unwrap();
 8887        };
 8888        result
 8889    })
 8890}
 8891
 8892pub fn open_new(
 8893    open_options: OpenOptions,
 8894    app_state: Arc<AppState>,
 8895    cx: &mut App,
 8896    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 8897) -> Task<anyhow::Result<()>> {
 8898    let task = Workspace::new_local(
 8899        Vec::new(),
 8900        app_state,
 8901        open_options.replace_window,
 8902        open_options.env,
 8903        Some(Box::new(init)),
 8904        cx,
 8905    );
 8906    cx.spawn(async move |cx| {
 8907        let (window, _opened_paths) = task.await?;
 8908        window
 8909            .update(cx, |_, window, _cx| {
 8910                window.activate_window();
 8911            })
 8912            .ok();
 8913        Ok(())
 8914    })
 8915}
 8916
 8917pub fn create_and_open_local_file(
 8918    path: &'static Path,
 8919    window: &mut Window,
 8920    cx: &mut Context<Workspace>,
 8921    default_content: impl 'static + Send + FnOnce() -> Rope,
 8922) -> Task<Result<Box<dyn ItemHandle>>> {
 8923    cx.spawn_in(window, async move |workspace, cx| {
 8924        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 8925        if !fs.is_file(path).await {
 8926            fs.create_file(path, Default::default()).await?;
 8927            fs.save(path, &default_content(), Default::default())
 8928                .await?;
 8929        }
 8930
 8931        workspace
 8932            .update_in(cx, |workspace, window, cx| {
 8933                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 8934                    let path = workspace
 8935                        .project
 8936                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 8937                    cx.spawn_in(window, async move |workspace, cx| {
 8938                        let path = path.await?;
 8939                        let mut items = workspace
 8940                            .update_in(cx, |workspace, window, cx| {
 8941                                workspace.open_paths(
 8942                                    vec![path.to_path_buf()],
 8943                                    OpenOptions {
 8944                                        visible: Some(OpenVisible::None),
 8945                                        ..Default::default()
 8946                                    },
 8947                                    None,
 8948                                    window,
 8949                                    cx,
 8950                                )
 8951                            })?
 8952                            .await;
 8953                        let item = items.pop().flatten();
 8954                        item.with_context(|| format!("path {path:?} is not a file"))?
 8955                    })
 8956                })
 8957            })?
 8958            .await?
 8959            .await
 8960    })
 8961}
 8962
 8963pub fn open_remote_project_with_new_connection(
 8964    window: WindowHandle<MultiWorkspace>,
 8965    remote_connection: Arc<dyn RemoteConnection>,
 8966    cancel_rx: oneshot::Receiver<()>,
 8967    delegate: Arc<dyn RemoteClientDelegate>,
 8968    app_state: Arc<AppState>,
 8969    paths: Vec<PathBuf>,
 8970    cx: &mut App,
 8971) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 8972    cx.spawn(async move |cx| {
 8973        let (workspace_id, serialized_workspace) =
 8974            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 8975                .await?;
 8976
 8977        let session = match cx
 8978            .update(|cx| {
 8979                remote::RemoteClient::new(
 8980                    ConnectionIdentifier::Workspace(workspace_id.0),
 8981                    remote_connection,
 8982                    cancel_rx,
 8983                    delegate,
 8984                    cx,
 8985                )
 8986            })
 8987            .await?
 8988        {
 8989            Some(result) => result,
 8990            None => return Ok(Vec::new()),
 8991        };
 8992
 8993        let project = cx.update(|cx| {
 8994            project::Project::remote(
 8995                session,
 8996                app_state.client.clone(),
 8997                app_state.node_runtime.clone(),
 8998                app_state.user_store.clone(),
 8999                app_state.languages.clone(),
 9000                app_state.fs.clone(),
 9001                true,
 9002                cx,
 9003            )
 9004        });
 9005
 9006        open_remote_project_inner(
 9007            project,
 9008            paths,
 9009            workspace_id,
 9010            serialized_workspace,
 9011            app_state,
 9012            window,
 9013            cx,
 9014        )
 9015        .await
 9016    })
 9017}
 9018
 9019pub fn open_remote_project_with_existing_connection(
 9020    connection_options: RemoteConnectionOptions,
 9021    project: Entity<Project>,
 9022    paths: Vec<PathBuf>,
 9023    app_state: Arc<AppState>,
 9024    window: WindowHandle<MultiWorkspace>,
 9025    cx: &mut AsyncApp,
 9026) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9027    cx.spawn(async move |cx| {
 9028        let (workspace_id, serialized_workspace) =
 9029            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9030
 9031        open_remote_project_inner(
 9032            project,
 9033            paths,
 9034            workspace_id,
 9035            serialized_workspace,
 9036            app_state,
 9037            window,
 9038            cx,
 9039        )
 9040        .await
 9041    })
 9042}
 9043
 9044async fn open_remote_project_inner(
 9045    project: Entity<Project>,
 9046    paths: Vec<PathBuf>,
 9047    workspace_id: WorkspaceId,
 9048    serialized_workspace: Option<SerializedWorkspace>,
 9049    app_state: Arc<AppState>,
 9050    window: WindowHandle<MultiWorkspace>,
 9051    cx: &mut AsyncApp,
 9052) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9053    let toolchains = DB.toolchains(workspace_id).await?;
 9054    for (toolchain, worktree_path, path) in toolchains {
 9055        project
 9056            .update(cx, |this, cx| {
 9057                let Some(worktree_id) =
 9058                    this.find_worktree(&worktree_path, cx)
 9059                        .and_then(|(worktree, rel_path)| {
 9060                            if rel_path.is_empty() {
 9061                                Some(worktree.read(cx).id())
 9062                            } else {
 9063                                None
 9064                            }
 9065                        })
 9066                else {
 9067                    return Task::ready(None);
 9068                };
 9069
 9070                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9071            })
 9072            .await;
 9073    }
 9074    let mut project_paths_to_open = vec![];
 9075    let mut project_path_errors = vec![];
 9076
 9077    for path in paths {
 9078        let result = cx
 9079            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9080            .await;
 9081        match result {
 9082            Ok((_, project_path)) => {
 9083                project_paths_to_open.push((path.clone(), Some(project_path)));
 9084            }
 9085            Err(error) => {
 9086                project_path_errors.push(error);
 9087            }
 9088        };
 9089    }
 9090
 9091    if project_paths_to_open.is_empty() {
 9092        return Err(project_path_errors.pop().context("no paths given")?);
 9093    }
 9094
 9095    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9096        telemetry::event!("SSH Project Opened");
 9097
 9098        let new_workspace = cx.new(|cx| {
 9099            let mut workspace =
 9100                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9101            workspace.update_history(cx);
 9102
 9103            if let Some(ref serialized) = serialized_workspace {
 9104                workspace.centered_layout = serialized.centered_layout;
 9105            }
 9106
 9107            workspace
 9108        });
 9109
 9110        multi_workspace.activate(new_workspace.clone(), cx);
 9111        new_workspace
 9112    })?;
 9113
 9114    let items = window
 9115        .update(cx, |_, window, cx| {
 9116            window.activate_window();
 9117            workspace.update(cx, |_workspace, cx| {
 9118                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9119            })
 9120        })?
 9121        .await?;
 9122
 9123    workspace.update(cx, |workspace, cx| {
 9124        for error in project_path_errors {
 9125            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9126                if let Some(path) = error.error_tag("path") {
 9127                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9128                }
 9129            } else {
 9130                workspace.show_error(&error, cx)
 9131            }
 9132        }
 9133    });
 9134
 9135    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9136}
 9137
 9138fn deserialize_remote_project(
 9139    connection_options: RemoteConnectionOptions,
 9140    paths: Vec<PathBuf>,
 9141    cx: &AsyncApp,
 9142) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9143    cx.background_spawn(async move {
 9144        let remote_connection_id = persistence::DB
 9145            .get_or_create_remote_connection(connection_options)
 9146            .await?;
 9147
 9148        let serialized_workspace =
 9149            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9150
 9151        let workspace_id = if let Some(workspace_id) =
 9152            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9153        {
 9154            workspace_id
 9155        } else {
 9156            persistence::DB.next_id().await?
 9157        };
 9158
 9159        Ok((workspace_id, serialized_workspace))
 9160    })
 9161}
 9162
 9163pub fn join_in_room_project(
 9164    project_id: u64,
 9165    follow_user_id: u64,
 9166    app_state: Arc<AppState>,
 9167    cx: &mut App,
 9168) -> Task<Result<()>> {
 9169    let windows = cx.windows();
 9170    cx.spawn(async move |cx| {
 9171        let existing_window_and_workspace: Option<(
 9172            WindowHandle<MultiWorkspace>,
 9173            Entity<Workspace>,
 9174        )> = windows.into_iter().find_map(|window_handle| {
 9175            window_handle
 9176                .downcast::<MultiWorkspace>()
 9177                .and_then(|window_handle| {
 9178                    window_handle
 9179                        .update(cx, |multi_workspace, _window, cx| {
 9180                            for workspace in multi_workspace.workspaces() {
 9181                                if workspace.read(cx).project().read(cx).remote_id()
 9182                                    == Some(project_id)
 9183                                {
 9184                                    return Some((window_handle, workspace.clone()));
 9185                                }
 9186                            }
 9187                            None
 9188                        })
 9189                        .unwrap_or(None)
 9190                })
 9191        });
 9192
 9193        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9194            existing_window_and_workspace
 9195        {
 9196            existing_window
 9197                .update(cx, |multi_workspace, _, cx| {
 9198                    multi_workspace.activate(target_workspace, cx);
 9199                })
 9200                .ok();
 9201            existing_window
 9202        } else {
 9203            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9204            let project = cx
 9205                .update(|cx| {
 9206                    active_call.0.join_project(
 9207                        project_id,
 9208                        app_state.languages.clone(),
 9209                        app_state.fs.clone(),
 9210                        cx,
 9211                    )
 9212                })
 9213                .await?;
 9214
 9215            let window_bounds_override = window_bounds_env_override();
 9216            cx.update(|cx| {
 9217                let mut options = (app_state.build_window_options)(None, cx);
 9218                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9219                cx.open_window(options, |window, cx| {
 9220                    let workspace = cx.new(|cx| {
 9221                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9222                    });
 9223                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9224                })
 9225            })?
 9226        };
 9227
 9228        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9229            cx.activate(true);
 9230            window.activate_window();
 9231
 9232            // We set the active workspace above, so this is the correct workspace.
 9233            let workspace = multi_workspace.workspace().clone();
 9234            workspace.update(cx, |workspace, cx| {
 9235                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9236                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9237                    .or_else(|| {
 9238                        // If we couldn't follow the given user, follow the host instead.
 9239                        let collaborator = workspace
 9240                            .project()
 9241                            .read(cx)
 9242                            .collaborators()
 9243                            .values()
 9244                            .find(|collaborator| collaborator.is_host)?;
 9245                        Some(collaborator.peer_id)
 9246                    });
 9247
 9248                if let Some(follow_peer_id) = follow_peer_id {
 9249                    workspace.follow(follow_peer_id, window, cx);
 9250                }
 9251            });
 9252        })?;
 9253
 9254        anyhow::Ok(())
 9255    })
 9256}
 9257
 9258pub fn reload(cx: &mut App) {
 9259    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9260    let mut workspace_windows = cx
 9261        .windows()
 9262        .into_iter()
 9263        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9264        .collect::<Vec<_>>();
 9265
 9266    // If multiple windows have unsaved changes, and need a save prompt,
 9267    // prompt in the active window before switching to a different window.
 9268    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9269
 9270    let mut prompt = None;
 9271    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9272        prompt = window
 9273            .update(cx, |_, window, cx| {
 9274                window.prompt(
 9275                    PromptLevel::Info,
 9276                    "Are you sure you want to restart?",
 9277                    None,
 9278                    &["Restart", "Cancel"],
 9279                    cx,
 9280                )
 9281            })
 9282            .ok();
 9283    }
 9284
 9285    cx.spawn(async move |cx| {
 9286        if let Some(prompt) = prompt {
 9287            let answer = prompt.await?;
 9288            if answer != 0 {
 9289                return anyhow::Ok(());
 9290            }
 9291        }
 9292
 9293        // If the user cancels any save prompt, then keep the app open.
 9294        for window in workspace_windows {
 9295            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9296                let workspace = multi_workspace.workspace().clone();
 9297                workspace.update(cx, |workspace, cx| {
 9298                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9299                })
 9300            }) && !should_close.await?
 9301            {
 9302                return anyhow::Ok(());
 9303            }
 9304        }
 9305        cx.update(|cx| cx.restart());
 9306        anyhow::Ok(())
 9307    })
 9308    .detach_and_log_err(cx);
 9309}
 9310
 9311fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9312    let mut parts = value.split(',');
 9313    let x: usize = parts.next()?.parse().ok()?;
 9314    let y: usize = parts.next()?.parse().ok()?;
 9315    Some(point(px(x as f32), px(y as f32)))
 9316}
 9317
 9318fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9319    let mut parts = value.split(',');
 9320    let width: usize = parts.next()?.parse().ok()?;
 9321    let height: usize = parts.next()?.parse().ok()?;
 9322    Some(size(px(width as f32), px(height as f32)))
 9323}
 9324
 9325/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9326/// appropriate.
 9327///
 9328/// The `border_radius_tiling` parameter allows overriding which corners get
 9329/// rounded, independently of the actual window tiling state. This is used
 9330/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9331/// we want square corners on the left (so the sidebar appears flush with the
 9332/// window edge) but we still need the shadow padding for proper visual
 9333/// appearance. Unlike actual window tiling, this only affects border radius -
 9334/// not padding or shadows.
 9335pub fn client_side_decorations(
 9336    element: impl IntoElement,
 9337    window: &mut Window,
 9338    cx: &mut App,
 9339    border_radius_tiling: Tiling,
 9340) -> Stateful<Div> {
 9341    const BORDER_SIZE: Pixels = px(1.0);
 9342    let decorations = window.window_decorations();
 9343    let tiling = match decorations {
 9344        Decorations::Server => Tiling::default(),
 9345        Decorations::Client { tiling } => tiling,
 9346    };
 9347
 9348    match decorations {
 9349        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9350        Decorations::Server => window.set_client_inset(px(0.0)),
 9351    }
 9352
 9353    struct GlobalResizeEdge(ResizeEdge);
 9354    impl Global for GlobalResizeEdge {}
 9355
 9356    div()
 9357        .id("window-backdrop")
 9358        .bg(transparent_black())
 9359        .map(|div| match decorations {
 9360            Decorations::Server => div,
 9361            Decorations::Client { .. } => div
 9362                .when(
 9363                    !(tiling.top
 9364                        || tiling.right
 9365                        || border_radius_tiling.top
 9366                        || border_radius_tiling.right),
 9367                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9368                )
 9369                .when(
 9370                    !(tiling.top
 9371                        || tiling.left
 9372                        || border_radius_tiling.top
 9373                        || border_radius_tiling.left),
 9374                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9375                )
 9376                .when(
 9377                    !(tiling.bottom
 9378                        || tiling.right
 9379                        || border_radius_tiling.bottom
 9380                        || border_radius_tiling.right),
 9381                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9382                )
 9383                .when(
 9384                    !(tiling.bottom
 9385                        || tiling.left
 9386                        || border_radius_tiling.bottom
 9387                        || border_radius_tiling.left),
 9388                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9389                )
 9390                .when(!tiling.top, |div| {
 9391                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9392                })
 9393                .when(!tiling.bottom, |div| {
 9394                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9395                })
 9396                .when(!tiling.left, |div| {
 9397                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9398                })
 9399                .when(!tiling.right, |div| {
 9400                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9401                })
 9402                .on_mouse_move(move |e, window, cx| {
 9403                    let size = window.window_bounds().get_bounds().size;
 9404                    let pos = e.position;
 9405
 9406                    let new_edge =
 9407                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9408
 9409                    let edge = cx.try_global::<GlobalResizeEdge>();
 9410                    if new_edge != edge.map(|edge| edge.0) {
 9411                        window
 9412                            .window_handle()
 9413                            .update(cx, |workspace, _, cx| {
 9414                                cx.notify(workspace.entity_id());
 9415                            })
 9416                            .ok();
 9417                    }
 9418                })
 9419                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9420                    let size = window.window_bounds().get_bounds().size;
 9421                    let pos = e.position;
 9422
 9423                    let edge = match resize_edge(
 9424                        pos,
 9425                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9426                        size,
 9427                        tiling,
 9428                    ) {
 9429                        Some(value) => value,
 9430                        None => return,
 9431                    };
 9432
 9433                    window.start_window_resize(edge);
 9434                }),
 9435        })
 9436        .size_full()
 9437        .child(
 9438            div()
 9439                .cursor(CursorStyle::Arrow)
 9440                .map(|div| match decorations {
 9441                    Decorations::Server => div,
 9442                    Decorations::Client { .. } => div
 9443                        .border_color(cx.theme().colors().border)
 9444                        .when(
 9445                            !(tiling.top
 9446                                || tiling.right
 9447                                || border_radius_tiling.top
 9448                                || border_radius_tiling.right),
 9449                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9450                        )
 9451                        .when(
 9452                            !(tiling.top
 9453                                || tiling.left
 9454                                || border_radius_tiling.top
 9455                                || border_radius_tiling.left),
 9456                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9457                        )
 9458                        .when(
 9459                            !(tiling.bottom
 9460                                || tiling.right
 9461                                || border_radius_tiling.bottom
 9462                                || border_radius_tiling.right),
 9463                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9464                        )
 9465                        .when(
 9466                            !(tiling.bottom
 9467                                || tiling.left
 9468                                || border_radius_tiling.bottom
 9469                                || border_radius_tiling.left),
 9470                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9471                        )
 9472                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9473                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9474                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9475                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9476                        .when(!tiling.is_tiled(), |div| {
 9477                            div.shadow(vec![gpui::BoxShadow {
 9478                                color: Hsla {
 9479                                    h: 0.,
 9480                                    s: 0.,
 9481                                    l: 0.,
 9482                                    a: 0.4,
 9483                                },
 9484                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9485                                spread_radius: px(0.),
 9486                                offset: point(px(0.0), px(0.0)),
 9487                            }])
 9488                        }),
 9489                })
 9490                .on_mouse_move(|_e, _, cx| {
 9491                    cx.stop_propagation();
 9492                })
 9493                .size_full()
 9494                .child(element),
 9495        )
 9496        .map(|div| match decorations {
 9497            Decorations::Server => div,
 9498            Decorations::Client { tiling, .. } => div.child(
 9499                canvas(
 9500                    |_bounds, window, _| {
 9501                        window.insert_hitbox(
 9502                            Bounds::new(
 9503                                point(px(0.0), px(0.0)),
 9504                                window.window_bounds().get_bounds().size,
 9505                            ),
 9506                            HitboxBehavior::Normal,
 9507                        )
 9508                    },
 9509                    move |_bounds, hitbox, window, cx| {
 9510                        let mouse = window.mouse_position();
 9511                        let size = window.window_bounds().get_bounds().size;
 9512                        let Some(edge) =
 9513                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 9514                        else {
 9515                            return;
 9516                        };
 9517                        cx.set_global(GlobalResizeEdge(edge));
 9518                        window.set_cursor_style(
 9519                            match edge {
 9520                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 9521                                ResizeEdge::Left | ResizeEdge::Right => {
 9522                                    CursorStyle::ResizeLeftRight
 9523                                }
 9524                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 9525                                    CursorStyle::ResizeUpLeftDownRight
 9526                                }
 9527                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 9528                                    CursorStyle::ResizeUpRightDownLeft
 9529                                }
 9530                            },
 9531                            &hitbox,
 9532                        );
 9533                    },
 9534                )
 9535                .size_full()
 9536                .absolute(),
 9537            ),
 9538        })
 9539}
 9540
 9541fn resize_edge(
 9542    pos: Point<Pixels>,
 9543    shadow_size: Pixels,
 9544    window_size: Size<Pixels>,
 9545    tiling: Tiling,
 9546) -> Option<ResizeEdge> {
 9547    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 9548    if bounds.contains(&pos) {
 9549        return None;
 9550    }
 9551
 9552    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 9553    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 9554    if !tiling.top && top_left_bounds.contains(&pos) {
 9555        return Some(ResizeEdge::TopLeft);
 9556    }
 9557
 9558    let top_right_bounds = Bounds::new(
 9559        Point::new(window_size.width - corner_size.width, px(0.)),
 9560        corner_size,
 9561    );
 9562    if !tiling.top && top_right_bounds.contains(&pos) {
 9563        return Some(ResizeEdge::TopRight);
 9564    }
 9565
 9566    let bottom_left_bounds = Bounds::new(
 9567        Point::new(px(0.), window_size.height - corner_size.height),
 9568        corner_size,
 9569    );
 9570    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 9571        return Some(ResizeEdge::BottomLeft);
 9572    }
 9573
 9574    let bottom_right_bounds = Bounds::new(
 9575        Point::new(
 9576            window_size.width - corner_size.width,
 9577            window_size.height - corner_size.height,
 9578        ),
 9579        corner_size,
 9580    );
 9581    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 9582        return Some(ResizeEdge::BottomRight);
 9583    }
 9584
 9585    if !tiling.top && pos.y < shadow_size {
 9586        Some(ResizeEdge::Top)
 9587    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 9588        Some(ResizeEdge::Bottom)
 9589    } else if !tiling.left && pos.x < shadow_size {
 9590        Some(ResizeEdge::Left)
 9591    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 9592        Some(ResizeEdge::Right)
 9593    } else {
 9594        None
 9595    }
 9596}
 9597
 9598fn join_pane_into_active(
 9599    active_pane: &Entity<Pane>,
 9600    pane: &Entity<Pane>,
 9601    window: &mut Window,
 9602    cx: &mut App,
 9603) {
 9604    if pane == active_pane {
 9605    } else if pane.read(cx).items_len() == 0 {
 9606        pane.update(cx, |_, cx| {
 9607            cx.emit(pane::Event::Remove {
 9608                focus_on_pane: None,
 9609            });
 9610        })
 9611    } else {
 9612        move_all_items(pane, active_pane, window, cx);
 9613    }
 9614}
 9615
 9616fn move_all_items(
 9617    from_pane: &Entity<Pane>,
 9618    to_pane: &Entity<Pane>,
 9619    window: &mut Window,
 9620    cx: &mut App,
 9621) {
 9622    let destination_is_different = from_pane != to_pane;
 9623    let mut moved_items = 0;
 9624    for (item_ix, item_handle) in from_pane
 9625        .read(cx)
 9626        .items()
 9627        .enumerate()
 9628        .map(|(ix, item)| (ix, item.clone()))
 9629        .collect::<Vec<_>>()
 9630    {
 9631        let ix = item_ix - moved_items;
 9632        if destination_is_different {
 9633            // Close item from previous pane
 9634            from_pane.update(cx, |source, cx| {
 9635                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 9636            });
 9637            moved_items += 1;
 9638        }
 9639
 9640        // This automatically removes duplicate items in the pane
 9641        to_pane.update(cx, |destination, cx| {
 9642            destination.add_item(item_handle, true, true, None, window, cx);
 9643            window.focus(&destination.focus_handle(cx), cx)
 9644        });
 9645    }
 9646}
 9647
 9648pub fn move_item(
 9649    source: &Entity<Pane>,
 9650    destination: &Entity<Pane>,
 9651    item_id_to_move: EntityId,
 9652    destination_index: usize,
 9653    activate: bool,
 9654    window: &mut Window,
 9655    cx: &mut App,
 9656) {
 9657    let Some((item_ix, item_handle)) = source
 9658        .read(cx)
 9659        .items()
 9660        .enumerate()
 9661        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 9662        .map(|(ix, item)| (ix, item.clone()))
 9663    else {
 9664        // Tab was closed during drag
 9665        return;
 9666    };
 9667
 9668    if source != destination {
 9669        // Close item from previous pane
 9670        source.update(cx, |source, cx| {
 9671            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 9672        });
 9673    }
 9674
 9675    // This automatically removes duplicate items in the pane
 9676    destination.update(cx, |destination, cx| {
 9677        destination.add_item_inner(
 9678            item_handle,
 9679            activate,
 9680            activate,
 9681            activate,
 9682            Some(destination_index),
 9683            window,
 9684            cx,
 9685        );
 9686        if activate {
 9687            window.focus(&destination.focus_handle(cx), cx)
 9688        }
 9689    });
 9690}
 9691
 9692pub fn move_active_item(
 9693    source: &Entity<Pane>,
 9694    destination: &Entity<Pane>,
 9695    focus_destination: bool,
 9696    close_if_empty: bool,
 9697    window: &mut Window,
 9698    cx: &mut App,
 9699) {
 9700    if source == destination {
 9701        return;
 9702    }
 9703    let Some(active_item) = source.read(cx).active_item() else {
 9704        return;
 9705    };
 9706    source.update(cx, |source_pane, cx| {
 9707        let item_id = active_item.item_id();
 9708        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 9709        destination.update(cx, |target_pane, cx| {
 9710            target_pane.add_item(
 9711                active_item,
 9712                focus_destination,
 9713                focus_destination,
 9714                Some(target_pane.items_len()),
 9715                window,
 9716                cx,
 9717            );
 9718        });
 9719    });
 9720}
 9721
 9722pub fn clone_active_item(
 9723    workspace_id: Option<WorkspaceId>,
 9724    source: &Entity<Pane>,
 9725    destination: &Entity<Pane>,
 9726    focus_destination: bool,
 9727    window: &mut Window,
 9728    cx: &mut App,
 9729) {
 9730    if source == destination {
 9731        return;
 9732    }
 9733    let Some(active_item) = source.read(cx).active_item() else {
 9734        return;
 9735    };
 9736    if !active_item.can_split(cx) {
 9737        return;
 9738    }
 9739    let destination = destination.downgrade();
 9740    let task = active_item.clone_on_split(workspace_id, window, cx);
 9741    window
 9742        .spawn(cx, async move |cx| {
 9743            let Some(clone) = task.await else {
 9744                return;
 9745            };
 9746            destination
 9747                .update_in(cx, |target_pane, window, cx| {
 9748                    target_pane.add_item(
 9749                        clone,
 9750                        focus_destination,
 9751                        focus_destination,
 9752                        Some(target_pane.items_len()),
 9753                        window,
 9754                        cx,
 9755                    );
 9756                })
 9757                .log_err();
 9758        })
 9759        .detach();
 9760}
 9761
 9762#[derive(Debug)]
 9763pub struct WorkspacePosition {
 9764    pub window_bounds: Option<WindowBounds>,
 9765    pub display: Option<Uuid>,
 9766    pub centered_layout: bool,
 9767}
 9768
 9769pub fn remote_workspace_position_from_db(
 9770    connection_options: RemoteConnectionOptions,
 9771    paths_to_open: &[PathBuf],
 9772    cx: &App,
 9773) -> Task<Result<WorkspacePosition>> {
 9774    let paths = paths_to_open.to_vec();
 9775
 9776    cx.background_spawn(async move {
 9777        let remote_connection_id = persistence::DB
 9778            .get_or_create_remote_connection(connection_options)
 9779            .await
 9780            .context("fetching serialized ssh project")?;
 9781        let serialized_workspace =
 9782            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9783
 9784        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 9785            (Some(WindowBounds::Windowed(bounds)), None)
 9786        } else {
 9787            let restorable_bounds = serialized_workspace
 9788                .as_ref()
 9789                .and_then(|workspace| {
 9790                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
 9791                })
 9792                .or_else(|| persistence::read_default_window_bounds());
 9793
 9794            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
 9795                (Some(serialized_bounds), Some(serialized_display))
 9796            } else {
 9797                (None, None)
 9798            }
 9799        };
 9800
 9801        let centered_layout = serialized_workspace
 9802            .as_ref()
 9803            .map(|w| w.centered_layout)
 9804            .unwrap_or(false);
 9805
 9806        Ok(WorkspacePosition {
 9807            window_bounds,
 9808            display,
 9809            centered_layout,
 9810        })
 9811    })
 9812}
 9813
 9814pub fn with_active_or_new_workspace(
 9815    cx: &mut App,
 9816    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 9817) {
 9818    match cx
 9819        .active_window()
 9820        .and_then(|w| w.downcast::<MultiWorkspace>())
 9821    {
 9822        Some(multi_workspace) => {
 9823            cx.defer(move |cx| {
 9824                multi_workspace
 9825                    .update(cx, |multi_workspace, window, cx| {
 9826                        let workspace = multi_workspace.workspace().clone();
 9827                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
 9828                    })
 9829                    .log_err();
 9830            });
 9831        }
 9832        None => {
 9833            let app_state = AppState::global(cx);
 9834            if let Some(app_state) = app_state.upgrade() {
 9835                open_new(
 9836                    OpenOptions::default(),
 9837                    app_state,
 9838                    cx,
 9839                    move |workspace, window, cx| f(workspace, window, cx),
 9840                )
 9841                .detach_and_log_err(cx);
 9842            }
 9843        }
 9844    }
 9845}
 9846
 9847#[cfg(test)]
 9848mod tests {
 9849    use std::{cell::RefCell, rc::Rc};
 9850
 9851    use super::*;
 9852    use crate::{
 9853        dock::{PanelEvent, test::TestPanel},
 9854        item::{
 9855            ItemBufferKind, ItemEvent,
 9856            test::{TestItem, TestProjectItem},
 9857        },
 9858    };
 9859    use fs::FakeFs;
 9860    use gpui::{
 9861        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 9862        UpdateGlobal, VisualTestContext, px,
 9863    };
 9864    use project::{Project, ProjectEntryId};
 9865    use serde_json::json;
 9866    use settings::SettingsStore;
 9867    use util::rel_path::rel_path;
 9868
 9869    #[gpui::test]
 9870    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 9871        init_test(cx);
 9872
 9873        let fs = FakeFs::new(cx.executor());
 9874        let project = Project::test(fs, [], cx).await;
 9875        let (workspace, cx) =
 9876            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9877
 9878        // Adding an item with no ambiguity renders the tab without detail.
 9879        let item1 = cx.new(|cx| {
 9880            let mut item = TestItem::new(cx);
 9881            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 9882            item
 9883        });
 9884        workspace.update_in(cx, |workspace, window, cx| {
 9885            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9886        });
 9887        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 9888
 9889        // Adding an item that creates ambiguity increases the level of detail on
 9890        // both tabs.
 9891        let item2 = cx.new_window_entity(|_window, cx| {
 9892            let mut item = TestItem::new(cx);
 9893            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9894            item
 9895        });
 9896        workspace.update_in(cx, |workspace, window, cx| {
 9897            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9898        });
 9899        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9900        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9901
 9902        // Adding an item that creates ambiguity increases the level of detail only
 9903        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 9904        // we stop at the highest detail available.
 9905        let item3 = cx.new(|cx| {
 9906            let mut item = TestItem::new(cx);
 9907            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9908            item
 9909        });
 9910        workspace.update_in(cx, |workspace, window, cx| {
 9911            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9912        });
 9913        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9914        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9915        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9916    }
 9917
 9918    #[gpui::test]
 9919    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 9920        init_test(cx);
 9921
 9922        let fs = FakeFs::new(cx.executor());
 9923        fs.insert_tree(
 9924            "/root1",
 9925            json!({
 9926                "one.txt": "",
 9927                "two.txt": "",
 9928            }),
 9929        )
 9930        .await;
 9931        fs.insert_tree(
 9932            "/root2",
 9933            json!({
 9934                "three.txt": "",
 9935            }),
 9936        )
 9937        .await;
 9938
 9939        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 9940        let (workspace, cx) =
 9941            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9942        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9943        let worktree_id = project.update(cx, |project, cx| {
 9944            project.worktrees(cx).next().unwrap().read(cx).id()
 9945        });
 9946
 9947        let item1 = cx.new(|cx| {
 9948            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 9949        });
 9950        let item2 = cx.new(|cx| {
 9951            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 9952        });
 9953
 9954        // Add an item to an empty pane
 9955        workspace.update_in(cx, |workspace, window, cx| {
 9956            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 9957        });
 9958        project.update(cx, |project, cx| {
 9959            assert_eq!(
 9960                project.active_entry(),
 9961                project
 9962                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 9963                    .map(|e| e.id)
 9964            );
 9965        });
 9966        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 9967
 9968        // Add a second item to a non-empty pane
 9969        workspace.update_in(cx, |workspace, window, cx| {
 9970            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 9971        });
 9972        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 9973        project.update(cx, |project, cx| {
 9974            assert_eq!(
 9975                project.active_entry(),
 9976                project
 9977                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
 9978                    .map(|e| e.id)
 9979            );
 9980        });
 9981
 9982        // Close the active item
 9983        pane.update_in(cx, |pane, window, cx| {
 9984            pane.close_active_item(&Default::default(), window, cx)
 9985        })
 9986        .await
 9987        .unwrap();
 9988        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 9989        project.update(cx, |project, cx| {
 9990            assert_eq!(
 9991                project.active_entry(),
 9992                project
 9993                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 9994                    .map(|e| e.id)
 9995            );
 9996        });
 9997
 9998        // Add a project folder
 9999        project
10000            .update(cx, |project, cx| {
10001                project.find_or_create_worktree("root2", true, cx)
10002            })
10003            .await
10004            .unwrap();
10005        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10006
10007        // Remove a project folder
10008        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10009        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10010    }
10011
10012    #[gpui::test]
10013    async fn test_close_window(cx: &mut TestAppContext) {
10014        init_test(cx);
10015
10016        let fs = FakeFs::new(cx.executor());
10017        fs.insert_tree("/root", json!({ "one": "" })).await;
10018
10019        let project = Project::test(fs, ["root".as_ref()], cx).await;
10020        let (workspace, cx) =
10021            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10022
10023        // When there are no dirty items, there's nothing to do.
10024        let item1 = cx.new(TestItem::new);
10025        workspace.update_in(cx, |w, window, cx| {
10026            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10027        });
10028        let task = workspace.update_in(cx, |w, window, cx| {
10029            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10030        });
10031        assert!(task.await.unwrap());
10032
10033        // When there are dirty untitled items, prompt to save each one. If the user
10034        // cancels any prompt, then abort.
10035        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10036        let item3 = cx.new(|cx| {
10037            TestItem::new(cx)
10038                .with_dirty(true)
10039                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10040        });
10041        workspace.update_in(cx, |w, window, cx| {
10042            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10043            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10044        });
10045        let task = workspace.update_in(cx, |w, window, cx| {
10046            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10047        });
10048        cx.executor().run_until_parked();
10049        cx.simulate_prompt_answer("Cancel"); // cancel save all
10050        cx.executor().run_until_parked();
10051        assert!(!cx.has_pending_prompt());
10052        assert!(!task.await.unwrap());
10053    }
10054
10055    #[gpui::test]
10056    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10057        init_test(cx);
10058
10059        let fs = FakeFs::new(cx.executor());
10060        fs.insert_tree("/root", json!({ "one": "" })).await;
10061
10062        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10063        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10064        let multi_workspace_handle =
10065            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10066        cx.run_until_parked();
10067
10068        let workspace_a = multi_workspace_handle
10069            .read_with(cx, |mw, _| mw.workspace().clone())
10070            .unwrap();
10071
10072        let workspace_b = multi_workspace_handle
10073            .update(cx, |mw, window, cx| {
10074                mw.test_add_workspace(project_b, window, cx)
10075            })
10076            .unwrap();
10077
10078        // Activate workspace A
10079        multi_workspace_handle
10080            .update(cx, |mw, window, cx| {
10081                mw.activate_index(0, window, cx);
10082            })
10083            .unwrap();
10084
10085        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10086
10087        // Workspace A has a clean item
10088        let item_a = cx.new(TestItem::new);
10089        workspace_a.update_in(cx, |w, window, cx| {
10090            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10091        });
10092
10093        // Workspace B has a dirty item
10094        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10095        workspace_b.update_in(cx, |w, window, cx| {
10096            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10097        });
10098
10099        // Verify workspace A is active
10100        multi_workspace_handle
10101            .read_with(cx, |mw, _| {
10102                assert_eq!(mw.active_workspace_index(), 0);
10103            })
10104            .unwrap();
10105
10106        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10107        multi_workspace_handle
10108            .update(cx, |mw, window, cx| {
10109                mw.close_window(&CloseWindow, window, cx);
10110            })
10111            .unwrap();
10112        cx.run_until_parked();
10113
10114        // Workspace B should now be active since it has dirty items that need attention
10115        multi_workspace_handle
10116            .read_with(cx, |mw, _| {
10117                assert_eq!(
10118                    mw.active_workspace_index(),
10119                    1,
10120                    "workspace B should be activated when it prompts"
10121                );
10122            })
10123            .unwrap();
10124
10125        // User cancels the save prompt from workspace B
10126        cx.simulate_prompt_answer("Cancel");
10127        cx.run_until_parked();
10128
10129        // Window should still exist because workspace B's close was cancelled
10130        assert!(
10131            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10132            "window should still exist after cancelling one workspace's close"
10133        );
10134    }
10135
10136    #[gpui::test]
10137    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10138        init_test(cx);
10139
10140        // Register TestItem as a serializable item
10141        cx.update(|cx| {
10142            register_serializable_item::<TestItem>(cx);
10143        });
10144
10145        let fs = FakeFs::new(cx.executor());
10146        fs.insert_tree("/root", json!({ "one": "" })).await;
10147
10148        let project = Project::test(fs, ["root".as_ref()], cx).await;
10149        let (workspace, cx) =
10150            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10151
10152        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10153        let item1 = cx.new(|cx| {
10154            TestItem::new(cx)
10155                .with_dirty(true)
10156                .with_serialize(|| Some(Task::ready(Ok(()))))
10157        });
10158        let item2 = cx.new(|cx| {
10159            TestItem::new(cx)
10160                .with_dirty(true)
10161                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10162                .with_serialize(|| Some(Task::ready(Ok(()))))
10163        });
10164        workspace.update_in(cx, |w, window, cx| {
10165            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10166            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10167        });
10168        let task = workspace.update_in(cx, |w, window, cx| {
10169            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10170        });
10171        assert!(task.await.unwrap());
10172    }
10173
10174    #[gpui::test]
10175    async fn test_close_pane_items(cx: &mut TestAppContext) {
10176        init_test(cx);
10177
10178        let fs = FakeFs::new(cx.executor());
10179
10180        let project = Project::test(fs, None, cx).await;
10181        let (workspace, cx) =
10182            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10183
10184        let item1 = cx.new(|cx| {
10185            TestItem::new(cx)
10186                .with_dirty(true)
10187                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10188        });
10189        let item2 = cx.new(|cx| {
10190            TestItem::new(cx)
10191                .with_dirty(true)
10192                .with_conflict(true)
10193                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10194        });
10195        let item3 = cx.new(|cx| {
10196            TestItem::new(cx)
10197                .with_dirty(true)
10198                .with_conflict(true)
10199                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10200        });
10201        let item4 = cx.new(|cx| {
10202            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10203                let project_item = TestProjectItem::new_untitled(cx);
10204                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10205                project_item
10206            }])
10207        });
10208        let pane = workspace.update_in(cx, |workspace, window, cx| {
10209            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10210            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10211            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10212            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10213            workspace.active_pane().clone()
10214        });
10215
10216        let close_items = pane.update_in(cx, |pane, window, cx| {
10217            pane.activate_item(1, true, true, window, cx);
10218            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10219            let item1_id = item1.item_id();
10220            let item3_id = item3.item_id();
10221            let item4_id = item4.item_id();
10222            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10223                [item1_id, item3_id, item4_id].contains(&id)
10224            })
10225        });
10226        cx.executor().run_until_parked();
10227
10228        assert!(cx.has_pending_prompt());
10229        cx.simulate_prompt_answer("Save all");
10230
10231        cx.executor().run_until_parked();
10232
10233        // Item 1 is saved. There's a prompt to save item 3.
10234        pane.update(cx, |pane, cx| {
10235            assert_eq!(item1.read(cx).save_count, 1);
10236            assert_eq!(item1.read(cx).save_as_count, 0);
10237            assert_eq!(item1.read(cx).reload_count, 0);
10238            assert_eq!(pane.items_len(), 3);
10239            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10240        });
10241        assert!(cx.has_pending_prompt());
10242
10243        // Cancel saving item 3.
10244        cx.simulate_prompt_answer("Discard");
10245        cx.executor().run_until_parked();
10246
10247        // Item 3 is reloaded. There's a prompt to save item 4.
10248        pane.update(cx, |pane, cx| {
10249            assert_eq!(item3.read(cx).save_count, 0);
10250            assert_eq!(item3.read(cx).save_as_count, 0);
10251            assert_eq!(item3.read(cx).reload_count, 1);
10252            assert_eq!(pane.items_len(), 2);
10253            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10254        });
10255
10256        // There's a prompt for a path for item 4.
10257        cx.simulate_new_path_selection(|_| Some(Default::default()));
10258        close_items.await.unwrap();
10259
10260        // The requested items are closed.
10261        pane.update(cx, |pane, cx| {
10262            assert_eq!(item4.read(cx).save_count, 0);
10263            assert_eq!(item4.read(cx).save_as_count, 1);
10264            assert_eq!(item4.read(cx).reload_count, 0);
10265            assert_eq!(pane.items_len(), 1);
10266            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10267        });
10268    }
10269
10270    #[gpui::test]
10271    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10272        init_test(cx);
10273
10274        let fs = FakeFs::new(cx.executor());
10275        let project = Project::test(fs, [], cx).await;
10276        let (workspace, cx) =
10277            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10278
10279        // Create several workspace items with single project entries, and two
10280        // workspace items with multiple project entries.
10281        let single_entry_items = (0..=4)
10282            .map(|project_entry_id| {
10283                cx.new(|cx| {
10284                    TestItem::new(cx)
10285                        .with_dirty(true)
10286                        .with_project_items(&[dirty_project_item(
10287                            project_entry_id,
10288                            &format!("{project_entry_id}.txt"),
10289                            cx,
10290                        )])
10291                })
10292            })
10293            .collect::<Vec<_>>();
10294        let item_2_3 = cx.new(|cx| {
10295            TestItem::new(cx)
10296                .with_dirty(true)
10297                .with_buffer_kind(ItemBufferKind::Multibuffer)
10298                .with_project_items(&[
10299                    single_entry_items[2].read(cx).project_items[0].clone(),
10300                    single_entry_items[3].read(cx).project_items[0].clone(),
10301                ])
10302        });
10303        let item_3_4 = cx.new(|cx| {
10304            TestItem::new(cx)
10305                .with_dirty(true)
10306                .with_buffer_kind(ItemBufferKind::Multibuffer)
10307                .with_project_items(&[
10308                    single_entry_items[3].read(cx).project_items[0].clone(),
10309                    single_entry_items[4].read(cx).project_items[0].clone(),
10310                ])
10311        });
10312
10313        // Create two panes that contain the following project entries:
10314        //   left pane:
10315        //     multi-entry items:   (2, 3)
10316        //     single-entry items:  0, 2, 3, 4
10317        //   right pane:
10318        //     single-entry items:  4, 1
10319        //     multi-entry items:   (3, 4)
10320        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10321            let left_pane = workspace.active_pane().clone();
10322            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10323            workspace.add_item_to_active_pane(
10324                single_entry_items[0].boxed_clone(),
10325                None,
10326                true,
10327                window,
10328                cx,
10329            );
10330            workspace.add_item_to_active_pane(
10331                single_entry_items[2].boxed_clone(),
10332                None,
10333                true,
10334                window,
10335                cx,
10336            );
10337            workspace.add_item_to_active_pane(
10338                single_entry_items[3].boxed_clone(),
10339                None,
10340                true,
10341                window,
10342                cx,
10343            );
10344            workspace.add_item_to_active_pane(
10345                single_entry_items[4].boxed_clone(),
10346                None,
10347                true,
10348                window,
10349                cx,
10350            );
10351
10352            let right_pane =
10353                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10354
10355            let boxed_clone = single_entry_items[1].boxed_clone();
10356            let right_pane = window.spawn(cx, async move |cx| {
10357                right_pane.await.inspect(|right_pane| {
10358                    right_pane
10359                        .update_in(cx, |pane, window, cx| {
10360                            pane.add_item(boxed_clone, true, true, None, window, cx);
10361                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10362                        })
10363                        .unwrap();
10364                })
10365            });
10366
10367            (left_pane, right_pane)
10368        });
10369        let right_pane = right_pane.await.unwrap();
10370        cx.focus(&right_pane);
10371
10372        let close = right_pane.update_in(cx, |pane, window, cx| {
10373            pane.close_all_items(&CloseAllItems::default(), window, cx)
10374                .unwrap()
10375        });
10376        cx.executor().run_until_parked();
10377
10378        let msg = cx.pending_prompt().unwrap().0;
10379        assert!(msg.contains("1.txt"));
10380        assert!(!msg.contains("2.txt"));
10381        assert!(!msg.contains("3.txt"));
10382        assert!(!msg.contains("4.txt"));
10383
10384        // With best-effort close, cancelling item 1 keeps it open but items 4
10385        // and (3,4) still close since their entries exist in left pane.
10386        cx.simulate_prompt_answer("Cancel");
10387        close.await;
10388
10389        right_pane.read_with(cx, |pane, _| {
10390            assert_eq!(pane.items_len(), 1);
10391        });
10392
10393        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10394        left_pane
10395            .update_in(cx, |left_pane, window, cx| {
10396                left_pane.close_item_by_id(
10397                    single_entry_items[3].entity_id(),
10398                    SaveIntent::Skip,
10399                    window,
10400                    cx,
10401                )
10402            })
10403            .await
10404            .unwrap();
10405
10406        let close = left_pane.update_in(cx, |pane, window, cx| {
10407            pane.close_all_items(&CloseAllItems::default(), window, cx)
10408                .unwrap()
10409        });
10410        cx.executor().run_until_parked();
10411
10412        let details = cx.pending_prompt().unwrap().1;
10413        assert!(details.contains("0.txt"));
10414        assert!(details.contains("3.txt"));
10415        assert!(details.contains("4.txt"));
10416        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10417        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10418        // assert!(!details.contains("2.txt"));
10419
10420        cx.simulate_prompt_answer("Save all");
10421        cx.executor().run_until_parked();
10422        close.await;
10423
10424        left_pane.read_with(cx, |pane, _| {
10425            assert_eq!(pane.items_len(), 0);
10426        });
10427    }
10428
10429    #[gpui::test]
10430    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10431        init_test(cx);
10432
10433        let fs = FakeFs::new(cx.executor());
10434        let project = Project::test(fs, [], cx).await;
10435        let (workspace, cx) =
10436            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10437        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10438
10439        let item = cx.new(|cx| {
10440            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10441        });
10442        let item_id = item.entity_id();
10443        workspace.update_in(cx, |workspace, window, cx| {
10444            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10445        });
10446
10447        // Autosave on window change.
10448        item.update(cx, |item, cx| {
10449            SettingsStore::update_global(cx, |settings, cx| {
10450                settings.update_user_settings(cx, |settings| {
10451                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10452                })
10453            });
10454            item.is_dirty = true;
10455        });
10456
10457        // Deactivating the window saves the file.
10458        cx.deactivate_window();
10459        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10460
10461        // Re-activating the window doesn't save the file.
10462        cx.update(|window, _| window.activate_window());
10463        cx.executor().run_until_parked();
10464        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10465
10466        // Autosave on focus change.
10467        item.update_in(cx, |item, window, cx| {
10468            cx.focus_self(window);
10469            SettingsStore::update_global(cx, |settings, cx| {
10470                settings.update_user_settings(cx, |settings| {
10471                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10472                })
10473            });
10474            item.is_dirty = true;
10475        });
10476        // Blurring the item saves the file.
10477        item.update_in(cx, |_, window, _| window.blur());
10478        cx.executor().run_until_parked();
10479        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10480
10481        // Deactivating the window still saves the file.
10482        item.update_in(cx, |item, window, cx| {
10483            cx.focus_self(window);
10484            item.is_dirty = true;
10485        });
10486        cx.deactivate_window();
10487        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10488
10489        // Autosave after delay.
10490        item.update(cx, |item, cx| {
10491            SettingsStore::update_global(cx, |settings, cx| {
10492                settings.update_user_settings(cx, |settings| {
10493                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10494                        milliseconds: 500.into(),
10495                    });
10496                })
10497            });
10498            item.is_dirty = true;
10499            cx.emit(ItemEvent::Edit);
10500        });
10501
10502        // Delay hasn't fully expired, so the file is still dirty and unsaved.
10503        cx.executor().advance_clock(Duration::from_millis(250));
10504        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10505
10506        // After delay expires, the file is saved.
10507        cx.executor().advance_clock(Duration::from_millis(250));
10508        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10509
10510        // Autosave after delay, should save earlier than delay if tab is closed
10511        item.update(cx, |item, cx| {
10512            item.is_dirty = true;
10513            cx.emit(ItemEvent::Edit);
10514        });
10515        cx.executor().advance_clock(Duration::from_millis(250));
10516        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10517
10518        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10519        pane.update_in(cx, |pane, window, cx| {
10520            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10521        })
10522        .await
10523        .unwrap();
10524        assert!(!cx.has_pending_prompt());
10525        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10526
10527        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10528        workspace.update_in(cx, |workspace, window, cx| {
10529            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10530        });
10531        item.update_in(cx, |item, _window, cx| {
10532            item.is_dirty = true;
10533            for project_item in &mut item.project_items {
10534                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10535            }
10536        });
10537        cx.run_until_parked();
10538        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10539
10540        // Autosave on focus change, ensuring closing the tab counts as such.
10541        item.update(cx, |item, cx| {
10542            SettingsStore::update_global(cx, |settings, cx| {
10543                settings.update_user_settings(cx, |settings| {
10544                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10545                })
10546            });
10547            item.is_dirty = true;
10548            for project_item in &mut item.project_items {
10549                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10550            }
10551        });
10552
10553        pane.update_in(cx, |pane, window, cx| {
10554            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10555        })
10556        .await
10557        .unwrap();
10558        assert!(!cx.has_pending_prompt());
10559        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10560
10561        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10562        workspace.update_in(cx, |workspace, window, cx| {
10563            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10564        });
10565        item.update_in(cx, |item, window, cx| {
10566            item.project_items[0].update(cx, |item, _| {
10567                item.entry_id = None;
10568            });
10569            item.is_dirty = true;
10570            window.blur();
10571        });
10572        cx.run_until_parked();
10573        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10574
10575        // Ensure autosave is prevented for deleted files also when closing the buffer.
10576        let _close_items = pane.update_in(cx, |pane, window, cx| {
10577            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10578        });
10579        cx.run_until_parked();
10580        assert!(cx.has_pending_prompt());
10581        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10582    }
10583
10584    #[gpui::test]
10585    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10586        init_test(cx);
10587
10588        let fs = FakeFs::new(cx.executor());
10589
10590        let project = Project::test(fs, [], cx).await;
10591        let (workspace, cx) =
10592            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10593
10594        let item = cx.new(|cx| {
10595            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10596        });
10597        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10598        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10599        let toolbar_notify_count = Rc::new(RefCell::new(0));
10600
10601        workspace.update_in(cx, |workspace, window, cx| {
10602            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10603            let toolbar_notification_count = toolbar_notify_count.clone();
10604            cx.observe_in(&toolbar, window, move |_, _, _, _| {
10605                *toolbar_notification_count.borrow_mut() += 1
10606            })
10607            .detach();
10608        });
10609
10610        pane.read_with(cx, |pane, _| {
10611            assert!(!pane.can_navigate_backward());
10612            assert!(!pane.can_navigate_forward());
10613        });
10614
10615        item.update_in(cx, |item, _, cx| {
10616            item.set_state("one".to_string(), cx);
10617        });
10618
10619        // Toolbar must be notified to re-render the navigation buttons
10620        assert_eq!(*toolbar_notify_count.borrow(), 1);
10621
10622        pane.read_with(cx, |pane, _| {
10623            assert!(pane.can_navigate_backward());
10624            assert!(!pane.can_navigate_forward());
10625        });
10626
10627        workspace
10628            .update_in(cx, |workspace, window, cx| {
10629                workspace.go_back(pane.downgrade(), window, cx)
10630            })
10631            .await
10632            .unwrap();
10633
10634        assert_eq!(*toolbar_notify_count.borrow(), 2);
10635        pane.read_with(cx, |pane, _| {
10636            assert!(!pane.can_navigate_backward());
10637            assert!(pane.can_navigate_forward());
10638        });
10639    }
10640
10641    #[gpui::test]
10642    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10643        init_test(cx);
10644        let fs = FakeFs::new(cx.executor());
10645        let project = Project::test(fs, [], cx).await;
10646        let (multi_workspace, cx) =
10647            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10648        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10649
10650        workspace.update_in(cx, |workspace, window, cx| {
10651            let first_item = cx.new(|cx| {
10652                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10653            });
10654            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10655            workspace.split_pane(
10656                workspace.active_pane().clone(),
10657                SplitDirection::Right,
10658                window,
10659                cx,
10660            );
10661            workspace.split_pane(
10662                workspace.active_pane().clone(),
10663                SplitDirection::Right,
10664                window,
10665                cx,
10666            );
10667        });
10668
10669        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10670            let panes = workspace.center.panes();
10671            assert!(panes.len() >= 2);
10672            (
10673                panes.first().expect("at least one pane").entity_id(),
10674                panes.last().expect("at least one pane").entity_id(),
10675            )
10676        });
10677
10678        workspace.update_in(cx, |workspace, window, cx| {
10679            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
10680        });
10681        workspace.update(cx, |workspace, _| {
10682            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
10683            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
10684        });
10685
10686        cx.dispatch_action(ActivateLastPane);
10687
10688        workspace.update(cx, |workspace, _| {
10689            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
10690        });
10691    }
10692
10693    #[gpui::test]
10694    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10695        init_test(cx);
10696        let fs = FakeFs::new(cx.executor());
10697
10698        let project = Project::test(fs, [], cx).await;
10699        let (workspace, cx) =
10700            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10701
10702        let panel = workspace.update_in(cx, |workspace, window, cx| {
10703            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10704            workspace.add_panel(panel.clone(), window, cx);
10705
10706            workspace
10707                .right_dock()
10708                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10709
10710            panel
10711        });
10712
10713        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10714        pane.update_in(cx, |pane, window, cx| {
10715            let item = cx.new(TestItem::new);
10716            pane.add_item(Box::new(item), true, true, None, window, cx);
10717        });
10718
10719        // Transfer focus from center to panel
10720        workspace.update_in(cx, |workspace, window, cx| {
10721            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10722        });
10723
10724        workspace.update_in(cx, |workspace, window, cx| {
10725            assert!(workspace.right_dock().read(cx).is_open());
10726            assert!(!panel.is_zoomed(window, cx));
10727            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10728        });
10729
10730        // Transfer focus from panel to center
10731        workspace.update_in(cx, |workspace, window, cx| {
10732            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10733        });
10734
10735        workspace.update_in(cx, |workspace, window, cx| {
10736            assert!(workspace.right_dock().read(cx).is_open());
10737            assert!(!panel.is_zoomed(window, cx));
10738            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10739        });
10740
10741        // Close the dock
10742        workspace.update_in(cx, |workspace, window, cx| {
10743            workspace.toggle_dock(DockPosition::Right, window, cx);
10744        });
10745
10746        workspace.update_in(cx, |workspace, window, cx| {
10747            assert!(!workspace.right_dock().read(cx).is_open());
10748            assert!(!panel.is_zoomed(window, cx));
10749            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10750        });
10751
10752        // Open the dock
10753        workspace.update_in(cx, |workspace, window, cx| {
10754            workspace.toggle_dock(DockPosition::Right, window, cx);
10755        });
10756
10757        workspace.update_in(cx, |workspace, window, cx| {
10758            assert!(workspace.right_dock().read(cx).is_open());
10759            assert!(!panel.is_zoomed(window, cx));
10760            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10761        });
10762
10763        // Focus and zoom panel
10764        panel.update_in(cx, |panel, window, cx| {
10765            cx.focus_self(window);
10766            panel.set_zoomed(true, window, cx)
10767        });
10768
10769        workspace.update_in(cx, |workspace, window, cx| {
10770            assert!(workspace.right_dock().read(cx).is_open());
10771            assert!(panel.is_zoomed(window, cx));
10772            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10773        });
10774
10775        // Transfer focus to the center closes the dock
10776        workspace.update_in(cx, |workspace, window, cx| {
10777            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10778        });
10779
10780        workspace.update_in(cx, |workspace, window, cx| {
10781            assert!(!workspace.right_dock().read(cx).is_open());
10782            assert!(panel.is_zoomed(window, cx));
10783            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10784        });
10785
10786        // Transferring focus back to the panel keeps it zoomed
10787        workspace.update_in(cx, |workspace, window, cx| {
10788            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10789        });
10790
10791        workspace.update_in(cx, |workspace, window, cx| {
10792            assert!(workspace.right_dock().read(cx).is_open());
10793            assert!(panel.is_zoomed(window, cx));
10794            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10795        });
10796
10797        // Close the dock while it is zoomed
10798        workspace.update_in(cx, |workspace, window, cx| {
10799            workspace.toggle_dock(DockPosition::Right, window, cx)
10800        });
10801
10802        workspace.update_in(cx, |workspace, window, cx| {
10803            assert!(!workspace.right_dock().read(cx).is_open());
10804            assert!(panel.is_zoomed(window, cx));
10805            assert!(workspace.zoomed.is_none());
10806            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10807        });
10808
10809        // Opening the dock, when it's zoomed, retains focus
10810        workspace.update_in(cx, |workspace, window, cx| {
10811            workspace.toggle_dock(DockPosition::Right, window, cx)
10812        });
10813
10814        workspace.update_in(cx, |workspace, window, cx| {
10815            assert!(workspace.right_dock().read(cx).is_open());
10816            assert!(panel.is_zoomed(window, cx));
10817            assert!(workspace.zoomed.is_some());
10818            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10819        });
10820
10821        // Unzoom and close the panel, zoom the active pane.
10822        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
10823        workspace.update_in(cx, |workspace, window, cx| {
10824            workspace.toggle_dock(DockPosition::Right, window, cx)
10825        });
10826        pane.update_in(cx, |pane, window, cx| {
10827            pane.toggle_zoom(&Default::default(), window, cx)
10828        });
10829
10830        // Opening a dock unzooms the pane.
10831        workspace.update_in(cx, |workspace, window, cx| {
10832            workspace.toggle_dock(DockPosition::Right, window, cx)
10833        });
10834        workspace.update_in(cx, |workspace, window, cx| {
10835            let pane = pane.read(cx);
10836            assert!(!pane.is_zoomed());
10837            assert!(!pane.focus_handle(cx).is_focused(window));
10838            assert!(workspace.right_dock().read(cx).is_open());
10839            assert!(workspace.zoomed.is_none());
10840        });
10841    }
10842
10843    #[gpui::test]
10844    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
10845        init_test(cx);
10846        let fs = FakeFs::new(cx.executor());
10847
10848        let project = Project::test(fs, [], cx).await;
10849        let (workspace, cx) =
10850            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10851
10852        let panel = workspace.update_in(cx, |workspace, window, cx| {
10853            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10854            workspace.add_panel(panel.clone(), window, cx);
10855            panel
10856        });
10857
10858        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10859        pane.update_in(cx, |pane, window, cx| {
10860            let item = cx.new(TestItem::new);
10861            pane.add_item(Box::new(item), true, true, None, window, cx);
10862        });
10863
10864        // Enable close_panel_on_toggle
10865        cx.update_global(|store: &mut SettingsStore, cx| {
10866            store.update_user_settings(cx, |settings| {
10867                settings.workspace.close_panel_on_toggle = Some(true);
10868            });
10869        });
10870
10871        // Panel starts closed. Toggling should open and focus it.
10872        workspace.update_in(cx, |workspace, window, cx| {
10873            assert!(!workspace.right_dock().read(cx).is_open());
10874            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10875        });
10876
10877        workspace.update_in(cx, |workspace, window, cx| {
10878            assert!(
10879                workspace.right_dock().read(cx).is_open(),
10880                "Dock should be open after toggling from center"
10881            );
10882            assert!(
10883                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10884                "Panel should be focused after toggling from center"
10885            );
10886        });
10887
10888        // Panel is open and focused. Toggling should close the panel and
10889        // return focus to the center.
10890        workspace.update_in(cx, |workspace, window, cx| {
10891            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10892        });
10893
10894        workspace.update_in(cx, |workspace, window, cx| {
10895            assert!(
10896                !workspace.right_dock().read(cx).is_open(),
10897                "Dock should be closed after toggling from focused panel"
10898            );
10899            assert!(
10900                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10901                "Panel should not be focused after toggling from focused panel"
10902            );
10903        });
10904
10905        // Open the dock and focus something else so the panel is open but not
10906        // focused. Toggling should focus the panel (not close it).
10907        workspace.update_in(cx, |workspace, window, cx| {
10908            workspace
10909                .right_dock()
10910                .update(cx, |dock, cx| dock.set_open(true, window, cx));
10911            window.focus(&pane.read(cx).focus_handle(cx), cx);
10912        });
10913
10914        workspace.update_in(cx, |workspace, window, cx| {
10915            assert!(workspace.right_dock().read(cx).is_open());
10916            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10917            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10918        });
10919
10920        workspace.update_in(cx, |workspace, window, cx| {
10921            assert!(
10922                workspace.right_dock().read(cx).is_open(),
10923                "Dock should remain open when toggling focuses an open-but-unfocused panel"
10924            );
10925            assert!(
10926                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10927                "Panel should be focused after toggling an open-but-unfocused panel"
10928            );
10929        });
10930
10931        // Now disable the setting and verify the original behavior: toggling
10932        // from a focused panel moves focus to center but leaves the dock open.
10933        cx.update_global(|store: &mut SettingsStore, cx| {
10934            store.update_user_settings(cx, |settings| {
10935                settings.workspace.close_panel_on_toggle = Some(false);
10936            });
10937        });
10938
10939        workspace.update_in(cx, |workspace, window, cx| {
10940            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10941        });
10942
10943        workspace.update_in(cx, |workspace, window, cx| {
10944            assert!(
10945                workspace.right_dock().read(cx).is_open(),
10946                "Dock should remain open when setting is disabled"
10947            );
10948            assert!(
10949                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10950                "Panel should not be focused after toggling with setting disabled"
10951            );
10952        });
10953    }
10954
10955    #[gpui::test]
10956    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
10957        init_test(cx);
10958        let fs = FakeFs::new(cx.executor());
10959
10960        let project = Project::test(fs, [], cx).await;
10961        let (workspace, cx) =
10962            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10963
10964        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
10965            workspace.active_pane().clone()
10966        });
10967
10968        // Add an item to the pane so it can be zoomed
10969        workspace.update_in(cx, |workspace, window, cx| {
10970            let item = cx.new(TestItem::new);
10971            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
10972        });
10973
10974        // Initially not zoomed
10975        workspace.update_in(cx, |workspace, _window, cx| {
10976            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
10977            assert!(
10978                workspace.zoomed.is_none(),
10979                "Workspace should track no zoomed pane"
10980            );
10981            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
10982        });
10983
10984        // Zoom In
10985        pane.update_in(cx, |pane, window, cx| {
10986            pane.zoom_in(&crate::ZoomIn, window, cx);
10987        });
10988
10989        workspace.update_in(cx, |workspace, window, cx| {
10990            assert!(
10991                pane.read(cx).is_zoomed(),
10992                "Pane should be zoomed after ZoomIn"
10993            );
10994            assert!(
10995                workspace.zoomed.is_some(),
10996                "Workspace should track the zoomed pane"
10997            );
10998            assert!(
10999                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11000                "ZoomIn should focus the pane"
11001            );
11002        });
11003
11004        // Zoom In again is a no-op
11005        pane.update_in(cx, |pane, window, cx| {
11006            pane.zoom_in(&crate::ZoomIn, window, cx);
11007        });
11008
11009        workspace.update_in(cx, |workspace, window, cx| {
11010            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11011            assert!(
11012                workspace.zoomed.is_some(),
11013                "Workspace still tracks zoomed pane"
11014            );
11015            assert!(
11016                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11017                "Pane remains focused after repeated ZoomIn"
11018            );
11019        });
11020
11021        // Zoom Out
11022        pane.update_in(cx, |pane, window, cx| {
11023            pane.zoom_out(&crate::ZoomOut, window, cx);
11024        });
11025
11026        workspace.update_in(cx, |workspace, _window, cx| {
11027            assert!(
11028                !pane.read(cx).is_zoomed(),
11029                "Pane should unzoom after ZoomOut"
11030            );
11031            assert!(
11032                workspace.zoomed.is_none(),
11033                "Workspace clears zoom tracking after ZoomOut"
11034            );
11035        });
11036
11037        // Zoom Out again is a no-op
11038        pane.update_in(cx, |pane, window, cx| {
11039            pane.zoom_out(&crate::ZoomOut, window, cx);
11040        });
11041
11042        workspace.update_in(cx, |workspace, _window, cx| {
11043            assert!(
11044                !pane.read(cx).is_zoomed(),
11045                "Second ZoomOut keeps pane unzoomed"
11046            );
11047            assert!(
11048                workspace.zoomed.is_none(),
11049                "Workspace remains without zoomed pane"
11050            );
11051        });
11052    }
11053
11054    #[gpui::test]
11055    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11056        init_test(cx);
11057        let fs = FakeFs::new(cx.executor());
11058
11059        let project = Project::test(fs, [], cx).await;
11060        let (workspace, cx) =
11061            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11062        workspace.update_in(cx, |workspace, window, cx| {
11063            // Open two docks
11064            let left_dock = workspace.dock_at_position(DockPosition::Left);
11065            let right_dock = workspace.dock_at_position(DockPosition::Right);
11066
11067            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11068            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11069
11070            assert!(left_dock.read(cx).is_open());
11071            assert!(right_dock.read(cx).is_open());
11072        });
11073
11074        workspace.update_in(cx, |workspace, window, cx| {
11075            // Toggle all docks - should close both
11076            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11077
11078            let left_dock = workspace.dock_at_position(DockPosition::Left);
11079            let right_dock = workspace.dock_at_position(DockPosition::Right);
11080            assert!(!left_dock.read(cx).is_open());
11081            assert!(!right_dock.read(cx).is_open());
11082        });
11083
11084        workspace.update_in(cx, |workspace, window, cx| {
11085            // Toggle again - should reopen both
11086            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11087
11088            let left_dock = workspace.dock_at_position(DockPosition::Left);
11089            let right_dock = workspace.dock_at_position(DockPosition::Right);
11090            assert!(left_dock.read(cx).is_open());
11091            assert!(right_dock.read(cx).is_open());
11092        });
11093    }
11094
11095    #[gpui::test]
11096    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11097        init_test(cx);
11098        let fs = FakeFs::new(cx.executor());
11099
11100        let project = Project::test(fs, [], cx).await;
11101        let (workspace, cx) =
11102            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11103        workspace.update_in(cx, |workspace, window, cx| {
11104            // Open two docks
11105            let left_dock = workspace.dock_at_position(DockPosition::Left);
11106            let right_dock = workspace.dock_at_position(DockPosition::Right);
11107
11108            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11109            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11110
11111            assert!(left_dock.read(cx).is_open());
11112            assert!(right_dock.read(cx).is_open());
11113        });
11114
11115        workspace.update_in(cx, |workspace, window, cx| {
11116            // Close them manually
11117            workspace.toggle_dock(DockPosition::Left, window, cx);
11118            workspace.toggle_dock(DockPosition::Right, window, cx);
11119
11120            let left_dock = workspace.dock_at_position(DockPosition::Left);
11121            let right_dock = workspace.dock_at_position(DockPosition::Right);
11122            assert!(!left_dock.read(cx).is_open());
11123            assert!(!right_dock.read(cx).is_open());
11124        });
11125
11126        workspace.update_in(cx, |workspace, window, cx| {
11127            // Toggle all docks - only last closed (right dock) should reopen
11128            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11129
11130            let left_dock = workspace.dock_at_position(DockPosition::Left);
11131            let right_dock = workspace.dock_at_position(DockPosition::Right);
11132            assert!(!left_dock.read(cx).is_open());
11133            assert!(right_dock.read(cx).is_open());
11134        });
11135    }
11136
11137    #[gpui::test]
11138    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11139        init_test(cx);
11140        let fs = FakeFs::new(cx.executor());
11141        let project = Project::test(fs, [], cx).await;
11142        let (multi_workspace, cx) =
11143            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11144        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11145
11146        // Open two docks (left and right) with one panel each
11147        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11148            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11149            workspace.add_panel(left_panel.clone(), window, cx);
11150
11151            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11152            workspace.add_panel(right_panel.clone(), window, cx);
11153
11154            workspace.toggle_dock(DockPosition::Left, window, cx);
11155            workspace.toggle_dock(DockPosition::Right, window, cx);
11156
11157            // Verify initial state
11158            assert!(
11159                workspace.left_dock().read(cx).is_open(),
11160                "Left dock should be open"
11161            );
11162            assert_eq!(
11163                workspace
11164                    .left_dock()
11165                    .read(cx)
11166                    .visible_panel()
11167                    .unwrap()
11168                    .panel_id(),
11169                left_panel.panel_id(),
11170                "Left panel should be visible in left dock"
11171            );
11172            assert!(
11173                workspace.right_dock().read(cx).is_open(),
11174                "Right dock should be open"
11175            );
11176            assert_eq!(
11177                workspace
11178                    .right_dock()
11179                    .read(cx)
11180                    .visible_panel()
11181                    .unwrap()
11182                    .panel_id(),
11183                right_panel.panel_id(),
11184                "Right panel should be visible in right dock"
11185            );
11186            assert!(
11187                !workspace.bottom_dock().read(cx).is_open(),
11188                "Bottom dock should be closed"
11189            );
11190
11191            (left_panel, right_panel)
11192        });
11193
11194        // Focus the left panel and move it to the next position (bottom dock)
11195        workspace.update_in(cx, |workspace, window, cx| {
11196            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11197            assert!(
11198                left_panel.read(cx).focus_handle(cx).is_focused(window),
11199                "Left panel should be focused"
11200            );
11201        });
11202
11203        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11204
11205        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11206        workspace.update(cx, |workspace, cx| {
11207            assert!(
11208                !workspace.left_dock().read(cx).is_open(),
11209                "Left dock should be closed"
11210            );
11211            assert!(
11212                workspace.bottom_dock().read(cx).is_open(),
11213                "Bottom dock should now be open"
11214            );
11215            assert_eq!(
11216                left_panel.read(cx).position,
11217                DockPosition::Bottom,
11218                "Left panel should now be in the bottom dock"
11219            );
11220            assert_eq!(
11221                workspace
11222                    .bottom_dock()
11223                    .read(cx)
11224                    .visible_panel()
11225                    .unwrap()
11226                    .panel_id(),
11227                left_panel.panel_id(),
11228                "Left panel should be the visible panel in the bottom dock"
11229            );
11230        });
11231
11232        // Toggle all docks off
11233        workspace.update_in(cx, |workspace, window, cx| {
11234            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11235            assert!(
11236                !workspace.left_dock().read(cx).is_open(),
11237                "Left dock should be closed"
11238            );
11239            assert!(
11240                !workspace.right_dock().read(cx).is_open(),
11241                "Right dock should be closed"
11242            );
11243            assert!(
11244                !workspace.bottom_dock().read(cx).is_open(),
11245                "Bottom dock should be closed"
11246            );
11247        });
11248
11249        // Toggle all docks back on and verify positions are restored
11250        workspace.update_in(cx, |workspace, window, cx| {
11251            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11252            assert!(
11253                !workspace.left_dock().read(cx).is_open(),
11254                "Left dock should remain closed"
11255            );
11256            assert!(
11257                workspace.right_dock().read(cx).is_open(),
11258                "Right dock should remain open"
11259            );
11260            assert!(
11261                workspace.bottom_dock().read(cx).is_open(),
11262                "Bottom dock should remain open"
11263            );
11264            assert_eq!(
11265                left_panel.read(cx).position,
11266                DockPosition::Bottom,
11267                "Left panel should remain in the bottom dock"
11268            );
11269            assert_eq!(
11270                right_panel.read(cx).position,
11271                DockPosition::Right,
11272                "Right panel should remain in the right dock"
11273            );
11274            assert_eq!(
11275                workspace
11276                    .bottom_dock()
11277                    .read(cx)
11278                    .visible_panel()
11279                    .unwrap()
11280                    .panel_id(),
11281                left_panel.panel_id(),
11282                "Left panel should be the visible panel in the right dock"
11283            );
11284        });
11285    }
11286
11287    #[gpui::test]
11288    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11289        init_test(cx);
11290
11291        let fs = FakeFs::new(cx.executor());
11292
11293        let project = Project::test(fs, None, cx).await;
11294        let (workspace, cx) =
11295            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11296
11297        // Let's arrange the panes like this:
11298        //
11299        // +-----------------------+
11300        // |         top           |
11301        // +------+--------+-------+
11302        // | left | center | right |
11303        // +------+--------+-------+
11304        // |        bottom         |
11305        // +-----------------------+
11306
11307        let top_item = cx.new(|cx| {
11308            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11309        });
11310        let bottom_item = cx.new(|cx| {
11311            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11312        });
11313        let left_item = cx.new(|cx| {
11314            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11315        });
11316        let right_item = cx.new(|cx| {
11317            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11318        });
11319        let center_item = cx.new(|cx| {
11320            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11321        });
11322
11323        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11324            let top_pane_id = workspace.active_pane().entity_id();
11325            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11326            workspace.split_pane(
11327                workspace.active_pane().clone(),
11328                SplitDirection::Down,
11329                window,
11330                cx,
11331            );
11332            top_pane_id
11333        });
11334        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11335            let bottom_pane_id = workspace.active_pane().entity_id();
11336            workspace.add_item_to_active_pane(
11337                Box::new(bottom_item.clone()),
11338                None,
11339                false,
11340                window,
11341                cx,
11342            );
11343            workspace.split_pane(
11344                workspace.active_pane().clone(),
11345                SplitDirection::Up,
11346                window,
11347                cx,
11348            );
11349            bottom_pane_id
11350        });
11351        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11352            let left_pane_id = workspace.active_pane().entity_id();
11353            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11354            workspace.split_pane(
11355                workspace.active_pane().clone(),
11356                SplitDirection::Right,
11357                window,
11358                cx,
11359            );
11360            left_pane_id
11361        });
11362        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11363            let right_pane_id = workspace.active_pane().entity_id();
11364            workspace.add_item_to_active_pane(
11365                Box::new(right_item.clone()),
11366                None,
11367                false,
11368                window,
11369                cx,
11370            );
11371            workspace.split_pane(
11372                workspace.active_pane().clone(),
11373                SplitDirection::Left,
11374                window,
11375                cx,
11376            );
11377            right_pane_id
11378        });
11379        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11380            let center_pane_id = workspace.active_pane().entity_id();
11381            workspace.add_item_to_active_pane(
11382                Box::new(center_item.clone()),
11383                None,
11384                false,
11385                window,
11386                cx,
11387            );
11388            center_pane_id
11389        });
11390        cx.executor().run_until_parked();
11391
11392        workspace.update_in(cx, |workspace, window, cx| {
11393            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11394
11395            // Join into next from center pane into right
11396            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11397        });
11398
11399        workspace.update_in(cx, |workspace, window, cx| {
11400            let active_pane = workspace.active_pane();
11401            assert_eq!(right_pane_id, active_pane.entity_id());
11402            assert_eq!(2, active_pane.read(cx).items_len());
11403            let item_ids_in_pane =
11404                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11405            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11406            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11407
11408            // Join into next from right pane into bottom
11409            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11410        });
11411
11412        workspace.update_in(cx, |workspace, window, cx| {
11413            let active_pane = workspace.active_pane();
11414            assert_eq!(bottom_pane_id, active_pane.entity_id());
11415            assert_eq!(3, active_pane.read(cx).items_len());
11416            let item_ids_in_pane =
11417                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11418            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11419            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11420            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11421
11422            // Join into next from bottom pane into left
11423            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11424        });
11425
11426        workspace.update_in(cx, |workspace, window, cx| {
11427            let active_pane = workspace.active_pane();
11428            assert_eq!(left_pane_id, active_pane.entity_id());
11429            assert_eq!(4, active_pane.read(cx).items_len());
11430            let item_ids_in_pane =
11431                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11432            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11433            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11434            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11435            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11436
11437            // Join into next from left pane into top
11438            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11439        });
11440
11441        workspace.update_in(cx, |workspace, window, cx| {
11442            let active_pane = workspace.active_pane();
11443            assert_eq!(top_pane_id, active_pane.entity_id());
11444            assert_eq!(5, active_pane.read(cx).items_len());
11445            let item_ids_in_pane =
11446                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11447            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11448            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11449            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11450            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11451            assert!(item_ids_in_pane.contains(&top_item.item_id()));
11452
11453            // Single pane left: no-op
11454            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11455        });
11456
11457        workspace.update(cx, |workspace, _cx| {
11458            let active_pane = workspace.active_pane();
11459            assert_eq!(top_pane_id, active_pane.entity_id());
11460        });
11461    }
11462
11463    fn add_an_item_to_active_pane(
11464        cx: &mut VisualTestContext,
11465        workspace: &Entity<Workspace>,
11466        item_id: u64,
11467    ) -> Entity<TestItem> {
11468        let item = cx.new(|cx| {
11469            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11470                item_id,
11471                "item{item_id}.txt",
11472                cx,
11473            )])
11474        });
11475        workspace.update_in(cx, |workspace, window, cx| {
11476            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11477        });
11478        item
11479    }
11480
11481    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11482        workspace.update_in(cx, |workspace, window, cx| {
11483            workspace.split_pane(
11484                workspace.active_pane().clone(),
11485                SplitDirection::Right,
11486                window,
11487                cx,
11488            )
11489        })
11490    }
11491
11492    #[gpui::test]
11493    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11494        init_test(cx);
11495        let fs = FakeFs::new(cx.executor());
11496        let project = Project::test(fs, None, cx).await;
11497        let (workspace, cx) =
11498            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11499
11500        add_an_item_to_active_pane(cx, &workspace, 1);
11501        split_pane(cx, &workspace);
11502        add_an_item_to_active_pane(cx, &workspace, 2);
11503        split_pane(cx, &workspace); // empty pane
11504        split_pane(cx, &workspace);
11505        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11506
11507        cx.executor().run_until_parked();
11508
11509        workspace.update(cx, |workspace, cx| {
11510            let num_panes = workspace.panes().len();
11511            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11512            let active_item = workspace
11513                .active_pane()
11514                .read(cx)
11515                .active_item()
11516                .expect("item is in focus");
11517
11518            assert_eq!(num_panes, 4);
11519            assert_eq!(num_items_in_current_pane, 1);
11520            assert_eq!(active_item.item_id(), last_item.item_id());
11521        });
11522
11523        workspace.update_in(cx, |workspace, window, cx| {
11524            workspace.join_all_panes(window, cx);
11525        });
11526
11527        workspace.update(cx, |workspace, cx| {
11528            let num_panes = workspace.panes().len();
11529            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11530            let active_item = workspace
11531                .active_pane()
11532                .read(cx)
11533                .active_item()
11534                .expect("item is in focus");
11535
11536            assert_eq!(num_panes, 1);
11537            assert_eq!(num_items_in_current_pane, 3);
11538            assert_eq!(active_item.item_id(), last_item.item_id());
11539        });
11540    }
11541    struct TestModal(FocusHandle);
11542
11543    impl TestModal {
11544        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11545            Self(cx.focus_handle())
11546        }
11547    }
11548
11549    impl EventEmitter<DismissEvent> for TestModal {}
11550
11551    impl Focusable for TestModal {
11552        fn focus_handle(&self, _cx: &App) -> FocusHandle {
11553            self.0.clone()
11554        }
11555    }
11556
11557    impl ModalView for TestModal {}
11558
11559    impl Render for TestModal {
11560        fn render(
11561            &mut self,
11562            _window: &mut Window,
11563            _cx: &mut Context<TestModal>,
11564        ) -> impl IntoElement {
11565            div().track_focus(&self.0)
11566        }
11567    }
11568
11569    #[gpui::test]
11570    async fn test_panels(cx: &mut gpui::TestAppContext) {
11571        init_test(cx);
11572        let fs = FakeFs::new(cx.executor());
11573
11574        let project = Project::test(fs, [], cx).await;
11575        let (multi_workspace, cx) =
11576            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11577        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11578
11579        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11580            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11581            workspace.add_panel(panel_1.clone(), window, cx);
11582            workspace.toggle_dock(DockPosition::Left, window, cx);
11583            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11584            workspace.add_panel(panel_2.clone(), window, cx);
11585            workspace.toggle_dock(DockPosition::Right, window, cx);
11586
11587            let left_dock = workspace.left_dock();
11588            assert_eq!(
11589                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11590                panel_1.panel_id()
11591            );
11592            assert_eq!(
11593                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11594                panel_1.size(window, cx)
11595            );
11596
11597            left_dock.update(cx, |left_dock, cx| {
11598                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11599            });
11600            assert_eq!(
11601                workspace
11602                    .right_dock()
11603                    .read(cx)
11604                    .visible_panel()
11605                    .unwrap()
11606                    .panel_id(),
11607                panel_2.panel_id(),
11608            );
11609
11610            (panel_1, panel_2)
11611        });
11612
11613        // Move panel_1 to the right
11614        panel_1.update_in(cx, |panel_1, window, cx| {
11615            panel_1.set_position(DockPosition::Right, window, cx)
11616        });
11617
11618        workspace.update_in(cx, |workspace, window, cx| {
11619            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11620            // Since it was the only panel on the left, the left dock should now be closed.
11621            assert!(!workspace.left_dock().read(cx).is_open());
11622            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11623            let right_dock = workspace.right_dock();
11624            assert_eq!(
11625                right_dock.read(cx).visible_panel().unwrap().panel_id(),
11626                panel_1.panel_id()
11627            );
11628            assert_eq!(
11629                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11630                px(1337.)
11631            );
11632
11633            // Now we move panel_2 to the left
11634            panel_2.set_position(DockPosition::Left, window, cx);
11635        });
11636
11637        workspace.update(cx, |workspace, cx| {
11638            // Since panel_2 was not visible on the right, we don't open the left dock.
11639            assert!(!workspace.left_dock().read(cx).is_open());
11640            // And the right dock is unaffected in its displaying of panel_1
11641            assert!(workspace.right_dock().read(cx).is_open());
11642            assert_eq!(
11643                workspace
11644                    .right_dock()
11645                    .read(cx)
11646                    .visible_panel()
11647                    .unwrap()
11648                    .panel_id(),
11649                panel_1.panel_id(),
11650            );
11651        });
11652
11653        // Move panel_1 back to the left
11654        panel_1.update_in(cx, |panel_1, window, cx| {
11655            panel_1.set_position(DockPosition::Left, window, cx)
11656        });
11657
11658        workspace.update_in(cx, |workspace, window, cx| {
11659            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11660            let left_dock = workspace.left_dock();
11661            assert!(left_dock.read(cx).is_open());
11662            assert_eq!(
11663                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11664                panel_1.panel_id()
11665            );
11666            assert_eq!(
11667                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11668                px(1337.)
11669            );
11670            // And the right dock should be closed as it no longer has any panels.
11671            assert!(!workspace.right_dock().read(cx).is_open());
11672
11673            // Now we move panel_1 to the bottom
11674            panel_1.set_position(DockPosition::Bottom, window, cx);
11675        });
11676
11677        workspace.update_in(cx, |workspace, window, cx| {
11678            // Since panel_1 was visible on the left, we close the left dock.
11679            assert!(!workspace.left_dock().read(cx).is_open());
11680            // The bottom dock is sized based on the panel's default size,
11681            // since the panel orientation changed from vertical to horizontal.
11682            let bottom_dock = workspace.bottom_dock();
11683            assert_eq!(
11684                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11685                panel_1.size(window, cx),
11686            );
11687            // Close bottom dock and move panel_1 back to the left.
11688            bottom_dock.update(cx, |bottom_dock, cx| {
11689                bottom_dock.set_open(false, window, cx)
11690            });
11691            panel_1.set_position(DockPosition::Left, window, cx);
11692        });
11693
11694        // Emit activated event on panel 1
11695        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11696
11697        // Now the left dock is open and panel_1 is active and focused.
11698        workspace.update_in(cx, |workspace, window, cx| {
11699            let left_dock = workspace.left_dock();
11700            assert!(left_dock.read(cx).is_open());
11701            assert_eq!(
11702                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11703                panel_1.panel_id(),
11704            );
11705            assert!(panel_1.focus_handle(cx).is_focused(window));
11706        });
11707
11708        // Emit closed event on panel 2, which is not active
11709        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11710
11711        // Wo don't close the left dock, because panel_2 wasn't the active panel
11712        workspace.update(cx, |workspace, cx| {
11713            let left_dock = workspace.left_dock();
11714            assert!(left_dock.read(cx).is_open());
11715            assert_eq!(
11716                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11717                panel_1.panel_id(),
11718            );
11719        });
11720
11721        // Emitting a ZoomIn event shows the panel as zoomed.
11722        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11723        workspace.read_with(cx, |workspace, _| {
11724            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11725            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11726        });
11727
11728        // Move panel to another dock while it is zoomed
11729        panel_1.update_in(cx, |panel, window, cx| {
11730            panel.set_position(DockPosition::Right, window, cx)
11731        });
11732        workspace.read_with(cx, |workspace, _| {
11733            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11734
11735            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11736        });
11737
11738        // This is a helper for getting a:
11739        // - valid focus on an element,
11740        // - that isn't a part of the panes and panels system of the Workspace,
11741        // - and doesn't trigger the 'on_focus_lost' API.
11742        let focus_other_view = {
11743            let workspace = workspace.clone();
11744            move |cx: &mut VisualTestContext| {
11745                workspace.update_in(cx, |workspace, window, cx| {
11746                    if workspace.active_modal::<TestModal>(cx).is_some() {
11747                        workspace.toggle_modal(window, cx, TestModal::new);
11748                        workspace.toggle_modal(window, cx, TestModal::new);
11749                    } else {
11750                        workspace.toggle_modal(window, cx, TestModal::new);
11751                    }
11752                })
11753            }
11754        };
11755
11756        // If focus is transferred to another view that's not a panel or another pane, we still show
11757        // the panel as zoomed.
11758        focus_other_view(cx);
11759        workspace.read_with(cx, |workspace, _| {
11760            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11761            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11762        });
11763
11764        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
11765        workspace.update_in(cx, |_workspace, window, cx| {
11766            cx.focus_self(window);
11767        });
11768        workspace.read_with(cx, |workspace, _| {
11769            assert_eq!(workspace.zoomed, None);
11770            assert_eq!(workspace.zoomed_position, None);
11771        });
11772
11773        // If focus is transferred again to another view that's not a panel or a pane, we won't
11774        // show the panel as zoomed because it wasn't zoomed before.
11775        focus_other_view(cx);
11776        workspace.read_with(cx, |workspace, _| {
11777            assert_eq!(workspace.zoomed, None);
11778            assert_eq!(workspace.zoomed_position, None);
11779        });
11780
11781        // When the panel is activated, it is zoomed again.
11782        cx.dispatch_action(ToggleRightDock);
11783        workspace.read_with(cx, |workspace, _| {
11784            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11785            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11786        });
11787
11788        // Emitting a ZoomOut event unzooms the panel.
11789        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
11790        workspace.read_with(cx, |workspace, _| {
11791            assert_eq!(workspace.zoomed, None);
11792            assert_eq!(workspace.zoomed_position, None);
11793        });
11794
11795        // Emit closed event on panel 1, which is active
11796        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11797
11798        // Now the left dock is closed, because panel_1 was the active panel
11799        workspace.update(cx, |workspace, cx| {
11800            let right_dock = workspace.right_dock();
11801            assert!(!right_dock.read(cx).is_open());
11802        });
11803    }
11804
11805    #[gpui::test]
11806    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
11807        init_test(cx);
11808
11809        let fs = FakeFs::new(cx.background_executor.clone());
11810        let project = Project::test(fs, [], cx).await;
11811        let (workspace, cx) =
11812            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11813        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11814
11815        let dirty_regular_buffer = cx.new(|cx| {
11816            TestItem::new(cx)
11817                .with_dirty(true)
11818                .with_label("1.txt")
11819                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11820        });
11821        let dirty_regular_buffer_2 = cx.new(|cx| {
11822            TestItem::new(cx)
11823                .with_dirty(true)
11824                .with_label("2.txt")
11825                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11826        });
11827        let dirty_multi_buffer_with_both = cx.new(|cx| {
11828            TestItem::new(cx)
11829                .with_dirty(true)
11830                .with_buffer_kind(ItemBufferKind::Multibuffer)
11831                .with_label("Fake Project Search")
11832                .with_project_items(&[
11833                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11834                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11835                ])
11836        });
11837        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11838        workspace.update_in(cx, |workspace, window, cx| {
11839            workspace.add_item(
11840                pane.clone(),
11841                Box::new(dirty_regular_buffer.clone()),
11842                None,
11843                false,
11844                false,
11845                window,
11846                cx,
11847            );
11848            workspace.add_item(
11849                pane.clone(),
11850                Box::new(dirty_regular_buffer_2.clone()),
11851                None,
11852                false,
11853                false,
11854                window,
11855                cx,
11856            );
11857            workspace.add_item(
11858                pane.clone(),
11859                Box::new(dirty_multi_buffer_with_both.clone()),
11860                None,
11861                false,
11862                false,
11863                window,
11864                cx,
11865            );
11866        });
11867
11868        pane.update_in(cx, |pane, window, cx| {
11869            pane.activate_item(2, true, true, window, cx);
11870            assert_eq!(
11871                pane.active_item().unwrap().item_id(),
11872                multi_buffer_with_both_files_id,
11873                "Should select the multi buffer in the pane"
11874            );
11875        });
11876        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11877            pane.close_other_items(
11878                &CloseOtherItems {
11879                    save_intent: Some(SaveIntent::Save),
11880                    close_pinned: true,
11881                },
11882                None,
11883                window,
11884                cx,
11885            )
11886        });
11887        cx.background_executor.run_until_parked();
11888        assert!(!cx.has_pending_prompt());
11889        close_all_but_multi_buffer_task
11890            .await
11891            .expect("Closing all buffers but the multi buffer failed");
11892        pane.update(cx, |pane, cx| {
11893            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
11894            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
11895            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
11896            assert_eq!(pane.items_len(), 1);
11897            assert_eq!(
11898                pane.active_item().unwrap().item_id(),
11899                multi_buffer_with_both_files_id,
11900                "Should have only the multi buffer left in the pane"
11901            );
11902            assert!(
11903                dirty_multi_buffer_with_both.read(cx).is_dirty,
11904                "The multi buffer containing the unsaved buffer should still be dirty"
11905            );
11906        });
11907
11908        dirty_regular_buffer.update(cx, |buffer, cx| {
11909            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
11910        });
11911
11912        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11913            pane.close_active_item(
11914                &CloseActiveItem {
11915                    save_intent: Some(SaveIntent::Close),
11916                    close_pinned: false,
11917                },
11918                window,
11919                cx,
11920            )
11921        });
11922        cx.background_executor.run_until_parked();
11923        assert!(
11924            cx.has_pending_prompt(),
11925            "Dirty multi buffer should prompt a save dialog"
11926        );
11927        cx.simulate_prompt_answer("Save");
11928        cx.background_executor.run_until_parked();
11929        close_multi_buffer_task
11930            .await
11931            .expect("Closing the multi buffer failed");
11932        pane.update(cx, |pane, cx| {
11933            assert_eq!(
11934                dirty_multi_buffer_with_both.read(cx).save_count,
11935                1,
11936                "Multi buffer item should get be saved"
11937            );
11938            // Test impl does not save inner items, so we do not assert them
11939            assert_eq!(
11940                pane.items_len(),
11941                0,
11942                "No more items should be left in the pane"
11943            );
11944            assert!(pane.active_item().is_none());
11945        });
11946    }
11947
11948    #[gpui::test]
11949    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
11950        cx: &mut TestAppContext,
11951    ) {
11952        init_test(cx);
11953
11954        let fs = FakeFs::new(cx.background_executor.clone());
11955        let project = Project::test(fs, [], cx).await;
11956        let (workspace, cx) =
11957            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11958        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11959
11960        let dirty_regular_buffer = cx.new(|cx| {
11961            TestItem::new(cx)
11962                .with_dirty(true)
11963                .with_label("1.txt")
11964                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11965        });
11966        let dirty_regular_buffer_2 = cx.new(|cx| {
11967            TestItem::new(cx)
11968                .with_dirty(true)
11969                .with_label("2.txt")
11970                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11971        });
11972        let clear_regular_buffer = cx.new(|cx| {
11973            TestItem::new(cx)
11974                .with_label("3.txt")
11975                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11976        });
11977
11978        let dirty_multi_buffer_with_both = cx.new(|cx| {
11979            TestItem::new(cx)
11980                .with_dirty(true)
11981                .with_buffer_kind(ItemBufferKind::Multibuffer)
11982                .with_label("Fake Project Search")
11983                .with_project_items(&[
11984                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11985                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11986                    clear_regular_buffer.read(cx).project_items[0].clone(),
11987                ])
11988        });
11989        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11990        workspace.update_in(cx, |workspace, window, cx| {
11991            workspace.add_item(
11992                pane.clone(),
11993                Box::new(dirty_regular_buffer.clone()),
11994                None,
11995                false,
11996                false,
11997                window,
11998                cx,
11999            );
12000            workspace.add_item(
12001                pane.clone(),
12002                Box::new(dirty_multi_buffer_with_both.clone()),
12003                None,
12004                false,
12005                false,
12006                window,
12007                cx,
12008            );
12009        });
12010
12011        pane.update_in(cx, |pane, window, cx| {
12012            pane.activate_item(1, true, true, window, cx);
12013            assert_eq!(
12014                pane.active_item().unwrap().item_id(),
12015                multi_buffer_with_both_files_id,
12016                "Should select the multi buffer in the pane"
12017            );
12018        });
12019        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12020            pane.close_active_item(
12021                &CloseActiveItem {
12022                    save_intent: None,
12023                    close_pinned: false,
12024                },
12025                window,
12026                cx,
12027            )
12028        });
12029        cx.background_executor.run_until_parked();
12030        assert!(
12031            cx.has_pending_prompt(),
12032            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12033        );
12034    }
12035
12036    /// Tests that when `close_on_file_delete` is enabled, files are automatically
12037    /// closed when they are deleted from disk.
12038    #[gpui::test]
12039    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12040        init_test(cx);
12041
12042        // Enable the close_on_disk_deletion setting
12043        cx.update_global(|store: &mut SettingsStore, cx| {
12044            store.update_user_settings(cx, |settings| {
12045                settings.workspace.close_on_file_delete = Some(true);
12046            });
12047        });
12048
12049        let fs = FakeFs::new(cx.background_executor.clone());
12050        let project = Project::test(fs, [], cx).await;
12051        let (workspace, cx) =
12052            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12053        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12054
12055        // Create a test item that simulates a file
12056        let item = cx.new(|cx| {
12057            TestItem::new(cx)
12058                .with_label("test.txt")
12059                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12060        });
12061
12062        // Add item to workspace
12063        workspace.update_in(cx, |workspace, window, cx| {
12064            workspace.add_item(
12065                pane.clone(),
12066                Box::new(item.clone()),
12067                None,
12068                false,
12069                false,
12070                window,
12071                cx,
12072            );
12073        });
12074
12075        // Verify the item is in the pane
12076        pane.read_with(cx, |pane, _| {
12077            assert_eq!(pane.items().count(), 1);
12078        });
12079
12080        // Simulate file deletion by setting the item's deleted state
12081        item.update(cx, |item, _| {
12082            item.set_has_deleted_file(true);
12083        });
12084
12085        // Emit UpdateTab event to trigger the close behavior
12086        cx.run_until_parked();
12087        item.update(cx, |_, cx| {
12088            cx.emit(ItemEvent::UpdateTab);
12089        });
12090
12091        // Allow the close operation to complete
12092        cx.run_until_parked();
12093
12094        // Verify the item was automatically closed
12095        pane.read_with(cx, |pane, _| {
12096            assert_eq!(
12097                pane.items().count(),
12098                0,
12099                "Item should be automatically closed when file is deleted"
12100            );
12101        });
12102    }
12103
12104    /// Tests that when `close_on_file_delete` is disabled (default), files remain
12105    /// open with a strikethrough when they are deleted from disk.
12106    #[gpui::test]
12107    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12108        init_test(cx);
12109
12110        // Ensure close_on_disk_deletion is disabled (default)
12111        cx.update_global(|store: &mut SettingsStore, cx| {
12112            store.update_user_settings(cx, |settings| {
12113                settings.workspace.close_on_file_delete = Some(false);
12114            });
12115        });
12116
12117        let fs = FakeFs::new(cx.background_executor.clone());
12118        let project = Project::test(fs, [], cx).await;
12119        let (workspace, cx) =
12120            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12121        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12122
12123        // Create a test item that simulates a file
12124        let item = cx.new(|cx| {
12125            TestItem::new(cx)
12126                .with_label("test.txt")
12127                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12128        });
12129
12130        // Add item to workspace
12131        workspace.update_in(cx, |workspace, window, cx| {
12132            workspace.add_item(
12133                pane.clone(),
12134                Box::new(item.clone()),
12135                None,
12136                false,
12137                false,
12138                window,
12139                cx,
12140            );
12141        });
12142
12143        // Verify the item is in the pane
12144        pane.read_with(cx, |pane, _| {
12145            assert_eq!(pane.items().count(), 1);
12146        });
12147
12148        // Simulate file deletion
12149        item.update(cx, |item, _| {
12150            item.set_has_deleted_file(true);
12151        });
12152
12153        // Emit UpdateTab event
12154        cx.run_until_parked();
12155        item.update(cx, |_, cx| {
12156            cx.emit(ItemEvent::UpdateTab);
12157        });
12158
12159        // Allow any potential close operation to complete
12160        cx.run_until_parked();
12161
12162        // Verify the item remains open (with strikethrough)
12163        pane.read_with(cx, |pane, _| {
12164            assert_eq!(
12165                pane.items().count(),
12166                1,
12167                "Item should remain open when close_on_disk_deletion is disabled"
12168            );
12169        });
12170
12171        // Verify the item shows as deleted
12172        item.read_with(cx, |item, _| {
12173            assert!(
12174                item.has_deleted_file,
12175                "Item should be marked as having deleted file"
12176            );
12177        });
12178    }
12179
12180    /// Tests that dirty files are not automatically closed when deleted from disk,
12181    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12182    /// unsaved changes without being prompted.
12183    #[gpui::test]
12184    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12185        init_test(cx);
12186
12187        // Enable the close_on_file_delete setting
12188        cx.update_global(|store: &mut SettingsStore, cx| {
12189            store.update_user_settings(cx, |settings| {
12190                settings.workspace.close_on_file_delete = Some(true);
12191            });
12192        });
12193
12194        let fs = FakeFs::new(cx.background_executor.clone());
12195        let project = Project::test(fs, [], cx).await;
12196        let (workspace, cx) =
12197            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12198        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12199
12200        // Create a dirty test item
12201        let item = cx.new(|cx| {
12202            TestItem::new(cx)
12203                .with_dirty(true)
12204                .with_label("test.txt")
12205                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12206        });
12207
12208        // Add item to workspace
12209        workspace.update_in(cx, |workspace, window, cx| {
12210            workspace.add_item(
12211                pane.clone(),
12212                Box::new(item.clone()),
12213                None,
12214                false,
12215                false,
12216                window,
12217                cx,
12218            );
12219        });
12220
12221        // Simulate file deletion
12222        item.update(cx, |item, _| {
12223            item.set_has_deleted_file(true);
12224        });
12225
12226        // Emit UpdateTab event to trigger the close behavior
12227        cx.run_until_parked();
12228        item.update(cx, |_, cx| {
12229            cx.emit(ItemEvent::UpdateTab);
12230        });
12231
12232        // Allow any potential close operation to complete
12233        cx.run_until_parked();
12234
12235        // Verify the item remains open (dirty files are not auto-closed)
12236        pane.read_with(cx, |pane, _| {
12237            assert_eq!(
12238                pane.items().count(),
12239                1,
12240                "Dirty items should not be automatically closed even when file is deleted"
12241            );
12242        });
12243
12244        // Verify the item is marked as deleted and still dirty
12245        item.read_with(cx, |item, _| {
12246            assert!(
12247                item.has_deleted_file,
12248                "Item should be marked as having deleted file"
12249            );
12250            assert!(item.is_dirty, "Item should still be dirty");
12251        });
12252    }
12253
12254    /// Tests that navigation history is cleaned up when files are auto-closed
12255    /// due to deletion from disk.
12256    #[gpui::test]
12257    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12258        init_test(cx);
12259
12260        // Enable the close_on_file_delete setting
12261        cx.update_global(|store: &mut SettingsStore, cx| {
12262            store.update_user_settings(cx, |settings| {
12263                settings.workspace.close_on_file_delete = Some(true);
12264            });
12265        });
12266
12267        let fs = FakeFs::new(cx.background_executor.clone());
12268        let project = Project::test(fs, [], cx).await;
12269        let (workspace, cx) =
12270            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12271        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12272
12273        // Create test items
12274        let item1 = cx.new(|cx| {
12275            TestItem::new(cx)
12276                .with_label("test1.txt")
12277                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12278        });
12279        let item1_id = item1.item_id();
12280
12281        let item2 = cx.new(|cx| {
12282            TestItem::new(cx)
12283                .with_label("test2.txt")
12284                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12285        });
12286
12287        // Add items to workspace
12288        workspace.update_in(cx, |workspace, window, cx| {
12289            workspace.add_item(
12290                pane.clone(),
12291                Box::new(item1.clone()),
12292                None,
12293                false,
12294                false,
12295                window,
12296                cx,
12297            );
12298            workspace.add_item(
12299                pane.clone(),
12300                Box::new(item2.clone()),
12301                None,
12302                false,
12303                false,
12304                window,
12305                cx,
12306            );
12307        });
12308
12309        // Activate item1 to ensure it gets navigation entries
12310        pane.update_in(cx, |pane, window, cx| {
12311            pane.activate_item(0, true, true, window, cx);
12312        });
12313
12314        // Switch to item2 and back to create navigation history
12315        pane.update_in(cx, |pane, window, cx| {
12316            pane.activate_item(1, true, true, window, cx);
12317        });
12318        cx.run_until_parked();
12319
12320        pane.update_in(cx, |pane, window, cx| {
12321            pane.activate_item(0, true, true, window, cx);
12322        });
12323        cx.run_until_parked();
12324
12325        // Simulate file deletion for item1
12326        item1.update(cx, |item, _| {
12327            item.set_has_deleted_file(true);
12328        });
12329
12330        // Emit UpdateTab event to trigger the close behavior
12331        item1.update(cx, |_, cx| {
12332            cx.emit(ItemEvent::UpdateTab);
12333        });
12334        cx.run_until_parked();
12335
12336        // Verify item1 was closed
12337        pane.read_with(cx, |pane, _| {
12338            assert_eq!(
12339                pane.items().count(),
12340                1,
12341                "Should have 1 item remaining after auto-close"
12342            );
12343        });
12344
12345        // Check navigation history after close
12346        let has_item = pane.read_with(cx, |pane, cx| {
12347            let mut has_item = false;
12348            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12349                if entry.item.id() == item1_id {
12350                    has_item = true;
12351                }
12352            });
12353            has_item
12354        });
12355
12356        assert!(
12357            !has_item,
12358            "Navigation history should not contain closed item entries"
12359        );
12360    }
12361
12362    #[gpui::test]
12363    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12364        cx: &mut TestAppContext,
12365    ) {
12366        init_test(cx);
12367
12368        let fs = FakeFs::new(cx.background_executor.clone());
12369        let project = Project::test(fs, [], cx).await;
12370        let (workspace, cx) =
12371            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12372        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12373
12374        let dirty_regular_buffer = cx.new(|cx| {
12375            TestItem::new(cx)
12376                .with_dirty(true)
12377                .with_label("1.txt")
12378                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12379        });
12380        let dirty_regular_buffer_2 = cx.new(|cx| {
12381            TestItem::new(cx)
12382                .with_dirty(true)
12383                .with_label("2.txt")
12384                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12385        });
12386        let clear_regular_buffer = cx.new(|cx| {
12387            TestItem::new(cx)
12388                .with_label("3.txt")
12389                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12390        });
12391
12392        let dirty_multi_buffer = cx.new(|cx| {
12393            TestItem::new(cx)
12394                .with_dirty(true)
12395                .with_buffer_kind(ItemBufferKind::Multibuffer)
12396                .with_label("Fake Project Search")
12397                .with_project_items(&[
12398                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12399                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12400                    clear_regular_buffer.read(cx).project_items[0].clone(),
12401                ])
12402        });
12403        workspace.update_in(cx, |workspace, window, cx| {
12404            workspace.add_item(
12405                pane.clone(),
12406                Box::new(dirty_regular_buffer.clone()),
12407                None,
12408                false,
12409                false,
12410                window,
12411                cx,
12412            );
12413            workspace.add_item(
12414                pane.clone(),
12415                Box::new(dirty_regular_buffer_2.clone()),
12416                None,
12417                false,
12418                false,
12419                window,
12420                cx,
12421            );
12422            workspace.add_item(
12423                pane.clone(),
12424                Box::new(dirty_multi_buffer.clone()),
12425                None,
12426                false,
12427                false,
12428                window,
12429                cx,
12430            );
12431        });
12432
12433        pane.update_in(cx, |pane, window, cx| {
12434            pane.activate_item(2, true, true, window, cx);
12435            assert_eq!(
12436                pane.active_item().unwrap().item_id(),
12437                dirty_multi_buffer.item_id(),
12438                "Should select the multi buffer in the pane"
12439            );
12440        });
12441        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12442            pane.close_active_item(
12443                &CloseActiveItem {
12444                    save_intent: None,
12445                    close_pinned: false,
12446                },
12447                window,
12448                cx,
12449            )
12450        });
12451        cx.background_executor.run_until_parked();
12452        assert!(
12453            !cx.has_pending_prompt(),
12454            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12455        );
12456        close_multi_buffer_task
12457            .await
12458            .expect("Closing multi buffer failed");
12459        pane.update(cx, |pane, cx| {
12460            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12461            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12462            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12463            assert_eq!(
12464                pane.items()
12465                    .map(|item| item.item_id())
12466                    .sorted()
12467                    .collect::<Vec<_>>(),
12468                vec![
12469                    dirty_regular_buffer.item_id(),
12470                    dirty_regular_buffer_2.item_id(),
12471                ],
12472                "Should have no multi buffer left in the pane"
12473            );
12474            assert!(dirty_regular_buffer.read(cx).is_dirty);
12475            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12476        });
12477    }
12478
12479    #[gpui::test]
12480    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12481        init_test(cx);
12482        let fs = FakeFs::new(cx.executor());
12483        let project = Project::test(fs, [], cx).await;
12484        let (multi_workspace, cx) =
12485            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12486        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12487
12488        // Add a new panel to the right dock, opening the dock and setting the
12489        // focus to the new panel.
12490        let panel = workspace.update_in(cx, |workspace, window, cx| {
12491            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12492            workspace.add_panel(panel.clone(), window, cx);
12493
12494            workspace
12495                .right_dock()
12496                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12497
12498            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12499
12500            panel
12501        });
12502
12503        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12504        // panel to the next valid position which, in this case, is the left
12505        // dock.
12506        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12507        workspace.update(cx, |workspace, cx| {
12508            assert!(workspace.left_dock().read(cx).is_open());
12509            assert_eq!(panel.read(cx).position, DockPosition::Left);
12510        });
12511
12512        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12513        // panel to the next valid position which, in this case, is the bottom
12514        // dock.
12515        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12516        workspace.update(cx, |workspace, cx| {
12517            assert!(workspace.bottom_dock().read(cx).is_open());
12518            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12519        });
12520
12521        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12522        // around moving the panel to its initial position, the right dock.
12523        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12524        workspace.update(cx, |workspace, cx| {
12525            assert!(workspace.right_dock().read(cx).is_open());
12526            assert_eq!(panel.read(cx).position, DockPosition::Right);
12527        });
12528
12529        // Remove focus from the panel, ensuring that, if the panel is not
12530        // focused, the `MoveFocusedPanelToNextPosition` action does not update
12531        // the panel's position, so the panel is still in the right dock.
12532        workspace.update_in(cx, |workspace, window, cx| {
12533            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12534        });
12535
12536        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12537        workspace.update(cx, |workspace, cx| {
12538            assert!(workspace.right_dock().read(cx).is_open());
12539            assert_eq!(panel.read(cx).position, DockPosition::Right);
12540        });
12541    }
12542
12543    #[gpui::test]
12544    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12545        init_test(cx);
12546
12547        let fs = FakeFs::new(cx.executor());
12548        let project = Project::test(fs, [], cx).await;
12549        let (workspace, cx) =
12550            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12551
12552        let item_1 = cx.new(|cx| {
12553            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12554        });
12555        workspace.update_in(cx, |workspace, window, cx| {
12556            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12557            workspace.move_item_to_pane_in_direction(
12558                &MoveItemToPaneInDirection {
12559                    direction: SplitDirection::Right,
12560                    focus: true,
12561                    clone: false,
12562                },
12563                window,
12564                cx,
12565            );
12566            workspace.move_item_to_pane_at_index(
12567                &MoveItemToPane {
12568                    destination: 3,
12569                    focus: true,
12570                    clone: false,
12571                },
12572                window,
12573                cx,
12574            );
12575
12576            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12577            assert_eq!(
12578                pane_items_paths(&workspace.active_pane, cx),
12579                vec!["first.txt".to_string()],
12580                "Single item was not moved anywhere"
12581            );
12582        });
12583
12584        let item_2 = cx.new(|cx| {
12585            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12586        });
12587        workspace.update_in(cx, |workspace, window, cx| {
12588            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12589            assert_eq!(
12590                pane_items_paths(&workspace.panes[0], cx),
12591                vec!["first.txt".to_string(), "second.txt".to_string()],
12592            );
12593            workspace.move_item_to_pane_in_direction(
12594                &MoveItemToPaneInDirection {
12595                    direction: SplitDirection::Right,
12596                    focus: true,
12597                    clone: false,
12598                },
12599                window,
12600                cx,
12601            );
12602
12603            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12604            assert_eq!(
12605                pane_items_paths(&workspace.panes[0], cx),
12606                vec!["first.txt".to_string()],
12607                "After moving, one item should be left in the original pane"
12608            );
12609            assert_eq!(
12610                pane_items_paths(&workspace.panes[1], cx),
12611                vec!["second.txt".to_string()],
12612                "New item should have been moved to the new pane"
12613            );
12614        });
12615
12616        let item_3 = cx.new(|cx| {
12617            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12618        });
12619        workspace.update_in(cx, |workspace, window, cx| {
12620            let original_pane = workspace.panes[0].clone();
12621            workspace.set_active_pane(&original_pane, window, cx);
12622            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12623            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12624            assert_eq!(
12625                pane_items_paths(&workspace.active_pane, cx),
12626                vec!["first.txt".to_string(), "third.txt".to_string()],
12627                "New pane should be ready to move one item out"
12628            );
12629
12630            workspace.move_item_to_pane_at_index(
12631                &MoveItemToPane {
12632                    destination: 3,
12633                    focus: true,
12634                    clone: false,
12635                },
12636                window,
12637                cx,
12638            );
12639            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12640            assert_eq!(
12641                pane_items_paths(&workspace.active_pane, cx),
12642                vec!["first.txt".to_string()],
12643                "After moving, one item should be left in the original pane"
12644            );
12645            assert_eq!(
12646                pane_items_paths(&workspace.panes[1], cx),
12647                vec!["second.txt".to_string()],
12648                "Previously created pane should be unchanged"
12649            );
12650            assert_eq!(
12651                pane_items_paths(&workspace.panes[2], cx),
12652                vec!["third.txt".to_string()],
12653                "New item should have been moved to the new pane"
12654            );
12655        });
12656    }
12657
12658    #[gpui::test]
12659    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12660        init_test(cx);
12661
12662        let fs = FakeFs::new(cx.executor());
12663        let project = Project::test(fs, [], cx).await;
12664        let (workspace, cx) =
12665            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12666
12667        let item_1 = cx.new(|cx| {
12668            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12669        });
12670        workspace.update_in(cx, |workspace, window, cx| {
12671            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12672            workspace.move_item_to_pane_in_direction(
12673                &MoveItemToPaneInDirection {
12674                    direction: SplitDirection::Right,
12675                    focus: true,
12676                    clone: true,
12677                },
12678                window,
12679                cx,
12680            );
12681        });
12682        cx.run_until_parked();
12683        workspace.update_in(cx, |workspace, window, cx| {
12684            workspace.move_item_to_pane_at_index(
12685                &MoveItemToPane {
12686                    destination: 3,
12687                    focus: true,
12688                    clone: true,
12689                },
12690                window,
12691                cx,
12692            );
12693        });
12694        cx.run_until_parked();
12695
12696        workspace.update(cx, |workspace, cx| {
12697            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12698            for pane in workspace.panes() {
12699                assert_eq!(
12700                    pane_items_paths(pane, cx),
12701                    vec!["first.txt".to_string()],
12702                    "Single item exists in all panes"
12703                );
12704            }
12705        });
12706
12707        // verify that the active pane has been updated after waiting for the
12708        // pane focus event to fire and resolve
12709        workspace.read_with(cx, |workspace, _app| {
12710            assert_eq!(
12711                workspace.active_pane(),
12712                &workspace.panes[2],
12713                "The third pane should be the active one: {:?}",
12714                workspace.panes
12715            );
12716        })
12717    }
12718
12719    #[gpui::test]
12720    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12721        init_test(cx);
12722
12723        let fs = FakeFs::new(cx.executor());
12724        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12725
12726        let project = Project::test(fs, ["root".as_ref()], cx).await;
12727        let (workspace, cx) =
12728            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12729
12730        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12731        // Add item to pane A with project path
12732        let item_a = cx.new(|cx| {
12733            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12734        });
12735        workspace.update_in(cx, |workspace, window, cx| {
12736            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12737        });
12738
12739        // Split to create pane B
12740        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12741            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12742        });
12743
12744        // Add item with SAME project path to pane B, and pin it
12745        let item_b = cx.new(|cx| {
12746            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12747        });
12748        pane_b.update_in(cx, |pane, window, cx| {
12749            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12750            pane.set_pinned_count(1);
12751        });
12752
12753        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12754        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12755
12756        // close_pinned: false should only close the unpinned copy
12757        workspace.update_in(cx, |workspace, window, cx| {
12758            workspace.close_item_in_all_panes(
12759                &CloseItemInAllPanes {
12760                    save_intent: Some(SaveIntent::Close),
12761                    close_pinned: false,
12762                },
12763                window,
12764                cx,
12765            )
12766        });
12767        cx.executor().run_until_parked();
12768
12769        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
12770        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12771        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
12772        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
12773
12774        // Split again, seeing as closing the previous item also closed its
12775        // pane, so only pane remains, which does not allow us to properly test
12776        // that both items close when `close_pinned: true`.
12777        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
12778            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
12779        });
12780
12781        // Add an item with the same project path to pane C so that
12782        // close_item_in_all_panes can determine what to close across all panes
12783        // (it reads the active item from the active pane, and split_pane
12784        // creates an empty pane).
12785        let item_c = cx.new(|cx| {
12786            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12787        });
12788        pane_c.update_in(cx, |pane, window, cx| {
12789            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
12790        });
12791
12792        // close_pinned: true should close the pinned copy too
12793        workspace.update_in(cx, |workspace, window, cx| {
12794            let panes_count = workspace.panes().len();
12795            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
12796
12797            workspace.close_item_in_all_panes(
12798                &CloseItemInAllPanes {
12799                    save_intent: Some(SaveIntent::Close),
12800                    close_pinned: true,
12801                },
12802                window,
12803                cx,
12804            )
12805        });
12806        cx.executor().run_until_parked();
12807
12808        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12809        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
12810        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
12811        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
12812    }
12813
12814    mod register_project_item_tests {
12815
12816        use super::*;
12817
12818        // View
12819        struct TestPngItemView {
12820            focus_handle: FocusHandle,
12821        }
12822        // Model
12823        struct TestPngItem {}
12824
12825        impl project::ProjectItem for TestPngItem {
12826            fn try_open(
12827                _project: &Entity<Project>,
12828                path: &ProjectPath,
12829                cx: &mut App,
12830            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12831                if path.path.extension().unwrap() == "png" {
12832                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
12833                } else {
12834                    None
12835                }
12836            }
12837
12838            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12839                None
12840            }
12841
12842            fn project_path(&self, _: &App) -> Option<ProjectPath> {
12843                None
12844            }
12845
12846            fn is_dirty(&self) -> bool {
12847                false
12848            }
12849        }
12850
12851        impl Item for TestPngItemView {
12852            type Event = ();
12853            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12854                "".into()
12855            }
12856        }
12857        impl EventEmitter<()> for TestPngItemView {}
12858        impl Focusable for TestPngItemView {
12859            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12860                self.focus_handle.clone()
12861            }
12862        }
12863
12864        impl Render for TestPngItemView {
12865            fn render(
12866                &mut self,
12867                _window: &mut Window,
12868                _cx: &mut Context<Self>,
12869            ) -> impl IntoElement {
12870                Empty
12871            }
12872        }
12873
12874        impl ProjectItem for TestPngItemView {
12875            type Item = TestPngItem;
12876
12877            fn for_project_item(
12878                _project: Entity<Project>,
12879                _pane: Option<&Pane>,
12880                _item: Entity<Self::Item>,
12881                _: &mut Window,
12882                cx: &mut Context<Self>,
12883            ) -> Self
12884            where
12885                Self: Sized,
12886            {
12887                Self {
12888                    focus_handle: cx.focus_handle(),
12889                }
12890            }
12891        }
12892
12893        // View
12894        struct TestIpynbItemView {
12895            focus_handle: FocusHandle,
12896        }
12897        // Model
12898        struct TestIpynbItem {}
12899
12900        impl project::ProjectItem for TestIpynbItem {
12901            fn try_open(
12902                _project: &Entity<Project>,
12903                path: &ProjectPath,
12904                cx: &mut App,
12905            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12906                if path.path.extension().unwrap() == "ipynb" {
12907                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
12908                } else {
12909                    None
12910                }
12911            }
12912
12913            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12914                None
12915            }
12916
12917            fn project_path(&self, _: &App) -> Option<ProjectPath> {
12918                None
12919            }
12920
12921            fn is_dirty(&self) -> bool {
12922                false
12923            }
12924        }
12925
12926        impl Item for TestIpynbItemView {
12927            type Event = ();
12928            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12929                "".into()
12930            }
12931        }
12932        impl EventEmitter<()> for TestIpynbItemView {}
12933        impl Focusable for TestIpynbItemView {
12934            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12935                self.focus_handle.clone()
12936            }
12937        }
12938
12939        impl Render for TestIpynbItemView {
12940            fn render(
12941                &mut self,
12942                _window: &mut Window,
12943                _cx: &mut Context<Self>,
12944            ) -> impl IntoElement {
12945                Empty
12946            }
12947        }
12948
12949        impl ProjectItem for TestIpynbItemView {
12950            type Item = TestIpynbItem;
12951
12952            fn for_project_item(
12953                _project: Entity<Project>,
12954                _pane: Option<&Pane>,
12955                _item: Entity<Self::Item>,
12956                _: &mut Window,
12957                cx: &mut Context<Self>,
12958            ) -> Self
12959            where
12960                Self: Sized,
12961            {
12962                Self {
12963                    focus_handle: cx.focus_handle(),
12964                }
12965            }
12966        }
12967
12968        struct TestAlternatePngItemView {
12969            focus_handle: FocusHandle,
12970        }
12971
12972        impl Item for TestAlternatePngItemView {
12973            type Event = ();
12974            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12975                "".into()
12976            }
12977        }
12978
12979        impl EventEmitter<()> for TestAlternatePngItemView {}
12980        impl Focusable for TestAlternatePngItemView {
12981            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12982                self.focus_handle.clone()
12983            }
12984        }
12985
12986        impl Render for TestAlternatePngItemView {
12987            fn render(
12988                &mut self,
12989                _window: &mut Window,
12990                _cx: &mut Context<Self>,
12991            ) -> impl IntoElement {
12992                Empty
12993            }
12994        }
12995
12996        impl ProjectItem for TestAlternatePngItemView {
12997            type Item = TestPngItem;
12998
12999            fn for_project_item(
13000                _project: Entity<Project>,
13001                _pane: Option<&Pane>,
13002                _item: Entity<Self::Item>,
13003                _: &mut Window,
13004                cx: &mut Context<Self>,
13005            ) -> Self
13006            where
13007                Self: Sized,
13008            {
13009                Self {
13010                    focus_handle: cx.focus_handle(),
13011                }
13012            }
13013        }
13014
13015        #[gpui::test]
13016        async fn test_register_project_item(cx: &mut TestAppContext) {
13017            init_test(cx);
13018
13019            cx.update(|cx| {
13020                register_project_item::<TestPngItemView>(cx);
13021                register_project_item::<TestIpynbItemView>(cx);
13022            });
13023
13024            let fs = FakeFs::new(cx.executor());
13025            fs.insert_tree(
13026                "/root1",
13027                json!({
13028                    "one.png": "BINARYDATAHERE",
13029                    "two.ipynb": "{ totally a notebook }",
13030                    "three.txt": "editing text, sure why not?"
13031                }),
13032            )
13033            .await;
13034
13035            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13036            let (workspace, cx) =
13037                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13038
13039            let worktree_id = project.update(cx, |project, cx| {
13040                project.worktrees(cx).next().unwrap().read(cx).id()
13041            });
13042
13043            let handle = workspace
13044                .update_in(cx, |workspace, window, cx| {
13045                    let project_path = (worktree_id, rel_path("one.png"));
13046                    workspace.open_path(project_path, None, true, window, cx)
13047                })
13048                .await
13049                .unwrap();
13050
13051            // Now we can check if the handle we got back errored or not
13052            assert_eq!(
13053                handle.to_any_view().entity_type(),
13054                TypeId::of::<TestPngItemView>()
13055            );
13056
13057            let handle = workspace
13058                .update_in(cx, |workspace, window, cx| {
13059                    let project_path = (worktree_id, rel_path("two.ipynb"));
13060                    workspace.open_path(project_path, None, true, window, cx)
13061                })
13062                .await
13063                .unwrap();
13064
13065            assert_eq!(
13066                handle.to_any_view().entity_type(),
13067                TypeId::of::<TestIpynbItemView>()
13068            );
13069
13070            let handle = workspace
13071                .update_in(cx, |workspace, window, cx| {
13072                    let project_path = (worktree_id, rel_path("three.txt"));
13073                    workspace.open_path(project_path, None, true, window, cx)
13074                })
13075                .await;
13076            assert!(handle.is_err());
13077        }
13078
13079        #[gpui::test]
13080        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13081            init_test(cx);
13082
13083            cx.update(|cx| {
13084                register_project_item::<TestPngItemView>(cx);
13085                register_project_item::<TestAlternatePngItemView>(cx);
13086            });
13087
13088            let fs = FakeFs::new(cx.executor());
13089            fs.insert_tree(
13090                "/root1",
13091                json!({
13092                    "one.png": "BINARYDATAHERE",
13093                    "two.ipynb": "{ totally a notebook }",
13094                    "three.txt": "editing text, sure why not?"
13095                }),
13096            )
13097            .await;
13098            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13099            let (workspace, cx) =
13100                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13101            let worktree_id = project.update(cx, |project, cx| {
13102                project.worktrees(cx).next().unwrap().read(cx).id()
13103            });
13104
13105            let handle = workspace
13106                .update_in(cx, |workspace, window, cx| {
13107                    let project_path = (worktree_id, rel_path("one.png"));
13108                    workspace.open_path(project_path, None, true, window, cx)
13109                })
13110                .await
13111                .unwrap();
13112
13113            // This _must_ be the second item registered
13114            assert_eq!(
13115                handle.to_any_view().entity_type(),
13116                TypeId::of::<TestAlternatePngItemView>()
13117            );
13118
13119            let handle = workspace
13120                .update_in(cx, |workspace, window, cx| {
13121                    let project_path = (worktree_id, rel_path("three.txt"));
13122                    workspace.open_path(project_path, None, true, window, cx)
13123                })
13124                .await;
13125            assert!(handle.is_err());
13126        }
13127    }
13128
13129    #[gpui::test]
13130    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13131        init_test(cx);
13132
13133        let fs = FakeFs::new(cx.executor());
13134        let project = Project::test(fs, [], cx).await;
13135        let (workspace, _cx) =
13136            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13137
13138        // Test with status bar shown (default)
13139        workspace.read_with(cx, |workspace, cx| {
13140            let visible = workspace.status_bar_visible(cx);
13141            assert!(visible, "Status bar should be visible by default");
13142        });
13143
13144        // Test with status bar hidden
13145        cx.update_global(|store: &mut SettingsStore, cx| {
13146            store.update_user_settings(cx, |settings| {
13147                settings.status_bar.get_or_insert_default().show = Some(false);
13148            });
13149        });
13150
13151        workspace.read_with(cx, |workspace, cx| {
13152            let visible = workspace.status_bar_visible(cx);
13153            assert!(!visible, "Status bar should be hidden when show is false");
13154        });
13155
13156        // Test with status bar shown explicitly
13157        cx.update_global(|store: &mut SettingsStore, cx| {
13158            store.update_user_settings(cx, |settings| {
13159                settings.status_bar.get_or_insert_default().show = Some(true);
13160            });
13161        });
13162
13163        workspace.read_with(cx, |workspace, cx| {
13164            let visible = workspace.status_bar_visible(cx);
13165            assert!(visible, "Status bar should be visible when show is true");
13166        });
13167    }
13168
13169    #[gpui::test]
13170    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13171        init_test(cx);
13172
13173        let fs = FakeFs::new(cx.executor());
13174        let project = Project::test(fs, [], cx).await;
13175        let (multi_workspace, cx) =
13176            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13177        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13178        let panel = workspace.update_in(cx, |workspace, window, cx| {
13179            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13180            workspace.add_panel(panel.clone(), window, cx);
13181
13182            workspace
13183                .right_dock()
13184                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13185
13186            panel
13187        });
13188
13189        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13190        let item_a = cx.new(TestItem::new);
13191        let item_b = cx.new(TestItem::new);
13192        let item_a_id = item_a.entity_id();
13193        let item_b_id = item_b.entity_id();
13194
13195        pane.update_in(cx, |pane, window, cx| {
13196            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13197            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13198        });
13199
13200        pane.read_with(cx, |pane, _| {
13201            assert_eq!(pane.items_len(), 2);
13202            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13203        });
13204
13205        workspace.update_in(cx, |workspace, window, cx| {
13206            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13207        });
13208
13209        workspace.update_in(cx, |_, window, cx| {
13210            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13211        });
13212
13213        // Assert that the `pane::CloseActiveItem` action is handled at the
13214        // workspace level when one of the dock panels is focused and, in that
13215        // case, the center pane's active item is closed but the focus is not
13216        // moved.
13217        cx.dispatch_action(pane::CloseActiveItem::default());
13218        cx.run_until_parked();
13219
13220        pane.read_with(cx, |pane, _| {
13221            assert_eq!(pane.items_len(), 1);
13222            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13223        });
13224
13225        workspace.update_in(cx, |workspace, window, cx| {
13226            assert!(workspace.right_dock().read(cx).is_open());
13227            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13228        });
13229    }
13230
13231    #[gpui::test]
13232    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13233        init_test(cx);
13234        let fs = FakeFs::new(cx.executor());
13235
13236        let project_a = Project::test(fs.clone(), [], cx).await;
13237        let project_b = Project::test(fs, [], cx).await;
13238
13239        let multi_workspace_handle =
13240            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13241        cx.run_until_parked();
13242
13243        let workspace_a = multi_workspace_handle
13244            .read_with(cx, |mw, _| mw.workspace().clone())
13245            .unwrap();
13246
13247        let _workspace_b = multi_workspace_handle
13248            .update(cx, |mw, window, cx| {
13249                mw.test_add_workspace(project_b, window, cx)
13250            })
13251            .unwrap();
13252
13253        // Switch to workspace A
13254        multi_workspace_handle
13255            .update(cx, |mw, window, cx| {
13256                mw.activate_index(0, window, cx);
13257            })
13258            .unwrap();
13259
13260        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13261
13262        // Add a panel to workspace A's right dock and open the dock
13263        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13264            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13265            workspace.add_panel(panel.clone(), window, cx);
13266            workspace
13267                .right_dock()
13268                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13269            panel
13270        });
13271
13272        // Focus the panel through the workspace (matching existing test pattern)
13273        workspace_a.update_in(cx, |workspace, window, cx| {
13274            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13275        });
13276
13277        // Zoom the panel
13278        panel.update_in(cx, |panel, window, cx| {
13279            panel.set_zoomed(true, window, cx);
13280        });
13281
13282        // Verify the panel is zoomed and the dock is open
13283        workspace_a.update_in(cx, |workspace, window, cx| {
13284            assert!(
13285                workspace.right_dock().read(cx).is_open(),
13286                "dock should be open before switch"
13287            );
13288            assert!(
13289                panel.is_zoomed(window, cx),
13290                "panel should be zoomed before switch"
13291            );
13292            assert!(
13293                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13294                "panel should be focused before switch"
13295            );
13296        });
13297
13298        // Switch to workspace B
13299        multi_workspace_handle
13300            .update(cx, |mw, window, cx| {
13301                mw.activate_index(1, window, cx);
13302            })
13303            .unwrap();
13304        cx.run_until_parked();
13305
13306        // Switch back to workspace A
13307        multi_workspace_handle
13308            .update(cx, |mw, window, cx| {
13309                mw.activate_index(0, window, cx);
13310            })
13311            .unwrap();
13312        cx.run_until_parked();
13313
13314        // Verify the panel is still zoomed and the dock is still open
13315        workspace_a.update_in(cx, |workspace, window, cx| {
13316            assert!(
13317                workspace.right_dock().read(cx).is_open(),
13318                "dock should still be open after switching back"
13319            );
13320            assert!(
13321                panel.is_zoomed(window, cx),
13322                "panel should still be zoomed after switching back"
13323            );
13324        });
13325    }
13326
13327    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13328        pane.read(cx)
13329            .items()
13330            .flat_map(|item| {
13331                item.project_paths(cx)
13332                    .into_iter()
13333                    .map(|path| path.path.display(PathStyle::local()).into_owned())
13334            })
13335            .collect()
13336    }
13337
13338    pub fn init_test(cx: &mut TestAppContext) {
13339        cx.update(|cx| {
13340            let settings_store = SettingsStore::test(cx);
13341            cx.set_global(settings_store);
13342            theme::init(theme::LoadThemes::JustBase, cx);
13343        });
13344    }
13345
13346    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13347        let item = TestProjectItem::new(id, path, cx);
13348        item.update(cx, |item, _| {
13349            item.is_dirty = true;
13350        });
13351        item
13352    }
13353
13354    #[gpui::test]
13355    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13356        cx: &mut gpui::TestAppContext,
13357    ) {
13358        init_test(cx);
13359        let fs = FakeFs::new(cx.executor());
13360
13361        let project = Project::test(fs, [], cx).await;
13362        let (workspace, cx) =
13363            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13364
13365        let panel = workspace.update_in(cx, |workspace, window, cx| {
13366            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13367            workspace.add_panel(panel.clone(), window, cx);
13368            workspace
13369                .right_dock()
13370                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13371            panel
13372        });
13373
13374        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13375        pane.update_in(cx, |pane, window, cx| {
13376            let item = cx.new(TestItem::new);
13377            pane.add_item(Box::new(item), true, true, None, window, cx);
13378        });
13379
13380        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13381        // mirrors the real-world flow and avoids side effects from directly
13382        // focusing the panel while the center pane is active.
13383        workspace.update_in(cx, |workspace, window, cx| {
13384            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13385        });
13386
13387        panel.update_in(cx, |panel, window, cx| {
13388            panel.set_zoomed(true, window, cx);
13389        });
13390
13391        workspace.update_in(cx, |workspace, window, cx| {
13392            assert!(workspace.right_dock().read(cx).is_open());
13393            assert!(panel.is_zoomed(window, cx));
13394            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13395        });
13396
13397        // Simulate a spurious pane::Event::Focus on the center pane while the
13398        // panel still has focus. This mirrors what happens during macOS window
13399        // activation: the center pane fires a focus event even though actual
13400        // focus remains on the dock panel.
13401        pane.update_in(cx, |_, _, cx| {
13402            cx.emit(pane::Event::Focus);
13403        });
13404
13405        // The dock must remain open because the panel had focus at the time the
13406        // event was processed. Before the fix, dock_to_preserve was None for
13407        // panels that don't implement pane(), causing the dock to close.
13408        workspace.update_in(cx, |workspace, window, cx| {
13409            assert!(
13410                workspace.right_dock().read(cx).is_open(),
13411                "Dock should stay open when its zoomed panel (without pane()) still has focus"
13412            );
13413            assert!(panel.is_zoomed(window, cx));
13414        });
13415    }
13416}